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

MerryDay

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

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

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

The above video, explains the basics of providing good specifications to AI which results in better scripts.
AOzhl05.png
 
Last edited:
I have looking an auto fib that will plot on each new range candle . I look at a lot of auto fibs on this forum but i dont know if any of them will do this.
bSHIQnZ.png
I got ChatGPT to make this one but I cant get it to remove the past Fibonacci levels or the current bar being formed any ideas on how to get it to plot only the last bar closed?

Ruby:
# Define global colors for customization
DefineGlobalColor("Color100", CreateColor(255, 0, 0)); # RED
DefineGlobalColor("Color75", CreateColor(153, 153, 153)); # Blue
DefineGlobalColor("Color66", CreateColor(0, 153, 51)); # Cyan
DefineGlobalColor("Color50", CreateColor(255, 0, 255)); # Magenta
DefineGlobalColor("Color33", CreateColor(0, 153, 51)); # Yellow
DefineGlobalColor("Color25", CreateColor(153, 153, 153)); # Orange
DefineGlobalColor("Color0", CreateColor(255, 0, 0)); # Red

# Inputs for customization
input style100 = Curve.FIRM;
input style75 = Curve.FIRM;
input style66 = Curve.FIRM;
input style50 = Curve.FIRM;
input style33 = Curve.FIRM;
input style25 = Curve.FIRM;
input style0 = Curve.FIRM;

# Define high, low, and close of the last closed range candle
def lastClosedBar = if !IsNaN(close[1]) then BarNumber() else lastClosedBar[1];
def isLastClosedCandle = BarNumber() == lastClosedBar;

# Calculate high, low, and range of the last closed range candle
def rangeHigh = if isLastClosedCandle then high[1] else Double.NaN;
def rangeLow = if isLastClosedCandle then low[1] else Double.NaN;

# Calculate Fibonacci levels
def level100 = if isLastClosedCandle then rangeHigh else Double.NaN;
def level75 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.25 else Double.NaN;
def level66 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.3334 else Double.NaN;
def level50 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.5 else Double.NaN;
def level33 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.6666 else Double.NaN;
def level25 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.75 else Double.NaN;
def level0 = if isLastClosedCandle then rangeLow else Double.NaN;

# Plot Fibonacci levels
plot P100 = level100;
plot P75 = level75;
plot P66 = level66;
plot P50 = level50;
plot P33 = level33;
plot P25 = level25;
plot P0 = level0;

# Set color and style for each Fibonacci level
P100.SetDefaultColor(GlobalColor("Color100"));
P100.SetStyle(style100);
P100.SetLineWeight(1);
P100.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P75.SetDefaultColor(GlobalColor("Color75"));
P75.SetStyle(style75);
P75.SetLineWeight(1);
P75.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P66.SetDefaultColor(GlobalColor("Color66"));
P66.SetStyle(style66);
P66.SetLineWeight(1);
P66.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P50.SetDefaultColor(GlobalColor("Color50"));
P50.SetStyle(style50);
P50.SetLineWeight(1);
P50.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P33.SetDefaultColor(GlobalColor("Color33"));
P33.SetStyle(style33);
P33.SetLineWeight(1);
P33.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P25.SetDefaultColor(GlobalColor("Color25"));
P25.SetStyle(style25);
P25.SetLineWeight(1);
P25.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P0.SetDefaultColor(GlobalColor("Color0"));
P0.SetStyle(style0);
P0.SetLineWeight(1);
P0.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
#


I made this script and it seem to do what i want but the market is close atm so im not sure if it will plot on the next bar that closes.

Code:
DefineGlobalColor("Color100", CreateColor(255, 0, 0)); # RED
DefineGlobalColor("Color75", CreateColor(153, 153, 153)); # GRAY

DefineGlobalColor("Color618", CreateColor(0, 153, 51)); # BLUE
DefineGlobalColor("Color50", CreateColor(255, 0, 255)); # MAGENTA
DefineGlobalColor("Color382", CreateColor(0, 153, 51)); # ORANGE

DefineGlobalColor("Color25", CreateColor(153, 153, 153)); # GRAY
DefineGlobalColor("Color0", CreateColor(255, 0, 0)); # RED

# Input to choose how many bars back to calculate Fibonacci levels
input barsBack = 1;

# Calculate the current BarNumber
def bn = BarNumber();

# Count bars from right to left
def currentBar = HighestAll(if !IsNaN(close) then bn else Double.NaN);
def pastIndex = currentBar - bn;

# Identify the high and low of the bar "barsBack" bars ago
def targetBar = pastIndex == barsBack;
def rangeHigh = if targetBar then high else Double.NaN;
def rangeLow = if targetBar then low else Double.NaN;

# Hold the high and low values of the target bar for subsequent bars
def lastRangeHigh = if !IsNaN(rangeHigh) then rangeHigh else lastRangeHigh[1];
def lastRangeLow = if !IsNaN(rangeLow) then rangeLow else lastRangeLow[1];

# Calculate Fibonacci levels based on the target bar
def level100 = lastRangeHigh;
def level75 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.25;
def level618 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.618;
def level50 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.5;
def level382 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.382;
def level25 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.75;
def level0 = lastRangeLow;

# Plot Fibonacci levels as horizontal lines extending across the chart
plot P100 = if !IsNaN(close) then level100 else Double.NaN;
plot P75 = if !IsNaN(close) then level75 else Double.NaN;
plot P618 = if !IsNaN(close) then level618 else Double.NaN;
plot P50 = if !IsNaN(close) then level50 else Double.NaN;
plot P382 = if !IsNaN(close) then level382 else Double.NaN;
plot P25 = if !IsNaN(close) then level25 else Double.NaN;
plot P0 = if !IsNaN(close) then level0 else Double.NaN;

# Set color and style for each Fibonacci level
P100.SetDefaultColor(GlobalColor("Color100"));
P100.SetStyle(Curve.FIRM);
P100.SetLineWeight(1);
P100.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P75.SetDefaultColor(GlobalColor("Color75"));
P75.SetStyle(Curve.SHORT_DASH);
P75.SetLineWeight(1);
P75.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P618.SetDefaultColor(GlobalColor("Color618"));
P618.SetStyle(Curve.SHORT_DASH);
P618.SetLineWeight(1);
P618.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P50.SetDefaultColor(GlobalColor("Color50"));
P50.SetStyle(Curve.SHORT_DASH);
P50.SetLineWeight(1);
P50.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P382.SetDefaultColor(GlobalColor("Color382"));
P382.SetStyle(Curve.SHORT_DASH);
P382.SetLineWeight(1);
P382.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P25.SetDefaultColor(GlobalColor("Color25"));
P25.SetStyle(Curve.SHORT_DASH);
P25.SetLineWeight(1);
P25.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P0.SetDefaultColor(GlobalColor("Color0"));
P0.SetStyle(Curve.FIRM);
P0.SetLineWeight(1);
P0.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Last edited by a moderator:

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

Hello, I created this script to monitor a watchlist to let me know when the MACD is in a upward trend. However, for some reason it's not reporting the indicator correctly. It never shows me the diff from the fast line - signal line as - or + just always positive so it only shows the one. can you take a look and tell me where I went wrong?

# Input settings to match the lower MACD study
input fastLength = 11;
input slowLength = 21;
input macdLength = 9;
input averageType = AverageType.WEIGHTED;

# Access the MACD study directly to get the exact Fast Line and Signal Line values using the chart's timeframe
def macdFastLine = MACD(fastLength, slowLength, macdLength, averageType).Value;
def macdSignalLine = MACD(fastLength, slowLength, macdLength, averageType).Avg;

# Subtract the MACD Fast Line value from the Signal Line value
def macdDiffValue = macdFastLine - macdSignalLine;

# Determine if the result is positive or negative and assign 1 or 0 accordingly
def macdDiffCondition = if macdDiffValue > 0 then 1 else 0;

# Plot the exact difference in the watchlist column: negative or positive value
plot Data = macdDiffValue;

# Set the font color based on the value: white if 0, yellow if 1
Data.AssignValueColor(if macdDiffCondition == 1 then Color.YELLOW else Color.WHITE);

# Debugging Labels for verification with 0 or 1 in parentheses
AddLabel(yes, "MACD Fast Line: " + macdFastLine, Color.WHITE);
AddLabel(yes, "MACD Signal Line: " + macdSignalLine, Color.WHITE);
AddLabel(yes, "MACD Diff Value: " + macdDiffValue + " (" + macdDiffCondition + ")",
if macdDiffCondition == 1 then Color.YELLOW else Color.RED);
 
I have looking an auto fib that will plot on each new range candle . I look at a lot of auto fibs on this forum but i dont know if any of them will do this. I got ChatGPT to make this one but I cant get it to remove the past Fibonacci levels or the current bar being formed any ideas on how to get it to plot only the last bar closed?

Ruby:
# Define global colors for customization
DefineGlobalColor("Color100", CreateColor(255, 0, 0)); # RED
DefineGlobalColor("Color75", CreateColor(153, 153, 153)); # Blue
DefineGlobalColor("Color66", CreateColor(0, 153, 51)); # Cyan
DefineGlobalColor("Color50", CreateColor(255, 0, 255)); # Magenta
DefineGlobalColor("Color33", CreateColor(0, 153, 51)); # Yellow
DefineGlobalColor("Color25", CreateColor(153, 153, 153)); # Orange
DefineGlobalColor("Color0", CreateColor(255, 0, 0)); # Red

# Inputs for customization
input style100 = Curve.FIRM;
input style75 = Curve.FIRM;
input style66 = Curve.FIRM;
input style50 = Curve.FIRM;
input style33 = Curve.FIRM;
input style25 = Curve.FIRM;
input style0 = Curve.FIRM;

# Define high, low, and close of the last closed range candle
def lastClosedBar = if !IsNaN(close[1]) then BarNumber() else lastClosedBar[1];
def isLastClosedCandle = BarNumber() == lastClosedBar;

# Calculate high, low, and range of the last closed range candle
def rangeHigh = if isLastClosedCandle then high[1] else Double.NaN;
def rangeLow = if isLastClosedCandle then low[1] else Double.NaN;

# Calculate Fibonacci levels
def level100 = if isLastClosedCandle then rangeHigh else Double.NaN;
def level75 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.25 else Double.NaN;
def level66 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.3334 else Double.NaN;
def level50 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.5 else Double.NaN;
def level33 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.6666 else Double.NaN;
def level25 = if isLastClosedCandle then rangeHigh - (rangeHigh - rangeLow) * 0.75 else Double.NaN;
def level0 = if isLastClosedCandle then rangeLow else Double.NaN;

# Plot Fibonacci levels
plot P100 = level100;
plot P75 = level75;
plot P66 = level66;
plot P50 = level50;
plot P33 = level33;
plot P25 = level25;
plot P0 = level0;

# Set color and style for each Fibonacci level
P100.SetDefaultColor(GlobalColor("Color100"));
P100.SetStyle(style100);
P100.SetLineWeight(1);
P100.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P75.SetDefaultColor(GlobalColor("Color75"));
P75.SetStyle(style75);
P75.SetLineWeight(1);
P75.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P66.SetDefaultColor(GlobalColor("Color66"));
P66.SetStyle(style66);
P66.SetLineWeight(1);
P66.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P50.SetDefaultColor(GlobalColor("Color50"));
P50.SetStyle(style50);
P50.SetLineWeight(1);
P50.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P33.SetDefaultColor(GlobalColor("Color33"));
P33.SetStyle(style33);
P33.SetLineWeight(1);
P33.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P25.SetDefaultColor(GlobalColor("Color25"));
P25.SetStyle(style25);
P25.SetLineWeight(1);
P25.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P0.SetDefaultColor(GlobalColor("Color0"));
P0.SetStyle(style0);
P0.SetLineWeight(1);
P0.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
#


I made this script and it seem to do what i want but the market is close atm so im not sure if it will plot on the next bar that closes.

Code:
DefineGlobalColor("Color100", CreateColor(255, 0, 0)); # RED
DefineGlobalColor("Color75", CreateColor(153, 153, 153)); # GRAY

DefineGlobalColor("Color618", CreateColor(0, 153, 51)); # BLUE
DefineGlobalColor("Color50", CreateColor(255, 0, 255)); # MAGENTA
DefineGlobalColor("Color382", CreateColor(0, 153, 51)); # ORANGE

DefineGlobalColor("Color25", CreateColor(153, 153, 153)); # GRAY
DefineGlobalColor("Color0", CreateColor(255, 0, 0)); # RED

# Input to choose how many bars back to calculate Fibonacci levels
input barsBack = 1;

# Calculate the current BarNumber
def bn = BarNumber();

# Count bars from right to left
def currentBar = HighestAll(if !IsNaN(close) then bn else Double.NaN);
def pastIndex = currentBar - bn;

# Identify the high and low of the bar "barsBack" bars ago
def targetBar = pastIndex == barsBack;
def rangeHigh = if targetBar then high else Double.NaN;
def rangeLow = if targetBar then low else Double.NaN;

# Hold the high and low values of the target bar for subsequent bars
def lastRangeHigh = if !IsNaN(rangeHigh) then rangeHigh else lastRangeHigh[1];
def lastRangeLow = if !IsNaN(rangeLow) then rangeLow else lastRangeLow[1];

# Calculate Fibonacci levels based on the target bar
def level100 = lastRangeHigh;
def level75 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.25;
def level618 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.618;
def level50 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.5;
def level382 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.382;
def level25 = lastRangeHigh - (lastRangeHigh - lastRangeLow) * 0.75;
def level0 = lastRangeLow;

# Plot Fibonacci levels as horizontal lines extending across the chart
plot P100 = if !IsNaN(close) then level100 else Double.NaN;
plot P75 = if !IsNaN(close) then level75 else Double.NaN;
plot P618 = if !IsNaN(close) then level618 else Double.NaN;
plot P50 = if !IsNaN(close) then level50 else Double.NaN;
plot P382 = if !IsNaN(close) then level382 else Double.NaN;
plot P25 = if !IsNaN(close) then level25 else Double.NaN;
plot P0 = if !IsNaN(close) then level0 else Double.NaN;

# Set color and style for each Fibonacci level
P100.SetDefaultColor(GlobalColor("Color100"));
P100.SetStyle(Curve.FIRM);
P100.SetLineWeight(1);
P100.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P75.SetDefaultColor(GlobalColor("Color75"));
P75.SetStyle(Curve.SHORT_DASH);
P75.SetLineWeight(1);
P75.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P618.SetDefaultColor(GlobalColor("Color618"));
P618.SetStyle(Curve.SHORT_DASH);
P618.SetLineWeight(1);
P618.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P50.SetDefaultColor(GlobalColor("Color50"));
P50.SetStyle(Curve.SHORT_DASH);
P50.SetLineWeight(1);
P50.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P382.SetDefaultColor(GlobalColor("Color382"));
P382.SetStyle(Curve.SHORT_DASH);
P382.SetLineWeight(1);
P382.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P25.SetDefaultColor(GlobalColor("Color25"));
P25.SetStyle(Curve.SHORT_DASH);
P25.SetLineWeight(1);
P25.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

P0.SetDefaultColor(GlobalColor("Color0"));
P0.SetStyle(Curve.FIRM);
P0.SetLineWeight(1);
P0.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

reply to 281
i edited your post, separated the 2 codes

i have no idea what you are asking for?
what is a range candle?
no idea what i am supposed to be looking at in the image?
what does this mean, plot only the last bar closed. do you mean just use the last bar data?

use more words and explain what you want to see.

it is drawing lines between the 2nd to last bar. that isn't a normal fib, which is from a peak to a valley.
 

Attachments

  • Capture.JPG
    Capture.JPG
    32.7 KB · Views: 40
Last edited:
Working on TTM Squeeze scan the issue seems to the script may still be interpreting length as a variable rather than a literal constant.

The issue likely stems from the fact that, despite attempts to hardcode length, the script may still be interpreting length as a variable rather than a literal constant. Help would be appreciated
Code:
# TTM Squeeze Scanner
# Original code by TSL 11.13.2019
# Modified into a scanner by @MerryDay 8/2022

input price = close;
input nK = 1.5;       # Multiplier for Keltner Channels
input nBB = 2.0;      # Multiplier for Bollinger Bands
input alertLine = 1.0;
input maLength = 50;  # Moving average length
input rsiLength = 14; # RSI length for filtering
input rsiOverbought = 70; # RSI overbought level
input rsiOversold = 30;   # RSI oversold level
input volumeMultiplier = 1.5; # Multiplier for detecting volume spikes

# Directly using 20 as the literal constant where required
def squeezeHistogram = TTM_Squeeze(price, 20, nK, nBB, alertLine).Histogram;  # Hardcoded 20

# Calculate the moving average
def movingAverage = Average(price, maLength);

# Calculate the RSI
def rsi = RSI(price, rsiLength);

# Detect significant volume spikes using a literal constant for length
def volumeSpike = volume > Average(volume, 20) * volumeMultiplier;  # Hardcoded 20

# Determine squeeze stages based on histogram behavior
def squeezeStages;
if squeezeHistogram >= 0 then {
    if squeezeHistogram > squeezeHistogram[1] then {
        squeezeStages = 1;  # Cyan: Positive increasing (potential breakout)
    } else {
        squeezeStages = 2;  # Blue: Positive decreasing (potential weakening)
    }
} else {
    if squeezeHistogram < squeezeHistogram[1] then {
        squeezeStages = 3;  # Red: Negative decreasing (potential reversal)
    } else {
        squeezeStages = 4;  # Yellow: Negative increasing (potential weakening)
    }
}

# Scan for transition from Yellow to Cyan Histogram
plot scan_YellowToCyan = squeezeStages[1] == 4 and squeezeStages == 1;

# Scan for transition from Blue to Red Histogram
plot scan_BlueToRed = squeezeStages[1] == 2 and squeezeStages == 3;

### Breakout Scan
# Detect breakouts from a squeeze with price above moving average and volume spike
def priceBreakout = price > Highest(price, 20);  # Literal constant of 20 used
plot scan_Breakout =
    squeezeStages == 1 and  # Cyan stage indicates potential breakout
    priceBreakout and
    price > movingAverage and
    volumeSpike;

### Separate Reversal Signal Scans
# Detect Bullish Reversals
plot scan_BullishReversal =
    squeezeStages == 3 and rsi < rsiOversold;  # Red stage with RSI Oversold

# Detect Bearish Reversals
plot scan_BearishReversal =
    squeezeStages == 4 and rsi > rsiOverbought;  # Yellow stage with RSI Overbought
 
Last edited by a moderator:
Working on TTM Squeeze scan the issue seems to the script may still be interpreting length as a variable rather than a literal constant.

The issue likely stems from the fact that, despite attempts to hardcode length, the script may still be interpreting length as a variable rather than a literal constant. Help would be appreciated
Code:
# TTM Squeeze Scanner
# Original code by TSL 11.13.2019
# Modified into a scanner by @MerryDay 8/2022

input price = close;
input nK = 1.5;       # Multiplier for Keltner Channels
input nBB = 2.0;      # Multiplier for Bollinger Bands
input alertLine = 1.0;
input maLength = 50;  # Moving average length
input rsiLength = 14; # RSI length for filtering
input rsiOverbought = 70; # RSI overbought level
input rsiOversold = 30;   # RSI oversold level
input volumeMultiplier = 1.5; # Multiplier for detecting volume spikes

# Directly using 20 as the literal constant where required
def squeezeHistogram = TTM_Squeeze(price, 20, nK, nBB, alertLine).Histogram;  # Hardcoded 20

# Calculate the moving average
def movingAverage = Average(price, maLength);

# Calculate the RSI
def rsi = RSI(price, rsiLength);

# Detect significant volume spikes using a literal constant for length
def volumeSpike = volume > Average(volume, 20) * volumeMultiplier;  # Hardcoded 20

# Determine squeeze stages based on histogram behavior
def squeezeStages;
if squeezeHistogram >= 0 then {
    if squeezeHistogram > squeezeHistogram[1] then {
        squeezeStages = 1;  # Cyan: Positive increasing (potential breakout)
    } else {
        squeezeStages = 2;  # Blue: Positive decreasing (potential weakening)
    }
} else {
    if squeezeHistogram < squeezeHistogram[1] then {
        squeezeStages = 3;  # Red: Negative decreasing (potential reversal)
    } else {
        squeezeStages = 4;  # Yellow: Negative increasing (potential weakening)
    }
}

# Scan for transition from Yellow to Cyan Histogram
plot scan_YellowToCyan = squeezeStages[1] == 4 and squeezeStages == 1;

# Scan for transition from Blue to Red Histogram
plot scan_BlueToRed = squeezeStages[1] == 2 and squeezeStages == 3;

### Breakout Scan
# Detect breakouts from a squeeze with price above moving average and volume spike
def priceBreakout = price > Highest(price, 20);  # Literal constant of 20 used
plot scan_Breakout =
    squeezeStages == 1 and  # Cyan stage indicates potential breakout
    priceBreakout and
    price > movingAverage and
    volumeSpike;

### Separate Reversal Signal Scans
# Detect Bullish Reversals
plot scan_BullishReversal =
    squeezeStages == 3 and rsi < rsiOversold;  # Red stage with RSI Oversold

# Detect Bearish Reversals
plot scan_BearishReversal =
    squeezeStages == 4 and rsi > rsiOverbought;  # Yellow stage with RSI Overbought

reply to 286


rsi() error,
def rsi = RSI(price, rsiLength);

go look at RSI() code and see what the inputs are
input length = 14;
input over_Bought = 70;
input over_Sold = 30;
input price = close;
input averageType = AverageType.WILDERS;
input showBreakoutSignals = no;

you have the parameters in wrong sequence.
can get around that by using the parameter names.

def rsi = RSI(price = price, length = rsiLength);


i made this a lower study for you to experiment with.
before you use this as a scan, choose which plot you want to keep and disable the others.

Code:
#chat286_ttm_sqz_scan

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

# TTM Squeeze Scanner
# Original code by TSL 11.13.2019
# Modified into a scanner by @MerryDay 8/2022

declare lower;

input price = close;
input nK = 1.5;       # Multiplier for Keltner Channels
input nBB = 2.0;      # Multiplier for Bollinger Bands
input alertLine = 1.0;
input maLength = 50;  # Moving average length
input rsiLength = 14; # RSI length for filtering
input rsiOverbought = 70; # RSI overbought level
input rsiOversold = 30;   # RSI oversold level
input volumeMultiplier = 1.5; # Multiplier for detecting volume spikes

# Directly using 20 as the literal constant where required
def squeezeHistogram = TTM_Squeeze(price, 20, nK, nBB, alertLine).Histogram;  # Hardcoded 20

# Calculate the moving average
def movingAverage = Average(price, maLength);

# Calculate the RSI
# parameters in wrong sequence
#def rsi = RSI(price, rsiLength);
# add parameter names
def rsi = RSI(price = price, length = rsiLength);

# Detect significant volume spikes using a literal constant for length
def volumeSpike = volume > Average(volume, 20) * volumeMultiplier;  # Hardcoded 20

# Determine squeeze stages based on histogram behavior
def squeezeStages;
if squeezeHistogram >= 0
then {
    if squeezeHistogram > squeezeHistogram[1]
    then {
        squeezeStages = 1;  # Cyan: Positive increasing (potential breakout)
    } else {
        squeezeStages = 2;  # Blue: Positive decreasing (potential weakening)
    }
} else {
    if squeezeHistogram < squeezeHistogram[1]
    then {
        squeezeStages = 3;  # Red: Negative decreasing (potential reversal)
    } else {
        squeezeStages = 4;  # Yellow: Negative increasing (potential weakening)
    }
}

# Scan for transition from Yellow to Cyan Histogram
plot scan_YellowToCyan = squeezeStages[1] == 4 and squeezeStages == 1;

# Scan for transition from Blue to Red Histogram
plot scan_BlueToRed = squeezeStages[1] == 2 and squeezeStages == 3;

### Breakout Scan
# Detect breakouts from a squeeze with price above moving average and volume spike
def priceBreakout = price > Highest(price, 20);  # Literal constant of 20 used
plot scan_Breakout =
    squeezeStages == 1 and  # Cyan stage indicates potential breakout
    priceBreakout and
    price > movingAverage and
    volumeSpike;

### Separate Reversal Signal Scans
# Detect Bullish Reversals
plot scan_BullishReversal =
    squeezeStages == 3 and rsi < rsiOversold;  # Red stage with RSI Oversold

# Detect Bearish Reversals
plot scan_BearishReversal =
    squeezeStages == 4 and rsi > rsiOverbought;  # Yellow stage with RSI Overbought
#
 

Attachments

  • img1.JPG
    img1.JPG
    70.3 KB · Views: 65
reply to 279

good on you for trying something, even though the aggregation didn't fix it. that's how i learned, i kept trying things.

set the chart on week,
then on the upper chart, look in the upper left. is there a small white circle with a ! in it.
click on it and it will say portfolio functions don't work with all time periods.

look up portfolio functions
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Portfolio
you have a GetOpenPL() in the last line, in a label.
disable that line and it will work.
Thank you! You fixed it.
 
I asked ChatGPT to re-create the new Big 3 Squeeze from simpler trading. It's close but not displaying properly for me. Everything is really compressed and hard to see. If anyone wants to play around with it, I think this is a good start:

# Big 3 Squeeze Indicator by Taylor Horton
# This script combines elements of the TTM Squeeze with custom buy/sell signals

declare lower;

input length = 20;
input mult = 2.0;
input momentumLength = 12;
input momentumMultiplier = 1.5;
input smoothingLength = 3;

def price = close;
def avg = SimpleMovingAvg(price, length);
def stdev = stdev(price, length);
def upperBand = avg + (mult * stdev);
def lowerBand = avg - (mult * stdev);

def K = (price - lowerBand) / (upperBand - lowerBand);
def D = ExpAverage(K, smoothingLength);
def J = 3 * K - 2 * D;

def MomentumHistogram = (price - ExpAverage(price, momentumLength)) / (momentumMultiplier * stdev);

plot Histogram = MomentumHistogram;
Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Histogram.AssignValueColor(if MomentumHistogram >= 0 then Color.GREEN else Color.RED);

# Big 3 Buy and Sell Signals
def buySignal = K crosses above D and K < 0.2 and ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def sellSignal = K crosses below D and K > 0.8 and ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BuyArrow = if buySignal then low else Double.NaN;
BuyArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuyArrow.SetDefaultColor(Color.GREEN);
BuyArrow.SetLineWeight(5);

plot SellArrow = if sellSignal then high else Double.NaN;
SellArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellArrow.SetDefaultColor(Color.RED);
SellArrow.SetLineWeight(5);

# Squeeze Signal
def squeeze = K > 0 and K < 1 and D > 0 and D < 1;
plot SqueezeDots = if squeeze then 0 else Double.NaN;
SqueezeDots.SetPaintingStrategy(PaintingStrategy.POINTS);
SqueezeDots.SetDefaultColor(Color.BLUE);
SqueezeDots.SetLineWeight(5);

# Labels for A+ Setups
AddLabel(buySignal, "A+ Buy Setup", Color.GREEN);
AddLabel(sellSignal, "A+ Sell Setup", Color.RED);

# Multi-Time Frame Labels
def weeklySqueeze = Highest(squeeze, 5) > 0;
def dailySqueeze = Highest(squeeze, 1) > 0;
def intraDaySqueeze = squeeze;

AddLabel(weeklySqueeze, "Weekly Squeeze", Color.BLUE);
AddLabel(dailySqueeze, "Daily Squeeze", Color.YELLOW);
AddLabel(intraDaySqueeze, "Intra-Day Squeeze", Color.MAGENTA);

# Additional Structure Criteria
def structureBuy = ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def structureSell = ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BullStructure = if structureBuy then low else Double.NaN;
BullStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BullStructure.SetDefaultColor(Color.GREEN);
BullStructure.SetLineWeight(5);

plot BearStructure = if structureSell then high else Double.NaN;
BearStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BearStructure.SetDefaultColor(Color.RED);
BearStructure.SetLineWeight(5);

# Trailing Stop Labels
def trailingStopValue = ExpAverage(close, 10);

AddLabel(close > trailingStopValue, "Above Trailing Stop", Color.GREEN);
AddLabel(close < trailingStopValue, "Below Trailing Stop", Color.RED);

plot TrailingStopLine = trailingStopValue;
TrailingStopLine.SetDefaultColor(Color.ORANGE);
TrailingStopLine.SetStyle(Curve.MEDIUM_DASH);
TrailingStopLine.SetLineWeight(3);

# Bull and Bear Target Labels
def bullTarget = close + 3 * stdev;
def bearTarget = close - 3 * stdev;

AddLabel(close >= bullTarget, "Bull Target Hit", Color.GREEN);
AddLabel(close <= bearTarget, "Bear Target Hit", Color.RED);
 

Attachments

  • Big3.docx
    118.4 KB · Views: 48
I asked ChatGPT to re-create the new Big 3 Squeeze from simpler trading. It's close but not displaying properly for me. Everything is really compressed and hard to see. If anyone wants to play around with it, I think this is a good start:

# Big 3 Squeeze Indicator by Taylor Horton
# This script combines elements of the TTM Squeeze with custom buy/sell signals

declare lower;

input length = 20;
input mult = 2.0;
input momentumLength = 12;
input momentumMultiplier = 1.5;
input smoothingLength = 3;

def price = close;
def avg = SimpleMovingAvg(price, length);
def stdev = stdev(price, length);
def upperBand = avg + (mult * stdev);
def lowerBand = avg - (mult * stdev);

def K = (price - lowerBand) / (upperBand - lowerBand);
def D = ExpAverage(K, smoothingLength);
def J = 3 * K - 2 * D;

def MomentumHistogram = (price - ExpAverage(price, momentumLength)) / (momentumMultiplier * stdev);

plot Histogram = MomentumHistogram;
Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Histogram.AssignValueColor(if MomentumHistogram >= 0 then Color.GREEN else Color.RED);

# Big 3 Buy and Sell Signals
def buySignal = K crosses above D and K < 0.2 and ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def sellSignal = K crosses below D and K > 0.8 and ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BuyArrow = if buySignal then low else Double.NaN;
BuyArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuyArrow.SetDefaultColor(Color.GREEN);
BuyArrow.SetLineWeight(5);

plot SellArrow = if sellSignal then high else Double.NaN;
SellArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellArrow.SetDefaultColor(Color.RED);
SellArrow.SetLineWeight(5);

# Squeeze Signal
def squeeze = K > 0 and K < 1 and D > 0 and D < 1;
plot SqueezeDots = if squeeze then 0 else Double.NaN;
SqueezeDots.SetPaintingStrategy(PaintingStrategy.POINTS);
SqueezeDots.SetDefaultColor(Color.BLUE);
SqueezeDots.SetLineWeight(5);

# Labels for A+ Setups
AddLabel(buySignal, "A+ Buy Setup", Color.GREEN);
AddLabel(sellSignal, "A+ Sell Setup", Color.RED);

# Multi-Time Frame Labels
def weeklySqueeze = Highest(squeeze, 5) > 0;
def dailySqueeze = Highest(squeeze, 1) > 0;
def intraDaySqueeze = squeeze;

AddLabel(weeklySqueeze, "Weekly Squeeze", Color.BLUE);
AddLabel(dailySqueeze, "Daily Squeeze", Color.YELLOW);
AddLabel(intraDaySqueeze, "Intra-Day Squeeze", Color.MAGENTA);

# Additional Structure Criteria
def structureBuy = ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def structureSell = ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BullStructure = if structureBuy then low else Double.NaN;
BullStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BullStructure.SetDefaultColor(Color.GREEN);
BullStructure.SetLineWeight(5);

plot BearStructure = if structureSell then high else Double.NaN;
BearStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BearStructure.SetDefaultColor(Color.RED);
BearStructure.SetLineWeight(5);

# Trailing Stop Labels
def trailingStopValue = ExpAverage(close, 10);

AddLabel(close > trailingStopValue, "Above Trailing Stop", Color.GREEN);
AddLabel(close < trailingStopValue, "Below Trailing Stop", Color.RED);

plot TrailingStopLine = trailingStopValue;
TrailingStopLine.SetDefaultColor(Color.ORANGE);
TrailingStopLine.SetStyle(Curve.MEDIUM_DASH);
TrailingStopLine.SetLineWeight(3);

# Bull and Bear Target Labels
def bullTarget = close + 3 * stdev;
def bearTarget = close - 3 * stdev;

AddLabel(close >= bullTarget, "Bull Target Hit", Color.GREEN);
AddLabel(close <= bearTarget, "Bear Target Hit", Color.RED);
This is dirty. I separated them into two and overlay them on to each other and it's doesn't compress. But, either the histogram and squeeze need to be moved up to match the moving averages, or the moving averages need to be moved down to oscillate around the histogram.
1st-
# Big 3 Squeeze Indicator by Taylor Horton
# This script combines elements of the TTM Squeeze with custom buy/sell signals

declare lower;

input length = 20;
input mult = 2.0;
input momentumLength = 12;
input momentumMultiplier = 1.5;
input smoothingLength = 3;

def price = close;
def avg = SimpleMovingAvg(price, length);
def stdev = stdev(price, length);
def upperBand = avg + (mult * stdev);
def lowerBand = avg - (mult * stdev);

def K = (price - lowerBand) / (upperBand - lowerBand);
def D = ExpAverage(K, smoothingLength);
def J = 3 * K - 2 * D;

def MomentumHistogram = (price - ExpAverage(price, momentumLength)) / (momentumMultiplier * stdev);


# Big 3 Buy and Sell Signals
def buySignal = K crosses above D and K < 0.2 and ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def sellSignal = K crosses below D and K > 0.8 and ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BuyArrow = if buySignal then low else Double.NaN;
BuyArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuyArrow.SetDefaultColor(Color.GREEN);
BuyArrow.SetLineWeight(5);

plot SellArrow = if sellSignal then high else Double.NaN;
SellArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellArrow.SetDefaultColor(Color.RED);
SellArrow.SetLineWeight(5);

# Squeeze Signal
def squeeze = K > 0 and K < 1 and D > 0 and D < 1;


# Labels for A+ Setups
AddLabel(buySignal, "A+ Buy Setup", Color.GREEN);
AddLabel(sellSignal, "A+ Sell Setup", Color.RED);

# Multi-Time Frame Labels
def weeklySqueeze = Highest(squeeze, 5) > 0;
def dailySqueeze = Highest(squeeze, 1) > 0;
def intraDaySqueeze = squeeze;

AddLabel(weeklySqueeze, "Weekly Squeeze", Color.BLUE);
AddLabel(dailySqueeze, "Daily Squeeze", Color.YELLOW);
AddLabel(intraDaySqueeze, "Intra-Day Squeeze", Color.MAGENTA);

# Additional Structure Criteria
def structureBuy = ExpAverage(close, 21) > SimpleMovingAvg(close, 50);
def structureSell = ExpAverage(close, 21) < SimpleMovingAvg(close, 50);

plot BullStructure = if structureBuy then low else Double.NaN;
BullStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BullStructure.SetDefaultColor(Color.GREEN);
BullStructure.SetLineWeight(5);

plot BearStructure = if structureSell then high else Double.NaN;
BearStructure.SetPaintingStrategy(PaintingStrategy.BOOLEAN_POINTS);
BearStructure.SetDefaultColor(Color.RED);
BearStructure.SetLineWeight(5);

# Trailing Stop Labels
def trailingStopValue = ExpAverage(close, 10);

AddLabel(close > trailingStopValue, "Above Trailing Stop", Color.GREEN);
AddLabel(close < trailingStopValue, "Below Trailing Stop", Color.RED);

plot TrailingStopLine = trailingStopValue;
TrailingStopLine.SetDefaultColor(Color.ORANGE);
TrailingStopLine.SetStyle(Curve.MEDIUM_DASH);
TrailingStopLine.SetLineWeight(3);

# Bull and Bear Target Labels
def bullTarget = close + 3 * stdev;
def bearTarget = close - 3 * stdev;

AddLabel(close >= bullTarget, "Bull Target Hit", Color.GREEN);
AddLabel(close <= bearTarget, "Bear Target Hit", Color.RED);
2nd-

# Big 3 Squeeze Indicator by Taylor Horton
# This script combines elements of the TTM Squeeze with custom buy/sell signals

declare lower;

input length = 20;
input mult = 2.0;
input momentumLength = 12;
input momentumMultiplier = 1.5;
input smoothingLength = 3;


def price = close;
def avg = SimpleMovingAvg(price, length);
def stdev = stdev(price, length);
def upperBand = avg + (mult * stdev);
def lowerBand = avg - (mult * stdev);

def K = (price - lowerBand) / (upperBand - lowerBand);
def D = ExpAverage(K, smoothingLength);
def J = 3 * K - 2 * D;

def MomentumHistogram = (price - ExpAverage(price, momentumLength)) / (momentumMultiplier * stdev);

plot Histogram = MomentumHistogram;
Histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Histogram.AssignValueColor(if MomentumHistogram >= 0 then Color.GREEN else Color.RED);

# Squeeze Signal
def squeeze = K > 0 and K < 1 and D > 0 and D < 1;
plot SqueezeDots = if squeeze then 0 else Double.NaN;
SqueezeDots.SetPaintingStrategy(PaintingStrategy.POINTS);
SqueezeDots.SetDefaultColor(Color.BLUE);
SqueezeDots.SetLineWeight(5);
Edit - Fixed the second one. It still plotted the trailing stop value which compressed the histogram. Now they should overlay properly.
 
Last edited:
I am building a study that uses some sort of rolling context window to measure local mins and maxs to determine trends. I have not figured out how to implement a context window correctly. ToS isn't throwing any errors, it just doesn't print anything on the indicator. The code below does print certain conditions, just without the context window. Does anyone know how to implement this?


Code:
declare lower;

input overBought = 80;
input overSold = 20;
input KPeriod = 10;
input DPeriod = 10;
input priceH = high;
input priceL = low;
input priceC = close;
input averageType = AverageType.SIMPLE;
input showBreakoutSignals = yes;
input lookbackWindow = 50;  # Lookback window for trend detection

# Calculate FastK, SlowK, and SlowD
def highK = Highest(priceH, KPeriod);
def lowK = Lowest(priceL, KPeriod);
def FastK = 100 * (priceC - lowK) / (highK - lowK);
def SlowK = MovingAverage(averageType, FastK, 3);  # 3-period moving average of FastK
def SlowD = MovingAverage(averageType, SlowK, DPeriod);  # DPeriod moving average of SlowK

# Plot SlowK and SlowD
plot SlowKPlot = SlowK;
SlowKPlot.SetDefaultColor(GetColor(1));
plot SlowDPlot = SlowD;
SlowDPlot.SetDefaultColor(GetColor(5));

# Overbought and Oversold lines
plot OverBoughtLine = overBought;
OverBoughtLine.SetDefaultColor(Color.RED);
OverBoughtLine.SetStyle(Curve.FIRM);
OverBoughtLine.SetLineWeight(1);
plot OverSoldLine = overSold;
OverSoldLine.SetDefaultColor(Color.GREEN);
OverSoldLine.SetStyle(Curve.FIRM);
OverSoldLine.SetLineWeight(1);

# Local highs and lows for SlowD
def isLocalHigh = SlowD > SlowD[1] and SlowD > SlowD[-1];
def isLocalLow = SlowD < SlowD[1] and SlowD < SlowD[-1];

# Filtered local highs and lows based on SlowD value
def filteredLocalHigh = isLocalHigh and SlowD >= 60;
def filteredLocalLow = isLocalLow and SlowD <= 30;

# Track the last three filtered local highs and lows
def lastFilteredHigh = if filteredLocalHigh then SlowD else lastFilteredHigh[1];
def secondLastFilteredHigh = if filteredLocalHigh then lastFilteredHigh[1] else secondLastFilteredHigh[1];
def thirdLastFilteredHigh = if filteredLocalHigh then secondLastFilteredHigh[1] else thirdLastFilteredHigh[1];

def lastFilteredLow = if filteredLocalLow then SlowD else lastFilteredLow[1];
def secondLastFilteredLow = if filteredLocalLow then lastFilteredLow[1] else secondLastFilteredLow[1];
def thirdLastFilteredLow = if filteredLocalLow then secondLastFilteredLow[1] else thirdLastFilteredLow[1];

# Breakout conditions
def upBreakout = SlowK crosses above overSold;
def downBreakout = SlowK crosses below overBought;

# Conditions for white dots (improved logic)
def downBreakoutDotCondition = downBreakout and SlowD < Min(lastFilteredHigh, secondLastFilteredHigh) and !IsNaN(lastFilteredHigh) and !IsNaN(secondLastFilteredHigh);
def upBreakoutDotCondition = upBreakout and SlowD > Max(lastFilteredLow, secondLastFilteredLow) and !IsNaN(lastFilteredLow) and !IsNaN(secondLastFilteredLow);

# Check for presence of any colored dot
def hasColoredDot = filteredLocalHigh or filteredLocalLow or upBreakoutDotCondition or downBreakoutDotCondition;

# Plot breakout signals only when there's a colored dot
plot UpSignal = if showBreakoutSignals and upBreakout and hasColoredDot then overSold else Double.NaN;
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetLineWeight(2);

plot DownSignal = if showBreakoutSignals and downBreakout and hasColoredDot then overBought else Double.NaN;
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
DownSignal.SetDefaultColor(Color.DOWNTICK);
DownSignal.SetLineWeight(2);

# Plot white dots
plot UpBreakoutDot = if upBreakoutDotCondition then SlowD else Double.NaN;
UpBreakoutDot.SetPaintingStrategy(PaintingStrategy.POINTS);
UpBreakoutDot.SetDefaultColor(Color.WHITE);
UpBreakoutDot.SetLineWeight(3);

plot DownBreakoutDot = if downBreakoutDotCondition then SlowD else Double.NaN;
DownBreakoutDot.SetPaintingStrategy(PaintingStrategy.POINTS);
DownBreakoutDot.SetDefaultColor(Color.WHITE);
DownBreakoutDot.SetLineWeight(3);

# Plot filtered local highs and lows (for reference)
plot LocalHigh = if filteredLocalHigh then SlowD else Double.NaN;
LocalHigh.SetPaintingStrategy(PaintingStrategy.POINTS);
LocalHigh.SetDefaultColor(Color.BLUE);
LocalHigh.SetLineWeight(3);

plot LocalLow = if filteredLocalLow then SlowD else Double.NaN;
LocalLow.SetPaintingStrategy(PaintingStrategy.POINTS);
LocalLow.SetDefaultColor(Color.YELLOW);
LocalLow.SetLineWeight(3);
 
Hello Everyone,

I got this code through AI however it requires to be tweaked to only show entries and exit arrows once it retest the EMAs:

Code:
# Define the moving averages
input length13 = 13;
input length48 = 48;
input length200 = 200;

def ema13 = ExpAverage(close, length13);
def ema48 = ExpAverage(close, length48);
def ema200 = ExpAverage(close, length200);

# Identify the trend
def higherHigh = high > high[1];
def higherLow = low > low[1];
def lowerHigh = high < high[1];
def lowerLow = low < low[1];

def uptrend = higherHigh and higherLow;
def downtrend = lowerHigh and lowerLow;

# Entry signals
def closeAbove13EMA = close > ema13;
def closeBelow13EMA = close < ema13;
def closeAbove48EMA = close > ema48;
def closeBelow48EMA = close < ema48;

# Track previous trend and signals
def wasInUptrend = uptrend[1];
def wasInDowntrend = downtrend[1];
def longEntrySignal = uptrend and !wasInUptrend and closeAbove13EMA and close[1] <= ema13[1] and close > ema13;
def longEntrySignal48 = uptrend and !wasInUptrend and closeAbove48EMA and close[1] <= ema48[1] and close > ema48;
def shortEntrySignal = downtrend and !wasInDowntrend and closeBelow13EMA and close[1] >= ema13[1] and close < ema13;
def shortEntrySignal48 = downtrend and !wasInDowntrend and closeBelow48EMA and close[1] >= ema48[1] and close < ema48;

# Exit signals
def exitLongSignal = close < ema13 or close < ema48;
def exitShortSignal = close > ema13 or close > ema48;

# Track the signals
def longEntryPlotted = longEntrySignal or longEntrySignal48;
def shortEntryPlotted = shortEntrySignal or shortEntrySignal48;
def exitLongPlotted = exitLongSignal;
def exitShortPlotted = exitShortSignal;

# Plot arrows
plot longEntryArrow = if longEntryPlotted and !longEntryPlotted[1] then low else Double.NaN;
plot shortEntryArrow = if shortEntryPlotted and !shortEntryPlotted[1] then high else Double.NaN;
plot exitLongArrow = if exitLongPlotted and !exitLongPlotted[1] then low else Double.NaN;
plot exitShortArrow = if exitShortPlotted and !exitShortPlotted[1] then high else Double.NaN;

# Styling
longEntryArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
longEntryArrow.SetDefaultColor(Color.GREEN);
shortEntryArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
shortEntryArrow.SetDefaultColor(Color.RED);
exitLongArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
exitLongArrow.SetDefaultColor(Color.RED);
exitShortArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
exitShortArrow.SetDefaultColor(Color.GREEN);

Is it possible to have it tweaked?

Thank you! :)
 
Hello Everyone,

I got this code through AI however it requires to be tweaked to only show entries and exit arrows once it retest the EMAs:

Code:
# Define the moving averages
input length13 = 13;
input length48 = 48;
input length200 = 200;

def ema13 = ExpAverage(close, length13);
def ema48 = ExpAverage(close, length48);
def ema200 = ExpAverage(close, length200);

# Identify the trend
def higherHigh = high > high[1];
def higherLow = low > low[1];
def lowerHigh = high < high[1];
def lowerLow = low < low[1];

def uptrend = higherHigh and higherLow;
def downtrend = lowerHigh and lowerLow;

# Entry signals
def closeAbove13EMA = close > ema13;
def closeBelow13EMA = close < ema13;
def closeAbove48EMA = close > ema48;
def closeBelow48EMA = close < ema48;

# Track previous trend and signals
def wasInUptrend = uptrend[1];
def wasInDowntrend = downtrend[1];
def longEntrySignal = uptrend and !wasInUptrend and closeAbove13EMA and close[1] <= ema13[1] and close > ema13;
def longEntrySignal48 = uptrend and !wasInUptrend and closeAbove48EMA and close[1] <= ema48[1] and close > ema48;
def shortEntrySignal = downtrend and !wasInDowntrend and closeBelow13EMA and close[1] >= ema13[1] and close < ema13;
def shortEntrySignal48 = downtrend and !wasInDowntrend and closeBelow48EMA and close[1] >= ema48[1] and close < ema48;

# Exit signals
def exitLongSignal = close < ema13 or close < ema48;
def exitShortSignal = close > ema13 or close > ema48;

# Track the signals
def longEntryPlotted = longEntrySignal or longEntrySignal48;
def shortEntryPlotted = shortEntrySignal or shortEntrySignal48;
def exitLongPlotted = exitLongSignal;
def exitShortPlotted = exitShortSignal;

# Plot arrows
plot longEntryArrow = if longEntryPlotted and !longEntryPlotted[1] then low else Double.NaN;
plot shortEntryArrow = if shortEntryPlotted and !shortEntryPlotted[1] then high else Double.NaN;
plot exitLongArrow = if exitLongPlotted and !exitLongPlotted[1] then low else Double.NaN;
plot exitShortArrow = if exitShortPlotted and !exitShortPlotted[1] then high else Double.NaN;

# Styling
longEntryArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
longEntryArrow.SetDefaultColor(Color.GREEN);
shortEntryArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
shortEntryArrow.SetDefaultColor(Color.RED);
exitLongArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
exitLongArrow.SetDefaultColor(Color.RED);
exitShortArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
exitShortArrow.SetDefaultColor(Color.GREEN);

Is it possible to have it tweaked?

Thank you! :)

maybe, with 3 averages, looking for restests on all 3 would be too many signals.
write up some rules to do what you really want.
 
I am building a study that uses some sort of rolling context window to measure local mins and maxs to determine trends. I have not figured out how to implement a context window correctly. ToS isn't throwing any errors, it just doesn't print anything on the indicator. The code below does print certain conditions, just without the context window. Does anyone know how to implement this?


Code:
declare lower;

input overBought = 80;
input overSold = 20;
input KPeriod = 10;
input DPeriod = 10;
input priceH = high;
input priceL = low;
input priceC = close;
input averageType = AverageType.SIMPLE;
input showBreakoutSignals = yes;
input lookbackWindow = 50;  # Lookback window for trend detection

# Calculate FastK, SlowK, and SlowD
def highK = Highest(priceH, KPeriod);
def lowK = Lowest(priceL, KPeriod);
def FastK = 100 * (priceC - lowK) / (highK - lowK);
def SlowK = MovingAverage(averageType, FastK, 3);  # 3-period moving average of FastK
def SlowD = MovingAverage(averageType, SlowK, DPeriod);  # DPeriod moving average of SlowK

# Plot SlowK and SlowD
plot SlowKPlot = SlowK;
SlowKPlot.SetDefaultColor(GetColor(1));
plot SlowDPlot = SlowD;
SlowDPlot.SetDefaultColor(GetColor(5));

# Overbought and Oversold lines
plot OverBoughtLine = overBought;
OverBoughtLine.SetDefaultColor(Color.RED);
OverBoughtLine.SetStyle(Curve.FIRM);
OverBoughtLine.SetLineWeight(1);
plot OverSoldLine = overSold;
OverSoldLine.SetDefaultColor(Color.GREEN);
OverSoldLine.SetStyle(Curve.FIRM);
OverSoldLine.SetLineWeight(1);

# Local highs and lows for SlowD
def isLocalHigh = SlowD > SlowD[1] and SlowD > SlowD[-1];
def isLocalLow = SlowD < SlowD[1] and SlowD < SlowD[-1];

# Filtered local highs and lows based on SlowD value
def filteredLocalHigh = isLocalHigh and SlowD >= 60;
def filteredLocalLow = isLocalLow and SlowD <= 30;

# Track the last three filtered local highs and lows
def lastFilteredHigh = if filteredLocalHigh then SlowD else lastFilteredHigh[1];
def secondLastFilteredHigh = if filteredLocalHigh then lastFilteredHigh[1] else secondLastFilteredHigh[1];
def thirdLastFilteredHigh = if filteredLocalHigh then secondLastFilteredHigh[1] else thirdLastFilteredHigh[1];

def lastFilteredLow = if filteredLocalLow then SlowD else lastFilteredLow[1];
def secondLastFilteredLow = if filteredLocalLow then lastFilteredLow[1] else secondLastFilteredLow[1];
def thirdLastFilteredLow = if filteredLocalLow then secondLastFilteredLow[1] else thirdLastFilteredLow[1];

# Breakout conditions
def upBreakout = SlowK crosses above overSold;
def downBreakout = SlowK crosses below overBought;

# Conditions for white dots (improved logic)
def downBreakoutDotCondition = downBreakout and SlowD < Min(lastFilteredHigh, secondLastFilteredHigh) and !IsNaN(lastFilteredHigh) and !IsNaN(secondLastFilteredHigh);
def upBreakoutDotCondition = upBreakout and SlowD > Max(lastFilteredLow, secondLastFilteredLow) and !IsNaN(lastFilteredLow) and !IsNaN(secondLastFilteredLow);

# Check for presence of any colored dot
def hasColoredDot = filteredLocalHigh or filteredLocalLow or upBreakoutDotCondition or downBreakoutDotCondition;

# Plot breakout signals only when there's a colored dot
plot UpSignal = if showBreakoutSignals and upBreakout and hasColoredDot then overSold else Double.NaN;
UpSignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
UpSignal.SetDefaultColor(Color.UPTICK);
UpSignal.SetLineWeight(2);

plot DownSignal = if showBreakoutSignals and downBreakout and hasColoredDot then overBought else Double.NaN;
DownSignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
DownSignal.SetDefaultColor(Color.DOWNTICK);
DownSignal.SetLineWeight(2);

# Plot white dots
plot UpBreakoutDot = if upBreakoutDotCondition then SlowD else Double.NaN;
UpBreakoutDot.SetPaintingStrategy(PaintingStrategy.POINTS);
UpBreakoutDot.SetDefaultColor(Color.WHITE);
UpBreakoutDot.SetLineWeight(3);

plot DownBreakoutDot = if downBreakoutDotCondition then SlowD else Double.NaN;
DownBreakoutDot.SetPaintingStrategy(PaintingStrategy.POINTS);
DownBreakoutDot.SetDefaultColor(Color.WHITE);
DownBreakoutDot.SetLineWeight(3);

# Plot filtered local highs and lows (for reference)
plot LocalHigh = if filteredLocalHigh then SlowD else Double.NaN;
LocalHigh.SetPaintingStrategy(PaintingStrategy.POINTS);
LocalHigh.SetDefaultColor(Color.BLUE);
LocalHigh.SetLineWeight(3);

plot LocalLow = if filteredLocalLow then SlowD else Double.NaN;
LocalLow.SetPaintingStrategy(PaintingStrategy.POINTS);
LocalLow.SetDefaultColor(Color.YELLOW);
LocalLow.SetLineWeight(3);
sorry, no idea what you are asking for.
you are using words that have no meaning.
what is a context window? what do you want to see and where? could put a bubble somewhere.
what is local min and max? what do you really mean?
 
reply to 286


rsi() error,
def rsi = RSI(price, rsiLength);

go look at RSI() code and see what the inputs are
input length = 14;
input over_Bought = 70;
input over_Sold = 30;
input price = close;
input averageType = AverageType.WILDERS;
input showBreakoutSignals = no;

you have the parameters in wrong sequence.
can get around that by using the parameter names.

def rsi = RSI(price = price, length = rsiLength);


i made this a lower study for you to experiment with.
before you use this as a scan, choose which plot you want to keep and disable the others.

Code:
#chat286_ttm_sqz_scan

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

# TTM Squeeze Scanner
# Original code by TSL 11.13.2019
# Modified into a scanner by @MerryDay 8/2022

declare lower;

input price = close;
input nK = 1.5;       # Multiplier for Keltner Channels
input nBB = 2.0;      # Multiplier for Bollinger Bands
input alertLine = 1.0;
input maLength = 50;  # Moving average length
input rsiLength = 14; # RSI length for filtering
input rsiOverbought = 70; # RSI overbought level
input rsiOversold = 30;   # RSI oversold level
input volumeMultiplier = 1.5; # Multiplier for detecting volume spikes

# Directly using 20 as the literal constant where required
def squeezeHistogram = TTM_Squeeze(price, 20, nK, nBB, alertLine).Histogram;  # Hardcoded 20

# Calculate the moving average
def movingAverage = Average(price, maLength);

# Calculate the RSI
# parameters in wrong sequence
#def rsi = RSI(price, rsiLength);
# add parameter names
def rsi = RSI(price = price, length = rsiLength);

# Detect significant volume spikes using a literal constant for length
def volumeSpike = volume > Average(volume, 20) * volumeMultiplier;  # Hardcoded 20

# Determine squeeze stages based on histogram behavior
def squeezeStages;
if squeezeHistogram >= 0
then {
    if squeezeHistogram > squeezeHistogram[1]
    then {
        squeezeStages = 1;  # Cyan: Positive increasing (potential breakout)
    } else {
        squeezeStages = 2;  # Blue: Positive decreasing (potential weakening)
    }
} else {
    if squeezeHistogram < squeezeHistogram[1]
    then {
        squeezeStages = 3;  # Red: Negative decreasing (potential reversal)
    } else {
        squeezeStages = 4;  # Yellow: Negative increasing (potential weakening)
    }
}

# Scan for transition from Yellow to Cyan Histogram
plot scan_YellowToCyan = squeezeStages[1] == 4 and squeezeStages == 1;

# Scan for transition from Blue to Red Histogram
plot scan_BlueToRed = squeezeStages[1] == 2 and squeezeStages == 3;

### Breakout Scan
# Detect breakouts from a squeeze with price above moving average and volume spike
def priceBreakout = price > Highest(price, 20);  # Literal constant of 20 used
plot scan_Breakout =
    squeezeStages == 1 and  # Cyan stage indicates potential breakout
    priceBreakout and
    price > movingAverage and
    volumeSpike;

### Separate Reversal Signal Scans
# Detect Bullish Reversals
plot scan_BullishReversal =
    squeezeStages == 3 and rsi < rsiOversold;  # Red stage with RSI Oversold

# Detect Bearish Reversals
plot scan_BearishReversal =
    squeezeStages == 4 and rsi > rsiOverbought;  # Yellow stage with RSI Overbought
#
@halcyonguy thank you .
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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