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

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
AOzhl05.png

5GoWQY3.png
 
Last edited:

BenTen

Administrative
Staff member
Staff
VIP
Lifetime
Hello,

messing around with Chat GPT and ThinkScript and just seeing what it can do. Having an issue with this if statement on line 60 under "# Reset the trend change flag". I've only just made this, haven't backtested anything yet, just seeing what GPT can do, don't take this and think it is going to be any kind of successful.

Code:
# Define the input variables
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input emaPeriod = 9;
input rsiPeriod = 14;
input vwapLength = 20;

# Define the MACD line
def MACDLine = MACD(fastLength, slowLength, MACDLength).Diff;

# Define the MACD signal line
def SignalLine = MACD(fastLength, slowLength, MACDLength).Avg;

# Define the MACD histogram
def Histogram = MACDLine - SignalLine;

# Define the 9EMA
def EMA9 = ExpAverage(close, emaPeriod);

# Define the RSI
input rsiPeriod = 14;
def RSIValue = RSI(close, rsiPeriod);

# Define the aggregation period for VWAP
def AggregationPeriod = AggregationPeriod.DAY;
# Define the VWAP
def VWAPValue = VWAP;

# Define the CCI
input cciPeriod = 14;
def CCIValue = CCI(cciPeriod);

# Define the trend direction
def Trend = if close > EMA9 then 1 else if close < EMA9 then -1 else 0;

# Initialize the trend change flag
def TrendChanged = 0;

# Determine if the trend has changed
def TrendChanged = if Trend != Trend[1] then 1 else 0;

# Define the conditions for a buy signal
def BuySignal = MACDLine > SignalLine and Histogram > 0 and close > EMA9 and RSIValue > 50 and close > VWAPValue and CCIValue > 0;

# Define the conditions for a sell signal
def SellSignal = MACDLine < SignalLine and Histogram < 0 and close < EMA9 and RSIValue < 50 and close < VWAPValue and CCIValue < 0;

# Determine if a signal should be generated
def Signal = if BuySignal and Trend > 0 and TrendChanged == 1 then 1 else if SellSignal and Trend < 0 and TrendChanged == 1 then -1 else 0;

# Update the trend direction
def NewTrend = if Signal == 1 then 1 else if Signal == -1 then -1 else Trend;
Trend = NewTrend;

# Determine if the trend has changed
def TrendChanged = if highest(Trend, TrendPeriod) != lowest(Trend, TrendPeriod) then 1 else 0;

# Reset the trend change flag
if Trend == Trend[1] {
    TrendChanged := 0;
}


# Plot a green arrow for a buy signal and a red arrow for a sell signal
plot BuySignalArrow = if Signal == 1 then low - 5 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.GREEN);

plot SellSignalArrow = if Signal == -1 then high + 5 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.RED);

What are you trying to do? I see MACD, VWAP, RSI, etc.
 

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

Rob3

New member
VIP
Plus
What are you trying to do? I see MACD, VWAP, RSI, etc.
So I asked it to essentially come up with a buy sell signal to scalp spy and I'm backtesting it off of the last 50 years. Just going to try each one individually (I'll comment them out) and then try different pairs etc and see what it can do.
 

halcyonguy

Well-known member
VIP
Lifetime
Hello,

messing around with Chat GPT and ThinkScript and just seeing what it can do. Having an issue with this if statement on line 60 under "# Reset the trend change flag". I've only just made this, haven't backtested anything yet, just seeing what GPT can do, don't take this and think it is going to be any kind of successful.

Code:
# Define the input variables
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input emaPeriod = 9;
input rsiPeriod = 14;
input vwapLength = 20;

# Define the MACD line
def MACDLine = MACD(fastLength, slowLength, MACDLength).Diff;

# Define the MACD signal line
def SignalLine = MACD(fastLength, slowLength, MACDLength).Avg;

# Define the MACD histogram
def Histogram = MACDLine - SignalLine;

# Define the 9EMA
def EMA9 = ExpAverage(close, emaPeriod);

# Define the RSI
input rsiPeriod = 14;
def RSIValue = RSI(close, rsiPeriod);

# Define the aggregation period for VWAP
def AggregationPeriod = AggregationPeriod.DAY;
# Define the VWAP
def VWAPValue = VWAP;

# Define the CCI
input cciPeriod = 14;
def CCIValue = CCI(cciPeriod);

# Define the trend direction
def Trend = if close > EMA9 then 1 else if close < EMA9 then -1 else 0;

# Initialize the trend change flag
def TrendChanged = 0;

# Determine if the trend has changed
def TrendChanged = if Trend != Trend[1] then 1 else 0;

# Define the conditions for a buy signal
def BuySignal = MACDLine > SignalLine and Histogram > 0 and close > EMA9 and RSIValue > 50 and close > VWAPValue and CCIValue > 0;

# Define the conditions for a sell signal
def SellSignal = MACDLine < SignalLine and Histogram < 0 and close < EMA9 and RSIValue < 50 and close < VWAPValue and CCIValue < 0;

# Determine if a signal should be generated
def Signal = if BuySignal and Trend > 0 and TrendChanged == 1 then 1 else if SellSignal and Trend < 0 and TrendChanged == 1 then -1 else 0;

# Update the trend direction
def NewTrend = if Signal == 1 then 1 else if Signal == -1 then -1 else Trend;
Trend = NewTrend;

# Determine if the trend has changed
def TrendChanged = if highest(Trend, TrendPeriod) != lowest(Trend, TrendPeriod) then 1 else 0;

# Reset the trend change flag
if Trend == Trend[1] {
    TrendChanged := 0;
}


# Plot a green arrow for a buy signal and a red arrow for a sell signal
plot BuySignalArrow = if Signal == 1 then low - 5 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.GREEN);

plot SellSignalArrow = if Signal == -1 then high + 5 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.RED);

reply to 100

i got rid of the errors so you can experiment with it.
i didn't analyze the logic.


disable duplicate input
input parameters were in wrong sequence, add parameter names so can add just desired ones.
# Define the RSI
#input rsiPeriod = 14;
def RSIValue = RSI(length = rsiPeriod, price = close);


disable line
#Trend = NewTrend;


# add an input , length #
input TrendPeriod = 14;


disable lines
# Reset the trend change flag
#if Trend == Trend[1] {
# TrendChanged := 0;
#}


changed plots,
was +-5
changed to use * , so it scfales with all prices
when specifying price for a shape, don't use boolean plots. remove boolean
plot BuySignalArrow = if Signal == 1 then low*0.998 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);


there are several formulas for signal ,trend, newtrend,
that seem to be redundant...


Code:
# chat100_fix_ifthen

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

#messing around with Chat GPT and ThinkScript and just seeing what it can do. Having an issue with this if statement on line 60 under "# Reset the trend change flag". I've only just made this, haven't backtested anything yet, just seeing what GPT can do, don't take this and think it is going to be any kind of successful.


# Define the input variables
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input emaPeriod = 9;
input rsiPeriod = 14;
input vwapLength = 20;

# Define the MACD line
def MACDLine = MACD(fastLength, slowLength, MACDLength).Diff;

# Define the MACD signal line
def SignalLine = MACD(fastLength, slowLength, MACDLength).Avg;

# Define the MACD histogram
def Histogram = MACDLine - SignalLine;

# Define the 9EMA
def EMA9 = ExpAverage(close, emaPeriod);

# Define the RSI
#input rsiPeriod = 14;
#def RSIValue = RSI(close, rsiPeriod);
def RSIValue = RSI(length = rsiPeriod, price = close);

# Define the aggregation period for VWAP
def AggregationPeriod = AggregationPeriod.DAY;
# Define the VWAP
def VWAPValue = vwap;

# Define the CCI
input cciPeriod = 14;
def CCIValue = CCI(cciPeriod);

# Define the trend direction
def Trend = if close > EMA9 then 1 else if close < EMA9 then -1 else 0;

# Initialize the trend change flag
#def TrendChanged = 0;

# Determine if the trend has changed
def TrendChanged = if Trend != Trend[1] then 1 else 0;

# Define the conditions for a buy signal
def BuySignal = MACDLine > SignalLine and Histogram > 0 and close > EMA9 and RSIValue > 50 and close > VWAPValue and CCIValue > 0;

# Define the conditions for a sell signal
def SellSignal = MACDLine < SignalLine and Histogram < 0 and close < EMA9 and RSIValue < 50 and close < VWAPValue and CCIValue < 0;

# Determine if a signal should be generated
def Signal = if BuySignal and Trend > 0 and TrendChanged == 1 then 1 else if SellSignal and Trend < 0 and TrendChanged == 1 then -1 else 0;

# Update the trend direction
def NewTrend = if Signal == 1 then 1 else if Signal == -1 then -1 else Trend;

#Trend = NewTrend;

# Determine if the trend has changed
# add a length #
input TrendPeriod = 14;
def TrendChanged2 = if Highest(Trend, TrendPeriod) != Lowest(Trend, TrendPeriod) then 1 else 0;

# Reset the trend change flag
#if Trend == Trend[1] {
#    TrendChanged := 0;
#}


# Plot a green arrow for a buy signal and a red arrow for a sell signal
plot BuySignalArrow = if Signal == 1 then low*0.998 else Double.NaN;
    BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
    BuySignalArrow.SetDefaultColor(Color.GREEN);

    plot SellSignalArrow = if Signal == -1 then high*1.002 else Double.NaN;
    SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
    SellSignalArrow.SetDefaultColor(Color.RED);

#
 

Mike64

New member
I have the following script that plots the share count accumulation. How do I create an Add label to show the Share Count held in the previous year?

Can someone please help with the below syntax?

# Plots the share count held
def Year = GetYear();
def PrevioustYear = year[1];
def shares = GetQuantity();

plot sharecount = if GetYear() == lastYear then shares else Double.NaN;
shareCount.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
shareCount.AssignValueColor(if shareCount > 0 then Color.GREEN else if shareCount < 0 then Color.RED else Color.GRAY);
shareCount.HideBubble();

# Add label for previous year's count
def yearEND = if GetYear() == PreviousYear then GetYear() - 1 else GetLastYear();
def sharesYREnd =GetQuantity(); how to extract last year share count, the GetQuantity syntax gives the current share count
AddLabel(yes, "Shares Held in " + yearEND + ": " + sharesYREND, Color.CYAN);
 
Last edited:

MerryDay

Administrative
Staff member
Staff
VIP
Lifetime
I have the following script that plots the share count accumulation. How do I create an Add label to show the Share Count held in the previous year?

Can someone please help with the below syntax?

# Plots the share count held
def Year = GetYear();
def PrevioustYear = year[1];
def shares = GetQuantity();

plot sharecount = if GetYear() == lastYear then shares else Double.NaN;
shareCount.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
shareCount.AssignValueColor(if shareCount > 0 then Color.GREEN else if shareCount < 0 then Color.RED else Color.GRAY);
shareCount.HideBubble();

# Add label for previous year's count
def yearEND = if GetYear() == PreviousYear then GetYear() - 1 else GetLastYear();
def sharesYREnd =GetQuantity(); how to extract last year share count, the GetQuantity syntax gives the current share count
AddLabel(yes, "Shares Held in " + yearEND + ": " + sharesYREND, Color.CYAN);
The ToS platform does not provide the ability to access data for closed trades.
The limited trade data available is only based on current open trades.

It is not within the ToS's capabilities, to write a script to provide you with the data, you are looking for.
 
Last edited:

Scratchfury

New member
VIP
Can This Code Snippet Be Repaired?

Right up front I'll tell you that this was generated by ChatGPT. What I wanted it to do was keep a running total of positive ticks ($TICK/Q) and negative ticks for each 1 minute candle, and place those totals in a bubble, positive above (Green), and negative below (Red).

Thinkscript, in the code editor, seems to be choking on the "Format Bubbles" section at the very bottom. I've stared at and tried to discover the error but I'm throwing in the towel and asking for help. Or a clue. Or a hint. Or anything that will get me closer to implementing this Study code.

Code:
# Define variables
declare lower;

input length = 20;
input aggregationPeriod = AggregationPeriod.DAY;

# Calculate tick direction
def tickDirection = close - open;

# Calculate cumulative sum of positive and negative ticks
def sumPositiveTicks = if tickDirection > 0 then tickDirection + sumPositiveTicks[1] else tickDirection;
def sumNegativeTicks = if tickDirection < 0 then tickDirection + sumNegativeTicks[1] else tickDirection;

# Plotting the bubbles
plot bubblesAbove = sumPositiveTicks;
plot bubblesBelow = sumNegativeTicks;

# Format bubbles
bubblesAbove.SetDefaultColor(Color.GREEN);
bubblesAbove.SetPaintingStrategy(PaintingStrategy.BUBBLES);
bubblesAbove.SetLineWeight(1);
bubblesAbove.SetStyle(Curve.FIRM);

bubblesBelow.SetDefaultColor(Color.RED);
bubblesBelow.SetPaintingStrategy(PaintingStrategy.BUBBLES);
bubblesBelow.SetLineWeight(1);
bubblesBelow.SetStyle(Curve.FIRM);
 

halcyonguy

Well-known member
VIP
Lifetime
Can This Code Snippet Be Repaired?

Right up front I'll tell you that this was generated by ChatGPT. What I wanted it to do was keep a running total of positive ticks ($TICK/Q) and negative ticks for each 1 minute candle, and place those totals in a bubble, positive above (Green), and negative below (Red).

Thinkscript, in the code editor, seems to be choking on the "Format Bubbles" section at the very bottom. I've stared at and tried to discover the error but I'm throwing in the towel and asking for help. Or a clue. Or a hint. Or anything that will get me closer to implementing this Study code.

Code:
# Define variables
declare lower;

input length = 20;
input aggregationPeriod = AggregationPeriod.DAY;

# Calculate tick direction
def tickDirection = close - open;

# Calculate cumulative sum of positive and negative ticks
def sumPositiveTicks = if tickDirection > 0 then tickDirection + sumPositiveTicks[1] else tickDirection;
def sumNegativeTicks = if tickDirection < 0 then tickDirection + sumNegativeTicks[1] else tickDirection;

# Plotting the bubbles
plot bubblesAbove = sumPositiveTicks;
plot bubblesBelow = sumNegativeTicks;

# Format bubbles
bubblesAbove.SetDefaultColor(Color.GREEN);
bubblesAbove.SetPaintingStrategy(PaintingStrategy.BUBBLES);
bubblesAbove.SetLineWeight(1);
bubblesAbove.SetStyle(Curve.FIRM);

bubblesBelow.SetDefaultColor(Color.RED);
bubblesBelow.SetPaintingStrategy(PaintingStrategy.BUBBLES);
bubblesBelow.SetLineWeight(1);
bubblesBelow.SetStyle(Curve.FIRM);

there is no bubble paintingstrategy.
try values above
https://tlc.thinkorswim.com/center/reference/thinkScript/Constants/PaintingStrategy


otherwise, read up on addchartbubble()
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddChartBubble
 

iprph90

New member
Hello,
I'm wondering if someone can help with a swing trade code that I asked chatgpt to write for QQQ. Gave "Invalid Statement" on line (*) 36, 37 under # define plot colors when i tried to create code in ToS


# QQQ Swing Trading Strategy on Daily Time Frame

# Define Inputs
input atrLength = 14; # Length of ATR
input profitTarget = 2.0; # Profit target in ATR multiples
input stopLoss = 1.0; # Stop loss in ATR multiples

# Define ATR
def atr = AvgTrueRange(high, close, low, atrLength);

# Define Buy and Sell Signals
def buySignal = close > Highest(close[1], 50) and close > Highest(close[2], 50) and close > Highest(close[3], 50);
def sellSignal = close < Lowest(close[1], 50) and close < Lowest(close[2], 50) and close < Lowest(close[3], 50);

# Define Long Entry and Exit Signals
def longEntrySignal = buySignal;
def longExitSignal = close >= (entryPrice + (profitTarget * atr)) or close <= (entryPrice - (stopLoss * atr));

# Define Short Entry and Exit Signals
def shortEntrySignal = sellSignal;
def shortExitSignal = close <= (entryPrice - (profitTarget * atr)) or close >= (entryPrice + (stopLoss * atr));

# Define Entry Price and Position
def entryPrice = if longEntrySignal then close else if shortEntrySignal then close else Double.NaN;
def inPosition = if !isNaN(entryPrice) then 1 else if !inPosition[1] and (longExitSignal or shortExitSignal) then 0 else if inPosition[1] then 1 else 0;

# Define Stop Loss and Profit Target Prices
def stopLossPrice = if inPosition then entryPrice - (stopLoss * atr * Sign(entryPrice - entryPrice[1])) else Double.NaN;
def profitTargetPrice = if inPosition then entryPrice + (profitTarget * atr * Sign(entryPrice - entryPrice[1])) else Double.NaN;

# Define Plot Colors
def bullishColor = Color.GREEN;
def bearishColor = Color.RED;
def neutralColor = Color.GRAY;
*def entryColor = inPosition ? (if inPosition[1] then neutralColor else if longEntrySignal then bullishColor else bearishColor) : neutralColor;
*def exitColor = inPosition ? (if longExitSignal or shortExitSignal then bearishColor else neutralColor) : neutralColor;

# Plot Signals, Entry Price, Stop Loss, and Profit Target
plot BuySignal = buySignal;
BuySignal.AssignValueColor(entryColor);
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
plot SellSignal = sellSignal;
SellSignal.AssignValueColor(entryColor);
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
plot EntryPrice = entryPrice;
EntryPrice.AssignValueColor(entryColor);
EntryPrice.SetPaintingStrategy(PaintingStrategy.POINT);
plot StopLossPrice = stopLossPrice;
StopLossPrice.SetDefaultColor(Color.MAGENTA);
StopLossPrice.SetPaintingStrategy(PaintingStrategy.LINE);
plot ProfitTargetPrice = profitTargetPrice;
ProfitTargetPrice.SetDefaultColor(Color.CYAN);
ProfitTargetPrice.SetPaintingStrategy(PaintingStrategy.LINE);
 

TradeUp

Member
2019 Donor
Here is the link to the indicator from TradingView:
https://www.tradingview.com/script/HfAuYuG6-Strat-Trail-Stop-by-AlexsOptions/


Here is THINKSCRIPT CONVERTED BY CHATGPT: HAS 2 INVALID STATEMENTS:
Invalid statement: def at 18:1
Invalid statement: } at 20:1
Can someone please help fix these two invalid statements? @halcyonguy @samer800


CODE:
declare lower;

input timeframe = AggregationPeriod.DAY;
input timeframe2 = AggregationPeriod.WEEK;
input use_HTF_open = no;

def htf_open;
def htf1;
def htf2;
def htf3;

def trail1 = Double.NaN;
def trail_color;

def trail2 = Double.NaN;
def trail_color2;

def request_htf_candle(instrument, timeFrame, bar) {
instrument[bar];
}

def pdo1 = request_htf_candle(open, timeframe, 1);
def pdh1 = request_htf_candle(high, timeframe, 1);
def pdl1 = request_htf_candle(low, timeframe, 1);
def pdc1 = request_htf_candle(close, timeframe, 1);
def pdo2 = request_htf_candle(open, timeframe, 2);
def pdh2 = request_htf_candle(high, timeframe, 2);
def pdl2 = request_htf_candle(low, timeframe, 2);
def pdc2 = request_htf_candle(close, timeframe, 2);

if pdh1 > pdh2 and pdl1 > pdl2 {
trail1 = pdl1;
} else if pdh2 > pdh1 and pdl1 < pdl2 {
trail1 = pdh1;
} else {
trail1 = trail1[1];
}

trail_color = if close > trail1 then Color.GREEN
else if close < trail1 then Color.RED
else Color.GRAY;

plot TrailingStop1 = trail1;
TrailingStop1.SetDefaultColor(trail_color);
TrailingStop1.SetLineWeight(2);

def pwo1 = request_htf_candle(open, timeframe2, 1);
def pwh1 = request_htf_candle(high, timeframe2, 1);
def pwl1 = request_htf_candle(low, timeframe2, 1);
def pwc1 = request_htf_candle(close, timeframe2, 1);
def pwo2 = request_htf_candle(open, timeframe2, 2);
def pwh2 = request_htf_candle(high, timeframe2, 2);
def pwl2 = request_htf_candle(low, timeframe2, 2);
def pwc2 = request_htf_candle(close, timeframe2, 2);

if use_HTF_open {
trail2 = htf_open;
} else if pwh1 > pwh2 and pwl1 > pwl2 {
trail2 = pwl1;
} else if pwh2 > pwh1 and pwl1 < pwl2 {
trail2 = pwh1;
} else {
trail2 = trail2[1];
}

trail_color2 = if close > trail2 then Color.GREEN
else if close < trail2 then Color.RED
else Color.GRAY;

plot TrailingStop2 = trail2;
TrailingStop2.SetDefaultColor(trail_color2);
TrailingStop2.SetLineWeight(2);

def long_signal = trail_color2 == Color.GREEN and trail_color == Color.GREEN and GetValue(trail_color, 1) != Color.GREEN;
def short_signal = trail_color2 == Color.RED and trail_color == Color.RED and GetValue(trail_color, 1) != Color.RED;

AddChartBubble(long_signal, high, "Long", Color.GREEN);
AddChartBubble(short_signal, low, "Short", Color.RED);
 

halcyonguy

Well-known member
VIP
Lifetime
Here is the link to the indicator from TradingView:
https://www.tradingview.com/script/HfAuYuG6-Strat-Trail-Stop-by-AlexsOptions/


Here is THINKSCRIPT CONVERTED BY CHATGPT: HAS 2 INVALID STATEMENTS:
Invalid statement: def at 18:1
Invalid statement: } at 20:1
Can someone please help fix these two invalid statements? @halcyonguy @samer800


CODE:
declare lower;

input timeframe = AggregationPeriod.DAY;
input timeframe2 = AggregationPeriod.WEEK;
input use_HTF_open = no;

def htf_open;
def htf1;
def htf2;
def htf3;

def trail1 = Double.NaN;
def trail_color;

def trail2 = Double.NaN;
def trail_color2;

def request_htf_candle(instrument, timeFrame, bar) {
instrument[bar];
}

def pdo1 = request_htf_candle(open, timeframe, 1);
def pdh1 = request_htf_candle(high, timeframe, 1);
def pdl1 = request_htf_candle(low, timeframe, 1);
def pdc1 = request_htf_candle(close, timeframe, 1);
def pdo2 = request_htf_candle(open, timeframe, 2);
def pdh2 = request_htf_candle(high, timeframe, 2);
def pdl2 = request_htf_candle(low, timeframe, 2);
def pdc2 = request_htf_candle(close, timeframe, 2);

if pdh1 > pdh2 and pdl1 > pdl2 {
trail1 = pdl1;
} else if pdh2 > pdh1 and pdl1 < pdl2 {
trail1 = pdh1;
} else {
trail1 = trail1[1];
}

trail_color = if close > trail1 then Color.GREEN
else if close < trail1 then Color.RED
else Color.GRAY;

plot TrailingStop1 = trail1;
TrailingStop1.SetDefaultColor(trail_color);
TrailingStop1.SetLineWeight(2);

def pwo1 = request_htf_candle(open, timeframe2, 1);
def pwh1 = request_htf_candle(high, timeframe2, 1);
def pwl1 = request_htf_candle(low, timeframe2, 1);
def pwc1 = request_htf_candle(close, timeframe2, 1);
def pwo2 = request_htf_candle(open, timeframe2, 2);
def pwh2 = request_htf_candle(high, timeframe2, 2);
def pwl2 = request_htf_candle(low, timeframe2, 2);
def pwc2 = request_htf_candle(close, timeframe2, 2);

if use_HTF_open {
trail2 = htf_open;
} else if pwh1 > pwh2 and pwl1 > pwl2 {
trail2 = pwl1;
} else if pwh2 > pwh1 and pwl1 < pwl2 {
trail2 = pwh1;
} else {
trail2 = trail2[1];
}

trail_color2 = if close > trail2 then Color.GREEN
else if close < trail2 then Color.RED
else Color.GRAY;

plot TrailingStop2 = trail2;
TrailingStop2.SetDefaultColor(trail_color2);
TrailingStop2.SetLineWeight(2);

def long_signal = trail_color2 == Color.GREEN and trail_color == Color.GREEN and GetValue(trail_color, 1) != Color.GREEN;
def short_signal = trail_color2 == Color.RED and trail_color == Color.RED and GetValue(trail_color, 1) != Color.RED;

AddChartBubble(long_signal, high, "Long", Color.GREEN);
AddChartBubble(short_signal, low, "Short", Color.RED);

reply to 108
thinkscript is misleading when it comes to errors. it doesn't highlight all the wrong lines, just a couple. if these errors are fixed, then a few more will be highlighted, then a few more,....
almost every line is wrong. it would be easier to convert this from the original pine code.
 

halcyonguy

Well-known member
VIP
Lifetime
Hello,
I'm wondering if someone can help with a swing trade code that I asked chatgpt to write for QQQ. Gave "Invalid Statement" on line (*) 36, 37 under # define plot colors when i tried to create code in ToS


# QQQ Swing Trading Strategy on Daily Time Frame

# Define Inputs
input atrLength = 14; # Length of ATR
input profitTarget = 2.0; # Profit target in ATR multiples
input stopLoss = 1.0; # Stop loss in ATR multiples

# Define ATR
def atr = AvgTrueRange(high, close, low, atrLength);

# Define Buy and Sell Signals
def buySignal = close > Highest(close[1], 50) and close > Highest(close[2], 50) and close > Highest(close[3], 50);
def sellSignal = close < Lowest(close[1], 50) and close < Lowest(close[2], 50) and close < Lowest(close[3], 50);

# Define Long Entry and Exit Signals
def longEntrySignal = buySignal;
def longExitSignal = close >= (entryPrice + (profitTarget * atr)) or close <= (entryPrice - (stopLoss * atr));

# Define Short Entry and Exit Signals
def shortEntrySignal = sellSignal;
def shortExitSignal = close <= (entryPrice - (profitTarget * atr)) or close >= (entryPrice + (stopLoss * atr));

# Define Entry Price and Position
def entryPrice = if longEntrySignal then close else if shortEntrySignal then close else Double.NaN;
def inPosition = if !isNaN(entryPrice) then 1 else if !inPosition[1] and (longExitSignal or shortExitSignal) then 0 else if inPosition[1] then 1 else 0;

# Define Stop Loss and Profit Target Prices
def stopLossPrice = if inPosition then entryPrice - (stopLoss * atr * Sign(entryPrice - entryPrice[1])) else Double.NaN;
def profitTargetPrice = if inPosition then entryPrice + (profitTarget * atr * Sign(entryPrice - entryPrice[1])) else Double.NaN;

# Define Plot Colors
def bullishColor = Color.GREEN;
def bearishColor = Color.RED;
def neutralColor = Color.GRAY;
*def entryColor = inPosition ? (if inPosition[1] then neutralColor else if longEntrySignal then bullishColor else bearishColor) : neutralColor;
*def exitColor = inPosition ? (if longExitSignal or shortExitSignal then bearishColor else neutralColor) : neutralColor;

# Plot Signals, Entry Price, Stop Loss, and Profit Target
plot BuySignal = buySignal;
BuySignal.AssignValueColor(entryColor);
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
plot SellSignal = sellSignal;
SellSignal.AssignValueColor(entryColor);
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
plot EntryPrice = entryPrice;
EntryPrice.AssignValueColor(entryColor);
EntryPrice.SetPaintingStrategy(PaintingStrategy.POINT);
plot StopLossPrice = stopLossPrice;
StopLossPrice.SetDefaultColor(Color.MAGENTA);
StopLossPrice.SetPaintingStrategy(PaintingStrategy.LINE);
plot ProfitTargetPrice = profitTargetPrice;
ProfitTargetPrice.SetDefaultColor(Color.CYAN);
ProfitTargetPrice.SetPaintingStrategy(PaintingStrategy.LINE);

different study, same story ....
there are many errors, it just doesn't list them all at first.

..can't set a color to a variable
..using entryprice, but not defining it beforehand.
entryprice could imply configuring this as a strategy, which will need several more code lines
..AvgTrueRange() doesn't exist, it is atr() , with different inputs
 

mdpinch

New member
Supertend scanner

I want to create stocks scanner for the stocks which are above the supertrend in daily as well as hourly time frame. I dont have background or knowledge so i tried chatgpt which give me this one but it is not working . Can some one help correcting or writing it , Please

# SuperTrend indicator for daily time frame
declare lower;
input supertrendLength = 10;
input supertrendMultiplier = 3;

def dailyClose = close(period = AggregationPeriod.DAY);
def dailyATR = Average(TrueRange(high(period = AggregationPeriod.DAY), low(period = AggregationPeriod.DAY), dailyClose), supertrendLength);
def dailyUpperBand = dailyClose + (dailyATR * supertrendMultiplier);
def dailyLowerBand = dailyClose - (dailyATR * supertrendMultiplier);
def dailySuperTrend = if close > dailySuperTrend[1] then Max(dailyUpperBand, dailySuperTrend[1]) else Min(dailyLowerBand, dailySuperTrend[1]);

# SuperTrend indicator for hourly time frame
input hourlySupertrendLength = 10;
input hourlySupertrendMultiplier = 3;

def hourlyClose = close(period = AggregationPeriod.HOUR);
def hourlyATR = Average(TrueRange(high(period = AggregationPeriod.HOUR), low(period = AggregationPeriod.HOUR), hourlyClose), hourlySupertrendLength);
def hourlyUpperBand = hourlyClose + (hourlyATR * hourlySupertrendMultiplier);
def hourlyLowerBand = hourlyClose - (hourlyATR * hourlySupertrendMultiplier);
def hourlySuperTrend = if close > hourlySuperTrend[1] then Max(hourlyUpperBand, hourlySuperTrend[1]) else Min(hourlyLowerBand, hourlySuperTrend[1]);

# Check if stock is above SuperTrend in both time frames
def aboveDailySuperTrend = close > dailySuperTrend;
def aboveHourlySuperTrend = close > hourlySuperTrend;

# Plotting
plot DailySuperTrend = dailySuperTrend;
plot HourlySuperTrend = hourlySuperTrend;
plotshape(aboveDailySuperTrend, "Above Daily SuperTrend", shape.triangleup, location.belowbar, color.green, size.small);
plotshape(aboveHourlySuperTrend, "Above Hourly SuperTrend", shape.triangleup, location.abovebar, color.green, size.small);
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
245 Online
Create Post

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.
Top