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:

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

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;
 
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);

reply to 344

learn how to look up functions to see if they exist and the parameters
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time

gethour isn't a function
getminute isn't a function

learn how to write down each little step that the code needs to do. then create code to do each step

to define the premarket time period, you can use this,
input pre_start = 0400;
input pre_end = 0930;
def pre = if SecondsFromTime(pre_start) >= 0 and SecondsTillTime(pre_end) > 0 then 1 else 0;


i changed a few things
you had a lot of == 1 . not needed. just use the true/false variable.
changed how lines are calculated and drawn

i didn't look over the code after the averages

Code:
#chat344_fix

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

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

def d = getday();
def newday = d != d[1];

input pre_start = 0400;
input pre_end = 0930;
def pre = if SecondsFromTime(pre_start) >= 0 and SecondsTillTime(pre_end) > 0 then 1 else 0;

input start = 0930;
input end = 1600;
def daytime = if SecondsFromTime(start) >= 0 and SecondsTillTime(end) > 0 then 1 else 0;


# Add a label to show whether it's premarket
AddLabel(yes, (if Pre then "Is" else "Not") + " Premarket", (if Pre then Color.GREEN else Color.RED));

# premarket high and low
def premarketHigh = if newday then na
 else if !pre[1] and pre then high
 else if pre then Max(high, premarketHigh[1])
 else premarketHigh[1];

def premarketLow = if newday then na
 else if !pre[1] and pre then low
 else if pre then Min(low, premarketLow[1])
 else premarketLow[1];

plot z1 = premarkethigh;
plot z2 = premarketlow;
z1.SetDefaultColor(Color.cyan);
z2.SetDefaultColor(Color.yellow);



# Trend functions
# User inputs
input fast1Length = 5;
input slow1Length = 12;
input fast2Length = 12;
input slow2Length = 50;

def fastEMA1 = ExpAverage(close, fast1Length);
def slowEMA1 = ExpAverage(close, fast1Length);
def fastEMA2 = ExpAverage(close, fast2Length);
def slowEMA2 = ExpAverage(close, slow2Length);

# 1 for Bullish, -1 for Bearish
def trend512 = if fastEMA1 > slowEMA1 then 1 else -1;
def trend1250 = if fastEMA2 > slowEMA2 then 1 else -1;




#-----------   chopOrTrend  will always be false.
#-----------   close will never be higher than the highest high
# Chop or Trend determination
def chopOrTrend = if close > premarketHigh or close < premarketLow then 1 else 0;
# 1 for Trending, 0 for Chop Range


# turn this on to see chopOrTrend  is always 0
addchartbubble(0, low,
chopOrTrend
, (if chopOrTrend then color.yellow else color.gray), no);




# 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);

input show_averages = yes;
plot zf1 = if show_averages then fastEMA1 else na;
plot zs1 = if show_averages then slowEMA1 else na;
plot zf2 = if show_averages then fastEMA2 else na;
plot zs2 = if show_averages then slowEMA2 else na;
#
 

Attachments

  • img2.JPG
    img2.JPG
    45.9 KB · Views: 34
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);

reply to 345

change the red bubbles to end with no
AddChartBubble(bearishEngulfing, low, "SE", color.RED, no);
that way the bubbles will point up to bars and be below them, not on top of them.
 
your code is only looking at previous bars to find a peak.
so if you find a high, the next bar may be a higher high, then you have multiple peaks.
need to also look at future bars.

this code does that
https://usethinkscript.com/threads/...y-demand-zones-for-thinkorswim.172/#post-7048

Code:
#peaksvalleys_robert_03_updated
#https://usethinkscript.com/threads/zigzag-high-low-with-supply-demand-zones-for-thinkorswim.172/#post-7048
#          Robert Payne    

# define peaks / valleys
def na = double.nan;
def bn = BarNumber();

#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def lastbn = HighestAll(if IsNaN(close) then 0 else bn);
def lastbar = bn == lastbn;
#def lastbar = (!isnan(close) and isnan(close[-1]));

def highx = high;
def lowx = low;
input length = 7;

def offset = Min(length - 1, lastbn - bn);
def peak = highx > Highest(highx[1], length - 1) and highx == GetValue(Highest(highx, length), -offset);
def valley = lowx < Lowest(lowx[1], length - 1) and lowx == GetValue(Lowest(lowx, length), -offset);

plot zhi = if peak then high*1.001 else na;
plot zlo = if valley then low*0.999 else na;

zlo.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zlo.SetDefaultColor(Color.red);
zlo.setlineweight(1);
zlo.hidebubble();

zhi.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
zhi.SetDefaultColor(Color.green);
zhi.setlineweight(1);
zhi.hidebubble();
#
@halcyonguy Happy New Year! I was away for a couple of weeks and just came back today. I will test it. Really appreciate your help. Thanks again.
 
2025-01-20-TOS_CHARTS for Thinkscript FORUM.png

Entry buy signals triggered by HMA 10 20 cross up and both with positive slope up.

This is confirmed by MACD above signal line and both at or above the zero line.
Signals remain bullish as long as stock continues up,
10/20 HMA's are green and up, and MACD is going up and remains above signal and zero line.
Heikin-Ashi candles used here for green is entry Exit or short entry is tirggered by HMA's with 20 over 10 period, and confirmed by MACD below signal line, (downward slope of both lines), Helkin-Ashi red candle confirms red arrow down and exit of the trade or short entry.

Here is the script per ChatGPT to produce this:
Code:
# Pseudo-code for Buy and Sell signals based on your conditions

# Calculate HMA
def HMA(price, period):
# Calculate Hull Moving Average for the given period
return hull_moving_average(price, period)

# MACD Calculation
def MACD(price, fast_period, slow_period, signal_period):
# Calculate MACD line and Signal line
macd_line = macd(price, fast_period, slow_period)
signal_line = signal(macd_line, signal_period)
return macd_line, signal_line

# Determine Entry Signal (Buy)
def check_entry(price, hma_10, hma_20, macd_line, signal_line):
# Check if HMA 10 crosses above HMA 20 with positive slope for both HMAs
if hma_10 > hma_20 and is_positive_slope(hma_10) and is_positive_slope(hma_20):
# Check if MACD is above the signal line and both are above zero line
if macd_line > signal_line and macd_line > 0 and signal_line > 0:
# Check if Heikin-Ashi candle is green (bullish)
if is_heikin_ashi_green():
return "Buy Signal - Green Arrow"
return None

# Determine Exit Signal (Sell)
def check_exit(price, hma_10, hma_20, macd_line, signal_line):
# Check if HMA 20 crosses above HMA 10 with negative slope for both HMAs
if hma_20 > hma_10 and is_negative_slope(hma_20) and is_negative_slope(hma_10):
# Check if MACD is below the signal line and both are sloping downward
if macd_line < signal_line and macd_line < 0 and signal_line < 0:
# Check if Heikin-Ashi candle is red (bearish)
if is_heikin_ashi_red():
return "Sell Signal - Red Arrow"
return None
 

Attachments

  • Heiken Ashi Trading Strategy.docx
    894.6 KB · Views: 36
Last edited by a moderator:
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.
View attachment 16879
Is there another source that provides better coding that I should consider here that has proven to be more successful operating within ToS?
 
Is there another source that provides better coding that I should consider here that has proven to be more successful operating within ToS?
yes, your brain.
true AI doesn't exist and won't for decades.
just take the time and learn thinkscript. i am a slow learner, but after a few months , it started clicking for me.
 
Is this something that should be inserted into the code that is transferred into ToS as a strategy by means of the create code function?

hello, and welcome,

not sure what this means.
there is nothing that will create code. that's up to you and others.
i don't know what a create code function is.

what is the real question?
what are you trying to do?
 
View attachment 23893
Entry buy signals triggered by HMA 10 20 cross up and both with positive slope up.

This is confirmed by MACD above signal line and both at or above the zero line.
Signals remain bullish as long as stock continues up,
10/20 HMA's are green and up, and MACD is going up and remains above signal and zero line.
Heikin-Ashi candles used here for green is entry Exit or short entry is tirggered by HMA's with 20 over 10 period, and confirmed by MACD below signal line, (downward slope of both lines), Helkin-Ashi red candle confirms red arrow down and exit of the trade or short entry.

Here is the script per ChatGPT to produce this:
Code:
# Pseudo-code for Buy and Sell signals based on your conditions

# Calculate HMA
def HMA(price, period):
# Calculate Hull Moving Average for the given period
return hull_moving_average(price, period)

# MACD Calculation
def MACD(price, fast_period, slow_period, signal_period):
# Calculate MACD line and Signal line
macd_line = macd(price, fast_period, slow_period)
signal_line = signal(macd_line, signal_period)
return macd_line, signal_line

# Determine Entry Signal (Buy)
def check_entry(price, hma_10, hma_20, macd_line, signal_line):
# Check if HMA 10 crosses above HMA 20 with positive slope for both HMAs
if hma_10 > hma_20 and is_positive_slope(hma_10) and is_positive_slope(hma_20):
# Check if MACD is above the signal line and both are above zero line
if macd_line > signal_line and macd_line > 0 and signal_line > 0:
# Check if Heikin-Ashi candle is green (bullish)
if is_heikin_ashi_green():
return "Buy Signal - Green Arrow"
return None

# Determine Exit Signal (Sell)
def check_exit(price, hma_10, hma_20, macd_line, signal_line):
# Check if HMA 20 crosses above HMA 10 with negative slope for both HMAs
if hma_20 > hma_10 and is_negative_slope(hma_20) and is_negative_slope(hma_10):
# Check if MACD is below the signal line and both are sloping downward
if macd_line < signal_line and macd_line < 0 and signal_line < 0:
# Check if Heikin-Ashi candle is red (bearish)
if is_heikin_ashi_red():
return "Sell Signal - Red Arrow"
return None

reply to 352

programming is applying code to a set of specific rules.
your rules are vague and have a couple errors, that need clarifying.


HMA 10 20 cross up - instead say , HMA10 crosses above hma20

positive slope up , what defines this? the price difference of 2 adjacent bars? 2 bars, that are separated?

MACD above signal line , macd isn't a plot. signal isnt a plot. what signals are you talking about?
look up functions and get familiar with them.
https://toslc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD

stock continues up , what is compared to what to determine up? close to close in adjacent bars? high to high?

Heikin-Ashi candles used here for green is entry Exit , ?? entry-exit? which , how.
are heiken-ashi price levels supposed to be used in hull formulas and macd ?
 
Last edited:
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.
View attachment 16879
OK, I watched the entire video. First 45mins most pertinent to how to prompt ChatGPT relative to the language you give it. Should I write this out first in a Word document and then post that here for it to be assessed, prior to submitting it to ChatGPT for it to create the code upon request?
 
OK, I watched the entire video. First 45mins most pertinent to how to prompt ChatGPT relative to the language you give it. Should I write this out first in a Word document and then post that here for it to be assessed, prior to submitting it to ChatGPT for it to create the code upon request?

Based on the 200 failed chatGPT scripts submitted to this thread; the moral of the story is that chatGPT is a failure for most members, unless analysts with significant debugging abilities.

@halcyonguy gave the best answer:
Take the time and learn thinkscript. i am a slow learner, but after a few months , it started clicking for me.

You can certainly keep making chatGPT attempts.
But @halcyonguy is the forum's only chatGPT whisperer.
So not all submissions can be debugged.
 
Last edited:
Attached is the suggested edits by prompting ChatGPT using the suggestions that were provided. When I copy into the "Create" studies tab, the line is listed as red in the
Based on the 200 failed chatGPT scripts submitted to this thread; the moral of the story is that chatGPT is a failure for most members, unless analysts with significant debugging abilities.

@halcyonguy gave the best answer:


You can certainly keep making chatGPT attempts.
But @halcyonguy is the forum's only chatGPT whisperer.
So not all submissions can be debugged.
Are there successful scripts that you an suggest that mirror what I am trying to accomplish here that I can adopt and make the appropriate changes to bring this into compliance with what ThinkScript requires?
 
Attached is the suggested edits by prompting ChatGPT using the suggestions that were provided. When I copy into the "Create" studies tab, the line is listed as red in the

Are there successful scripts that you an suggest that mirror what I am trying to accomplish here that I can adopt and make the appropriate changes to bring this into compliance with what ThinkScript requires?
You need to start with answering @halcyonguy's questions.
reply to 352

programming is applying code to a set of specific rules.
your rules are vague and have a couple errors, that need clarifying.


HMA 10 20 cross up - instead say , HMA10 crosses above hma20

positive slope up , what defines this? the price difference of 2 adjacent bars? 2 bars, that are separated?

MACD above signal line , macd isn't a plot. signal isnt a plot. what signals are you talking about?
look up functions and get familiar with them.
https://toslc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD

stock continues up , what is compared to what to determine up? close to close in adjacent bars? high to high?

Heikin-Ashi candles used here for green is entry Exit , ?? entry-exit? which , how.
are heiken-ashi price levels supposed to be used in hull formulas and macd ?


Think through your specifications, step-by-step
Provide annotated images specifically explaining what you are attempting.

Understand that there are issues in attempting to use oscillators and lagging indicators for entry/exit signals:
https://usethinkscript.com/threads/how-to-read-an-oscillator-in-thinkorswim.11497/
https://usethinkscript.com/threads/lagging-indicator-accuracy-in-thinkorswim.15624/
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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