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:

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

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)
 
Hello everyone, I have little understanding of thinkscript programming. I am needing your help to debug a code that you gave me, in order to have a script that does a retrospective test of buying and selling operations, every time two Hull moving averages (10 and 20 periods respectively) cross each other and at the end sample the import in $ obtained (starting, for example, from an initial capital of $1,000).

I add the code below.-


# Get the symbol of the instrument on screen
symbol = symbol;

# Variables to store signals and data
buySignal = false;
sellSignal = false;
buyPrice = 0.0;
sellPrice = 0.0;
currentBalance = initialCapital;
totalProfit = 0.0;
totalTrades = 0;

# Calculate Hull moving averages
hullMA1 = hullMA(symbol, periodMA1);
hullMA2 = hullMA(symbol, periodMA2);

# Iterate through the defined time period
for (i = 0; i < barCount(symbol); i++) {
# Get the current data bar
bar = bar(symbol, i);

# Generate buy/sell signals
if (hullMA1 > hullMA2 and not buySignal) {
buySignal = true;
sellSignal = false;
buyPrice = bar.close;
log("Buy: " + bar.close + " - " + bar.date);
} else if (hullMA1 < hullMA2 and not sellSignal) {
buySignal = false;
sellSignal = true;
sellPrice = bar.close;
log("Sell: " + bar.close + " - " + bar.date);

# Calculate and record profit/loss
profit = sellPrice - buyPrice;
totalProfit += profit;
totalTrades++;

# Reinvest profit in the next buy
currentBalance += profit;
buyPrice = 0.0;
}
}

# Display results
plot("Hull MA1", hullMA1, color.blue);
plot("Hull MA2", hullMA2, color.orange);
plot("Close Price", bar.close, color.black);

# Display trade summary
log("Final Balance: $" + currentBalance);
log("Total Profit: $" + totalProfit);
log("Total Trades: " + totalTrades);

# Display summary message
if (totalProfit > 0) {
alert("Congratulations! You made a total profit of $" + totalProfit + " in " + totalTrades + " trades.");
} else if (totalProfit < 0) {
alert("Sorry, you had a total loss of $" + totalProfit + " in " + totalTrades + " trades.");
} else {
alert("No profit or loss was made in " + totalTrades + " trades.");
}

# Adjust parameters
def periodMA1 = 10;
def periodMA2 = 20;
def initialCapital = 1000.0;

strategy(periodMA1, periodMA2, initialCapital);
# END CODE

I greatly appreciate your contributions.-

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' ?

-------------------------


here is a strategy to experiment with


Code:
#chat220_strat_hull_cross_buys

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

input Balance = 1000;

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

#input avg1_type = AverageType.exponential;
input avg1_type = AverageType.hull;
input avg1_length = 10;
def avg1 = MovingAverage(avg1_type, data, avg1_length );

input avg2_type = AverageType.hull;
input avg2_length = 20;
def avg2 = MovingAverage(avg2_type, data, avg2_length );

input show_average_lines = yes;
plot zavg1 = if show_average_lines then avg1 else na;
plot zavg2 = if show_average_lines 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;

def sellcnt = if bn == 1 then 0 else if xdwn then sellcnt[1] + 1 else sellcnt[1];

def buyprice;
def gain;
def total;
if bn == 1 then {
  buyprice = 0;
  gain = 0;
  total = balance;
} else if xup and buyprice[1] == 0 then {
  buyprice = open[-1];
  gain = 0;
  total = total[1];
} else if xdwn then {
  buyprice = 0;
  gain = open[-1] - buyprice[1];
  total = total[1] + gain;
} else {
  buyprice = 0;
  gain = balance;
  total = total[1];
}

def diff = round(total - balance,2);

addlabel(1, "start amt " + balance, color.white);
addlabel(1, "ending amt " + round(total,2), color.white);
addlabel(1, "gain " + diff, (if diff > 0 then color.green else color.red));
addlabel(1, "trade quantity " + sellcnt, color.white);

def buy = xup;
def sell = xdwn;
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.yellow, arrowcolor = Color.yellow, name = "Sell");
#
 

Attachments

  • img2.JPG
    img2.JPG
    136.5 KB · Views: 63
Last edited:
Hi all, new to this great site! i wrote a code....hum... my friend chat wrote a code where cyan arrows appear on a chart when the current volume is greater than the volume 10bar moving average. Same with price in magenta. The issue i am facing is that the arrows are on top of the price candles vs below pointing up (volume in cyan) or above pointing down - price in magenta (which i would prefer both of these requirements to happen.)
declare lower;

# Define input for moving average length
input maLength = 10;

# Define condition for green candle
def isGreenCandle = close > open;

# Calculate the volume
def volumeAvg = Average(volume, maLength);

# Plot arrows above candles when conditions are met
plot BullishArrow = if isGreenCandle and volume > volumeAvg then high + 1 else Double.NaN;
BullishArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BullishArrow.SetLineWeight(3);
BullishArrow.SetDefaultColor(Color.CYAN);

and:

declare lower;

# Define input for moving average length
input maLength = 10;

# Define condition for green candle
def isGreenCandle = close > open;

# Calculate the price bar range (high-low)
def priceRange = high - low;

# Calculate the 10-bar moving average of the price bar range
def mvAvgPriceRange = MovingAverage(AverageType.SIMPLE, priceRange, maLength);

# Plot arrows above candles when conditions are met
plot BullishArrow = if isGreenCandle and priceRange > mvAvgPriceRange then high + 1 else Double.NaN;
BullishArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BullishArrow.SetLineWeight(3);
BullishArrow.SetDefaultColor(Color.MAGENTA);
any feedback on how to get these arrows to be adjusted? (cyan below pointing up) and (magenta above pointing down?)
 

Attachments

  • Screenshot 2024-03-25 224009.png
    Screenshot 2024-03-25 224009.png
    93.6 KB · Views: 34
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 #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);
#
 

Attachments

  • img1.JPG
    img1.JPG
    126.9 KB · Views: 61
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: 46
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: 33
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);
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
490 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