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:
How can I include coloring candles to this version ?
Code:
# Cumulative Volume Delta
# This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# © Ankit_1618 converted by Zlotko

declare upper;

# Calculate upper_wick, lower_wick, spread, and body_length
def upper_wick = if close > open then high - close else high - open;
def lower_wick = if close > open then open - low else close - low;
def spread = high - low;
def body_length = spread - (upper_wick + lower_wick);

# Calculate percent_upper_wick, percent_lower_wick, and percent_body_length
def percent_upper_wick = upper_wick / spread;
def percent_lower_wick = lower_wick / spread;
def percent_body_length = body_length / spread;

# Calculate buying_volume and selling_volume
def buying_volume = if close > open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;
def selling_volume = if close < open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;

# Input for cumulation_length
input cumulation_length = 14;

# Calculate cumulative_buying_volume and cumulative_selling_volume using EMA
def cumulative_buying_volume = ExpAverage(buying_volume, cumulation_length);
def cumulative_selling_volume = ExpAverage(selling_volume, cumulation_length);

# Calculate cumulative_volume_delta
def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

# Plot histograms to represent cumulative volume delta
plot hist = cumulative_volume_delta;
hist.AssignValueColor(if cumulative_volume_delta > 0 then color.green else color.red);
hist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
hist.SetLineWeight(1);
hist.SetDefaultColor(GetColor(1));
hist.SetStyle(Curve.FIRM);

# Calculate volume_strength_wave and plot its EMA
def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = ExpAverage(volume_strength_wave, cumulation_length);
#plot ema_volume_strength_wave(color = color.gray, transp = 80);
# 50%Line.SetDefaultColor(Color.GRAY);

#----Div-----------
input LookBackRight = 5; # "Pivot Lookback Right"
input LookBackLeft = 5; # "Pivot Lookback Left"
input MaxLookback = 60; # "Max of Lookback Range"
input MinLookback = 5; # "Min of Lookback Range"
input DivBull = yes; # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes; # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = cumulative_volume_delta;

def h = high;
def l = low;

script FindPivots {
input dat = close; # default data or study being evaluated
input HL = 0; # default high or low pivot designation, -1 low, +1 high
input lbL = 5; # default Pivot Lookback Left
input lbR = 1; # default Pivot Lookback Right
##############
def _nan; # used for non-number returns
def _BN; # the current barnumber
def _VStop; # confirms that the lookforward period continues the pivot trend
def _V; # the Value at the actual pivot point
##############
_BN = BarNumber();
_nan = Double.NaN;
_VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
fold a = 1 to lbR + 1 with b=1 while b do
if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
if (HL > 0) {
_V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
then dat else _nan;
} else {
_V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
then dat else _nan;
}
plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
input cond = yes;
input rangeUpper = 60;
input rangeLower = 5;
def bars = if cond then 0 else bars[1] + 1;
def inrange = (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1==0 then divSrc[1] else vlFound1;
def vlFound = if vlFound_!=vlFound_[1] then vlFound_[1] else vlFound[1];
#valuewhen(plFound, divSrc, MinLookback, MaxLookback, 1);
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1==0 then divSrc[1] else vhFound1;
def vhFound = if vhFound_!=vhFound_[1] then vhFound_[1] else vhFound[1];
#valuewhen(phFound, divSrc, MinLookback, MaxLookback, 1);
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1 == 0 then l[1] else plPrice1;
def plPrice = if plPrice_!=plPrice_[1] then plPrice_[1] else plPrice[1];
#valuewhen(plFound, l, MinLookback, MaxLookback, 1);
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1==0 then h[1] else phPrice1;
def phPrice = if phPrice_!=phPrice_[1] then phPrice_[1] else phPrice[1];
#valuewhen(phFound, h, MinLookback, MaxLookback, 1);

#// Regular Bullish
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH = divSrc < vhFound and inRangePh;
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);


#----End
 
Last edited by a moderator:
How can I include coloring candles to this version ?

# Cumulative Volume Delta
# This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# © Ankit_1618 converted by Zlotko

declare upper;

# Calculate upper_wick, lower_wick, spread, and body_length
def upper_wick = if close > open then high - close else high - open;
def lower_wick = if close > open then open - low else close - low;
def spread = high - low;
def body_length = spread - (upper_wick + lower_wick);

# Calculate percent_upper_wick, percent_lower_wick, and percent_body_length
def percent_upper_wick = upper_wick / spread;
def percent_lower_wick = lower_wick / spread;
def percent_body_length = body_length / spread;

# Calculate buying_volume and selling_volume
def buying_volume = if close > open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;
def selling_volume = if close < open then (percent_body_length + (percent_upper_wick + percent_lower_wick) / 2) * volume else ((percent_upper_wick + percent_lower_wick) / 2) * volume;

# Input for cumulation_length
input cumulation_length = 14;

# Calculate cumulative_buying_volume and cumulative_selling_volume using EMA
def cumulative_buying_volume = ExpAverage(buying_volume, cumulation_length);
def cumulative_selling_volume = ExpAverage(selling_volume, cumulation_length);

# Calculate cumulative_volume_delta
def cumulative_volume_delta = cumulative_buying_volume - cumulative_selling_volume;

# Plot histograms to represent cumulative volume delta
plot hist = cumulative_volume_delta;
hist.AssignValueColor(if cumulative_volume_delta > 0 then color.green else color.red);
hist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
hist.SetLineWeight(1);
hist.SetDefaultColor(GetColor(1));
hist.SetStyle(Curve.FIRM);

# Calculate volume_strength_wave and plot its EMA
def volume_strength_wave = if cumulative_buying_volume > cumulative_selling_volume then cumulative_buying_volume else cumulative_selling_volume;
def ema_volume_strength_wave = ExpAverage(volume_strength_wave, cumulation_length);
#plot ema_volume_strength_wave(color = color.gray, transp = 80);
# 50%Line.SetDefaultColor(Color.GRAY);

#----Div-----------
input LookBackRight = 5; # "Pivot Lookback Right"
input LookBackLeft = 5; # "Pivot Lookback Left"
input MaxLookback = 60; # "Max of Lookback Range"
input MinLookback = 5; # "Min of Lookback Range"
input DivBull = yes; # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes; # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"
def divSrc = cumulative_volume_delta;

def h = high;
def l = low;

script FindPivots {
input dat = close; # default data or study being evaluated
input HL = 0; # default high or low pivot designation, -1 low, +1 high
input lbL = 5; # default Pivot Lookback Left
input lbR = 1; # default Pivot Lookback Right
##############
def _nan; # used for non-number returns
def _BN; # the current barnumber
def _VStop; # confirms that the lookforward period continues the pivot trend
def _V; # the Value at the actual pivot point
##############
_BN = BarNumber();
_nan = Double.NaN;
_VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
fold a = 1 to lbR + 1 with b=1 while b do
if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
if (HL > 0) {
_V = if _BN > lbL + 1 and dat == Highest(dat, lbL + 1) and _VStop
then dat else _nan;
} else {
_V = if _BN > lbL + 1 and dat == Lowest(dat, lbL + 1) and _VStop
then dat else _nan;
}
plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#_inRange(cond) =>
script _inRange {
input cond = yes;
input rangeUpper = 60;
input rangeLower = 5;
def bars = if cond then 0 else bars[1] + 1;
def inrange = (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, LookBackLeft, LookBackRight);
def ph = findpivots(divSrc, 1, LookBackLeft, LookBackRight);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound1 = if plFound then divSrc else vlFound1[1];
def vlFound_ = if vlFound1==0 then divSrc[1] else vlFound1;
def vlFound = if vlFound_!=vlFound_[1] then vlFound_[1] else vlFound[1];
#valuewhen(plFound, divSrc, MinLookback, MaxLookback, 1);
def vhFound1 = if phFound then divSrc else vhFound1[1];
def vhFound_ = if vhFound1==0 then divSrc[1] else vhFound1;
def vhFound = if vhFound_!=vhFound_[1] then vhFound_[1] else vhFound[1];
#valuewhen(phFound, divSrc, MinLookback, MaxLookback, 1);
def plPrice1 = if plFound then l else plPrice1[1];
def plPrice_ = if plPrice1 == 0 then l[1] else plPrice1;
def plPrice = if plPrice_!=plPrice_[1] then plPrice_[1] else plPrice[1];
#valuewhen(plFound, l, MinLookback, MaxLookback, 1);
def phPrice1 = if phFound then h else phPrice1[1];
def phPrice_ = if phPrice1==0 then h[1] else phPrice1;
def phPrice = if phPrice_!=phPrice_[1] then phPrice_[1] else phPrice[1];
#valuewhen(phFound, h, MinLookback, MaxLookback, 1);

#// Regular Bullish
def inRangePl = _inRange(plFound[1],MaxLookback,MinLookback);
def oscHL = divSrc > vlFound and inRangePl;
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc < vlFound and inRangePl;
def priceHL = l > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def inRangePh = _inRange(phFound[1],MaxLookback,MinLookback);
def oscLH = divSrc < vhFound and inRangePh;
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and inRangePh;
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);


#----End
reply to 381

coloring based on what?

use this
https://toslc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignPriceColor

edit your post and add a link from where that code came from
 
Last edited:
I am trying to modify the Volume Profile indicator so that it starts at market open on a chart that shows premarket activity (the chart setting is TODAY: 10m). I've added in a session start time input but I keep getting the development error that states "Unexpected error has happened. An unexpected error has occurred. If the problem persists, please contact tech support. You are advised to restart your application now." Here is the code I am using:
Code:
input customRowHeight = 1.0;
input timePerProfile = {default CHART, MINUTE, HOUR, DAY, WEEK, MONTH, "OPT EXP", BAR};
input multiplier = 1;
input onExpansion = no;
input profiles = 1000;
input showPointOfControl = yes;
input showValueArea = yes;
input valueAreaPercent = 60;
input opacity = 20;
input sessionStartTime = 0930; # Custom session start time in HHMM format

# Calculate session start in seconds
def sessionStartHour = Floor(sessionStartTime / 100);
def sessionStartMinute = sessionStartTime % 100;
def sessionStartSeconds = (sessionStartHour * 3600) + (sessionStartMinute * 60);

# Adjusted time logic
def secondsSinceSessionStart = SecondsFromTime(sessionStartSeconds);
def isSessionActive = secondsSinceSessionStart >= 0;

# Calculate period based on the selected profile type
def yyyymmdd = GetYyyyMmDd();
def tradingDays = CountTradingDays(Min(First(yyyymmdd), yyyymmdd), yyyymmdd);
def period;
switch (timePerProfile) {
case CHART:
period = 0;
case MINUTE:
period = Floor(secondsSinceSessionStart / 60);
case HOUR:
period = Floor(secondsSinceSessionStart / 3600);
case DAY:
period = if isSessionActive then tradingDays - 1 else Double.NaN;
case WEEK:
period = Floor(DaysFromDate(First(yyyymmdd)) / 7);
case MONTH:
period = GetYear() * 12 + GetMonth() - First(GetYear() * 12 + GetMonth());
case "OPT EXP":
period = GetYear() * 12 + GetMonth() + (GetDayOfMonth(yyyymmdd) > 20);
case BAR:
period = BarNumber() - 1;
}

# Define conditions for starting a new profile
def count = CompoundValue(1, if period != period[1] then (count[1] + 1) % multiplier else count[1], 0);
def cond = count == 0;

# Determine price per row height
def height;
switch (pricePerRowHeightMode) {
case AUTOMATIC:
height = PricePerRow.AUTOMATIC;
case TICKSIZE:
height = PricePerRow.TICKSIZE;
case CUSTOM:
height = customRowHeight;
}

# Volume profile
profile vol = VolumeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent);
def pc = vol.GetPointOfControl();
def hVA = vol.GetHighestValueArea();
def lVA = vol.GetLowestValueArea();

# Plots
plot POC = if !IsNaN(pc) then pc else Double.NaN;
plot VAHigh = if !IsNaN(hVA) then hVA else Double.NaN;
plot VALow = if !IsNaN(lVA) then lVA else Double.NaN;

DefineGlobalColor("Profile", GetColor(1));
DefineGlobalColor("Point Of Control", GetColor(5));
DefineGlobalColor("Value Area", GetColor(8));

POC.SetDefaultColor(GlobalColor("Point Of Control"));
POC.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
VAHigh.SetDefaultColor(GlobalColor("Value Area"));
VAHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
VALow.SetDefaultColor(GlobalColor("Value Area"));
VALow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Last edited by a moderator:
I am trying to modify the Volume Profile indicator so that it starts at market open on a chart that shows premarket activity (the chart setting is TODAY: 10m). I've added in a session start time input but I keep getting the development error that states "Unexpected error has happened. An unexpected error has occurred. If the problem persists, please contact tech support. You are advised to restart your application now." Here is the code I am using:
Code:
input customRowHeight = 1.0;
input timePerProfile = {default CHART, MINUTE, HOUR, DAY, WEEK, MONTH, "OPT EXP", BAR};
input multiplier = 1;
input onExpansion = no;
input profiles = 1000;
input showPointOfControl = yes;
input showValueArea = yes;
input valueAreaPercent = 60;
input opacity = 20;
input sessionStartTime = 0930; # Custom session start time in HHMM format

# Calculate session start in seconds
def sessionStartHour = Floor(sessionStartTime / 100);
def sessionStartMinute = sessionStartTime % 100;
def sessionStartSeconds = (sessionStartHour * 3600) + (sessionStartMinute * 60);

# Adjusted time logic
def secondsSinceSessionStart = SecondsFromTime(sessionStartSeconds);
def isSessionActive = secondsSinceSessionStart >= 0;

# Calculate period based on the selected profile type
def yyyymmdd = GetYyyyMmDd();
def tradingDays = CountTradingDays(Min(First(yyyymmdd), yyyymmdd), yyyymmdd);
def period;
switch (timePerProfile) {
case CHART:
period = 0;
case MINUTE:
period = Floor(secondsSinceSessionStart / 60);
case HOUR:
period = Floor(secondsSinceSessionStart / 3600);
case DAY:
period = if isSessionActive then tradingDays - 1 else Double.NaN;
case WEEK:
period = Floor(DaysFromDate(First(yyyymmdd)) / 7);
case MONTH:
period = GetYear() * 12 + GetMonth() - First(GetYear() * 12 + GetMonth());
case "OPT EXP":
period = GetYear() * 12 + GetMonth() + (GetDayOfMonth(yyyymmdd) > 20);
case BAR:
period = BarNumber() - 1;
}

# Define conditions for starting a new profile
def count = CompoundValue(1, if period != period[1] then (count[1] + 1) % multiplier else count[1], 0);
def cond = count == 0;

# Determine price per row height
def height;
switch (pricePerRowHeightMode) {
case AUTOMATIC:
height = PricePerRow.AUTOMATIC;
case TICKSIZE:
height = PricePerRow.TICKSIZE;
case CUSTOM:
height = customRowHeight;
}

# Volume profile
profile vol = VolumeProfile("startNewProfile" = cond, "onExpansion" = onExpansion, "numberOfProfiles" = profiles, "pricePerRow" = height, "value area percent" = valueAreaPercent);
def pc = vol.GetPointOfControl();
def hVA = vol.GetHighestValueArea();
def lVA = vol.GetLowestValueArea();

# Plots
plot POC = if !IsNaN(pc) then pc else Double.NaN;
plot VAHigh = if !IsNaN(hVA) then hVA else Double.NaN;
plot VALow = if !IsNaN(lVA) then lVA else Double.NaN;

DefineGlobalColor("Profile", GetColor(1));
DefineGlobalColor("Point Of Control", GetColor(5));
DefineGlobalColor("Value Area", GetColor(8));

POC.SetDefaultColor(GlobalColor("Point Of Control"));
POC.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
VAHigh.SetDefaultColor(GlobalColor("Value Area"));
VAHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
VALow.SetDefaultColor(GlobalColor("Value Area"));
VALow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

reply to #383

@SleepyZ has posted many studies using profile. maybe he can take a look and answer this?
 
Last edited:
I am a newbie. How can we apply to future trading on TOS?
Code:
# Define Inputs
input coin = "CRV";
input direction = "LONG";
input leverage = 50;
input QFLVolumeMA = 6;
input deviationToBuyBelowBase = 0.005; # 0.5% expressed as a decimal
input deviationToOpen1stSafety = 0.005; # 0.5% expressed as a decimal
input TP = 0.01; # 1% take profit
input BO = 30; # Base order size
input SO = 60; # Safety order size
input SOVolume = 2; # Safety order volume multiplier
input SOStepScale = 2; # Step scale multiplier
input maxSafetyOrders = 6; # Max safety orders
input audibleAlertEnabled = yes; # Enable audible alerts

# Price Calculation
def price = close;

# Spread Calculation
def spread = high - low;

# Logic for Entry Conditions
def baseOrderCondition = price < price * (1 - deviationToBuyBelowBase);

# Safety Order Conditions
def safetyOrderCondition = price < price * (1 - deviationToOpen1stSafety);

# Take Profit Logic
def takeProfitCondition = price >= price * (1 + TP);

# Trigger Sell Conditional Order
def sellCondition = spread > spread[1]; # Example logic: Sell when spread increases

# Audible Alert
Alert(baseOrderCondition, "Base Order Condition Triggered", audibleAlertEnabled);
Alert(takeProfitCondition, "Take Profit Triggered", audibleAlertEnabled);
Alert(sellCondition, "Sell Condition Triggered", audibleAlertEnabled);

# Plot Base Order
plot baseOrder = if baseOrderCondition then price else Double.NaN;

# Plot Safety Orders
plot safetyOrders = if safetyOrderCondition then price else Double.NaN;

# Plot Exit Trade
plot exitTrade = if takeProfitCondition then price else Double.NaN;

# Plot Sell Conditional Order
plot sellOrder = if sellCondition then price else Double.NaN;
 
Last edited by a moderator:
I am completely new at this and any help would be great. I would like to create a simple bollinger band indicator but that would show the 5min values in the 1 minute timeframe. my issue is that unable to correctly sum the candles without re-counting the closing prices of the already counted bars or leaving some out. I am unable to use the regular functions because they would recount the same bars already counted. Below is the equation for bollinger bands

# Bollinger Bands Calculation
def sDev = stdev(price, length);
def midLine = SimpleMovingAvg(price, length);
def upperBand = midLine + numDev * sDev;
def lowerBand = midLine - numDev * sDev;

This is my code so far.
# Define the length and standard deviation multiplier for Bollinger Bands
input length = 20;
input numDev = 2.0;

# Initialize variables for manual calculation
def price = close;
def count = 5; # Number of 1-minute bars in 5 minutes

# Manually aggregate the 5-minute closing prices
def fiveMinClose = if (SecondsFromTime(0) % (count * 60) == 0) then price else fiveMinClose[1];

# Manually calculate the 5-minute simple moving average
def sumClose = fold j = 0 to length - 1 with sum = 0 do sum + GetValue(fiveMinClose, j);
def fiveMinSMA = sumClose / length;

# Manually calculate the standard deviation
def sumSqDiff = fold k = 0 to length - 1 with sqSum = 0 do sqSum + Sqr(GetValue(fiveMinClose, k) - fiveMinSMA);
def fiveMinStdDev = Sqrt(sumSqDiff / length);

# Calculate the Bollinger Bands
def upperBand = fiveMinSMA + numDev * fiveMinStdDev;
def lowerBand = fiveMinSMA - numDev * fiveMinStdDev;

# Plot the Bollinger Bands on the 1-minute chart
plot UpperBand1 = upperBand;
plot LowerBand1 = lowerBand;
plot MiddleBand1 = fiveMinSMA;

# Customize the plot appearance
UpperBand1.SetDefaultColor(Color.RED);
LowerBand1.SetDefaultColor(Color.GREEN);
MiddleBand1.SetDefaultColor(Color.BLUE);
 
I am completely new at this and any help would be great. I would like to create a simple bollinger band indicator but that would show the 5min values in the 1 minute timeframe. my issue is that unable to correctly sum the candles without re-counting the closing prices of the already counted bars or leaving some out. I am unable to use the regular functions because they would recount the same bars already counted. Below is the equation for bollinger bands

# Bollinger Bands Calculation
def sDev = stdev(price, length);
def midLine = SimpleMovingAvg(price, length);
def upperBand = midLine + numDev * sDev;
def lowerBand = midLine - numDev * sDev;

This is my code so far.
# Define the length and standard deviation multiplier for Bollinger Bands
input length = 20;
input numDev = 2.0;

# Initialize variables for manual calculation
def price = close;
def count = 5; # Number of 1-minute bars in 5 minutes

# Manually aggregate the 5-minute closing prices
def fiveMinClose = if (SecondsFromTime(0) % (count * 60) == 0) then price else fiveMinClose[1];

# Manually calculate the 5-minute simple moving average
def sumClose = fold j = 0 to length - 1 with sum = 0 do sum + GetValue(fiveMinClose, j);
def fiveMinSMA = sumClose / length;

# Manually calculate the standard deviation
def sumSqDiff = fold k = 0 to length - 1 with sqSum = 0 do sqSum + Sqr(GetValue(fiveMinClose, k) - fiveMinSMA);
def fiveMinStdDev = Sqrt(sumSqDiff / length);

# Calculate the Bollinger Bands
def upperBand = fiveMinSMA + numDev * fiveMinStdDev;
def lowerBand = fiveMinSMA - numDev * fiveMinStdDev;

# Plot the Bollinger Bands on the 1-minute chart
plot UpperBand1 = upperBand;
plot LowerBand1 = lowerBand;
plot MiddleBand1 = fiveMinSMA;

# Customize the plot appearance
UpperBand1.SetDefaultColor(Color.RED);
LowerBand1.SetDefaultColor(Color.GREEN);
MiddleBand1.SetDefaultColor(Color.BLUE);

reply to 386

take a look at this
https://usethinkscript.com/threads/bollinger-bands-mtf-multi-time-frame-for-thinkorswim.259/
searched mtf bollinger
 
Last edited:
Trying to find trends of times when stocks go up. Not sure if this is working like it should. Here is the code:

input daysBack = 10;
input forwardMinutes = 30;
input probabilityThreshold = 0.6;
input dollarMove = 1.20; # Change this value to test for different dollar moves

# Define three times (in 24-hour format)
input hour1 = 6;
input minute1 = 30;
input hour2 = 8;
input minute2 = 0;
input hour3 = 11;
input minute3 = 45;

def barSize = 5; # set this to your chart resolution in minutes
def forwardBars = forwardMinutes / barSize;

# Time match helpers
def time1 = SecondsFromTime(hour1 * 100 + minute1);
def time2 = SecondsFromTime(hour2 * 100 + minute2);
def time3 = SecondsFromTime(hour3 * 100 + minute3);

def isTime1 = time1 == 0;
def isTime2 = time2 == 0;
def isTime3 = time3 == 0;

# Unique day counter
def isNewDay = GetDay() != GetDay()[1];
def dayCounter = if isNewDay then dayCounter[1] + 1 else dayCounter[1];
def isToday = dayCounter == HighestAll(dayCounter);

# Function-like logic for each time slot
# Check if the stock increased by at least $1 from the target time
def wentUp1 = if isTime1 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp2 = if isTime2 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp3 = if isTime3 and close[forwardBars] >= close + dollarMove then 1 else 0;

# Alternative check (checking 2 or 3 bars after the time) for more flexibility
def wentUp1Alt = if isTime1 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp2Alt = if isTime2 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp3Alt = if isTime3 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;

# Use either the original or alternative logic
def wentUp1Final = wentUp1 or wentUp1Alt;
def wentUp2Final = wentUp2 or wentUp2Alt;
def wentUp3Final = wentUp3 or wentUp3Alt;

# Count occurrences
def count1 = if isTime1 then 1 else 0;
def count2 = if isTime2 then 1 else 0;
def count3 = if isTime3 then 1 else 0;

# Cumulative totals
def upSum1 = TotalSum(wentUp1Final);
def total1 = TotalSum(count1);
def prob1 = if total1 > 0 then upSum1 / total1 else 0;

def upSum2 = TotalSum(wentUp2Final);
def total2 = TotalSum(count2);
def prob2 = if total2 > 0 then upSum2 / total2 else 0;

def upSum3 = TotalSum(wentUp3Final);
def total3 = TotalSum(count3);
def prob3 = if total3 > 0 then upSum3 / total3 else 0;

# Plot arrows only on today's matching time if probability is high enough
plot Arrow1 = if isToday and isTime1 and prob1 > probabilityThreshold then low else Double.NaN;
Arrow1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow1.SetDefaultColor(Color.GREEN);

plot Arrow2 = if isToday and isTime2 and prob2 > probabilityThreshold then low else Double.NaN;
Arrow2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow2.SetDefaultColor(Color.BLUE);

plot Arrow3 = if isToday and isTime3 and prob3 > probabilityThreshold then low else Double.NaN;
Arrow3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow3.SetDefaultColor(Color.ORANGE);

# Show probability in chart label
AddLabel(yes, "Approx 6:30 Prob Increase $1", if prob1 > probabilityThreshold then Color.GREEN else Color.GRAY);
AddLabel(yes, " Approx 8:00 Prob Increase $1: ", if prob2 > probabilityThreshold then Color.BLUE else Color.GRAY);
AddLabel(yes, "Approx 11:45 Prob Increase $1: ", if prob3 > probabilityThreshold then Color.ORANGE else Color.GRAY);
 
Hi all!

I'm trying to make a scan to find stocks that are in a squeeze within 20 cents of ORB levels (squeeze above the 30 minute high, squeeze below the 30 minute low).. with ChatGPT, I got this but it doesn't seem to work properly. Some stocks coming up ARE in the correct spot, but some are not. Attached is a photo of MRNA today, 4/7 on the 1 minute chart. This is the ideal setup I'm looking for (purple candles on the right). Any help would be greatly appreciated!

Screen Shot 2025-04-07 at 12.04.54 PM.png


Code:
def marketOpen = 0930;
def firstBar = SecondsFromTime(marketOpen * 100) < 1800;
def thirtyMinHigh = Highest(high, 30);
def thirtyMinLow = Lowest(low, 30);

def inSqueeze = TTM_Squeeze().SqueezeAlert == 0;

def withinHighRange = AbsValue(close - thirtyMinHigh) <= 0.20;
def withinLowRange = AbsValue(close - thirtyMinLow) <= 0.20;

plot scan = inSqueeze and (withinHighRange or withinLowRange);
 
Trying to find trends of times when stocks go up. Not sure if this is working like it should. Here is the code:

input daysBack = 10;
input forwardMinutes = 30;
input probabilityThreshold = 0.6;
input dollarMove = 1.20; # Change this value to test for different dollar moves

# Define three times (in 24-hour format)
input hour1 = 6;
input minute1 = 30;
input hour2 = 8;
input minute2 = 0;
input hour3 = 11;
input minute3 = 45;

def barSize = 5; # set this to your chart resolution in minutes
def forwardBars = forwardMinutes / barSize;

# Time match helpers
def time1 = SecondsFromTime(hour1 * 100 + minute1);
def time2 = SecondsFromTime(hour2 * 100 + minute2);
def time3 = SecondsFromTime(hour3 * 100 + minute3);

def isTime1 = time1 == 0;
def isTime2 = time2 == 0;
def isTime3 = time3 == 0;

# Unique day counter
def isNewDay = GetDay() != GetDay()[1];
def dayCounter = if isNewDay then dayCounter[1] + 1 else dayCounter[1];
def isToday = dayCounter == HighestAll(dayCounter);

# Function-like logic for each time slot
# Check if the stock increased by at least $1 from the target time
def wentUp1 = if isTime1 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp2 = if isTime2 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp3 = if isTime3 and close[forwardBars] >= close + dollarMove then 1 else 0;

# Alternative check (checking 2 or 3 bars after the time) for more flexibility
def wentUp1Alt = if isTime1 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp2Alt = if isTime2 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp3Alt = if isTime3 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;

# Use either the original or alternative logic
def wentUp1Final = wentUp1 or wentUp1Alt;
def wentUp2Final = wentUp2 or wentUp2Alt;
def wentUp3Final = wentUp3 or wentUp3Alt;

# Count occurrences
def count1 = if isTime1 then 1 else 0;
def count2 = if isTime2 then 1 else 0;
def count3 = if isTime3 then 1 else 0;

# Cumulative totals
def upSum1 = TotalSum(wentUp1Final);
def total1 = TotalSum(count1);
def prob1 = if total1 > 0 then upSum1 / total1 else 0;

def upSum2 = TotalSum(wentUp2Final);
def total2 = TotalSum(count2);
def prob2 = if total2 > 0 then upSum2 / total2 else 0;

def upSum3 = TotalSum(wentUp3Final);
def total3 = TotalSum(count3);
def prob3 = if total3 > 0 then upSum3 / total3 else 0;

# Plot arrows only on today's matching time if probability is high enough
plot Arrow1 = if isToday and isTime1 and prob1 > probabilityThreshold then low else Double.NaN;
Arrow1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow1.SetDefaultColor(Color.GREEN);

plot Arrow2 = if isToday and isTime2 and prob2 > probabilityThreshold then low else Double.NaN;
Arrow2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow2.SetDefaultColor(Color.BLUE);

plot Arrow3 = if isToday and isTime3 and prob3 > probabilityThreshold then low else Double.NaN;
Arrow3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow3.SetDefaultColor(Color.ORANGE);

# Show probability in chart label
AddLabel(yes, "Approx 6:30 Prob Increase $1", if prob1 > probabilityThreshold then Color.GREEN else Color.GRAY);
AddLabel(yes, " Approx 8:00 Prob Increase $1: ", if prob2 > probabilityThreshold then Color.BLUE else Color.GRAY);
AddLabel(yes, "Approx 11:45 Prob Increase $1: ", if prob3 > probabilityThreshold then Color.ORANGE else Color.GRAY);

reply to 388 (was 391)

i am not sure what you want.
i changed a couple things. replaced constants with variables.
add vertical lines

it draws arrows sometimes
the times should be adjusted for a different time zone

Code:
#chat391_find_trends
#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-20#post-152298
#391
#Trying to find trends of times when stocks go up. Not sure if this is working like it should. Here is the code:


input daysBack = 10;
input forwardMinutes = 30;
input probabilityThreshold = 0.6;
input dollarMove = 1.20; # Change this value to test for different dollar moves

# Define three times (in 24-hour format)
input hour1 = 6;
input minute1 = 30;
input hour2 = 8;
input minute2 = 0;
input hour3 = 11;
input minute3 = 45;

#def barSize = 5; # set this to your chart resolution in minutes
# get chart minutes
#---------------------------------
# get chart agg time
def chartagg = getaggregationperiod();
def chartmin = chartagg/(1000*60);
#---------------------------------
def barSize = chartmin;
def forwardBars = forwardMinutes / barSize;


# Time match helpers
def time1 = SecondsFromTime(hour1 * 100 + minute1);
def time2 = SecondsFromTime(hour2 * 100 + minute2);
def time3 = SecondsFromTime(hour3 * 100 + minute3);

def isTime1 = time1 == 0;
def isTime2 = time2 == 0;
def isTime3 = time3 == 0;

# nearest bar
# def start = 0930;
# def x = SecondsFromTime(start)[1] < 0 and SecondsFromTime(start) >= 0;


addverticalline(istime1, "-", color.cyan);
addverticalline(istime2, "-", color.cyan);
addverticalline(istime3, "-", color.cyan);

addchartbubble(0, 235,
istime1 + "\n" +
istime2 + "\n" +
istime3 + "\n"
, (if istime1 or istime2 or istime3 then color.yellow else color.gray),no);


# Unique day counter
def isNewDay = GetDay() != GetDay()[1];
#def dayCounter = if isNewDay then dayCounter[1] + 1 else dayCounter[1];
#def isToday = dayCounter == HighestAll(dayCounter);

# new formula. gets rid of highestall and complex icon
def istoday = GetDay() == GetlastDay();


# Function-like logic for each time slot
# Check if the stock increased by at least $1 from the target time
def wentUp1 = if isTime1 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp2 = if isTime2 and close[forwardBars] >= close + dollarMove then 1 else 0;
def wentUp3 = if isTime3 and close[forwardBars] >= close + dollarMove then 1 else 0;

# Alternative check (checking 2 or 3 bars after the time) for more flexibility
def wentUp1Alt = if isTime1 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp2Alt = if isTime2 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;
def wentUp3Alt = if isTime3 and (close[1] >= close + dollarMove or close[2] >= close + dollarMove) then 1 else 0;

# Use either the original or alternative logic
def wentUp1Final = wentUp1 or wentUp1Alt;
def wentUp2Final = wentUp2 or wentUp2Alt;
def wentUp3Final = wentUp3 or wentUp3Alt;

# Count occurrences
def count1 = if isTime1 then 1 else 0;
def count2 = if isTime2 then 1 else 0;
def count3 = if isTime3 then 1 else 0;

# Cumulative totals
def upSum1 = TotalSum(wentUp1Final);
def total1 = TotalSum(count1);
def prob1 = if total1 > 0 then upSum1 / total1 else 0;

def upSum2 = TotalSum(wentUp2Final);
def total2 = TotalSum(count2);
def prob2 = if total2 > 0 then upSum2 / total2 else 0;

def upSum3 = TotalSum(wentUp3Final);
def total3 = TotalSum(count3);
def prob3 = if total3 > 0 then upSum3 / total3 else 0;

# Plot arrows only on today's matching time if probability is high enough
plot Arrow1 = if isToday and isTime1 and prob1 > probabilityThreshold then low else Double.NaN;
Arrow1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow1.SetDefaultColor(Color.GREEN);
arrow1.setlineweight(3);

plot Arrow2 = if isToday and isTime2 and prob2 > probabilityThreshold then low else Double.NaN;
Arrow2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow2.SetDefaultColor(Color.BLUE);
arrow2.setlineweight(3);

plot Arrow3 = if isToday and isTime3 and prob3 > probabilityThreshold then low else Double.NaN;
Arrow3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Arrow3.SetDefaultColor(Color.ORANGE);
arrow3.setlineweight(3);

addlabel(1, " ", color.black);
# Show probability in chart label
#AddLabel(yes, "Approx 6:30 Prob Increase $1", if prob1 > probabilityThreshold then Color.GREEN else Color.GRAY);
#AddLabel(yes, " Approx 8:00 Prob Increase $1: ", if prob2 > probabilityThreshold then Color.BLUE else Color.GRAY);
#AddLabel(yes, "Approx 11:45 Prob Increase $1: ", if prob3 > probabilityThreshold then Color.ORANGE else Color.GRAY);
AddLabel(yes, "Approx " + (hour1 + ":" + minute1) + " Prob Increase $1", if prob1 > probabilityThreshold then Color.GREEN else Color.GRAY);
AddLabel(yes, " Approx " + (hour2 + ":" + minute2) + " Prob Increase $1: ", if prob2 > probabilityThreshold then Color.BLUE else Color.GRAY);
AddLabel(yes, "Approx " + (hour3 + ":" + minute3) + " Prob Increase $1: ", if prob3 > probabilityThreshold then Color.ORANGE else Color.GRAY);


input test1_prob_bubbles = no;
addchartbubble(test1_prob_bubbles, low*0.98,
 prob1 + "\n" +
 prob2 + "\n" +
 prob3 + "\n" +
 probabilityThreshold
, (if prob1 > probabilityThreshold then Color.GREEN else
  if prob2 > probabilityThreshold then Color.BLUE else
  if prob3 > probabilityThreshold then Color.ORANGE else Color.GRAY), no);
#
 
Last edited:
I am new to using ToS forum, so I am unsure if I am in the right place.

I am looking for help writing a script for the charts tab. I am trying to create a "Return on Investment" line that follows the price chart.
The code I am using makes the price chart go away, I don't know why. There are no errors.
This is the code I am using.

Code:
# Define the starting price
def startingPrice = open(period = AggregationPeriod.DAY); # You can replace this value with the actual starting price

# Calculate the ROI
def currentPrice = close;
def roi = ((currentPrice - startingPrice) / startingPrice) * 100;

# Plot the ROI on the chart
plot ROIs = roi;
ROIs.SetDefaultColor(Color.GREEN);
ROIs.SetLineWeight(2);

# Display the ROI value
AddLabel(yes, "ROI: " + AsPercent(ROIs / 100), Color.YELLOW);
 
Last edited by a moderator:
I am new to using ToS forum, so I am unsure if I am in the right place.

I am looking for help writing a script for the charts tab. I am trying to create a "Return on Investment" line that follows the price chart.
The code I am using makes the price chart go away, I don't know why. There are no errors.
This is the code I am using.

Code:
# Define the starting price
def startingPrice = open(period = AggregationPeriod.DAY); # You can replace this value with the actual starting price

# Calculate the ROI
def currentPrice = close;
def roi = ((currentPrice - startingPrice) / startingPrice) * 100;

# Plot the ROI on the chart
plot ROIs = roi;
ROIs.SetDefaultColor(Color.GREEN);
ROIs.SetLineWeight(2);

# Display the ROI value
AddLabel(yes, "ROI: " + AsPercent(ROIs / 100), Color.YELLOW);

Works fine on my 3D 3m Chart...
pXwZ34r.png
 
Can I get some advice on what I need to do to get the CODE below to display the predicted chart data

# Predict TSLA Closing Price for 04/18/2025
declare upper;

input length = 20; # Number of bars for regression calculation
input projectionDays = 7; # Days to project forward (from 04/11 to 04/18)

# Regression calculations
def slope = Inertia(close, length); # Calculates the slope of the regression line
def intercept = Average(close, length) - slope * (length - 1) / 2; # Calculates the intercept

# Projected price calculation
def projectedPrice = slope * (length - 1 + projectionDays) + intercept;

# Define exactly one plot for the predicted price
plot PredictedPrice = projectedPrice;
PredictedPrice.SetDefaultColor(Color.CYAN);
PredictedPrice.SetLineWeight(2);
 
Can I get some advice on what I need to do to get the CODE below to display the predicted chart data

# Predict TSLA Closing Price for 04/18/2025
declare upper;

input length = 20; # Number of bars for regression calculation
input projectionDays = 7; # Days to project forward (from 04/11 to 04/18)

# Regression calculations
def slope = Inertia(close, length); # Calculates the slope of the regression line
def intercept = Average(close, length) - slope * (length - 1) / 2; # Calculates the intercept

# Projected price calculation
def projectedPrice = slope * (length - 1 + projectionDays) + intercept;

# Define exactly one plot for the predicted price
plot PredictedPrice = projectedPrice;
PredictedPrice.SetDefaultColor(Color.CYAN);
PredictedPrice.SetLineWeight(2);
reply to #394

i don't know what you are asking for?
this does draw a line...
but its not near price levels. so i would change it to
declare lower


other studies that may be of interest
https://usethinkscript.com/threads/6th-order-polynomial-best-fit-for-thinkorswim.15196/
https://usethinkscript.com/threads/polynomial-regression-channel-prc-quadratic-regression.1491/
 
Hi all!

I'm trying to make a scan to find stocks that are in a squeeze within 20 cents of ORB levels (squeeze above the 30 minute high, squeeze below the 30 minute low).. with ChatGPT, I got this but it doesn't seem to work properly. Some stocks coming up ARE in the correct spot, but some are not. Attached is a photo of MRNA today, 4/7 on the 1 minute chart. This is the ideal setup I'm looking for (purple candles on the right). Any help would be greatly appreciated!



Code:
def marketOpen = 0930;
def firstBar = SecondsFromTime(marketOpen * 100) < 1800;
def thirtyMinHigh = Highest(high, 30);
def thirtyMinLow = Lowest(low, 30);

def inSqueeze = TTM_Squeeze().SqueezeAlert == 0;

def withinHighRange = AbsValue(close - thirtyMinHigh) <= 0.20;
def withinLowRange = AbsValue(close - thirtyMinLow) <= 0.20;

plot scan = inSqueeze and (withinHighRange or withinLowRange);

reply #389

there are several things wrong with your code.
next time, go find an orb code and start with that.

i made an upper code first, so i can see what is going on and get the bugs out
i made colored bubbles that show a few values
draws lines at the orb levels
when the upper works, i copy it and modify it to be a lower/scan


upper chart code for testing
Code:
#chat389_scan_sqz_orb
#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-20#post-152277

def na = double.nan;
def bn = barnumber();
def marketOpen = 0930;
input orb_min = 30;
input orb_range = 0.2;

def orb_sec = orb_min *60;
#def firstBar = SecondsFromTime(marketOpen * 100) < 1800;
#def firstBar = SecondsFromTime(marketOpen) < 1800;
def orbBar = SecondsFromTime(marketOpen) >= 0 and SecondsFromTime(marketOpen) < orb_sec;

def gd = getday();
def n = 400;
def big = 99999;

# find last bar of orb period, then find highest and lowest of orb
def orbhi;
def orblo;
if gd != gd[1] then {
 orbhi = 0;
 orblo = 0;
} else
if (orbbar[0] and !orbbar[-1]) then {
 #def thirtyMinHigh = Highest(high, 30);
 #def thirtyMinLow = Lowest(low, 30);
# orbhi = Highest(high, 30);
# orblo = Lowest(low, 30);
 orbhi = fold a = 0 to n
 with b
 while getvalue(orbbar,a)
 do max(getvalue(high,a),b);

 orblo = fold c = 0 to n
 with d = big
 while getvalue(orbbar,c)
 do min(getvalue(low,c),d);
} else {
 orbhi = orbhi[1];
 orblo = orblo[1];
}


def orbafter = SecondsFromTime(marketOpen) >= orb_sec;
plot zhi = if orbafter and orbhi > 0 then orbhi else na;
plot zlo = if orbafter and orblo > 0 then orblo else na;

def inSqueeze = TTM_Squeeze().SqueezeAlert == 0;

#def withinHighRange = AbsValue(close - thirtyMinHigh) <= 0.20;
#def withinLowRange = AbsValue(close - thirtyMinLow) <= 0.20;
def withinHighRange = AbsValue(close - orbhi) <= orb_range;
def withinLowRange = AbsValue(close - orblo) <= orb_range;


def scan = inSqueeze and (withinHighRange or withinLowRange);
#plot z = scan;

addchartbubble(1, low*0.995,
# orb_sec + "\n" +
 SecondsFromTime(marketOpen) + "\n" +
 orbbar + "\n" +
# (orbbar[0] and !orbbar[-1]) + "\n" +
 (if inSqueeze then "SQZ" else "-") + "\n" +
 withinHighRange + "\n" +
 withinLowRange + "\n" +
 orbhi + "\n" +
 orblo + "\n" +
 scan
, ( if orbbar then color.blue else if scan then color.white else if withinHighRange then color.green else if withinlowRange then color.red else color.gray), no);
#


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

lower code, for scanning
Code:
#chat389_scan_sqz_orb_lower
#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-20#post-152277

declare lower;

def na = double.nan;
def bn = barnumber();
def marketOpen = 0930;
input orb_min = 30;
input orb_range = 0.2;

def orb_sec = orb_min *60;
#def firstBar = SecondsFromTime(marketOpen * 100) < 1800;
#def firstBar = SecondsFromTime(marketOpen) < 1800;
def orbBar = SecondsFromTime(marketOpen) >= 0 and SecondsFromTime(marketOpen) < orb_sec;

def gd = getday();
def n = 400;
def big = 99999;

# find last bar of orb period, then find highest and lowest of orb
def orbhi;
def orblo;
if gd != gd[1] then {
 orbhi = 0;
 orblo = 0;
} else
if (orbbar[0] and !orbbar[-1]) then {
 #def thirtyMinHigh = Highest(high, 30);
 #def thirtyMinLow = Lowest(low, 30);
# orbhi = Highest(high, 30);
# orblo = Lowest(low, 30);
 orbhi = fold a = 0 to n
 with b
 while getvalue(orbbar,a)
 do max(getvalue(high,a),b);

 orblo = fold c = 0 to n
 with d = big
 while getvalue(orbbar,c)
 do min(getvalue(low,c),d);
} else {
 orbhi = orbhi[1];
 orblo = orblo[1];
}


def orbafter = SecondsFromTime(marketOpen) >= orb_sec;
#plot zhi = if orbafter and orbhi > 0 then orbhi else na;
#plot zlo = if orbafter and orblo > 0 then orblo else na;

def inSqueeze = TTM_Squeeze().SqueezeAlert == 0;

#def withinHighRange = AbsValue(close - thirtyMinHigh) <= 0.20;
#def withinLowRange = AbsValue(close - thirtyMinLow) <= 0.20;
def withinHighRange = AbsValue(close - orbhi) <= orb_range;
def withinLowRange = AbsValue(close - orblo) <= orb_range;


def scan = inSqueeze and (withinHighRange or withinLowRange);
plot z = scan;

addchartbubble(0, low*0.995,
# orb_sec + "\n" +
 SecondsFromTime(marketOpen) + "\n" +
 orbbar + "\n" +
# (orbbar[0] and !orbbar[-1]) + "\n" +
 (if inSqueeze then "SQZ" else "-") + "\n" +
 withinHighRange + "\n" +
 withinLowRange + "\n" +
 orbhi + "\n" +
 orblo + "\n" +
 scan
, ( if orbbar then color.blue else if scan then color.white else if withinHighRange then color.green else if withinlowRange then color.red else color.gray), no);
#
 

Attachments

  • img1.JPG
    img1.JPG
    139 KB · Views: 21

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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