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

#### MerryDay

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

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

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

The above video, explains the basics of providing good specifications to AI which results in better scripts.

Last edited:
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;

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.

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.

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;

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

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;

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

Code:
``````# chat100_fix_ifthen

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

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

#``````

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?

# 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:
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?

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

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

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

Here is THINKSCRIPT CONVERTED BY CHATGPT: HAS 2 INVALID STATEMENTS:
Invalid statement: def at 18:1
Invalid statement: } at 20:1

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;

Here is THINKSCRIPT CONVERTED BY CHATGPT: HAS 2 INVALID STATEMENTS:
Invalid statement: def at 18:1
Invalid statement: } at 20:1

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;

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.

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

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

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

i don't scan, so someone else can verify this........

i think you will have to create 2 studies, one for day , 1 for hour.
then in the scanner, reference both of those studies.

# VWAP Bands Strategy with RSI Filter
# Buy when price crosses below VWAP LowerBand and RSI is below 30
# Sell when price crosses above VWAP UpperBand and RSI is above 70

input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default DAY, WEEK, MONTH};

def cap = GetAggregationPeriod();
def errorInAggregation =
timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
Assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");

def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
case DAY:
periodIndx = yyyyMmDd;
case WEEK:
periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
case MONTH:
periodIndx = RoundDown(yyyyMmDd / 100, 0);
}
def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
volumeSum = volume;
volumeVwapSum = volume * vwap;
volumeVwap2Sum = volume * Sqr(vwap);
} else {
volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
volumeVwapSum = CompoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
volumeVwap2Sum = CompoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def price = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(price), 0));

plot VWAP = price;
plot UpperBand = price + numDevUp * deviation;
plot LowerBand = price + numDevDn * deviation;

VWAP.SetDefaultColor(GetColor(0));
UpperBand.SetDefaultColor(GetColor(2));
LowerBand.SetDefaultColor(GetColor(4));

# RSI Calculation
def length = 14;
def NetChgAvg = MovingAverage(AverageType.EXPONENTIAL, close - close[1], length);
def TotChgAvg = MovingAverage(AverageType.EXPONENTIAL, AbsValue(close - close[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = Round(50 * (ChgRatio + 1), 0);

# Strategy
def buySignal = close crosses below LowerBand and RSI < 30;
def sellSignal = close crosses above UpperBand and RSI > 70;

# Plotting Buy and Sell signals on chart
plot SellSignal = if SellSignal then high else Double.NaN;

SellSignal.SetDefaultColor (Color.RED);

i aske chatgpt to creat fairvaluegap indicator i gave him 2 script from this website i dont do what it did i think he combined both of them

Code:
``````# First Fair Value Gap Indicator
input marketOpenTime = 0930;
input marketCloseTime = 1615;
input ATRLength = 28;
input ATRMultiplier = 1.5;

def secondsFromOpen = SecondsFromTime(marketOpenTime);
def secondsTillClose = SecondsTillTime(marketCloseTime);
def marketOpen = if secondsFromOpen >= 0 and secondsTillClose >= 0 then 1 else 0;
def newDay = if GetDay() != GetDay()[1] then 1 else 0;

def FVGbearCondition = close[3] <= high[2] and close[1] <= close[2] and high < low[2];
def FVGbullCondition = close[3] >= low[2] and close[1] >= close[2] and low > high[2];

def priceDiff = high[1] - low[1];
def ATRValue = Average(TrueRange(high, close, low), ATRLength);
def middleCandleVolatilityCondition = priceDiff > ATRValue * ATRMultiplier;

def isUpCandle = close > open;
def isGapClosed = if isUpCandle then high[2] >= low else low[2] <= high;
def isFairValueGap = (FVGbearCondition or FVGbullCondition) and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];

def gapUp = FVGbullCondition and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];
def GUhigh = if gapUp then low else GUhigh[1];
def GUlow = if gapUp then high[2] else GUlow[1];
def gapDown = FVGbearCondition and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];
def GDhigh = if gapDown then high else GDhigh[1];
def GDlow = if gapDown then low[2] else GDlow[1];
def hg = (if gapUp then high[2] + (GUhigh - GUlow) else if gapDown then high[2] + (GDlow - GDhigh) else 0) / 2;
def gapRemaining = if gapUp then GUhigh - GUlow else if gapDown then GDlow - GDhigh else 0;
def percentRemaining = 100 * gapRemaining / if gapUp then AbsValue(GUhigh - GUlow) else if gapDown then AbsValue(GDlow - GDhigh) else 0;
def gapFilled = if percentRemaining == 0 then 1 else 0;
def halfGapFilled = if percentRemaining <= 50 then 1 else 0;

# Second Fair Value Gap Indicator
input threshold = 0.001;
input aggregation = AggregationPeriod.FIFTEEN_MIN;

def fvgBear = if low(period = aggregation)[2] - high(period = aggregation) > 0 then 1 else 0;
def fvgBearPctg = if AbsValue((high(period = aggregation) - low(period = aggregation)[2]) / low(period = aggregation)[2]) > threshold then 1 else 0;

def fvgBull = if low(period = aggregation) - high(period = aggregation)[2] > 0 then 1 else 0;
def fvgBullPctg = if AbsValue((low(period = aggregation) - high(period = aggregation)[2]) / high(period = aggregation)[2]) > threshold then 1 else 0;

def fvgBearH = if fvgBear and fvgBearPctg then low(period = aggregation)[2] else 0;
def fvgBearL = if fvgBearH then high(period = aggregation) else Double.NaN;

def fvgBullH = if fvgBull and fvgBearPctg then low(period = aggregation) else 0;
def fvgBullL = if fvgBullH then high(period = aggregation)[2] else Double.NaN;

def fvgBearMem1 = if fvgBearH then fvgBearH else if high(period = aggregation) > fvgBearMem1[1] then Double.NaN else fvgBearMem1[1];
def fvgBearMem2 = if fvgBearH then fvgBearL else if high(period = aggregation) > fvgBearMem2[1] then Double.NaN else fvgBearMem2[1];

def fvgBullMem1 = if fvgBullH then fvgBullH else if low(period = aggregation) < fvgBullMem1[1] then Double.NaN else fvgBullMem1[1];
def fvgBullMem2 = if fvgBullH then fvgBullL else if low(period = aggregation) < fvgBullMem2[1] then Double.NaN else fvgBullMem2[1];

plot fvgBearM1 = fvgBearMem1;
plot fvgBearM2 = fvgBearMem2;

plot fvgBullM1 = fvgBullMem1;
plot fvgBullM2 = fvgBullMem2;

fvgBearM1.SetLineWeight(3);
fvgBearM2.SetLineWeight(3);
fvgBearM1.SetDefaultColor(Color.MAGENTA);
fvgBearM2.SetDefaultColor(Color.MAGENTA);
fvgBearM1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
fvgBearM2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

fvgBullM1.SetLineWeight(3);
fvgBullM2.SetLineWeight(3);
fvgBullM1.SetDefaultColor(Color.YELLOW);
fvgBullM2.SetDefaultColor(Color.YELLOW);
fvgBullM1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
fvgBullM2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Combine Signals
def combinedSignal = isFairValueGap and (fvgBearH or fvgBullH);

# Plot Combined Signal
plot signal = combinedSignal;
signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signal.SetDefaultColor(Color.GREEN);``````

I ask CHATGPT to convert this futu indicator to thinkorswim indicator ,it finished most but at last part ,it can't do .

Code:
``````# Define variables
def A1 = Inertia(ExpAverage(close, 5), 6);
def A2 = Inertia(ExpAverage(close, 8), 6);
def A3 = Inertia(ExpAverage(close, 11), 6);
def A4 = Inertia(ExpAverage(close, 14), 6);
def A5 = Inertia(ExpAverage(close, 17), 6);
def B = A1 + A2 + A3 + A4 - 4 * A5;
def TOWERC = ExpAverage(B, 2);

# Plotting
plot Forecast1 = Inertia(ExpAverage(B, 3), 6);
Forecast1.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast1.SetDefaultColor(Color.GREEN);

plot Forecast2 = Inertia(ExpAverage(B, 4), 6);
Forecast2.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast2.SetDefaultColor(Color.GREEN);

plot Forecast3 = Inertia(ExpAverage(B, 5), 6);
Forecast3.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast3.SetDefaultColor(Color.GREEN);

plot Forecast4 = Inertia(ExpAverage(B, 6), 6);
Forecast4.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast4.SetDefaultColor(Color.GREEN);

plot Forecast5 = Inertia(ExpAverage(B, 7), 6);
Forecast5.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast5.SetDefaultColor(Color.GREEN);

plot Forecast6 = Inertia(ExpAverage(B, 8), 6);
Forecast6.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast6.SetDefaultColor(Color.GREEN);

plot Forecast7 = Inertia(ExpAverage(B, 9), 6);
Forecast7.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast7.SetDefaultColor(Color.GREEN);

plot Forecast8 = Inertia(ExpAverage(B, 10), 6);
Forecast8.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast8.SetDefaultColor(Color.GREEN);

plot Forecast9 = Inertia(ExpAverage(B, 11), 6);
Forecast9.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast9.SetDefaultColor(Color.GREEN);

plot Forecast10 = Inertia(ExpAverage(B, 12), 6);
Forecast10.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast10.SetDefaultColor(Color.GREEN);

plot Forecast11 = Inertia(ExpAverage(B, 13), 6);
Forecast11.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast11.SetDefaultColor(Color.GREEN);

plot Forecast12 = Inertia(ExpAverage(B, 14), 6);
Forecast12.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast12.SetDefaultColor(Color.GREEN);

plot Forecast13 = Inertia(ExpAverage(B, 15), 6);
Forecast13.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast13.SetDefaultColor(Color.GREEN);

plot Forecast14 = Inertia(ExpAverage(B, 16), 6);
Forecast14.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast14.SetDefaultColor(Color.GREEN);

plot Forecast15 = Inertia(ExpAverage(B, 17), 6);
Forecast15.SetPaintingStrategy(PaintingStrategy.POINTS);
Forecast15.SetDefaultColor(Color.GREEN);

# Draw sticks
def StickLineUp = if TOWERC >= TOWERC[1] then TOWERC else Double.NaN;
plot StickLine = StickLineUp;
StickLine.SetPaintingStrategy(PaintingStrategy.STICKS);
StickLine``````

this part not working:
# Draw sticks
def StickLineUp = if TOWERC >= TOWERC[1] then TOWERC else Double.NaN;
plot StickLine = StickLineUp;
StickLine.SetPaintingStrategy(PaintingStrategy.STICKS);
StickLine

# VWAP Bands Strategy with RSI Filter
# Buy when price crosses below VWAP LowerBand and RSI is below 30
# Sell when price crosses above VWAP UpperBand and RSI is above 70

input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default DAY, WEEK, MONTH};

def cap = GetAggregationPeriod();
def errorInAggregation =
timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
Assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");

def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
case DAY:
periodIndx = yyyyMmDd;
case WEEK:
periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
case MONTH:
periodIndx = RoundDown(yyyyMmDd / 100, 0);
}
def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
volumeSum = volume;
volumeVwapSum = volume * vwap;
volumeVwap2Sum = volume * Sqr(vwap);
} else {
volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
volumeVwapSum = CompoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
volumeVwap2Sum = CompoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def price = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(price), 0));

plot VWAP = price;
plot UpperBand = price + numDevUp * deviation;
plot LowerBand = price + numDevDn * deviation;

VWAP.SetDefaultColor(GetColor(0));
UpperBand.SetDefaultColor(GetColor(2));
LowerBand.SetDefaultColor(GetColor(4));

# RSI Calculation
def length = 14;
def NetChgAvg = MovingAverage(AverageType.EXPONENTIAL, close - close[1], length);
def TotChgAvg = MovingAverage(AverageType.EXPONENTIAL, AbsValue(close - close[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = Round(50 * (ChgRatio + 1), 0);

# Strategy
def buySignal = close crosses below LowerBand and RSI < 30;
def sellSignal = close crosses above UpperBand and RSI > 70;

# Plotting Buy and Sell signals on chart
plot SellSignal = if SellSignal then high else Double.NaN;

SellSignal.SetDefaultColor (Color.RED);

when posting, include a question. tell us about the code.
you just posted some code, so we have no idea what you want.
does it work and you want it modified? does it not work?
where did the code come from?

i aske chatgpt to creat fairvaluegap indicator i gave him 2 script from this website i dont do what it did i think he combined both of them

Code:
``````# First Fair Value Gap Indicator
input marketOpenTime = 0930;
input marketCloseTime = 1615;
input ATRLength = 28;
input ATRMultiplier = 1.5;

def secondsFromOpen = SecondsFromTime(marketOpenTime);
def secondsTillClose = SecondsTillTime(marketCloseTime);
def marketOpen = if secondsFromOpen >= 0 and secondsTillClose >= 0 then 1 else 0;
def newDay = if GetDay() != GetDay()[1] then 1 else 0;

def FVGbearCondition = close[3] <= high[2] and close[1] <= close[2] and high < low[2];
def FVGbullCondition = close[3] >= low[2] and close[1] >= close[2] and low > high[2];

def priceDiff = high[1] - low[1];
def ATRValue = Average(TrueRange(high, close, low), ATRLength);
def middleCandleVolatilityCondition = priceDiff > ATRValue * ATRMultiplier;

def isUpCandle = close > open;
def isGapClosed = if isUpCandle then high[2] >= low else low[2] <= high;
def isFairValueGap = (FVGbearCondition or FVGbullCondition) and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];

def gapUp = FVGbullCondition and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];
def GUhigh = if gapUp then low else GUhigh[1];
def GUlow = if gapUp then high[2] else GUlow[1];
def gapDown = FVGbearCondition and !isGapClosed and middleCandleVolatilityCondition and !isFairValueGap[1];
def GDhigh = if gapDown then high else GDhigh[1];
def GDlow = if gapDown then low[2] else GDlow[1];
def hg = (if gapUp then high[2] + (GUhigh - GUlow) else if gapDown then high[2] + (GDlow - GDhigh) else 0) / 2;
def gapRemaining = if gapUp then GUhigh - GUlow else if gapDown then GDlow - GDhigh else 0;
def percentRemaining = 100 * gapRemaining / if gapUp then AbsValue(GUhigh - GUlow) else if gapDown then AbsValue(GDlow - GDhigh) else 0;
def gapFilled = if percentRemaining == 0 then 1 else 0;
def halfGapFilled = if percentRemaining <= 50 then 1 else 0;

# Second Fair Value Gap Indicator
input threshold = 0.001;
input aggregation = AggregationPeriod.FIFTEEN_MIN;

def fvgBear = if low(period = aggregation)[2] - high(period = aggregation) > 0 then 1 else 0;
def fvgBearPctg = if AbsValue((high(period = aggregation) - low(period = aggregation)[2]) / low(period = aggregation)[2]) > threshold then 1 else 0;

def fvgBull = if low(period = aggregation) - high(period = aggregation)[2] > 0 then 1 else 0;
def fvgBullPctg = if AbsValue((low(period = aggregation) - high(period = aggregation)[2]) / high(period = aggregation)[2]) > threshold then 1 else 0;

def fvgBearH = if fvgBear and fvgBearPctg then low(period = aggregation)[2] else 0;
def fvgBearL = if fvgBearH then high(period = aggregation) else Double.NaN;

def fvgBullH = if fvgBull and fvgBearPctg then low(period = aggregation) else 0;
def fvgBullL = if fvgBullH then high(period = aggregation)[2] else Double.NaN;

def fvgBearMem1 = if fvgBearH then fvgBearH else if high(period = aggregation) > fvgBearMem1[1] then Double.NaN else fvgBearMem1[1];
def fvgBearMem2 = if fvgBearH then fvgBearL else if high(period = aggregation) > fvgBearMem2[1] then Double.NaN else fvgBearMem2[1];

def fvgBullMem1 = if fvgBullH then fvgBullH else if low(period = aggregation) < fvgBullMem1[1] then Double.NaN else fvgBullMem1[1];
def fvgBullMem2 = if fvgBullH then fvgBullL else if low(period = aggregation) < fvgBullMem2[1] then Double.NaN else fvgBullMem2[1];

plot fvgBearM1 = fvgBearMem1;
plot fvgBearM2 = fvgBearMem2;

plot fvgBullM1 = fvgBullMem1;
plot fvgBullM2 = fvgBullMem2;

fvgBearM1.SetLineWeight(3);
fvgBearM2.SetLineWeight(3);
fvgBearM1.SetDefaultColor(Color.MAGENTA);
fvgBearM2.SetDefaultColor(Color.MAGENTA);
fvgBearM1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
fvgBearM2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

fvgBullM1.SetLineWeight(3);
fvgBullM2.SetLineWeight(3);
fvgBullM1.SetDefaultColor(Color.YELLOW);
fvgBullM2.SetDefaultColor(Color.YELLOW);
fvgBullM1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
fvgBullM2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Combine Signals
def combinedSignal = isFairValueGap and (fvgBearH or fvgBullH);

# Plot Combined Signal
plot signal = combinedSignal;
signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signal.SetDefaultColor(Color.GREEN);``````

fairvaluegap is a made up word. it has no meaning. if you want a study to do something try listing out the rules that it should follow.
when close crosses this signal, do this.
if close is > 2 signals do this....

what is wrong with the code you posted?
what do you think needs to be changed?

i don't know what fairvaluegap is and i'm not going to go searching for definitions of it and guess i found the correct one. that is the job of the poster, you, to provide all the info you can, so that a stranger, not familiar with your request, can help.

you didn't tell us what 2 studies you looked at. what was wrong with them? why not use them?

you can get a link to a post, by clicking on the post number, then copy the web address.

To ChatGPT: create a thinkorswim script that indicates buy and/or sell signals using price action candlestick reversal patterns at key levels or demand and supply zone areas

I'm receiving an error message for this line: def keyLevel = referencePoints(keyLevelPercent);
"No such function: referencePoints at 8:16"
can anyone resolve this? Thanks in advance!

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

# Candlestick Reversal Patterns with Key Levels/Supply-Demand Zones
# Buy Signal: Reversal pattern bullish candlestick at key support or demand zone
# Sell Signal: Reversal pattern bearish candlestick at key resistance or supply zone

input keyLevelPercent = 1.0; # Percentage deviation from key levels/zones
input reversalPattern = {default "Bullish Engulfing", "Bearish Engulfing", "Hammer", "Shooting Star"};

def keyLevel = referencePoints(keyLevelPercent);
def pattern;

switch (reversalPattern) {
case "Bullish Engulfing":
pattern = Engulfing().Bullish;
case "Bearish Engulfing":
pattern = Engulfing().Bearish;
case "Hammer":
pattern = Hammer();
case "Shooting Star":
pattern = ShootingStar();
}

def bullishSignal = pattern and low <= keyLevel;
def bearishSignal = pattern and high >= keyLevel;

plot SellSignal = bearishSignal;

SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(Color.RED);

87k+ Posts
331 Online

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 1 full year of unlimited support

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?