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

MerryDay

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

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

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

The above video, explains the basics of providing good specifications to AI which results in better scripts.
AOzhl05.png
 
Last edited:
View attachment 23893
Entry buy signals triggered by HMA 10 20 cross up and both with positive slope up.

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

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

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

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

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

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

reply to 352

here is something to experiment with
it plots arrows when all the average and macd signals happen.
the problem with looking for several signals on the same bar, is that they rarely will all happen.

if you want to look for several signals happening within x bars of the average line crossing, that will be another study.


Code:
#macd_hull_ashi_signals

#https://usethinkscript.com/threads/macd-and-hull-ma-indicators-for-signals.20391/
#MACD and Hull MA indicators for signals
#Dr. Dave  1/20
#1

# buy signals,
#   HMA 10 20 cross up and both with positive slope up.
#   This is confirmed by MACD above signal line and both at or above the zero line.

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

#Here is the script per ChatGPT to produce this:



# Pseudo-code for Buy and Sell signals based on your conditions

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

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

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

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







#-------------------

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

#-------------------
# avgs
#https://toslc.thinkorswim.com/center/reference/thinkScript/Constants/AverageType
#input avg1_type = AverageType.Simple;
#input avg1_type = AverageType.exponential;
#input avg1_type = AverageType.hull;
#input avg1_type = AverageType.weighted;
#input avg1_type = AverageType.wilders;

def data = close;
def stk_up = data > data[1];
def stk_dwn = data < data[1];


input avg1_type = AverageType.hull;
input avg1_length = 10;
def avg1 = MovingAverage(avg1_type, data, avg1_length );

input avg2_type = AverageType.hull;
input avg2_length = 20;
def avg2 = MovingAverage(avg2_type, data, avg2_length );

# long -  HMA 10 20 cross up and both with positive slope up.
# crossing averages is the driver
def xup = avg1 crosses above avg2;
def xdwn = avg1 crosses below avg2;

def avg1_slope_up = avg1 > avg1[1];
def avg1_slope_dwn = avg1 < avg1[1];
def avg2_slope_up = avg2 > avg2[1];
def avg2_slope_dwn = avg2 < avg2[1];


input show_avg_lines = yes;
plot zavg1 = if show_avg_lines then avg1 else na;
plot zavg2 = if show_avg_lines then avg2 else na;
zavg1.SetDefaultColor(Color.cyan);
zavg1.setlineweight(1);
zavg1.hidebubble();
zavg2.SetDefaultColor(Color.yellow);
zavg2.setlineweight(1);
zavg2.hidebubble();

def avg_long_enter = xup and avg1_slope_up and avg2_slope_up;
def avg_short_enter = xdwn and avg1_slope_dwn and avg2_slope_dwn;


#-------------------
# macd
#declare lower;
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;
input averageType = AverageType.EXPONENTIAL;
input showBreakoutSignals = no;
def Value = MovingAverage(averageType, close, fastLength) - MovingAverage(averageType, close, slowLength);
def Avg = MovingAverage(averageType, Value, MACDLength);
def Diff = Value - Avg;
def ZeroLine = 0;
def UpSignal = if Diff crosses above ZeroLine then ZeroLine else Double.NaN;
def DownSignal = if Diff crosses below ZeroLine then ZeroLine else Double.NaN;


# long - MACD above signal line and both at or above the zero line.  value > avg
def m_valueup = value > avg;
def m_value_above0 = value >= 0;
# short - MACD below signal line and both at or below the zero line.  value < avg
def m_valuedwn = value < avg;
def m_value_below0 = value <= 0;

def macd_long_enter = m_valueup and m_value_above0;
def macd_short_enter = m_valuedwn and m_value_below0;


#---------------------

# arrows for entering trade .  green up for long , green down for short
input show_avg_enter = yes;
plot zavg_le = show_avg_enter and avg_long_enter and macd_long_enter;
#zavg_le.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_up);
zavg_le.SetPaintingStrategy(PaintingStrategy.boolean_ARROW_UP);
zavg_le.SetDefaultColor(Color.cyan);
zavg_le.setlineweight(2);
zavg_le.hidebubble();

plot zavg_se = show_avg_enter and avg_short_enter and macd_short_enter;
#zavg_se.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_down);
zavg_se.SetPaintingStrategy(PaintingStrategy.boolean_ARROW_down);
zavg_se.SetDefaultColor(Color.yellow);
zavg_se.setlineweight(2);
zavg_se.hidebubble();
#
 

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

Copied and pasted after removing the intro that wasn't strategy code. It did change the color of my HMA and gave me a few up arrows and one down arrow on my chart, but nothing that was terribly productive.
 
Copied and pasted after removing the intro that wasn't strategy code. It did change the color of my HMA and gave me a few up arrows and one down arrow on my chart, but nothing that was terribly productive.
Correct. Moving averages and oscillators are good for reviewing trend, ranges, and spans.
Not so much for entry or exit signals.

Read more:
https://usethinkscript.com/threads/lagging-indicator-accuracy-in-thinkorswim.15624/
https://usethinkscript.com/threads/how-to-read-an-oscillator-in-thinkorswim.11497/
 
Hello,
I’m working on a Multi-Timeframe Smoothed Heikin Ashi (MTF SHA) Indicator in ThinkScript, and I’ve encountered an issue where higher timeframe values (e.g., Monthly) change when switching to a lower timeframe (e.g., 4H, 1H, etc.).


Expected Behavior:
  • Monthly Heikin Ashi state should remain the same when switching to lower timeframes.


Code:
declare lower;

input _len = 8;
def _len2 = _len;
# Aggregation periods
def ag_month = AggregationPeriod.MONTH;
def ag_week = AggregationPeriod.Week;
def ag_day = AggregationPeriod.Day;
def ag_4H = AggregationPeriod.FOUR_HOURS;
def ag_1H = AggregationPeriod.HOUR;

### **MONTHLY**

def _open_month = open(period = ag_month);
def _close_month = close(period = ag_month);
def _high_month = high(period = ag_month);
def _low_month = low(period = ag_month);

# First Smoothing
def _smooth_open_month = compoundValue(1, ExpAverage(_open_month, _len), _open_month);
def _smooth_close_month = compoundValue(1, ExpAverage(_close_month, _len), _close_month);
def _smooth_high_month = compoundValue(1, ExpAverage(_high_month, _len), _high_month);
def _smooth_low_month = compoundValue(1, ExpAverage(_low_month, _len), _low_month);

# Calculate HA Values
def _haclose_month = (_smooth_open_month + _smooth_high_month + _smooth_low_month + _smooth_close_month) / 4;
def _haopen_month = CompoundValue(1, ( (_haopen_month[1] +  _haclose_month[1])/2.0), (_smooth_open_month + _smooth_close_month) / 2);

# Second Smoothing
def _final_open_month =  ExpAverage(_haopen_month, _len2);
def _final_close_month = ExpAverage(_haclose_month, _len2);

# Candle Size Analysis
def _candleSize_month = AbsValue(_final_close_month - _final_open_month);
def _prevCandleSize_month = _candleSize_month[1];

# Trend State
def _isBullish_month = _final_close_month > _final_open_month;
def _isBearish_month = _final_close_month < _final_open_month;
def _inBullishTrend_month = _isBullish_month and _isBullish_month[1];
def _inBearishTrend_month = _isBearish_month and _isBearish_month[1];

# Strong Trend Detection
def _isGrowingBull_month = _inBullishTrend_month ;
def _isGrowingBear_month = _inBearishTrend_month ;

def __Month_SHA8_state = if _isGrowingBull_month and _candleSize_month >= _prevCandleSize_month then 2
else if _isGrowingBear_month and  _candleSize_month >= _prevCandleSize_month then -2
else if _isGrowingBull_month and _candleSize_month < _prevCandleSize_month then 1
else if _isGrowingBear_month and _candleSize_month < _prevCandleSize_month then -1
else if _isGrowingBull_month and !_isGrowingBull_month[1] then 0.001
else -0.001
;

plot test = __Month_SHA8_state;
 
Last edited by a moderator:
I have tried to write a cycle prediction by averaging the last 14 days of cycle date and then (during trading time) plot the predicted cycle across the whole day prior to real time date to see or try to predict price action direction (can't get it to full day- HELP from the coders) . As you increase the time frame the deviation is sometimes wider than let's say the 1minute vs the 30 minute (just more data) the scripts are 5 minute vs 30 minute. The green dotted line will not show up next day until 930 EST.
Code:
# Predicted Cycle Based on Last X Days
input length = 14; # Number of days to average
input customTimeframe = {default "1 Minute", "5 Minute", "15 Minute", "30 Minute"}; # Timeframe options
input highlightDeviations = yes; # Option to display deviation plots

# Define timeframes based on selection
def aggregationPeriod = if customTimeframe == customTimeframe."1 Minute" then AggregationPeriod.MIN
                        else if customTimeframe == customTimeframe."5 Minute" then AggregationPeriod.FIVE_MIN
                        else if customTimeframe == customTimeframe."15 Minute" then AggregationPeriod.FIFTEEN_MIN
                        else AggregationPeriod.THIRTY_MIN;

# Get close price for selected aggregation period
def closePrice = close(period = aggregationPeriod);

# Average cycle calculation for each bar in the session over the past `length` days
def cycleSum = fold i = 1 to length + 1 with sum = 0 do sum + GetValue(closePrice, i);
def cycleAverage = cycleSum / length;

# Predicted cycle for today (Using the average cycle from the past 14 days)
def predictedCycleTodayCalc = cycleAverage;  # Renamed to avoid conflict

# Predicted Cycle for Tomorrow - Extending the pattern (using the average cycle)
def predictedCycleTomorrowCalc = predictedCycleTodayCalc[1]; # Use the pattern from the previous day

# Plots
plot TodayPrice = closePrice;
TodayPrice.SetDefaultColor(Color.ORANGE);
TodayPrice.SetLineWeight(2);

plot PredictedCycleToday = predictedCycleTodayCalc;
PredictedCycleToday.SetDefaultColor(Color.CYAN);
PredictedCycleToday.SetLineWeight(2);

# Deviation Plot (Optional) - Removed isRegularSession condition to allow plotting outside regular hours
def deviation = AbsValue(closePrice - predictedCycleTodayCalc);
plot DeviationPlot = if highlightDeviations then deviation else Double.NaN;
DeviationPlot.SetDefaultColor(Color.MAGENTA);
DeviationPlot.SetStyle(Curve.FIRM);
DeviationPlot.SetLineWeight(1);

# Forward Projection for Entire Day (Separate variable to avoid conflicts) - Removed isRegularSession condition
def predictedCycleForward = predictedCycleTomorrowCalc;
plot ForwardCycle = predictedCycleForward;
ForwardCycle.SetDefaultColor(Color.GREEN);
ForwardCycle.SetStyle(Curve.SHORT_DASH);
ForwardCycle.SetLineWeight(1);

# Add Labels for Timeframe Selection
AddLabel(yes, "Timeframe: " + if customTimeframe == customTimeframe."1 Minute" then "1 Min"
                      else if customTimeframe == customTimeframe."5 Minute" then "5 Min"
                      else if customTimeframe == customTimeframe."15 Minute" then "15 Min"
                      else "30 Min", Color.YELLOW);



with 500 units forward works better in 5 minute and 15
Code:
# Predicted Cycle Based on Last X Days
input length = 14; # Number of days to average
input customTimeframe = {default "1 Minute", "5 Minute", "15 Minute", "30 Minute"}; # Timeframe options
input highlightDeviations = yes; # Option to display deviation plots
input forecastBars = 500; # Number of future bars to project

# Define timeframes based on selection
def aggregationPeriod = if customTimeframe == customTimeframe."1 Minute" then AggregationPeriod.MIN
                        else if customTimeframe == customTimeframe."5 Minute" then AggregationPeriod.FIVE_MIN
                        else if customTimeframe == customTimeframe."15 Minute" then AggregationPeriod.FIFTEEN_MIN
                        else AggregationPeriod.THIRTY_MIN;

# Get close price for selected aggregation period
def closePrice = close(period = aggregationPeriod);

# Average cycle calculation for each bar in the session over the past `length` days
def cycleSum = fold i = 1 to length + 1 with sum = 0 do sum + GetValue(closePrice, i);
def cycleAverage = cycleSum / length;

# Predicted cycle for today (Using the average cycle from the past 14 days)
def predictedCycleTodayCalc = cycleAverage;  # Renamed to avoid conflict

# Predicted Cycle for Tomorrow - Extending the pattern (using the average cycle)
def predictedCycleTomorrowCalc = predictedCycleTodayCalc[1]; # Use the pattern from the previous day

# Plots
plot TodayPrice = closePrice;
TodayPrice.SetDefaultColor(Color.ORANGE);
TodayPrice.SetLineWeight(2);

plot PredictedCycleToday = predictedCycleTodayCalc;
PredictedCycleToday.SetDefaultColor(Color.CYAN);
PredictedCycleToday.SetLineWeight(2);

# Deviation Plot (Optional) - Removed isRegularSession condition to allow plotting outside regular hours
def deviation = AbsValue(closePrice - predictedCycleTodayCalc);
plot DeviationPlot = if highlightDeviations then deviation else Double.NaN;
DeviationPlot.SetDefaultColor(Color.MAGENTA);
DeviationPlot.SetStyle(Curve.FIRM);
DeviationPlot.SetLineWeight(1);

# Forward Projection for Entire Day (Separate variable to avoid conflicts) - Removed isRegularSession condition
def predictedCycleForwardCalc = predictedCycleTomorrowCalc;

# Project the predicted cycle forward by `forecastBars` bars
def forwardCycleProjection = if (BarNumber() <= BarNumber()[1] + forecastBars) then predictedCycleForwardCalc else Double.NaN;

plot ForwardCycleProjection1 = forwardCycleProjection;
ForwardCycleProjection1.SetDefaultColor(Color.GREEN);
ForwardCycleProjection1.SetStyle(Curve.SHORT_DASH);
ForwardCycleProjection1.SetLineWeight(1);

# Add Labels for Timeframe Selection
AddLabel(yes, "Timeframe: " + (if customTimeframe == customTimeframe."1 Minute" then "1 Min"
                               else if customTimeframe == customTimeframe."5 Minute" then "5 Min"
                               else if customTimeframe == customTimeframe."15 Minute" then "15 Min"
                               else "30 Min"), Color.YELLOW);
 
Last edited by a moderator:
I wrote a rough draft trying to identify gamma swings and really am not a coder or do I know everything that is available to chart from the TOS platform. Can someone take a look and see if this is relevant. https://tos.mx/!86KROEtj (The chart below I had to tweek the variables and exclude the IV crush)
oQfgVNN.png


declare lower;

input length = 14; # Lookback period for gamma swing
input threshold = 2.0;
input emaLength = 21;
input ivLookback = 10; # Lookback for IV crush
input oiThreshold = 10000; # Minimum open interest filter

# Price acceleration calculation
def priceChange = close - close[1];
def priceAccel = priceChange - priceChange[1];

# Standard deviation for volatility measurement
def avgAccel = Average(priceAccel, length);
def stdDev = StDev(priceAccel, length);

# 21 EMA for trend direction
def ema21 = ExpAverage(close, emaLength);

# Gamma swing condition
def gammaSwing = if AbsValue(priceAccel) > (avgAccel + threshold * stdDev) then priceAccel else Double.NaN;

# Directional filter
def bullish = close > ema21 and gammaSwing > 0;
def bearish = close < ema21 and gammaSwing < 0;

# Implied Volatility (IV) Crush Detection
def IV = imp_volatility;
def ivChange = IV - IV[1];
def avgIVChange = Average(ivChange, ivLookback);
def IV_Crush = ivChange < 0;

# Open Interest Confirmation
def OI = open_interest;
def highOI = OI > oiThreshold;

# Final conditions for confirmed signals
def confirmedBullish = bullish and IV_Crush and highOI;
def confirmedBearish = bearish and IV_Crush and highOI;

# Plot signals
plot BullishGammaSwing = if confirmedBullish then gammaSwing else Double.NaN;
BullishGammaSwing.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullishGammaSwing.SetDefaultColor(Color.GREEN);
BullishGammaSwing.SetLineWeight(2);

plot BearishGammaSwing = if confirmedBearish then gammaSwing else Double.NaN;
BearishGammaSwing.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearishGammaSwing.SetDefaultColor(Color.RED);
BearishGammaSwing.SetLineWeight(2);
 
Last edited by a moderator:
I have tried to write a cycle prediction by averaging the last 14 days of cycle date and then (during trading time) plot the predicted cycle across the whole day prior to real time date to see or try to predict price action direction (can't get it to full day- HELP from the coders) . As you increase the time frame the deviation is sometimes wider than let's say the 1minute vs the 30 minute (just more data) the scripts are 5 minute vs 30 minute. The green dotted line will not show up next day until 930 EST.
Code:
# Predicted Cycle Based on Last X Days
input length = 14; # Number of days to average
input customTimeframe = {default "1 Minute", "5 Minute", "15 Minute", "30 Minute"}; # Timeframe options
input highlightDeviations = yes; # Option to display deviation plots

# Define timeframes based on selection
def aggregationPeriod = if customTimeframe == customTimeframe."1 Minute" then AggregationPeriod.MIN
                        else if customTimeframe == customTimeframe."5 Minute" then AggregationPeriod.FIVE_MIN
                        else if customTimeframe == customTimeframe."15 Minute" then AggregationPeriod.FIFTEEN_MIN
                        else AggregationPeriod.THIRTY_MIN;

# Get close price for selected aggregation period
def closePrice = close(period = aggregationPeriod);

# Average cycle calculation for each bar in the session over the past `length` days
def cycleSum = fold i = 1 to length + 1 with sum = 0 do sum + GetValue(closePrice, i);
def cycleAverage = cycleSum / length;

# Predicted cycle for today (Using the average cycle from the past 14 days)
def predictedCycleTodayCalc = cycleAverage;  # Renamed to avoid conflict

# Predicted Cycle for Tomorrow - Extending the pattern (using the average cycle)
def predictedCycleTomorrowCalc = predictedCycleTodayCalc[1]; # Use the pattern from the previous day

# Plots
plot TodayPrice = closePrice;
TodayPrice.SetDefaultColor(Color.ORANGE);
TodayPrice.SetLineWeight(2);

plot PredictedCycleToday = predictedCycleTodayCalc;
PredictedCycleToday.SetDefaultColor(Color.CYAN);
PredictedCycleToday.SetLineWeight(2);

# Deviation Plot (Optional) - Removed isRegularSession condition to allow plotting outside regular hours
def deviation = AbsValue(closePrice - predictedCycleTodayCalc);
plot DeviationPlot = if highlightDeviations then deviation else Double.NaN;
DeviationPlot.SetDefaultColor(Color.MAGENTA);
DeviationPlot.SetStyle(Curve.FIRM);
DeviationPlot.SetLineWeight(1);

# Forward Projection for Entire Day (Separate variable to avoid conflicts) - Removed isRegularSession condition
def predictedCycleForward = predictedCycleTomorrowCalc;
plot ForwardCycle = predictedCycleForward;
ForwardCycle.SetDefaultColor(Color.GREEN);
ForwardCycle.SetStyle(Curve.SHORT_DASH);
ForwardCycle.SetLineWeight(1);

# Add Labels for Timeframe Selection
AddLabel(yes, "Timeframe: " + if customTimeframe == customTimeframe."1 Minute" then "1 Min"
                      else if customTimeframe == customTimeframe."5 Minute" then "5 Min"
                      else if customTimeframe == customTimeframe."15 Minute" then "15 Min"
                      else "30 Min", Color.YELLOW);



with 500 units forward works better in 5 minute and 15
Code:
# Predicted Cycle Based on Last X Days
input length = 14; # Number of days to average
input customTimeframe = {default "1 Minute", "5 Minute", "15 Minute", "30 Minute"}; # Timeframe options
input highlightDeviations = yes; # Option to display deviation plots
input forecastBars = 500; # Number of future bars to project

# Define timeframes based on selection
def aggregationPeriod = if customTimeframe == customTimeframe."1 Minute" then AggregationPeriod.MIN
                        else if customTimeframe == customTimeframe."5 Minute" then AggregationPeriod.FIVE_MIN
                        else if customTimeframe == customTimeframe."15 Minute" then AggregationPeriod.FIFTEEN_MIN
                        else AggregationPeriod.THIRTY_MIN;

# Get close price for selected aggregation period
def closePrice = close(period = aggregationPeriod);

# Average cycle calculation for each bar in the session over the past `length` days
def cycleSum = fold i = 1 to length + 1 with sum = 0 do sum + GetValue(closePrice, i);
def cycleAverage = cycleSum / length;

# Predicted cycle for today (Using the average cycle from the past 14 days)
def predictedCycleTodayCalc = cycleAverage;  # Renamed to avoid conflict

# Predicted Cycle for Tomorrow - Extending the pattern (using the average cycle)
def predictedCycleTomorrowCalc = predictedCycleTodayCalc[1]; # Use the pattern from the previous day

# Plots
plot TodayPrice = closePrice;
TodayPrice.SetDefaultColor(Color.ORANGE);
TodayPrice.SetLineWeight(2);

plot PredictedCycleToday = predictedCycleTodayCalc;
PredictedCycleToday.SetDefaultColor(Color.CYAN);
PredictedCycleToday.SetLineWeight(2);

# Deviation Plot (Optional) - Removed isRegularSession condition to allow plotting outside regular hours
def deviation = AbsValue(closePrice - predictedCycleTodayCalc);
plot DeviationPlot = if highlightDeviations then deviation else Double.NaN;
DeviationPlot.SetDefaultColor(Color.MAGENTA);
DeviationPlot.SetStyle(Curve.FIRM);
DeviationPlot.SetLineWeight(1);

# Forward Projection for Entire Day (Separate variable to avoid conflicts) - Removed isRegularSession condition
def predictedCycleForwardCalc = predictedCycleTomorrowCalc;

# Project the predicted cycle forward by `forecastBars` bars
def forwardCycleProjection = if (BarNumber() <= BarNumber()[1] + forecastBars) then predictedCycleForwardCalc else Double.NaN;

plot ForwardCycleProjection1 = forwardCycleProjection;
ForwardCycleProjection1.SetDefaultColor(Color.GREEN);
ForwardCycleProjection1.SetStyle(Curve.SHORT_DASH);
ForwardCycleProjection1.SetLineWeight(1);

# Add Labels for Timeframe Selection
AddLabel(yes, "Timeframe: " + (if customTimeframe == customTimeframe."1 Minute" then "1 Min"
                               else if customTimeframe == customTimeframe."5 Minute" then "5 Min"
                               else if customTimeframe == customTimeframe."15 Minute" then "15 Min"
                               else "30 Min"), Color.YELLOW);

reply to 367

what is the purpose to predict a future average line?
why not try to predict the close price?


maybe this will give you some ideas,
here is a study i made that extends 2 averages and shows where they would cross
https://usethinkscript.com/threads/rsi-prediction.8631/#post-83898
 
Last edited:
I wrote a rough draft trying to identify gamma swings and really am not a coder or do I know everything that is available to chart from the TOS platform. Can someone take a look and see if this is relevant. https://tos.mx/!86KROEtj (The chart below I had to tweek the variables and exclude the IV crush)


declare lower;

input length = 14; # Lookback period for gamma swing
input threshold = 2.0;
input emaLength = 21;
input ivLookback = 10; # Lookback for IV crush
input oiThreshold = 10000; # Minimum open interest filter

# Price acceleration calculation
def priceChange = close - close[1];
def priceAccel = priceChange - priceChange[1];

# Standard deviation for volatility measurement
def avgAccel = Average(priceAccel, length);
def stdDev = StDev(priceAccel, length);

# 21 EMA for trend direction
def ema21 = ExpAverage(close, emaLength);

# Gamma swing condition
def gammaSwing = if AbsValue(priceAccel) > (avgAccel + threshold * stdDev) then priceAccel else Double.NaN;

# Directional filter
def bullish = close > ema21 and gammaSwing > 0;
def bearish = close < ema21 and gammaSwing < 0;

# Implied Volatility (IV) Crush Detection
def IV = imp_volatility;
def ivChange = IV - IV[1];
def avgIVChange = Average(ivChange, ivLookback);
def IV_Crush = ivChange < 0;

# Open Interest Confirmation
def OI = open_interest;
def highOI = OI > oiThreshold;

# Final conditions for confirmed signals
def confirmedBullish = bullish and IV_Crush and highOI;
def confirmedBearish = bearish and IV_Crush and highOI;

# Plot signals
plot BullishGammaSwing = if confirmedBullish then gammaSwing else Double.NaN;
BullishGammaSwing.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BullishGammaSwing.SetDefaultColor(Color.GREEN);
BullishGammaSwing.SetLineWeight(2);

plot BearishGammaSwing = if confirmedBearish then gammaSwing else Double.NaN;
BearishGammaSwing.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
BearishGammaSwing.SetDefaultColor(Color.RED);
BearishGammaSwing.SetLineWeight(2);

reply to 368

sorry, i dont know what defines a gamma swing.
edit your post and describe it
 
Hello,
I’m working on a Multi-Timeframe Smoothed Heikin Ashi (MTF SHA) Indicator in ThinkScript, and I’ve encountered an issue where higher timeframe values (e.g., Monthly) change when switching to a lower timeframe (e.g., 4H, 1H, etc.).


Expected Behavior:
  • Monthly Heikin Ashi state should remain the same when switching to lower timeframes.


Code:
declare lower;

input _len = 8;
def _len2 = _len;
# Aggregation periods
def ag_month = AggregationPeriod.MONTH;
def ag_week = AggregationPeriod.Week;
def ag_day = AggregationPeriod.Day;
def ag_4H = AggregationPeriod.FOUR_HOURS;
def ag_1H = AggregationPeriod.HOUR;

### **MONTHLY**

def _open_month = open(period = ag_month);
def _close_month = close(period = ag_month);
def _high_month = high(period = ag_month);
def _low_month = low(period = ag_month);

# First Smoothing
def _smooth_open_month = compoundValue(1, ExpAverage(_open_month, _len), _open_month);
def _smooth_close_month = compoundValue(1, ExpAverage(_close_month, _len), _close_month);
def _smooth_high_month = compoundValue(1, ExpAverage(_high_month, _len), _high_month);
def _smooth_low_month = compoundValue(1, ExpAverage(_low_month, _len), _low_month);

# Calculate HA Values
def _haclose_month = (_smooth_open_month + _smooth_high_month + _smooth_low_month + _smooth_close_month) / 4;
def _haopen_month = CompoundValue(1, ( (_haopen_month[1] +  _haclose_month[1])/2.0), (_smooth_open_month + _smooth_close_month) / 2);

# Second Smoothing
def _final_open_month =  ExpAverage(_haopen_month, _len2);
def _final_close_month = ExpAverage(_haclose_month, _len2);

# Candle Size Analysis
def _candleSize_month = AbsValue(_final_close_month - _final_open_month);
def _prevCandleSize_month = _candleSize_month[1];

# Trend State
def _isBullish_month = _final_close_month > _final_open_month;
def _isBearish_month = _final_close_month < _final_open_month;
def _inBullishTrend_month = _isBullish_month and _isBullish_month[1];
def _inBearishTrend_month = _isBearish_month and _isBearish_month[1];

# Strong Trend Detection
def _isGrowingBull_month = _inBullishTrend_month ;
def _isGrowingBear_month = _inBearishTrend_month ;

def __Month_SHA8_state = if _isGrowingBull_month and _candleSize_month >= _prevCandleSize_month then 2
else if _isGrowingBear_month and  _candleSize_month >= _prevCandleSize_month then -2
else if _isGrowingBull_month and _candleSize_month < _prevCandleSize_month then 1
else if _isGrowingBear_month and _candleSize_month < _prevCandleSize_month then -1
else if _isGrowingBull_month and !_isGrowingBull_month[1] then 0.001
else -0.001
;

plot test = __Month_SHA8_state;

reply to 366

i don't have a good answer.
plots are similar , comparing 3yr day and 3yr week charts.
maybe strange things happen when the total time on chart is near the time of the quantity of mtf periods.
 
reply to 367

what is the purpose to predict a future average line?
why not try to predict the close price?


maybe this will give you some ideas,
here is a study i made that extends 2 averages and shows where they would cross
https://usethinkscript.com/threads/rsi-prediction.8631/#post-83898
I think personally predicting the average will have a smoothing out of volatility.
  • A single forward-predicted price can be highly sensitive to market fluctuations, outliers, or short-term noise.
  • A forward average price (e.g., moving average or weighted forecast) reduces erratic spikes and gives a more stable estimate of the trend.
Secondly, I think the average is a better way to handle or manage uncertainty.
  • The absolute predicted price is more prone to large deviations if the model miscalculates a particular point.
  • The forward average provides a range or expected trend, offering a probabilistic view instead of a single-point prediction.
 
reply to 368

sorry, i dont know what defines a gamma swing.
edit your post and describe it
A Gamma Swing refers to "large, rapid price movements caused by options market makers dynamically hedging their positions due to changes in gamma exposure. It occurs when dealers (market makers) aggressively hedge their options books, creating amplified price moves in the underlying stock." That is the text book version. Maybe better to describe what to look for.
  • Monitor Gamma Exposure (GEX) Data: Some platforms provide gamma exposure indicators. Since TOS does not, we have to look to open interest.
  • Look for Large Open Interest & Max Pain Levels: Price tends to pin to these levels.
  • Watch for Volatility Expansion & IV Drops: (IV crush?) This signals gamma-driven price swings.
  • Pay Attention to Dealer Positioning: (large blocks of volume?) If market makers are short gamma, expect wild swings.
 
I think personally predicting the average will have a smoothing out of volatility.
  • A single forward-predicted price can be highly sensitive to market fluctuations, outliers, or short-term noise.
  • A forward average price (e.g., moving average or weighted forecast) reduces erratic spikes and gives a more stable estimate of the trend.
Secondly, I think the average is a better way to handle or manage uncertainty.
  • The absolute predicted price is more prone to large deviations if the model miscalculates a particular point.
  • The forward average provides a range or expected trend, offering a probabilistic view instead of a single-point prediction.
maybe someone could apply this to your study, to develope a formula.
https://usethinkscript.com/threads/6th-order-polynomial-best-fit-for-thinkorswim.15196/#post-123924
 
Hello!

I am attempting to make a script which does the following:

  • When a 15 minute candle closes it will add 2 horizontal price markers across the full width of the chart (one at the top of the candle and one at the bottom candle)
  • It will also highlight the candle as yellow, and on the 5 minute time-frame all 3 candles will be highlighted yellow
  • After the next 15 minute candle closes it will remove the lines and highlights on the previous one and apply the same formula to the newly closed candle

This is what I currently have but it does not appear to be working, is anyone able to identify why?


Code:
declare upper;

# Define the 15-minute aggregation period
def lastHigh = high(period = AggregationPeriod.FIFTEEN_MIN)[1];
def lastLow = low(period = AggregationPeriod.FIFTEEN_MIN)[1];

# Identify the closing of a new 15-minute candle
def isNewBar = barNumber() != barNumber()[1] and SecondsTillTime(0930) == 0;

# Draw horizontal lines at the high and low of the last closed 15-min candle
plot TopLine = if isNewBar then lastHigh else Double.NaN;
plot BottomLine = if isNewBar then lastLow else Double.NaN;

TopLine.SetDefaultColor(Color.CYAN);
BottomLine.SetDefaultColor(Color.CYAN);
TopLine.SetStyle(Curve.SHORT_DASH);
BottomLine.SetStyle(Curve.SHORT_DASH);

# Highlight the most recent closed 15-minute candle
def isHighlight15 = isNewBar;
AssignPriceColor(if isHighlight15 then Color.YELLOW else Color.CURRENT);

# Highlight the corresponding 5-minute candles
input use5MinHighlight = yes;
def fiveMinBar = SecondsTillTime(0930) == 0;
def isHighlight5 = fiveMinBar and isHighlight15;

AssignPriceColor(if use5MinHighlight and isHighlight5 then Color.YELLOW else Color.CURRENT);

Thank you so much for your help!
 
Hello!

I am attempting to make a script which does the following:

  • When a 15 minute candle closes it will add 2 horizontal price markers across the full width of the chart (one at the top of the candle and one at the bottom candle)
  • It will also highlight the candle as yellow, and on the 5 minute time-frame all 3 candles will be highlighted yellow
  • After the next 15 minute candle closes it will remove the lines and highlights on the previous one and apply the same formula to the newly closed candle

This is what I currently have but it does not appear to be working, is anyone able to identify why?


Code:
declare upper;

# Define the 15-minute aggregation period
def lastHigh = high(period = AggregationPeriod.FIFTEEN_MIN)[1];
def lastLow = low(period = AggregationPeriod.FIFTEEN_MIN)[1];

# Identify the closing of a new 15-minute candle
def isNewBar = barNumber() != barNumber()[1] and SecondsTillTime(0930) == 0;

# Draw horizontal lines at the high and low of the last closed 15-min candle
plot TopLine = if isNewBar then lastHigh else Double.NaN;
plot BottomLine = if isNewBar then lastLow else Double.NaN;

TopLine.SetDefaultColor(Color.CYAN);
BottomLine.SetDefaultColor(Color.CYAN);
TopLine.SetStyle(Curve.SHORT_DASH);
BottomLine.SetStyle(Curve.SHORT_DASH);

# Highlight the most recent closed 15-minute candle
def isHighlight15 = isNewBar;
AssignPriceColor(if isHighlight15 then Color.YELLOW else Color.CURRENT);

# Highlight the corresponding 5-minute candles
input use5MinHighlight = yes;
def fiveMinBar = SecondsTillTime(0930) == 0;
def isHighlight5 = fiveMinBar and isHighlight15;

AssignPriceColor(if use5MinHighlight and isHighlight5 then Color.YELLOW else Color.CURRENT);

Thank you so much for your help!

reply to 373


hello and welcome

your method of finding a past bar is wrong.
the formula for isnewbar is wrong. it is never true.
def isNewBar = barNumber() != barNumber()[1] and SecondsTillTime(0930) == 0;

you can add a bubble to display values, to verify what is happening.

addchartbubble(1, low,
(barNumber() != barNumber()[1]) + "\n" +
(SecondsTillTime(0930) == 0) + "\n" +
isNewBar
, color.yellow, no);


(SecondsTillTime(0930) == 0)
this is only true on the first bar of the day

this is always false. which is strange because it should be always true
(barNumber() != barNumber()[1])

so isnewbar is always false

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

if things don't work, then simplify things
i would replace isnewbar,
def isnewbar = 1;
and see what happens

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

here is another test bubble

def bn = barnumber();
addchartbubble(1, low,
barNumber() + "\n" +
bn + "\n" +

(barNumber() != barNumber()[1]) + "\n" +
(bn != bn[1])
, color.yellow, no);


it displays the same numbers for the first 2 values,
and this is always true.
(bn != bn[1])

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


here is a new study,
. define an agg period. default is 15 min
. enter how many agg bars back to read data from. default is 1, for previous. (0 for current agg bar)
. can change the bar colors during the desired agg period. default is yellow

draws 2 horizontal lines, at the high and low, of the agg period.
. the lines are purple and yellow during the agg period.


Code:
#chat373_linesfrombar
#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-19#post-150335
# post 373

declare upper;

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

# Define the aggregation period
input agg = AggregationPeriod.FIFTEEN_MIN;

# how many agg bars, before lastbar, to read price levels from
input baroffset = 1;
def x = (!isnan(close(period=agg)[-baroffset]) and isnan(close(period=agg)[-(1+baroffset)]));

# read the high from the desired agg time period
def agghigh = if bn == 1 then na
 else if x then high(period = Agg)
 else 0;

def agghi = highestall(agghigh);

# read the low from the desired agg time period
def agglow = if bn == 1 then na
 else if x then low(period = Agg)
 else 0;

def agglo = highestall(agglow);

plot z1 = agghi;
z1.AssignValueColor(if x then color.yellow else color.magenta);
plot z2 = agglo;
z2.AssignValueColor(if x then color.yellow else color.magenta);


input change_bar_color = yes;
AssignPriceColor(if change_bar_color and x then Color.YELLOW else Color.CURRENT);

addlabel(1, "Agg Bar offset " + baroffset, color.yellow);


#-------------------
addchartbubble(0, low,
 barNumber() + "\n" +
 bn + "\n" +
 (barNumber() != barNumber()[1]) + "\n" +
 (bn != bn[1])
# (SecondsTillTime(0930) == 0) + "\n" 
, color.yellow, no);
#
 

Attachments

  • img1.JPG
    img1.JPG
    115.8 KB · Views: 56
Most people do not understand the limitations of current AI models. They're knowledge is not current and they're not fine tuned for specific coding tasks (thinkscripts for example). What people also don't understand is if you feed it information to learn, that could get you to your end result most of the time. AI won't do everything for you. You have to either have some knowledge of the task at hand or know where to get it.

Feed it documentation along with examples of what you're trying to accomplish. EXPLAIN that you don't want the same outcome but to use the example as an understanding of syntax. Doing that will get you so far. If you don't know where to go or what info to feed it, you're trying to run before you walk. Slow down and learn some stuff yourself.
 
Hi i am trying to get a label going that will display the volume during trading hours for the one minute chart.
if anyone can help me correct this as currently it displays the wrong volume
Code:
# Get the current time in seconds from midnight (00:00)
def rawTime = SecondsFromTime(0);

# Define the start and end of the regular market session (9:30 AM to 4:00 PM EST)
def marketOpen = 34200;  # 9:30 AM EST = 34200 seconds from midnight
def marketClose = 57600;  # 4:00 PM EST = 57600 seconds from midnight

# Define regular session volume calculation (9:30 AM to 4:00 PM EST)
def regularSessionVolume = if rawTime >= marketOpen and rawTime < marketClose then volume else 0;

# Calculate the total volume for the entire day, including pre-market, regular, and post-market
def totalVolume = CompoundValue(1, if IsNaN(totalVolume[1]) then volume else totalVolume[1] + volume, 0);

# After-Market Volume: Subtract regular session volume from total volume (after 4:00 PM EST)
def afterMarketVolume = if rawTime >= marketClose then totalVolume - regularSessionVolume else 0;

# Display the total volume, regular session volume, and after-market volume
AddLabel(yes, "Total Volume: " + totalVolume, Color.GREEN);
AddLabel(yes, "Regular Session Volume: " + regularSessionVolume, Color.RED);
AddLabel(yes, "After-Market Volume: " + afterMarketVolume, Color.ORANGE);
1739401326141.png
 
Hi i am trying to get a label going that will display the volume during trading hours for the one minute chart.
if anyone can help me correct this as currently it displays the wrong volume
Code:
# Get the current time in seconds from midnight (00:00)
def rawTime = SecondsFromTime(0);

# Define the start and end of the regular market session (9:30 AM to 4:00 PM EST)
def marketOpen = 34200;  # 9:30 AM EST = 34200 seconds from midnight
def marketClose = 57600;  # 4:00 PM EST = 57600 seconds from midnight

# Define regular session volume calculation (9:30 AM to 4:00 PM EST)
def regularSessionVolume = if rawTime >= marketOpen and rawTime < marketClose then volume else 0;

# Calculate the total volume for the entire day, including pre-market, regular, and post-market
def totalVolume = CompoundValue(1, if IsNaN(totalVolume[1]) then volume else totalVolume[1] + volume, 0);

# After-Market Volume: Subtract regular session volume from total volume (after 4:00 PM EST)
def afterMarketVolume = if rawTime >= marketClose then totalVolume - regularSessionVolume else 0;

# Display the total volume, regular session volume, and after-market volume
AddLabel(yes, "Total Volume: " + totalVolume, Color.GREEN);
AddLabel(yes, "Regular Session Volume: " + regularSessionVolume, Color.RED);
AddLabel(yes, "After-Market Volume: " + afterMarketVolume, Color.ORANGE);

reply to #376

try this to read total volume of ,
normal day , and pre/post market

Code:
#labels_volume_totals
#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-19#post-150700

def v = volume;
def start = 0930;
def end = 1600;
def daytime = if secondsfromTime(start) >= 0 and secondstillTime(end) > 0 then 1 else 0;

def pre = if secondsfromTime(0) >= 0 and secondstillTime(start) > 0 then 1 else 0;
def post = if secondsfromTime(end) >= 0 and secondstillTime(2359) >= 0 then 1 else 0;

def startbar = (secondsfromTime(start) == 0);
def endbar = (secondsfromTime(end) == 0);

def regularSessionVolume = if !daytime[1] and daytime then v
 else if daytime then regularSessionVolume[1] + v
 else regularSessionVolume[1];

# pre and post times
def afterMarketVolume =
  if !post[1] and post then v
  else if post then  afterMarketVolume[1] + v
    else if !pre[1] and pre then v
    else if pre then afterMarketVolume[1] + v
      else afterMarketVolume[1];

def totalVolume = regularSessionVolume + afterMarketVolume;


#addverticalline(pre ," pre ",color.cyan);
#addverticalline(daytime ,"--",color.yellow);
#addverticalline(post ," post ",color.magenta);


# Display the total volume, regular session volume, and after-market volume
AddLabel(yes, "Total Volume: " + totalVolume, Color.GREEN);
AddLabel(yes, "Regular Session Volume: " + regularSessionVolume, Color.RED);
AddLabel(yes, "After-Market Volume: " + afterMarketVolume, Color.ORANGE);
#
 

Attachments

  • Capture.JPG
    Capture.JPG
    22.3 KB · Views: 22
Last edited:
Hi everyone,

I've been slowly working on this conditional order strategy for a few months now. I have limited experience with thinkscript, so I've been prompting AI software...dun, dunn, DUNNNN. Needless to say, I need some help from real organic intelligence.

I trade on a 5-minute time frame, in a momentum fashion. The strategy starts with taking a buy or sell after the first 5-minute bar of the day. This depends upon a bullish (buy signal executes) or bearish (sell signal executes) candle - at the open of the second 5-minute candle (0935). This part of my strategy has been working properly.

I set a stationary stop loss at 5% of the 14 day ATR based off of the opening price of the second candle. The goal is to sell or buy back the shares if the price reverses and meets or exceeds the stop loss. Otherwise, I let the trade run to the end of the day to close out before the closing bell to avoid overnight market fluctuation.

For example --- If the first 5-minute candle is bullish, my buy signal triggers to execute a set number of shares, let's say 3 shares, at the open of the second 5-minute candle. This triggers a "sell conditional order" to place a stationary stop loss at 5% of the 14 day ATR. I want it to trigger when the low of the 5 minute candles in the rest of the trading day are at or below the stop loss to close out and sell my 3 shares (making it a loss for the day). IF the trend continues in my favor, I have a final conditional sell signal to exit/sell the shares during the last minute of trading. I place the orders as a First triggers OCO set up. With a "buy/sell/sell" and a "sell/buy/buy" order placed each morning so I take one trade per day.

The problem lies within the stop loss triggering code --- this stop loss conditional order (set to trigger "if true") will be executed prematurely, usually within the first few seconds after the buy or sell signal.

Here is the script; any advice would be greatly appreciated. I'm a Dad of three young kids and this seems like the best way to trade for me at the time - this strategy was based on some financial literature I read - putting it into a real, semi-automated strategy is a whole other animal...

Stop Loss (Sell to Cover) Script:
Code:
# === Bullish Stop-Loss Conditional Script for Regular Trading Hours ===

# Define regular trading hours (RTH)
def RTHStart = 0930; # 9:30 AM ET
def RTHEnd = 1600;  # 4:00 PM ET

# Define session boundaries for RTH
def inRTHSession = SecondsFromTime(RTHStart) >= 0 and SecondsTillTime(RTHEnd) > 0;

# Determine if it is the second candle of the day
def isSecondCandle = SecondsFromTime(0935) == 0;

# Calculate the 14-day ATR using daily candles
def dailyATR14 = Average(TrueRange(high(period = AggregationPeriod.DAY),
                                   close(period = AggregationPeriod.DAY),
                                   low(period = AggregationPeriod.DAY)), 14);

# Calculate the fixed stop-loss level (5% of ATR)
input stopLossPercent = 0.05;  # 5%
def stopLossValue = dailyATR14 * stopLossPercent;

# Detect the opening price of the second candle
rec secondCandleOpen = if isSecondCandle then open else secondCandleOpen[1];

# Set the stop-loss level for long positions
rec buyStopLoss = if isSecondCandle then secondCandleOpen - stopLossValue else buyStopLoss[1];

# Plot the stop-loss line during RTH
plot StopLossLine = if inRTHSession and !IsNaN(buyStopLoss)
                    then buyStopLoss
                    else Double.NaN;
StopLossLine.SetDefaultColor(Color.RED);
StopLossLine.SetLineWeight(2);
StopLossLine.SetStyle(Curve.MEDIUM_DASH);

# Trigger the sell-to-cover signal if price breaches the stop-loss level intrabar
def stopLossCondition = inRTHSession and low <= buyStopLoss;

# Output the stop-loss condition as true/false
plot BullishStopLossPlot = stopLossCondition;
BullishStopLossPlot.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BullishStopLossPlot.SetDefaultColor(Color.RED);
 
Last edited by a moderator:
Most people do not understand the limitations of current AI models. They're knowledge is not current and they're not fine tuned for specific coding tasks (thinkscripts for example). What people also don't understand is if you feed it information to learn, that could get you to your end result most of the time. AI won't do everything for you. You have to either have some knowledge of the task at hand or know where to get it.

Feed it documentation along with examples of what you're trying to accomplish. EXPLAIN that you don't want the same outcome but to use the example as an understanding of syntax. Doing that will get you so far. If you don't know where to go or what info to feed it, you're trying to run before you walk. Slow down and learn some stuff yourself.

reply 375
" Slow down and learn some stuff yourself."

exactly , just take the time to learn what interests you, instead of wasting time with bogus AI
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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