ChatGPT, BARD, Other AI Scripts Which Can't Be Used In ThinkOrSwim

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
90% of the members attempting chatGPT scripting; do not provide good detailed specifications.

Members know what end result that they want but lack the ability to tell chatGPT, the step-by-step logic required to code a script to achieve that end result.
This results in chatGPT providing poor code.

Here is a video on how to successfully have chatGPT create functional scripts.

The above video, explains the basics of providing good specifications to AI which results in better scripts.
AOzhl05.png
 
Last edited:
Hello everyone!! I am new to this and would like to request your help to
debug this script, so that it makes a profit and loss report, between two dates to be determined, in order to speed up the search for strategies. Thank you very much!!


# Initialize the capital
def capital = 10000
def initialcapital = capital
def current capital = capital
def start date=??
def finish date=??

# Initialize the number of shares
actions = 0

# Check the crossings and perform operations
if crossover(hullMA1, hullMA2)
{
# Make purchase
shares = currentcapital / close
currentcapital = 0
}

if crossunder(hullMA1, hullMA2)
{
# Make a sale
currentcapital = shares * close
actions = 0
}

# Calculate the accumulated money
accumulatedmoney = current capital + shares * close

# Show the report
AddLabel(yes, "Initial Capital: $" + InitialCapital + "\nCurrent Capital: $" + CurrentCapital + "\nAccumulatedMoney: $" + AccumulatedMoney)

reply to #222

here is something to experiment with,

uses the crossing of 2 averages to create buy and sell signals.
default is HULL , 22 and 66 lengths
when a buy happens , a horizontal line starts drawing at the buy price.
can pick 2 dates and choose to enable the range. if dates are on a weekend, it will find the next trading date.
can pick a starting balance.
on a buy signal, the maximum quantity of shares are calculated.

labels,
trading date range , if date range is enabled.
current account value
gain amount. (green or red)

if date range is enabled, then the average lines and signals and bubbles are restricted to within the date range.

can turn on test bubbles and lines. bubbles show shares , buy amount, balance,


Code:
# chat223_profit_loss1

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-12#post-139305
# post223
#  profit and loss report,  between 2 dates

def na = Double.NaN;
def bn = BarNumber();
def price = round(close, 2);

input starting_capital = 10000;
#  date  yyyymmdd
input start_date  = 20240303;
#input start_date  = 20240304;
input finish_date = 20240316;
#input finish_date = 20240317;
#input finish_date = 20240318;

input enable_trade_range = yes;
addlabel(enable_trade_range, asprice(start_date) + " to " + asprice(finish_date), color.yellow);


def date_en = if !enable_trade_range then 1
 else (DaysFromDate(start_date) >= 0 and DaysTillDate(finish_date) >= 0);

def date_start = enable_trade_range and DaysFromDate(start_date)[1] < 0 and DaysFromDate(start_date) >= 0;
def date_end = enable_trade_range and DaysfromDate(finish_date)[1] <0 and DaysfromDate(finish_date) >= 0;

addverticalline(date_start, "START  " + asprice(start_date), color.cyan);
addverticalline(date_end, "END  " + asprice(finish_date), color.cyan);

addchartbubble(0, low,
 DaysFromDate(start_date) + " F\n" +
 DaysTillDate(finish_date) + " T"
, color.yellow, no);


#input avg1_type = AverageType.exponential;
#input avg1_type = AverageType.Simple;
input avg1_type = AverageType.HULL;
input avg1_length = 22;
def avg1 = MovingAverage(avg1_type, price, avg1_length );

#input avg2_type = AverageType.Simple;
input avg2_type = AverageType.HULL;
input avg2_length = 66;
def avg2 = MovingAverage(avg2_type, price, avg2_length );

input show_average_lines = yes;
plot zavg1 = if show_average_lines and date_en then avg1 else na;
plot zavg2 = if show_average_lines and date_en then avg2 else na;
zavg1.SetDefaultColor(Color.CYAN);
zavg1.SetLineWeight(1);
zavg1.HideBubble();
zavg2.SetDefaultColor(Color.YELLOW);
zavg2.SetLineWeight(1);
zavg2.HideBubble();

def xup = avg1 crosses above avg2;
def xdwn = avg1 crosses below avg2;

# Check the crossings and perform buys/sells
# use all money on each trade
def shares;
def shares_value;
def current_capital;
def buy_price;
if bn == 1 then {
  buy_price = 0;
  shares = 0;
  shares_value = 0;
  current_capital = starting_capital;
} else if date_en and xup then {
#  buy
  buy_price = price;
  shares = floor(current_capital[1] / buy_price);
  shares_value = round(shares * price, 2);
  current_capital = current_capital[1] - shares_value;
} else if date_en and xdwn then {
#  sell
  buy_price = 0;
  shares = 0;
  shares_value = 0;
  current_capital = current_capital[1] + (shares[1] * price);
} else {
  buy_price = buy_price[1];
  shares = shares[1];
  shares_value = shares * price;
  current_capital = current_capital[1];
}

def current_value = Current_Capital + (shares[0] * price);
def gain_per = round(100 * (current_value-starting_capital)/starting_capital,2);


AddLabel(yes, "Initial Capital: $" +  starting_capital, color.yellow);
AddLabel(yes, "Current Capital: $" + current_value , color.yellow);
AddLabel(yes, "Gain " + gain_per + " %" , (if gain_per > 0 then color.green else color.red));

# buy price line
plot zb = if buy_price == 0 then na
 else if isnan(close[1]) then na
 else buy_price;


input test_bubbles = no;
addchartbubble(test_bubbles and date_en and (xup or xdwn), low,
 price + "\n" +
 shares + " shares\n" +
 shares_value + " $\n" +
 current_capital + " $\n"
, color.yellow, no);

addverticalline(test_bubbles and date_en and xup, "buy", color.green);
addverticalline(test_bubbles and date_en and xdwn, "sell", color.red);
#
 

Attachments

  • img1.JPG
    img1.JPG
    126.9 KB · Views: 199
Last edited:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Besides adding the support and resistance, knowing how much an instrument can move in a day/week and when that occurred can help with trading (Predominantly selling covered calls on low volatile instruments like SPY).

I am trying to add the following labels to my chart.
1. Maximum price delta (High - Low) that has occurred over the past x number of bars.
2. Exact date when the Maximum price delta (High - Low) has occurred.

Here is my attempt but I doubt the accuracy of the script.
Code:
# Initialize the maximum difference and its index variables
def maxDifference = fold i = 1 to 365 with maxDiff = Double.NEGATIVE_INFINITY do
    if AbsValue(high[i] - low[i]) > maxDiff then AbsValue(high[i] - low[i]) else maxDiff;

# Add a label to display the maxDifference and its date
AddLabel(yes, "Max Abs Difference: " + maxDifference + "   ", Color.YELLOW);

def maxIndex = fold j = 1 to 365 with idx = 0 do
    if AbsValue(high[j] - low[j]) == maxDifference then j else idx;

def daysPrior = 365 - maxIndex;

AddLabel(yes, "Days ago: " + daysPrior + "  ", Color.YELLOW);

Any help is appreciated.
 

Attachments

  • Screenshot 2024-04-01 at 10.30.33 PM.png
    Screenshot 2024-04-01 at 10.30.33 PM.png
    223.5 KB · Views: 157
Besides adding the support and resistance, knowing how much an instrument can move in a day/week and when that occurred can help with trading (Predominantly selling covered calls on low volatile instruments like SPY).

I am trying to add the following labels to my chart.
1. Maximum price delta (High - Low) that has occurred over the past x number of bars.
2. Exact date when the Maximum price delta (High - Low) has occurred.

Here is my attempt but I doubt the accuracy of the script.
Code:
# Initialize the maximum difference and its index variables
def maxDifference = fold i = 1 to 365 with maxDiff = Double.NEGATIVE_INFINITY do
    if AbsValue(high[i] - low[i]) > maxDiff then AbsValue(high[i] - low[i]) else maxDiff;

# Add a label to display the maxDifference and its date
AddLabel(yes, "Max Abs Difference: " + maxDifference + "   ", Color.YELLOW);

def maxIndex = fold j = 1 to 365 with idx = 0 do
    if AbsValue(high[j] - low[j]) == maxDifference then j else idx;

def daysPrior = 365 - maxIndex;

AddLabel(yes, "Days ago: " + daysPrior + "  ", Color.YELLOW);

Any help is appreciated.


reply to #226

a few things,
1. your loops are not using 'while' , so they look at all 365 possible values, so the result will be too high.


2. you don't need to subtract,
def daysPrior = 365 - maxIndex;
maxindex is the count of bars back to the desired one.
use this,
def daysPrior = maxIndex;

3. there are about 252 trading days in a year, not 365

instead of delta, i will be refering to the data as height, high - low.


when the loop count is bigger than the quantity of bars on the chart, it appears as if it reads data from bars before the first bar. with 251 chart bars, it found a value 270 bars back. i don't know if this is correct or not.
i added while conditions to the loops. they keep the loop active only 'while' that condition is true.
on the first loop, highest height, i added a while condition to the loop, to only read from bars with a valid price.
for the second loop, i used while to check if the bar height is not equal to the highest height. when it becomes equal, the loop stops.


Code:
#max_ht_prev_00

#https://usethinkscript.com/threads/max-price-delta-high-low-and-when-it-occurred.18348/
#Max Price Delta [High-Low] and when it occurred
#traderjoe777  4/2  #1

def na = double.nan;
def bn = barnumber();
# used in test code/bubbles
#def maxbn = highestall(if !isnan(close) then bn else 0);
#def revbn = maxbn - bn + 1;


# from tos chat - mobius
def data = getYYYYMMDD();
def yr = Round(data/10000, 0);
def mo = Round((data % 10000) / 100, 0);
def dy = (data % 100);
input test1 = no;
addLabel(test1, "date: " + mo + "/" + dy + "/" + AsPrice(yr), color.white);


# Initialize the maximum difference and its index variables
#def maxDifference = fold i = 1 to 365 with maxDiff = Double.NEGATIVE_INFINITY do
#    if AbsValue(high[i] - low[i]) > maxDiff then AbsValue(high[i] - low[i]) else maxDiff;
def ht = high - low;
input n = 365;
def maxDifference = fold i = 1 to n
  with maxDiff
  while (!isnan(close) and getvalue(bn,i) > 0)
  do max( (getvalue(high,i) - getvalue(low,i)), maxdiff );

# Add a label to display the maxDifference and its date
AddLabel(yes, "Max Abs Difference: " + maxDifference + "   ", Color.YELLOW);

#def maxIndex = fold j = 1 to 365 with idx = 0 do
#    if AbsValue(high[j] - low[j]) == maxDifference then j else idx;
def maxIndex = fold j = 1 to n
 with idx = 1
 while getvalue(ht,j) != maxDifference
 do idx + 1;


#def daysPrior = n - maxIndex;
def daysPrior = maxIndex;

def mo2 = getvalue(mo,maxIndex);
def dy2 = getvalue(dy,maxindex);
AddLabel(yes, "Days ago: " + daysPrior + "  ", Color.YELLOW);
AddLabel(yes, "Date: " + mo2 + " / " + dy2, Color.YELLOW);


input test2 = no;
def z1 = average(low,4);
addchartbubble(test2, z1*0.95,
bn + " bn\n" +
#maxbn + " mx\n" +
#revbn + " rev\n" + 
ht + "\n" +
maxIndex + "\n" 
, color.yellow, no);
#

this picture shows the labels,
max height , bars back , date
this shows test bubbles
 

Attachments

  • img1.JPG
    img1.JPG
    135 KB · Views: 139
nobody here gave you that code. it looks like tradingview pine.
everything is wrong with it, and it will have to be converted to thinkscript.

when asking about a code you found on this (or any) site, post a link to it. click on the post number in top right. then copy the web address.

what do you mean by 'import' ?
Hello, thanks for answering. I apologize, since the term import was wrong since it should have said: amount of accumulated money
 
Hello everyone. I’m trying to get thinkscript to divide High Price by Open Price on options chain with custom columns for each strike price.

The reason is to see how many times risk from open to high eliminating manually calculating for each strike.

# Calculate High divided by Open
def high_divided_by_open = high / open;

# Plot the result with value as label in canyon color
plot HighDividedByOpen = high_divided_by_open;
HighDividedByOpen.AssignValueColor(if high_divided_by_open > 1 then Color.CYAN else Color.RED);
HighDividedByOpen.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);

1711120838188.jpeg

It only shows 1.0 values
 
Hello everyone. I’m trying to get thinkscript to divide High Price by Open Price on options chain with custom columns for each strike price.

The reason is to see how many times risk from open to high eliminating manually calculating for each strike.

# Calculate High divided by Open
def high_divided_by_open = high / open;

# Plot the result with value as label in canyon color
plot HighDividedByOpen = high_divided_by_open;
HighDividedByOpen.AssignValueColor(if high_divided_by_open > 1 then Color.CYAN else Color.RED);
HighDividedByOpen.SetPaintingStrategy(PaintingStrategy.VALUES_BELOW);

It only shows 1.0 values

i put your code as a lower chart
that way i can see the numbers and see what is going on.

high is always >= open.
on a red candle with no top wick, open and high are =, and results in 1
any other candle will be a tiny ratio, with a number like 1.00005
that is why they are all 1.0

try something like this, to change the number to be something unique,
def high_divided_by_open = round(((high / open)-1)*1000,2);
 
Looking to create one fGarrette's offense/defense idea.

I've been working on one but I can't quite get it to come out the way I want it. Here's what I have so far:

# Calculate the daily open for offensive and defensive ETFs
def offenseDailyOpen = open(period = aggregationPeriod.DAY, symbol ="XLK") + open(period = aggregationPeriod.DAY, symbol ="XLY") + open(period = aggregationPeriod.DAY, symbol ="SMH") + open(period = aggregationPeriod.DAY, symbol ="ARKK");
def defenseDailyOpen = open(period = aggregationPeriod.DAY, symbol ="XLU") + open(period = aggregationPeriod.DAY, symbol ="XLP") +open (period = aggregationPeriod.DAY, symbol ="XLV") + open(period = aggregationPeriod.DAY, symbol ="UVXY");

# Calculate the current sum of closing prices for offensive and defensive ETFs
def offensive = close("XLK") + close("XLY") + close("SMH") + close("ARKK");
def defensive = close("XLU") + close("XLP") + close("XLV") + close("UVXY");

# Calculate the percentage change from the daily open for offensive and defensive ETFs
def offenseChange = (offensive - offenseDailyOpen) / offenseDailyOpen * 100;
def defenseChange = (defensive - defenseDailyOpen) / defenseDailyOpen * 100;

# Plot the percentage change difference
plot PercentageDifference = offenseChange - defenseChange;
 
Last edited by a moderator:
Strategy with errors Can I get clarification to fix errors?

def EMA8 = ExpAverage(close, 8);

# Define the crossover conditions
def buy = if EMA3 crosses above EMA8 then 1 else 0;
def sell = if EMA3 crosses below EMA8 then 1 else 0;

# Plot arrows on the chart where the conditions are met
plot BuySignal = if buy then low else Double.NaN;
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);

plot SellSignal = if sell then high else Double.NaN;
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);

# Alerts
# Alert(SoundAlerts and h > al , "Up", Alert.BAR, Sound.Bell);
# Alert(SoundAlerts and l < bl, "Down", Alert.BAR, Sound.Ding);
AddOrder(OrderType.BUY_AUTO, Bl <> Bl[1] , tickColor = GetColor(0), arrowColor
= GetColor(0), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, Al <> Al[1] , tickColor = GetColor(1),
arrowColor = GetColor(1), name = "Sell");


I'm getting the following errors


No such variable: Bl at 19:30
No such variable: Bl at 19:36
No such variable: Al at 21:35
No such variable: Al at 21:41
 
Strategy with errors Can I get clarification to fix errors?

def EMA8 = ExpAverage(close, 8);

# Define the crossover conditions
def buy = if EMA3 crosses above EMA8 then 1 else 0;
def sell = if EMA3 crosses below EMA8 then 1 else 0;

# Plot arrows on the chart where the conditions are met
plot BuySignal = if buy then low else Double.NaN;
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);

plot SellSignal = if sell then high else Double.NaN;
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);

# Alerts
# Alert(SoundAlerts and h > al , "Up", Alert.BAR, Sound.Bell);
# Alert(SoundAlerts and l < bl, "Down", Alert.BAR, Sound.Ding);
AddOrder(OrderType.BUY_AUTO, Bl <> Bl[1] , tickColor = GetColor(0), arrowColor
= GetColor(0), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, Al <> Al[1] , tickColor = GetColor(1),
arrowColor = GetColor(1), name = "Sell");


I'm getting the following errors


No such variable: Bl at 19:30
No such variable: Bl at 19:36
No such variable: Al at 21:35
No such variable: Al at 21:41

reply to 232

ema3 is not defined

in the buy and sell formulas,
crosses is highlighted red. but it isn't the problem.
quite often, the wrong word is highlighted red. you have to look at the whole code line or the line before it.
 
Last edited:
Looking to create one fGarrette's offense/defense idea.

I've been working on one but I can't quite get it to come out the way I want it. Here's what I have so far:

# Calculate the daily open for offensive and defensive ETFs
def offenseDailyOpen = open(period = aggregationPeriod.DAY, symbol ="XLK") + open(period = aggregationPeriod.DAY, symbol ="XLY") + open(period = aggregationPeriod.DAY, symbol ="SMH") + open(period = aggregationPeriod.DAY, symbol ="ARKK");
def defenseDailyOpen = open(period = aggregationPeriod.DAY, symbol ="XLU") + open(period = aggregationPeriod.DAY, symbol ="XLP") +open (period = aggregationPeriod.DAY, symbol ="XLV") + open(period = aggregationPeriod.DAY, symbol ="UVXY");

# Calculate the current sum of closing prices for offensive and defensive ETFs
def offensive = close("XLK") + close("XLY") + close("SMH") + close("ARKK");
def defensive = close("XLU") + close("XLP") + close("XLV") + close("UVXY");

# Calculate the percentage change from the daily open for offensive and defensive ETFs
def offenseChange = (offensive - offenseDailyOpen) / offenseDailyOpen * 100;
def defenseChange = (defensive - defenseDailyOpen) / defenseDailyOpen * 100;

# Plot the percentage change difference
plot PercentageDifference = offenseChange - defenseChange;

reply to 231

sorry, i have no idea who garret is.
when referencing some guys code, post a link to a site that talks about it.

can you tell us what the original code is supposed to do and what different thing you want it to do?
 
Last edited:
ema3 is not defined

in the buy and sell formulas,
crosses is highlighted red. but it isn't the problem.
quite often, the wrong word is highlighted red. you have to look at the whole code line or the line before it.
Thank you for your quick reply!
I added def EMA3 = ExpAverage(close, 3);

I am still getting errors
No such variable: Bl at 20:30
No such variable: Bl at 20:36
No such variable: Al at 22:35
No such variable: Al at 22:41

in add order section
 
Strategy with errors Can I get clarification to fix errors?

def EMA8 = ExpAverage(close, 8);

# Define the crossover conditions
def buy = if EMA3 crosses above EMA8 then 1 else 0;
def sell = if EMA3 crosses below EMA8 then 1 else 0;

# Plot arrows on the chart where the conditions are met
plot BuySignal = if buy then low else Double.NaN;
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);

plot SellSignal = if sell then high else Double.NaN;
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);

# Alerts
# Alert(SoundAlerts and h > al , "Up", Alert.BAR, Sound.Bell);
# Alert(SoundAlerts and l < bl, "Down", Alert.BAR, Sound.Ding);
AddOrder(OrderType.BUY_AUTO, Bl <> Bl[1] , tickColor = GetColor(0), arrowColor
= GetColor(0), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, Al <> Al[1] , tickColor = GetColor(1),
arrowColor = GetColor(1), name = "Sell");


I'm getting the following errors


No such variable: Bl at 19:30
No such variable: Bl at 19:36
No such variable: Al at 21:35
No such variable: Al at 21:41

same issue, trying to use variables that haven't been defined
AL and BL don't exist

i added some things and made it work.
it does a buy when buy is true.
it does a sell when sell is true.

this uses small lengths for the averages, so there could be many crossings when price moves sideways


Code:
#chat232_ema_crossing

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-12#post-140802

def na = double.nan;
def bn = barnumber();

input len3 = 3;
input len8 = 8;
def EMA3 = ExpAverage(close, len3);
def EMA8 = ExpAverage(close, len8);

input show_emas = no;
plot z1 = if show_emas then ema3 else na;
plot z2 = if show_emas then ema8 else na;

# Define the crossover conditions
def buy = if EMA3 crosses above EMA8 then 1 else 0;
def sell = if EMA3 crosses below EMA8 then 1 else 0;

# Plot arrows on the chart where the conditions are met
plot BuySignal = if buy then low*0.999 else na;
BuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);
BuySignal.setlineweight(2);
BuySignal.hidebubble();

plot SellSignal = if sell then high*1.001 else na;
SellSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);
sellSignal.setlineweight(2);
sellSignal.hidebubble();


#  variables used below but not defined
# Alerts
# Alert(SoundAlerts and h > al , "Up", Alert.BAR, Sound.Bell);
# Alert(SoundAlerts and l < bl, "Down", Alert.BAR, Sound.Ding);
#AddOrder(OrderType.BUY_to_open, Bl <> Bl[1], tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "Buy");
#AddOrder(OrderType.SELL_TO_CLOSE, Al <> Al[1], tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Sell");

# AddOrder ( type, condition, price, tradeSize, tickColor, arrowColor, name);  

input tradesize = 1;

AddOrder (
 type = ordertype.BUY_TO_OPEN
, condition = buy
, price = open[-1]
, tradeSize = tradeSize
, tickColor = color.green
, arrowColor = color.green
, name = "buy"
);  

AddOrder (
 type = ordertype.sell_to_close
, condition = sell
, price = open[-1]
, tradeSize = tradeSize
, tickColor = color.red
, arrowColor = color.red
, name = "sell"
);  
#


some other similar posts that might help
https://www.google.com/search?q=ust...CEYFZgDAJIHBzE4LjE1LjGgB77cAQ&sclient=gws-wiz
 
halcyon guysame issue, trying to use variables that haven't been defined
AL and BL don't exist

I added some things and made it work.
it does a buy when buy is true.
it does a sell when the sell is true.

this uses small lengths for the averages, so there could be many crossings when the price moves sideways


Code:
#chat232_ema_crossing

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-12#post-140802

def na = double.nan;
def bn = barnumber();

input len3 = 3;
input len8 = 8;
def EMA3 = ExpAverage(close, len3);
def EMA8 = ExpAverage(close, len8);

input show_emas = no;
plot z1 = if show_emas then ema3 else na;
plot z2 = if show_emas then ema8 else na;

# Define the crossover conditions
def buy = if EMA3 crosses above EMA8 then 1 else 0;
def sell = if EMA3 crosses below EMA8 then 1 else 0;

# Plot arrows on the chart where the conditions are met
plot BuySignal = if buy then low*0.999 else na;
BuySignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);
BuySignal.setline-weight(2);
BuySignal.hide bubble();

plot SellSignal = if sell then high*1.001 else na;
SellSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);
sellSignal.setlineweight(2);
sellSignal.hidebubble();


#  variables used below but not defined
# Alerts
# Alert(SoundAlerts and h > al , "Up", Alert.BAR, Sound.Bell);
# Alert(SoundAlerts and l < bl, "Down", Alert.BAR, Sound.Ding);
#AddOrder(OrderType.BUY_to_open, Bl <> Bl[1], tick color = GetColor(0), arrow color = GetColor(0), name = "Buy");
#AddOrder(OrderType.SELL_TO_CLOSE, Al <> Al[1], tick color = GetColor(1), arrow color = GetColor(1), name = "Sell");

# AddOrder ( type, condition, price, trade size, tickColor, arrow color, name); 

input tradesize = 1;

AddOrder (
 type = order type.BUY_TO_OPEN
, condition = buy
, price = open[-1]
, trade size = trade size
, tickColor = color.green
, arrowColor = color.green
, name = "buy"
); 

AddOrder (
 type = order type.sell_to_close
, condition = sell
, price = open[-1]
, trade size = trade size
, tickColor = color.red
, arrowColor = color.red
, name = "sell"
); 
#


some other similar posts that might help
https://www.google.com/search?q=usthinkscript+ema+crosses+addorder&sca_esv=619c697d276fe56b&sxsrf=ACQVn09SitLwT0vp1fsxTNb2fnyWsw60uQ:1713993407898&source=hp&ei=v3YpZuGgNbKI7NYPt7SlmAQ&iflsig=ANes7DEAAAAAZimEz09XSifivv_Kkix606ZGTOkYVXMn&ved=0ahUKEwih_OSB49uFAxUyBNsEHTdaCUMQ4dUDCBc&uact=5&oq=usthinkscript+ema+crosses+addorder&gs_lp=Egdnd3Mtd2l6IiJ1c3RoaW5rc2NyaXB0IGVtYSBjcm9zc2VzIGFkZG9yZGVyMgcQIRigARgKMgcQIRigARgKSNRmUABY5WBwAHgAkAEAmAHhAaABhBuqAQYyNC45LjG4AQPIAQD4AQGYAiKgArYcwgIEECMYJ8ICCxAAGIAEGLEDGIMBwgIREC4YgAQYsQMY0QMYgwEYxwHCAggQABiABBixA8ICDhAuGIAEGLEDGNEDGMcBwgIOEAAYgAQYsQMYgwEYigXCAgUQABiABMICCxAuGIAEGMcBGK8BwgILEC4YgAQYsQMYgwHCAgUQLhiABMICDRAuGIAEGNEDGMcBGArCAgcQLhiABBgKwgINEC4YgAQYsQMYgwEYCsICBxAAGIAEGArCAg0QLhiABBjHARgKGK8BwgIKEC4YgAQYsQMYCsICBxAAGIAEGA3CAgYQABgNGB7CAg0QABiABBixAxiDARgNwgIIEAAYgAQYogTCAgcQIxiwAhgnwgIEECEYFZgDAJIHBzE4LjE1LjGgB77cAQ&sclient=gws-wiz
Thank You again!
 
reply to #223

here is something to experiment with,

uses the crossing of 2 averages to create buy and sell signals.
default is HULL , 22 and 66 lengths
when a buy happens , a horizontal line starts drawing at the buy price.
can pick 2 dates and choose to enable the range. if dates are on a weekend, it will find the next trading date.
can pick a starting balance.
on a buy signal, the maximum quantity of shares are calculated.

labels,
trading date range , if date range is enabled.
current account value
gain amount. (green or red)

if date range is enabled, then the average lines and signals and bubbles are restricted to within the date range.

can turn on test bubbles and lines. bubbles show shares , buy amount, balance,


Code:
# chat223_profit_loss1

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-12#post-139305
# post223
#  profit and loss report,  between 2 dates

def na = Double.NaN;
def bn = BarNumber();
def price = round(close, 2);

input starting_capital = 10000;
#  date  yyyymmdd
input start_date  = 20240303;
#input start_date  = 20240304;
input finish_date = 20240316;
#input finish_date = 20240317;
#input finish_date = 20240318;

input enable_trade_range = yes;
addlabel(enable_trade_range, asprice(start_date) + " to " + asprice(finish_date), color.yellow);


def date_en = if !enable_trade_range then 1
 else (DaysFromDate(start_date) >= 0 and DaysTillDate(finish_date) >= 0);

def date_start = enable_trade_range and DaysFromDate(start_date)[1] < 0 and DaysFromDate(start_date) >= 0;
def date_end = enable_trade_range and DaysfromDate(finish_date)[1] <0 and DaysfromDate(finish_date) >= 0;

addverticalline(date_start, "START  " + asprice(start_date), color.cyan);
addverticalline(date_end, "END  " + asprice(finish_date), color.cyan);

addchartbubble(0, low,
 DaysFromDate(start_date) + " F\n" +
 DaysTillDate(finish_date) + " T"
, color.yellow, no);


#input avg1_type = AverageType.exponential;
#input avg1_type = AverageType.Simple;
input avg1_type = AverageType.HULL;
input avg1_length = 22;
def avg1 = MovingAverage(avg1_type, price, avg1_length );

#input avg2_type = AverageType.Simple;
input avg2_type = AverageType.HULL;
input avg2_length = 66;
def avg2 = MovingAverage(avg2_type, price, avg2_length );

input show_average_lines = yes;
plot zavg1 = if show_average_lines and date_en then avg1 else na;
plot zavg2 = if show_average_lines and date_en then avg2 else na;
zavg1.SetDefaultColor(Color.CYAN);
zavg1.SetLineWeight(1);
zavg1.HideBubble();
zavg2.SetDefaultColor(Color.YELLOW);
zavg2.SetLineWeight(1);
zavg2.HideBubble();

def xup = avg1 crosses above avg2;
def xdwn = avg1 crosses below avg2;

# Check the crossings and perform buys/sells
# use all money on each trade
def shares;
def shares_value;
def current_capital;
def buy_price;
if bn == 1 then {
  buy_price = 0;
  shares = 0;
  shares_value = 0;
  current_capital = starting_capital;
} else if date_en and xup then {
#  buy
  buy_price = price;
  shares = floor(current_capital[1] / buy_price);
  shares_value = round(shares * price, 2);
  current_capital = current_capital[1] - shares_value;
} else if date_en and xdwn then {
#  sell
  buy_price = 0;
  shares = 0;
  shares_value = 0;
  current_capital = current_capital[1] + (shares[1] * price);
} else {
  buy_price = buy_price[1];
  shares = shares[1];
  shares_value = shares * price;
  current_capital = current_capital[1];
}

def current_value = Current_Capital + (shares[0] * price);
def gain_per = round(100 * (current_value-starting_capital)/starting_capital,2);


AddLabel(yes, "Initial Capital: $" +  starting_capital, color.yellow);
AddLabel(yes, "Current Capital: $" + current_value , color.yellow);
AddLabel(yes, "Gain " + gain_per + " %" , (if gain_per > 0 then color.green else color.red));

# buy price line
plot zb = if buy_price == 0 then na
 else if isnan(close[1]) then na
 else buy_price;


input test_bubbles = no;
addchartbubble(test_bubbles and date_en and (xup or xdwn), low,
 price + "\n" +
 shares + " shares\n" +
 shares_value + " $\n" +
 current_capital + " $\n"
, color.yellow, no);

addverticalline(test_bubbles and date_en and xup, "buy", color.green);
addverticalline(test_bubbles and date_en and xdwn, "sell", color.red);
#
Thank you very much halcyonguy, thank you very much for the excellent script, it is very useful for backtesting! I am asking you and whoever may be interested, if there is a possibility of taking it to the next level, improving this script in two steps: 1) that it also considers short operations for the calculation of profits, and 2) if there is a possibility of making it The code compares all combinations, at their different lengths, of the two moving averages (and better yet, if possible, of all types of moving averages with each other), and then indicates which of them obtained the best profit. If possible, it would be a great and very useful tool for all users. -
I added a basic example of this, but I need someone experienced to incorporate it so that it works properly. -Thank you in advance.-

# Define the minimum and maximum lengths for the moving averages
input minLength = 5;
input maxLength = 50;

# List of moving average types to test
def maTypes = {SMA, WMA, HullMA, EMA}; # You can add other types of moving averages as needed

# Variables to store the best combination found
def bestProfit = Double.NEGATIVE_INFINITY;
def bestParams = "";

# Loop to test all combinations
foreach length in minLength..maxLength {
foreach maType in maTypes {
# Calculate profits for the current combination
def currentProfit = CalculateProfits(maType, length);

# Update the best combination if one with greater profits is found
if (currentProfit > bestProfit) {
bestProfit = currentProfit;
bestParams = maType + " Length: " + length;
}
}
}

# Print the best combination found
AddLabel(yes, "Best combination: " + bestParams + ", Profit: " + bestProfit);
 
Last edited:
Please help me find the error in this code. Thank you.
Goal of the code is to Scan for a Moving Average crossing above another moving average AFTER A SPECIFIED NUMBER OF DAYS (BARS)

# User inputs
input fastLength = 8;
input slowLength = 20;
input crossPeriod = 20;

# Calculate moving averages
def fastEMA = ExpAverage(close, fastLength);
def slowEMA = ExpAverage(close, slowLength);

# Check for crossover and if fastEMA has been below slowEMA for at least 5 days
def belowSlowEMA = fastEMA < slowEMA;
def belowSlowEMAPeriod = Sum(belowSlowEMA, crossPeriod) == crossPeriod;
def cross = if (fastEMA > slowEMA and belowSlowEMAPeriod) then 1 else 0;

# Plot the crossover signal
plot scanSignal = cross;
 
Lines at the last 3 highest volume vwap level within the last 52 weeks.
This is what i got from ChatGPT. Price is shown but no line is drawn on the chart. This is for just one line for the last highest vwap level.. I need it to draw 3 lines for the last 3 highest vwap level, add a number on each line in ascending order. Thank you for any help.



input lookbackPeriod = 52; # Lookback period in weeks

# Calculate the number of bars in the lookback period
def barsInPeriod = lookbackPeriod * 5;

# Find the highest volume day within the lookback period
def highestVolumeDay = Highest(volume, barsInPeriod);

# Calculate VWAP for the highest volume day
def vwapHighestVolumeDay = if volume == highestVolumeDay then reference VWAP() else Double.NaN;

# Plot horizontal line at the VWAP level of the highest volume day
plot VWAPLine = if !IsNaN(vwapHighestVolumeDay) then vwapHighestVolumeDay else Double.NaN;
VWAPLine.SetDefaultColor(Color.BLUE);
VWAPLine.SetLineWeight(1);
 
I Have a failed CH GPT failed script I would like help on for a scan
# Define the scan
# Weighted matrix of indicators
def weight_PS = 1;
def weight_PB = 2;
def weight_DIV_YIELD = 3;
def weight_ROE = 6;
def weight_EARNINGS_GROWTH = 5;
def weight_DEBT_TO_EQUITY = 3;
def weight_FCF = 3;
def weight_OPERATING_MARGIN = 4;
def weight_P_OCF = 2;
def weight_MARKET_CAP = 5;

# Calculate weighted score for each stock
def weighted_score = weight_PS * Fundamental(priceType = PriceType.SALES) +
weight_PB * Fundamental(priceType = PriceType.BOOK_VALUE_PER_SHARE) +
weight_DIV_YIELD * Fundamental(priceType = PriceType.DIVIDEND_YIELD) +
weight_ROE * Fundamental(priceType = PriceType.RETURN_ON_EQUITY) +
weight_EARNINGS_GROWTH * Fundamental(priceType = PriceType.EARNINGS_GROWTH_RATE) +
weight_DEBT_TO_EQUITY * Fundamental(priceType = PriceType.DEBT_TO_EQUITY) +
weight_FCF * Fundamental(priceType = PriceType.FREE_CASH_FLOW) +
weight_OPERATING_MARGIN * Fundamental(priceType = PriceType.OPERATING_MARGIN) +
weight_P_OCF * Fundamental(priceType = PriceType.PRICE_TO_OPERATING_CASH_FLOW) +
weight_MARKET_CAP * Fundamental(priceType = PriceType.MARKET_CAPITALIZATION);

# Scan condition for highest weighted score
plot scan_condition = weighted_score > Highest(weighted_score, 34);

reply to #238?? , original deleted ?

all of your pricetypes are wrong
pricetype can be only , Last, Ask, Bid, or Mark
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/Fundamental

fundamental doesn't have the data you are looking for
https://tlc.thinkorswim.com/center/reference/thinkScript/Constants/FundamentalType

take a look at these label and see if any of them are what you are looking for
https://usethinkscript.com/threads/financial-fundamentals-labels-for-thinkorswim.5308/
 
Last edited:
Please help me find the error in this code. Thank you.
Goal of the code is to Scan for a Moving Average crossing above another moving average AFTER A SPECIFIED NUMBER OF DAYS (BARS)

# User inputs
input fastLength = 8;
input slowLength = 20;
input crossPeriod = 20;

# Calculate moving averages
def fastEMA = ExpAverage(close, fastLength);
def slowEMA = ExpAverage(close, slowLength);

# Check for crossover and if fastEMA has been below slowEMA for at least 5 days
def belowSlowEMA = fastEMA < slowEMA;
def belowSlowEMAPeriod = Sum(belowSlowEMA, crossPeriod) == crossPeriod;
def cross = if (fastEMA > slowEMA and belowSlowEMAPeriod) then 1 else 0;

# Plot the crossover signal
plot scanSignal = cross;

reply to --
the cross = line is wrong,
it should be looking at the previous value of belowSlowEMAPeriod, not the current value.
i added an offset to read a value from 1 bar ago.

replace your code line with this one,
def cross = if (fastEMA > slowEMA and belowSlowEMAPeriod[1] ) then 1 else 0;
 
Last edited:
Hey guys i'm new here and not a coder by any means, but will appreciate very much if somebody helps me in this.

I would like to build a scan in ToS for at least 3 consistant bar close higher than Upper Bollinger band
to show me intraday overextended stocks like DELL on 04/04/2024
dell chart 04-04-2024.png
and CZOO on 04/24/2024
czoo 04-24-2024.png
When addressing this problem to ChatGPT it provided me with a code that don't work and idk why. The scan criteria are basically simple:

1. Stock should be above upper bollinger band intraday on 2-min chart.
2. Chart must have at least 3 consecutive 2min candles above Upper BB that closed higher one after previous ( so close of candle 3 > close of candle 2 > close of candle 1) and at least 3 consecutive 2min candles which lows are higher than previous two candles (low of candle3> low of candle2> low of candle1)

Below is the code that ChatGPT provided:
Code:
# Define variables
input length = 20;
input numCandles = 3;

# Calculate Bollinger Bands
def price = close;
def SD = StDev(price, length);
def upperBand = BollingerBands(price, length, 2.0, 2.0).UpperBand;

# Check condition
def aboveUpperBand = close > upperBand;

# Count consecutive candles above upper band
def count = if aboveUpperBand then count[1] + 1 else 0;

# Condition for scan
def signal = count >= numCandles;

# Output
plot scan = signal;

Any help or afdvice will be highly appreciated.
 
Last edited by a moderator:
Lines at the last 3 highest volume vwap level within the last 52 weeks.
This is what i got from ChatGPT. Price is shown but no line is drawn on the chart. This is for just one line for the last highest vwap level.. I need it to draw 3 lines for the last 3 highest vwap level, add a number on each line in ascending order. Thank you for any help.



input lookbackPeriod = 52; # Lookback period in weeks

# Calculate the number of bars in the lookback period
def barsInPeriod = lookbackPeriod * 5;

# Find the highest volume day within the lookback period
def highestVolumeDay = Highest(volume, barsInPeriod);

# Calculate VWAP for the highest volume day
def vwapHighestVolumeDay = if volume == highestVolumeDay then reference VWAP() else Double.NaN;

# Plot horizontal line at the VWAP level of the highest volume day
plot VWAPLine = if !IsNaN(vwapHighestVolumeDay) then vwapHighestVolumeDay else Double.NaN;
VWAPLine.SetDefaultColor(Color.BLUE);
VWAPLine.SetLineWeight(1);

reply to #--
on each bar, this finds the 3 highest volumes, in the past x bars. then finds a VWAP for those 3 volume bars, and draws 3 lines.

Code:
#chat241_3hi_vwap_lines

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-13#post-140670
#elborsagy  #241
#Lines at the last 3 highest volume vwap level within the last 52 weeks.

def na = double.nan;
def bn = barnumber();
def m = 1000000;
def rnd = 2;

input lookbackPeriod = 52; # Lookback period in weeks

# Calculate the number of bars in the lookback period
def barsInPeriod = lookbackPeriod * 5;

# Find the highest volume day within the lookback period
def v1 = volume;
def v1hi = Highest(v1, barsInPeriod);

def v2hi = fold i = 0 to barsInPeriod
  with m2
  do if v1hi > GetValue(v1, i) then max(GetValue(v1, i), m2) else m2;

def v3hi = fold j = 0 to barsInPeriod
  with m3
  do if v2hi > GetValue(v1, j) then max(GetValue(v1, j), m3) else m3;


# Calculate VWAP for the highest volume day
def vwapHi1Vol = if bn == 1 then na
 else if v1 == v1hi then reference VWAP()
 else vwapHi1Vol[1];
plot VWAP1 = vwapHi1Vol;
VWAP1.SetDefaultColor(Color.BLUE);
VWAP1.SetLineWeight(1);
vwap1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Calculate VWAP for the 2nd highest volume day
def vwapHi2Vol = if bn == 1 then na
 else if v1 == v2hi then reference VWAP()
 else vwapHi2Vol[1];
plot VWAP2 = vwapHi2Vol;
VWAP2.SetDefaultColor(Color.BLUE);
VWAP2.SetLineWeight(1);
vwap2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Calculate VWAP for the 3rd highest volume day
def vwapHi3Vol = if bn == 1 then na
 else if v1 == v3hi then reference VWAP()
 else vwapHi3Vol[1];
plot VWAP3 = vwapHi3Vol;
VWAP3.SetDefaultColor(Color.BLUE);
VWAP3.SetLineWeight(1);
vwap3.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

#---------------------

# test stuff
def vr1 = round(v1/m, rnd);
def vr1hi = round(v1hi/m, rnd);
def vr2hi = round(v2hi/m, rnd);
def vr3hi = round(v3hi/m, rnd);

def x = (!isnan(close[-(barsInPeriod-1)]) and isnan(close[-(barsInPeriod)]));
addverticalline(x, "-",color.cyan);

addchartbubble(0, low*0.999,
 bn + "\n" +
 vr1 + "  \n" +
 " " + "\n" +
 vr1hi + " 1\n" +
 vr2hi + " 2\n" +
 vr3hi + " 3\n"
, color.yellow, no);

#addlabel(1, "len " +  barsInPeriod, color.cyan);
#


----------------------------
here is a volume study for testing
it displays the volume number, in millions, above the bars
Code:
#vol_nums
def v = volume;
def m = 1000000;
def rnd = 2;
def vr1 = round(v/m, rnd);
addchartbubble(1, v, vr1, color.yellow, yes);
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
296 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top