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 creating non-working garbage 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:
Hey I just saw this thread
https://usethinkscript.com/threads/entryprice-always-return-nan-in-ondemand.19958/

and have been trying something similar by implementing similar code but with no success. I implemented some simple logic for and EMA crossing trade in TOS to just get the logic down but I still am no coder so please forgive my ignorance on how to resolve this. My code and results are as follow, any idea what I am doing wrong? I am simply trying to take long trades when the 8EMA open candle crosses the 21 EMA open above the 233EMA open candle for longs and shorts would be the reverse logic. I set a 3.5 point target price and stop loss for any trade. Any help is appreciated...


Code:
# Define the EMAs
input shortEMA = 8; # 8 EMA
input mediumEMA = 21; # 21 EMA
input longEMA = 233; # 233 EMA

# Define the stop loss and target (3.5 points)
input stopLoss = 3.5;
input targetPrice = 3.5;

# Calculate the EMAs of the open prices
def shortEMA_open = ExpAverage(open, shortEMA);
def mediumEMA_open = ExpAverage(open, mediumEMA);
def longEMA_open = ExpAverage(open, longEMA);

# Buy trigger condition
def buytrig = shortEMA_open crosses above mediumEMA_open and shortEMA_open > longEMA_open and mediumEMA_open > longEMA_open;

# Sell trigger condition (Short entry)
def selltrig = shortEMA_open crosses below mediumEMA_open and shortEMA_open < longEMA_open and mediumEMA_open < longEMA_open;

# Entry point variable
def ep;

# Bar number check for the first bar
if (BarNumber() == 1) {
    ep = 0;  # On the first bar, no entry point is set
} else {
    # If there's a buy trigger and the entry price was 0 previously, set it to the open price
    if (buytrig and ep[1] == 0) {
        ep = open[-1];  # Store the previous bar's open as entry price
    }
    # If there's a sell trigger, reset the entry price to 0
    else if (selltrig and ep[1] == 0) {
        ep = open[-1];
    }
    # Otherwise, retain the previous entry price
    else {
        ep = ep[1];
    }
}

# Define the stop loss and target conditions for buy and sell
def stopLossCondition = ep != 0 and (close <= ep - stopLoss or close >= ep + targetPrice);
def targetCondition = ep != 0 and (close >= ep + targetPrice or close <= ep - stopLoss);

# Add the orders for Buy (long) and Sell (short) positions
AddOrder(OrderType.BUY_TO_OPEN, buytrig, open[-1], 1, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, stopLossCondition or targetCondition, open[-1], 1, Color.RED, Color.RED);

# Add the orders for short (sell) positions
AddOrder(OrderType.SELL_TO_OPEN, selltrig, open[-1], 1, Color.RED, Color.RED);
AddOrder(OrderType.BUY_TO_CLOSE, stopLossCondition or targetCondition, open[-1], 1, Color.GREEN, Color.GREEN);

# Plot the EMAs for visualization
plot shortEMA_plot = shortEMA_open;
shortEMA_plot.SetDefaultColor(Color.CYAN);
plot mediumEMA_plot = mediumEMA_open;
mediumEMA_plot.SetDefaultColor(Color.YELLOW);
plot longEMA_plot = longEMA_open;
longEMA_plot.SetDefaultColor(Color.RED);
 
Last edited by a moderator:
Am I spinning my wheels and this is not possible or is there a simple fix?

not sure what your math is trying to do?

many things wrong,
look up the functions , and see proper spelling and parameters.


sum( price, len) missing a length parameter
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Sum
how many divs do you want to sum ?

dividends is not a valid function.
use this instead GetDividend()

GetDividend() returns a number 1 time each quarter. the other bars might be nan.
so you need a way to check the value and read it, then keep it. like this.
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Corporate-Actions/GetDividend
def DCont = if IsNaN(GetDividend()) then DCont[1] else GetDividend();

but this won't sum.
to do that , you need to determine how many to add up. 2,4,.... all?....

then use an if-then to test if not an error, then read div and add it to a variable, and increment a counter


def DCont = if IsNaN(GetDividend()) then DCont[1] else GetDividend();

def divsum;
def qty;
if !IsNaN(GetDividend()) then {
divsum = divsum[1] + dcont;
qty = qty[1] + 1;
} else {
divsum = divsum[1];
qty = qty[1];
}

def divavg = divsum/qty;

def avgcost =
def adjustedavgcost =
 
Hey I just saw this thread
https://usethinkscript.com/threads/entryprice-always-return-nan-in-ondemand.19958/

and have been trying something similar by implementing similar code but with no success. I implemented some simple logic for and EMA crossing trade in TOS to just get the logic down but I still am no coder so please forgive my ignorance on how to resolve this. My code and results are as follow, any idea what I am doing wrong? I am simply trying to take long trades when the 8EMA open candle crosses the 21 EMA open above the 233EMA open candle for longs and shorts would be the reverse logic. I set a 3.5 point target price and stop loss for any trade. Any help is appreciated...


Code:
# Define the EMAs
input shortEMA = 8; # 8 EMA
input mediumEMA = 21; # 21 EMA
input longEMA = 233; # 233 EMA

# Define the stop loss and target (3.5 points)
input stopLoss = 3.5;
input targetPrice = 3.5;

# Calculate the EMAs of the open prices
def shortEMA_open = ExpAverage(open, shortEMA);
def mediumEMA_open = ExpAverage(open, mediumEMA);
def longEMA_open = ExpAverage(open, longEMA);

# Buy trigger condition
def buytrig = shortEMA_open crosses above mediumEMA_open and shortEMA_open > longEMA_open and mediumEMA_open > longEMA_open;

# Sell trigger condition (Short entry)
def selltrig = shortEMA_open crosses below mediumEMA_open and shortEMA_open < longEMA_open and mediumEMA_open < longEMA_open;

# Entry point variable
def ep;

# Bar number check for the first bar
if (BarNumber() == 1) {
    ep = 0;  # On the first bar, no entry point is set
} else {
    # If there's a buy trigger and the entry price was 0 previously, set it to the open price
    if (buytrig and ep[1] == 0) {
        ep = open[-1];  # Store the previous bar's open as entry price
    }
    # If there's a sell trigger, reset the entry price to 0
    else if (selltrig and ep[1] == 0) {
        ep = open[-1];
    }
    # Otherwise, retain the previous entry price
    else {
        ep = ep[1];
    }
}

# Define the stop loss and target conditions for buy and sell
def stopLossCondition = ep != 0 and (close <= ep - stopLoss or close >= ep + targetPrice);
def targetCondition = ep != 0 and (close >= ep + targetPrice or close <= ep - stopLoss);

# Add the orders for Buy (long) and Sell (short) positions
AddOrder(OrderType.BUY_TO_OPEN, buytrig, open[-1], 1, Color.GREEN, Color.GREEN);
AddOrder(OrderType.SELL_TO_CLOSE, stopLossCondition or targetCondition, open[-1], 1, Color.RED, Color.RED);

# Add the orders for short (sell) positions
AddOrder(OrderType.SELL_TO_OPEN, selltrig, open[-1], 1, Color.RED, Color.RED);
AddOrder(OrderType.BUY_TO_CLOSE, stopLossCondition or targetCondition, open[-1], 1, Color.GREEN, Color.GREEN);

# Plot the EMAs for visualization
plot shortEMA_plot = shortEMA_open;
shortEMA_plot.SetDefaultColor(Color.CYAN);
plot mediumEMA_plot = mediumEMA_open;
mediumEMA_plot.SetDefaultColor(Color.YELLOW);
plot longEMA_plot = longEMA_open;
longEMA_plot.SetDefaultColor(Color.RED);

reply to 342

if short crosses above med, you don't need to check if short is greater than long
def buytrig = shortEMA_open crosses above mediumEMA_open and shortEMA_open > longEMA_open and mediumEMA_open > longEMA_open;
. becomes this,
def buytrig = shortEMA_open crosses above mediumEMA_open and mediumEMA_open > longEMA_open;


this won't be true.
. else if (selltrig and ep[1] == 0) {
when selling ep[1] will have a price
i think you need 2 ep's. one for longs one for shorts.


[-1] is the future bar, not the previous bar. just store the current bar price. [0]
ep = open[-1]; # Store the previous bar's open as entry price
 
This isn't working

declare lower;

# User inputs
input fastLength = 12;
input slowLength = 50;

//I am getting error saying Expected double in this code

input endHour = 9;
input endMinute = 30;

# Variables for current time
def currentHour = GetHour(); # Retrieves the current hour of the bar
def currentMinute = GetMinute(); # Retrieves the current minute of the bar

# Determine premarket status
def isPremarket = if currentHour < endHour or (currentHour == endHour and currentMinute <= endMinute) then 1 else 0;

# Convert isPremarket to a string for label display
def isPremarketText = if isPremarket == 1 then 1 else 0;

# Add a label to show whether it's premarket
AddLabel(yes, "Is Premarket: " + (if isPremarketText == 1 then "True" else "False"),
if isPremarketText == 1 then Color.GREEN else Color.RED);

# Variables for premarket high and low
rec premarketHigh = if isPremarket then Max(high, premarketHigh[1]) else premarketHigh[1];
rec premarketLow = if isPremarket then Min(low, premarketLow[1]) else premarketLow[1];

# Trend functions
def fastEMA = ExpAverage(close, fastLength);
def slowEMA = ExpAverage(close, slowLength);
def fastEMA_Short = ExpAverage(close, 5);
def slowEMA_Short = ExpAverage(close, 12);

def trend1250 = if fastEMA > slowEMA then 1 else -1; # 1 for Bullish, -1 for Bearish
def trend512 = if fastEMA_Short > slowEMA_Short then 1 else -1; # 1 for Bullish, -1 for Bearish

# Chop or Trend determination
def chopOrTrend = if close > premarketHigh or close < premarketLow then 1 else 0;
# 1 for Trending, 0 for Chop Range

# Price Action Trend
def priceActionTrend =
if chopOrTrend and close > premarketHigh then 1
else if chopOrTrend and close < premarketLow then -1
else 0;
# 1 for Bullish, -1 for Bearish, 0 for Chop Range

# Convert numerical conditions to strings for AddLabel
AddLabel(yes,
"Price Action: " +
(if priceActionTrend == 1 then "Bullish" else if priceActionTrend == -1 then "Bearish" else "Chop Range"),
if priceActionTrend == 1 then Color.GREEN else if priceActionTrend == -1 then Color.RED else Color.ORANGE);

AddLabel(yes,
"Ripster Clouds 12/50: " + (if trend1250 == 1 then "Bullish" else "Bearish"),
if trend1250 == 1 then Color.GREEN else Color.RED);

AddLabel(yes,
"Ripster Clouds 5/12: " + (if trend512 == 1 then "Bullish" else "Bearish"),
if trend512 == 1 then Color.GREEN else Color.RED);

# Highlighting premarket levels
plot premarketHighPlot = premarketHigh;
premarketHighPlot.SetDefaultColor(Color.LIGHT_GREEN);
premarketHighPlot.SetStyle(Curve.SHORT_DASH);

plot premarketLowPlot = premarketLow;
premarketLowPlot.SetDefaultColor(Color.LIGHT_RED);
premarketLowPlot.SetStyle(Curve.SHORT_DASH);
 
Last edited by a moderator:
Not sure if this is useful at all, but I gave Gemini a shot at writing some ThinkScript. Asked it to come up with a script to identify candlestick patterns. It's not something I use personally and it was simply to see how well it did. Took a couple iterations because it had some things wrong in terms of what TS could do, but it eventually landed on the following.

C:
# Define variables for candle body and shadows
def body = AbsValue(close - open);
def upperShadow = high - Max(open, close);
def lowerShadow = Min(open, close) - low;

#--------------------------------------------------
# Bullish Engulfing Pattern
#--------------------------------------------------
def bullishEngulfing =
    open[1] > close[1] and  # Previous candle is bearish
    close > open and       # Current candle is bullish
    close > open[1] and     # Current candle's close is higher than previous candle's open
    open < close[1];        # Current candle's open is lower than previous candle's close

#--------------------------------------------------
# Bearish Engulfing Pattern
#--------------------------------------------------
def bearishEngulfing =
    open[1] < close[1] and  # Previous candle is bullish
    close < open and       # Current candle is bearish
    close < open[1] and     # Current candle's close is lower than previous candle's open
    open > close[1];        # Current candle's open is higher than previous candle's close

#--------------------------------------------------
# Hammer Pattern
#--------------------------------------------------
def hammer =
    lowerShadow > 2 * body and  # Long lower shadow
    upperShadow < body / 2 and  # Short upper shadow
    close > open;              # Close is higher than open (for bullish hammer)

#--------------------------------------------------
# Inverted Hammer Pattern
#--------------------------------------------------
def invertedHammer =
    upperShadow > 2 * body and  # Long upper shadow
    lowerShadow < body / 2 and  # Short lower shadow
    close > open;              # Close is higher than open (for bullish inverted hammer)

#--------------------------------------------------
# Shooting Star Pattern (Bearish)
#--------------------------------------------------
def shootingStar =
    upperShadow > 2 * body and  # Long upper shadow
    lowerShadow < body / 2 and  # Short lower shadow
    close < open;              # Close is lower than open (for bearish shooting star)

#--------------------------------------------------
# Hanging Man Pattern (Bearish)
#--------------------------------------------------
def hangingMan =
    lowerShadow > 2 * body and  # Long lower shadow
    upperShadow < body / 2 and  # Short upper shadow
    close < open;              # Close is lower than open (for bearish hanging man)

#--------------------------------------------------
# Piercing Pattern (Bullish)
#--------------------------------------------------
def piercingPattern =
    open[1] > close[1] and  # Previous candle is bearish
    close > open and       # Current candle is bullish
    open < close[1] and     # Current candle's open is lower than previous candle's close
    close > (open[1] + close[1]) / 2;  # Current close is above midpoint of previous candle

#--------------------------------------------------
# Dark Cloud Cover Pattern (Bearish)
#--------------------------------------------------
def darkCloudCover =
    open[1] < close[1] and  # Previous candle is bullish
    close < open and       # Current candle is bearish
    open > close[1] and     # Current candle's open is higher than previous candle's close
    close < (open[1] + close[1]) / 2;  # Current close is below midpoint of previous candle

#--------------------------------------------------
# Morning Star Pattern (Bullish)
#--------------------------------------------------
def morningStar =
    open[2] > close[2] and  # First candle is bearish
    close[1] < open[1] and  # Second candle is bearish (often a small body)
    close > open and       # Third candle is bullish
    close > (open[2] + close[2]) / 2;  # Third candle's close is above midpoint of first candle

#--------------------------------------------------
# Evening Star Pattern (Bearish)
#--------------------------------------------------
def eveningStar =
    open[2] < close[2] and  # First candle is bullish
    close[1] > open[1] and  # Second candle is bullish (often a small body)
    close < open and       # Third candle is bearish
    close < (open[2] + close[2]) / 2;  # Third candle's close is below midpoint of first candle

#--------------------------------------------------
# Three White Soldiers Pattern (Bullish)
#--------------------------------------------------
def threeWhiteSoldiers =
    close[2] > open[2] and close[1] > open[1] and close > open and  # All three candles are bullish
    close > close[1] and close[1] > close[2] and                  # Consecutive higher closes
    open > close[1] and open[1] > close[2];                       # Consecutive higher opens

#--------------------------------------------------
# Three Black Crows Pattern (Bearish)
#--------------------------------------------------
def threeBlackCrows =
    close[2] < open[2] and close[1] < open[1] and close < open and  # All three candles are bearish
    close < close[1] and close[1] < close[2] and                  # Consecutive lower closes
    open < close[1] and open[1] < close[2];                       # Consecutive lower opens

#--------------------------------------------------
# Bullish Harami Pattern
#--------------------------------------------------
def bullishHarami =
    open[1] > close[1] and  # Previous candle is bearish
    close > open and       # Current candle is bullish
    close < open[1] and     # Current candle's close is lower than previous candle's open
    open > close[1];        # Current candle's open is higher than previous candle's close

#--------------------------------------------------
# Bearish Harami Pattern
#--------------------------------------------------
def bearishHarami =
    open[1] < close[1] and  # Previous candle is bullish
    close < open and       # Current candle is bearish
    close > open[1] and     # Current candle's close is higher than previous candle's open
    open < close[1];        # Current candle's open is lower than previous candle's close


# Plot the patterns on the chart using AddChartBubble
AddChartBubble(bullishEngulfing, high, "BE", color.GREEN,  yes);
AddChartBubble(bearishEngulfing, low, "SE", color.RED, yes);
AddChartBubble(hammer, high, "H", color.GREEN, yes);
AddChartBubble(invertedHammer, high, "IH", color.GREEN, yes);
AddChartBubble(shootingStar, low, "SS", color.RED, yes);
AddChartBubble(hangingMan, low, "HM", color.RED, yes);
AddChartBubble(piercingPattern, high, "PP", color.GREEN, yes);
AddChartBubble(darkCloudCover, low, "DCC", color.RED, yes);
AddChartBubble(morningStar, high, "MS", color.GREEN, yes);
AddChartBubble(eveningStar, low, "ES", color.RED, yes);
AddChartBubble(threeWhiteSoldiers, high, "3WS", color.GREEN, yes);
AddChartBubble(threeBlackCrows, low, "3BC", color.RED, yes);
AddChartBubble(bullishHarami, high, "BH", color.GREEN, yes);
AddChartBubble(bearishHarami, low, "SH", color.RED, yes);

Screenshot 2025-01-12 172655.png
 
Can someone help fix this code? I'm still getting error messages in TOS editor.
# Base Length
input baseLength = 14;

# Higher Time Frame
input higherTF = AggregationPeriod.DAY;

# LTF Transparency
input ltfTransparency = 10;

# HTF Min Transparency
input htfMinTransparency = 60;

# HTF Max Transparency
input htfMaxTransparency = 90;

# Current timeframe (LTF) calculations
def cur_high = Highest(high, baseLength);
def cur_low = Lowest(low, baseLength);
def cur_midpoint = (cur_high + cur_low) / 2;

# Higher timeframe (HTF) calculations
def htf_high = Highest(high(period = higherTF), baseLength);
def htf_low = Lowest(low(period = higherTF), baseLength);
def higher_midpoint = (htf_high + htf_low) / 2;

# Calculate divergence from the midpoint
def divergence = close - cur_midpoint;
def htf_divergence = close - higher_midpoint;

# Color settings for the histogram based on divergence
DefineGlobalColor("LTFUp", Color.BLUE);
DefineGlobalColor("LTFDown", Color.RED);

# Plot the LTF histograms
plot LTFDivergence = divergence;
LTFDivergence.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
LTFDivergence.SetLineWeight(3);
LTFDivergence.AssignValueColor(if divergence >= 0 then GlobalColor("LTFUp") else GlobalColor("LTFDown"));

# Plot the HTF divergence as a line
plot HTFDivergence = htf_divergence;
HTFDivergence.SetPaintingStrategy(PaintingStrategy.LINE);
HTFDivergence.SetLineWeight(2);
HTFDivergence.AssignValueColor(if htf_divergence >= 0 then Color.BLUE else Color.RED);

# Add a horizontal line at zero
AddHorizontalLine(0, Color.GRAY);
The TV script is here: https://www.tradingview.com/script/6IavcKJ6-Kurutoga-Histogram-with-HTF-and-LTF/
 
Last edited by a moderator:
Can someone help fix this code? I'm still getting error messages in TOS editor.

The TV script is here: https://www.tradingview.com/script/6IavcKJ6-Kurutoga-Histogram-with-HTF-and-LTF/

reply to 346

next time you are stuck, try to look up functions that are red.
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions


add this to the top of code, to make it a lower chart study
Code:
declare lower;


replace the last few lines of code with these
Code:
# Add a horizontal line at zero

# AddHorizontalLine() is not a function
#AddHorizontalLine(0, Color.GRAY);

# to get a horizontal line, plot a number.
plot z = 0;
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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