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

#### MerryDay

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

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

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

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

Last edited:
Hi,

Could someone help me with the code to show the distance in % terms between a chosen SMA/EMA and the daily ATR and/or Weekly/Session/Monthly VWAP ?

ChatGPT gave me start, but I don't want it to plot, I'd like for it to show as seperate labels. First label would be % away from ATR and second label would be % away from selected VWAP. And the EMA/SMA is adjustable (both the period and the type)

Code:
``````# Input for Moving Average Type
input maType = {default "SMA", "EMA"};

# Input for Moving Average Period
input maPeriod = 20;

# Input for VWAP Timeframe
input vwapTimeframe = {default "Daily", "Weekly", "Monthly"};

# Calculate Moving Average
def ma;
switch (maType) {
case "SMA":
ma = SimpleMovingAvg(close, maPeriod);
case "EMA":
ma = ExpAverage(close, maPeriod);
}

# Calculate VWAP based on selected timeframe
def vwap;
switch (vwapTimeframe) {
case "Daily":
vwap = VWAP();
case "Weekly":
vwap = VWAP(overlap = "WEEK");
case "Monthly":
vwap = VWAP(overlap = "MONTH");
}

# Calculate Percentage Difference between MA and VWAP
def percentDifference = (ma - vwap) / ma * 100;

# Plot the Percentage Difference
plot PercentDiffPlot = percentDifference;
PercentDiffPlot.SetDefaultColor(GetColor(1));  # Adjust color as needed
PercentDiffPlot.SetLineWeight(2);
PercentDiffPlot.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
PercentDiffPlot.AssignValueColor(if percentDifference > 0 then Color.GREEN else Color.RED);
PercentDiffPlot.SetLineWeight(2);
PercentDiffPlot.SetDefaultColor(Color.GRAY);

# Add a reference line at zero

Code:
``````#chat183_dist_from_avg

#hboogie
#183
#Could someone help me with the code to show the distance in % terms between a chosen SMA/EMA and the daily ATR and/or Weekly/Session/Monthly VWAP ?

#ChatGPT gave me start, but I don't want it to plot, I'd like for it to show as seperate labels. First label would be % away from ATR and second label would be % away from selected VWAP. And the EMA/SMA is adjustable (both the period and the type)

def na = double.nan;

# Input for Moving Average Type
input maType = {default "SMA", "EMA"};

# Input for Moving Average Period
input maPeriod = 20;

# Input for VWAP Timeframe
input vwapTimeframe = {default "Daily", "Weekly", "Monthly"};

# Calculate Moving Average
def ma;
switch (maType) {
case "SMA":
ma = SimpleMovingAvg(close, maPeriod);
case "EMA":
ma = ExpAverage(close, maPeriod);
}

# Calculate VWAP based on selected timeframe
def vwap1;
switch (vwapTimeframe) {
case "Daily":
#  vwap = vwap();
vwap1 = vwap(period = AggregationPeriod.DAY);
case "Weekly":
vwap1 = vwap(period = AggregationPeriod.week);
case "Monthly":
vwap1 = vwap(period = AggregationPeriod.month);
}

input show_avg = yes;
plot za = if show_avg then ma else na;
za.setdefaultcolor(color.yellow);

input show_vwap = yes;
plot zv = if show_vwap then vwap1 else na;
zv.setdefaultcolor(color.magenta);

# Calculate Percentage Difference between MA and VWAP
def percentDifference = (ma - vwap) / ma * 100;

addlabel(1, "diff" + percentDifference, (if percentDifference > 0 then Color.GREEN else Color.RED));

#
# Plot the Percentage Difference
#plot PercentDiffPlot = percentDifference;
#PercentDiffPlot.SetLineWeight(2);
#PercentDiffPlot.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#PercentDiffPlot.AssignValueColor(if percentDifference > 0 then Color.GREEN else Color.RED);
#PercentDiffPlot.SetLineWeight(2);
#``````

Code:
``````#chat183_dist_from_avg

#hboogie
#183
#Could someone help me with the code to show the distance in % terms between a chosen SMA/EMA and the daily ATR and/or Weekly/Session/Monthly VWAP ?

#ChatGPT gave me start, but I don't want it to plot, I'd like for it to show as seperate labels. First label would be % away from ATR and second label would be % away from selected VWAP. And the EMA/SMA is adjustable (both the period and the type)

def na = double.nan;

# Input for Moving Average Type
input maType = {default "SMA", "EMA"};

# Input for Moving Average Period
input maPeriod = 20;

# Input for VWAP Timeframe
input vwapTimeframe = {default "Daily", "Weekly", "Monthly"};

# Calculate Moving Average
def ma;
switch (maType) {
case "SMA":
ma = SimpleMovingAvg(close, maPeriod);
case "EMA":
ma = ExpAverage(close, maPeriod);
}

# Calculate VWAP based on selected timeframe
def vwap1;
switch (vwapTimeframe) {
case "Daily":
#  vwap = vwap();
vwap1 = vwap(period = AggregationPeriod.DAY);
case "Weekly":
vwap1 = vwap(period = AggregationPeriod.week);
case "Monthly":
vwap1 = vwap(period = AggregationPeriod.month);
}

input show_avg = yes;
plot za = if show_avg then ma else na;
za.setdefaultcolor(color.yellow);

input show_vwap = yes;
plot zv = if show_vwap then vwap1 else na;
zv.setdefaultcolor(color.magenta);

# Calculate Percentage Difference between MA and VWAP
def percentDifference = (ma - vwap) / ma * 100;

addlabel(1, "diff" + percentDifference, (if percentDifference > 0 then Color.GREEN else Color.RED));

#
# Plot the Percentage Difference
#plot PercentDiffPlot = percentDifference;
#PercentDiffPlot.SetLineWeight(2);
#PercentDiffPlot.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#PercentDiffPlot.AssignValueColor(if percentDifference > 0 then Color.GREEN else Color.RED);
#PercentDiffPlot.SetLineWeight(2);
#``````
Thanks!

This is great! I tried , but sadly can't do it. Hoping to add the ATR, both daily and weekly, as a separate label that shows distance from chosen SMA/EMA. IF both VWAP and ATR can't be defined in the same script, I'd default to being able to see the % diff from SMA/EMA to ATR, either daily or weekly.

Thank you!!

Edit* I noticed in the code that you have logic/label to show "Average" but don't see that defined? Hoping you can change that to ATR, both daily and weekly. Adding a bit to the post, but being able for me to input the length of the ATR would be helpful too. The default is 14, but if i can change the input, it would help me see how far price is intraday and watch it move real-time to confirm trend direction. For say ES, I'd want to see an ATR (3) vs standard 14 where a stock I'd like to see the standard 14.

So below ma period would be ATR period. And above vwap timeframe there would be an: ATR timeframe (daily, weekly)

Thank you for the plot logic below for histogram. I'll enable it just to see how it looks. You rock!

Hope this is clear.

Thanks!!!

Last edited:
Hi,

Working through creating an rvol script to use for option premium charts. This is my current code and could use a hand on the following items:

1. I don't want/need to plot a zero line with static values, would love for that to be dynamic and for it to adjust depending on the symbol.
2. I introduced exhaustion logic such that points would only paint if the rvol change thresholds met AND prior "1" volume bar is >= 20% lower than total of cumulative volume of the first 15 bars of the session. The code as written ( courtesy of chatgpt, is not doing that )
3. For good measure I would like to be able to create an input for that volume bar back number so that I can test with it during the day and see if the signals trigger better for 1-3 candles prior
Here is the code.

Code:
``````# --------------------------------------------------------------
# Relative Volume Code with Price Exhaustion Logic
# hboogie
# --------------------------------------------------------------

# Define Rvol Thresholds
declare lower;

input rvolMultiplier1 = 1.5;
input rvolMultiplier2 = 2.0;
input rvolMultiplier3 = 3.0;
input rvolMultiplier4 = 5.0;
input rvolMultiplier5 = 8.0;

input maPeriod = 21;
input pctvolchg = 5;  # Percentage volume change
input pctvolchg1 = 10;

# Calculate the total sum of volume from the first 15 bars
def startBar = secondsFromTime(0930) / secondsFromTime(1);  # 9:30 AM EST
def endBar = startBar + 14;  # First 15 bars
def sessionVolume = TotalSum(if BarNumber() >= startBar and BarNumber() <= endBar then volume else 0);

# Calculate the relative volume change
def rvolChange = ((volume - sessionVolume) / sessionVolume) * 100;

# Calculate the oscillator value
def oscillatorValue = Min(Max(rvolChange, -500), 500);

# Choose the Moving Average type (Exponential)
def maValue = ExpAverage(oscillatorValue, maPeriod);

# Determine spike thresholds based on a % increase
def spikeThreshold = rvolChange > pctvolchg;
def spikeThreshold1 = rvolChange > pctvolchg1;

# Define Rvol Thresholds
def rvolThreshold1 = rvolMultiplier1 * sessionVolume;
def rvolThreshold2 = rvolMultiplier2 * sessionVolume;
def rvolThreshold3 = rvolMultiplier3 * sessionVolume;
def rvolThreshold4 = rvolMultiplier4 * sessionVolume;
def rvolThreshold5 = rvolMultiplier5 * sessionVolume;

# Define logic for volume contraction
def volumeContraction = rvolChange < (0.6 * AbsValue(rvolChange[1]));

# Plot the zero line
plot ZeroLine = 0;
ZeroLine.SetPaintingStrategy(PaintingStrategy.LINE);
ZeroLine.SetDefaultColor(Color.GRAY);

# Plot colored points for the spike thresholds
plot SpikePoints = if spikeThreshold and volumeContraction then 0 else double.nan;
SpikePoints.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints.AssignValueColor(Color.GREEN);

# Plot points
plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints1.AssignValueColor(Color.VIOLET);

# Plot the oscillator in the lower pane (Exponential MA)
plot RelativeVolumeOscillator = maValue;
RelativeVolumeOscillator.AssignValueColor(
if rvolChange >= rvolThreshold5 then Color.RED
else if rvolChange >= rvolThreshold4 then Color.MAGENTA
else if rvolChange >= rvolThreshold3 then Color.CYAN
else if rvolChange >= rvolThreshold2 then Color.YELLOW
else if rvolChange >= rvolThreshold1 then Color.GREEN
else Color.GRAY
);
RelativeVolumeOscillator.SetLineWeight(1);
RelativeVolumeOscillator.HideTitle();``````

Hi,

Working through creating an rvol script to use for option premium charts. This is my current code and could use a hand on the following items:

1. I don't want/need to plot a zero line with static values, would love for that to be dynamic and for it to adjust depending on the symbol.
2. I introduced exhaustion logic such that points would only paint if the rvol change thresholds met AND prior "1" volume bar is >= 20% lower than total of cumulative volume of the first 15 bars of the session. The code as written ( courtesy of chatgpt, is not doing that )
3. For good measure I would like to be able to create an input for that volume bar back number so that I can test with it during the day and see if the signals trigger better for 1-3 candles prior
Here is the code.

Code:
``````# --------------------------------------------------------------
# Relative Volume Code with Price Exhaustion Logic
# hboogie
# --------------------------------------------------------------

# Define Rvol Thresholds
declare lower;

input rvolMultiplier1 = 1.5;
input rvolMultiplier2 = 2.0;
input rvolMultiplier3 = 3.0;
input rvolMultiplier4 = 5.0;
input rvolMultiplier5 = 8.0;

input maPeriod = 21;
input pctvolchg = 5;  # Percentage volume change
input pctvolchg1 = 10;

# Calculate the total sum of volume from the first 15 bars
def startBar = secondsFromTime(0930) / secondsFromTime(1);  # 9:30 AM EST
def endBar = startBar + 14;  # First 15 bars
def sessionVolume = TotalSum(if BarNumber() >= startBar and BarNumber() <= endBar then volume else 0);

# Calculate the relative volume change
def rvolChange = ((volume - sessionVolume) / sessionVolume) * 100;

# Calculate the oscillator value
def oscillatorValue = Min(Max(rvolChange, -500), 500);

# Choose the Moving Average type (Exponential)
def maValue = ExpAverage(oscillatorValue, maPeriod);

# Determine spike thresholds based on a % increase
def spikeThreshold = rvolChange > pctvolchg;
def spikeThreshold1 = rvolChange > pctvolchg1;

# Define Rvol Thresholds
def rvolThreshold1 = rvolMultiplier1 * sessionVolume;
def rvolThreshold2 = rvolMultiplier2 * sessionVolume;
def rvolThreshold3 = rvolMultiplier3 * sessionVolume;
def rvolThreshold4 = rvolMultiplier4 * sessionVolume;
def rvolThreshold5 = rvolMultiplier5 * sessionVolume;

# Define logic for volume contraction
def volumeContraction = rvolChange < (0.6 * AbsValue(rvolChange[1]));

# Plot the zero line
plot ZeroLine = 0;
ZeroLine.SetPaintingStrategy(PaintingStrategy.LINE);
ZeroLine.SetDefaultColor(Color.GRAY);

# Plot colored points for the spike thresholds
plot SpikePoints = if spikeThreshold and volumeContraction then 0 else double.nan;
SpikePoints.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints.AssignValueColor(Color.GREEN);

# Plot points
plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints1.AssignValueColor(Color.VIOLET);

# Plot the oscillator in the lower pane (Exponential MA)
plot RelativeVolumeOscillator = maValue;
RelativeVolumeOscillator.AssignValueColor(
if rvolChange >= rvolThreshold5 then Color.RED
else if rvolChange >= rvolThreshold4 then Color.MAGENTA
else if rvolChange >= rvolThreshold3 then Color.CYAN
else if rvolChange >= rvolThreshold2 then Color.YELLOW
else if rvolChange >= rvolThreshold1 then Color.GREEN
else Color.GRAY
);
RelativeVolumeOscillator.SetLineWeight(1);
RelativeVolumeOscillator.HideTitle();``````

most formulas are wrong,

this won't be a barnumber, just some number
#def startBar = secondsFromTime(0930) / secondsFromTime(1); # 9:30 AM EST

sessionVolume should not include the volume from the current bar

sessionVolume should be divided by the quantity of bars, in the desired time periods, to get an average,
an average, not the total, should be used in this formula,
old
def rvolChange = ((sessionVolume - volume) / sessionVolume) * 100;

new
def rvol_avg = sessionVolume / bar_qty;
def rvolChange = ((rvol_avg - volume) / rvol_avg) * 100;

having 2 plots at the same time, when both are true, wont ever show the 2nd color.
need to combine them into 1 plot formula.
plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
plot SpikePoints2 = if

this should use an average, not sessionVolume.
def rvolThreshold1 = rvolMultiplier1 * sessionVolume;

this will never be true, when sessionVolume is used in prev formula
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if absrvol >= rvolThreshold5 then Color.RED

this uses sessionvolume, so is too big
# Define Rvol Thresholds
#def rvolThreshold1 = rvolMultiplier1 * sessionVolume;

if the sessionVolume is replaced with the average volume, rvolThreshold1 will still be too big.
the change in volume will almost never be bigger than the average
i think the rvolMultiplier numbers need to be smaller

add a factor to make threshold numbers smaller
def f = 1/10000;
# Define Rvol Thresholds
def rvolThreshold1 = rvolMultiplier1 * rvol_avg * f;

rvolChange can be negative, so some values will be missed in this plot. use absvalue( ) on it.
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if rvolChange >= rvolThreshold5 then Color.RED

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

i didn't address your 3 questions. i didn't understand them. (fyi, i don't care if you call something exhaustion, that word doesn't describe what a formula has to do).
go ahead and experiment with this, clean it up. turn on the bubbles and look at variable values. learn what is going on.
then make a new post with clear questions as to what the next version will be.

Code:
``````#rvol_compare_first_xbars_01

#Dynamic Zero Line and Rvol Contraction
#hboogie  Nov 21, 2023

#Working through creating an rvol script to use for option premium charts. This is my current code and could use a hand on the following items:

#I don't want/need to plot a zero line with static values, would love for that to be dynamic and for it to adjust depending on the symbol.
#I introduced exhaustion logic such that points would only paint if the rvol change thresholds met AND prior "1" volume bar is >= 20% lower than total of cumulative volume of the first 15 bars of the session. The code as written ( courtesy of chatgpt, is not doing that )
#For good measure I would like to be able to create an input for that volume bar back number so that I can test with it during the day and see if the signals trigger better for 1-3 candles prior

# --------------------------------------------------------------
# Relative Volume Code with Price Exhaustion Logic
# hboogie
# --------------------------------------------------------------

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

def gd = getday();
def lastday = getlastday();
def currentday = gd == lastday;

def lastbar = (!isnan(close) and isnan(close[-1]));

# Define Rvol Thresholds
declare lower;

input rvolMultiplier1 = 1.5;
input rvolMultiplier2 = 2.0;
input rvolMultiplier3 = 3.0;
input rvolMultiplier4 = 5.0;
input rvolMultiplier5 = 8.0;

input maPeriod = 21;
input pctvolchg1 = 5;  # Percentage volume change
input pctvolchg2 = 10;

def period_bars = 15;

# find barnumber at day open, each day
#def startBar = secondsFromTime(0930) / secondsFromTime(1);  # 9:30 AM EST
def startBar = if secondsFromTime(0930) == 0 then bn else startbar[1];

def barcnt = if bn == 1 then 1 else if secondsFromTime(0930) == 0 then 1 else barcnt[1] + 1;

def endBar = startBar + period_bars - 1;  # First 15 bars

#def sessionVolume = TotalSum(if BarNumber() >= startBar and BarNumber() <= endBar then volume else 0);

def bars_en = (BarNumber() >= startBar and BarNumber() <= endBar);

# Calculate the total sum of volume from the first 15 bars, of each day ( except current bar
#def sessionVolume = TotalSum(if bars_en and !lastbar then volume else 0);

def sessionVolume =  if bars_en and !lastbar then sessionVolume[1] + volume else sessionVolume[1];
#if bn == 1 then 0 else

# get qty of bars, exclude last bar
def bar_qty = if bars_en and !lastbar then bar_qty[1] + 1 else bar_qty[1];

# rvol average
def rvol_avg = sessionVolume / bar_qty;

# session   v  needs to be divided by qty to get avg
#sessionVolume should be divided by a quantity of bars, to get an average, to be used in this,
#and sessionVolume should not include the volume from current bar

# Calculate the relative volume change
#def rvolChange = ((volume - sessionVolume) / sessionVolume) * 100;
#def rvolChange = ((sessionVolume - volume) / sessionVolume) * 100;
def rvolChange = ((rvol_avg - volume) / rvol_avg) * 100;

def n_bars = 500;
# Calculate the oscillator value
def oscillatorValue = Min(Max(rvolChange, -n_bars), n_bars);

# Choose the Moving Average type (Exponential)
def maValue = ExpAverage(oscillatorValue, maPeriod);

# Determine spike thresholds based on a % increase
def spikeThreshold1 = rvolChange > pctvolchg1;
def spikeThreshold2 = rvolChange > pctvolchg2;

# add a factor to make threshold numbers smaller, close to the vol change
def f = 1/10000;
# Define Rvol Thresholds
#def rvolThreshold1 = rvolMultiplier1 * sessionVolume;
#def rvolThreshold2 = rvolMultiplier2 * sessionVolume;
#def rvolThreshold3 = rvolMultiplier3 * sessionVolume;
#def rvolThreshold4 = rvolMultiplier4 * sessionVolume;
#def rvolThreshold5 = rvolMultiplier5 * sessionVolume;
def rvolThreshold1 = rvolMultiplier1 * rvol_avg * f;
def rvolThreshold2 = rvolMultiplier2 * rvol_avg * f;
def rvolThreshold3 = rvolMultiplier3 * rvol_avg * f;
def rvolThreshold4 = rvolMultiplier4 * rvol_avg * f;
def rvolThreshold5 = rvolMultiplier5 * rvol_avg * f;

# Define logic for volume contraction
def volumeContraction = rvolChange < (0.6 * AbsValue(rvolChange[1]));

# Plot the zero line
plot ZeroLine = 0;
ZeroLine.SetPaintingStrategy(PaintingStrategy.LINE);
ZeroLine.SetDefaultColor(Color.GRAY);

# Plot colored points for the spike thresholds
#plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
#SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
#SpikePoints1.AssignValueColor(Color.GREEN);
#SpikePoints1.setlineweight(3);
#SpikePoints1.hidebubble();

# Plot points
#plot SpikePoints2 = if spikeThreshold2 and volumeContraction then 0 else double.nan;
#SpikePoints2.SetPaintingStrategy(PaintingStrategy.POINTS);
#SpikePoints2.AssignValueColor(Color.VIOLET);
#SpikePoints2.setlineweight(3);
#SpikePoints2.hidebubble();

plot SpikePoints1 = if (spikeThreshold1 or spikeThreshold2) and volumeContraction then 0 else double.nan;
SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints1.AssignValueColor(if spikeThreshold2 then color.magenta else if spikeThreshold1 then Color.GREEN else color.gray);
SpikePoints1.setlineweight(3);
SpikePoints1.hidebubble();

def absrvol = absvalue(rvolChange);

# Plot the oscillator in the lower pane (Exponential MA)
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if absrvol >= rvolThreshold5 then Color.RED
else if absrvol >= rvolThreshold4 then Color.MAGENTA
else if absrvol >= rvolThreshold3 then Color.CYAN
else if absrvol >= rvolThreshold2 then Color.YELLOW
else if absrvol >= rvolThreshold1 then Color.GREEN
else Color.GRAY
);

rel_vol_osc.SetLineWeight(1);
rel_vol_osc.HideTitle();

bn + "\n" +
#startBar  + "\n" +
#bars_en + "\n" +
#barcnt
rvolChange + "\n" +
#sessionVolume + "\n" +
#sessionVolume2 + "\n" +
bar_qty + "\n" +
rvol_avg + "\n" +
#spikeThreshold1 + "\n" +
#spikeThreshold2
volume
#" "
, color.yellow, no);

absrvol + "\n" +
rvolThreshold5 + "\n" +
rvolThreshold4 + "\n" +
rvolThreshold3 + "\n" +
rvolThreshold2 + "\n" +
rvolThreshold1 + "\n"
, color.yellow, no);

#``````

most formulas are wrong,

this won't be a barnumber, just some number
#def startBar = secondsFromTime(0930) / secondsFromTime(1); # 9:30 AM EST

sessionVolume should not include the volume from the current bar

sessionVolume should be divided by the quantity of bars, in the desired time periods, to get an average,
an average, not the total, should be used in this formula,
old
def rvolChange = ((sessionVolume - volume) / sessionVolume) * 100;

new
def rvol_avg = sessionVolume / bar_qty;
def rvolChange = ((rvol_avg - volume) / rvol_avg) * 100;

having 2 plots at the same time, when both are true, wont ever show the 2nd color.
need to combine them into 1 plot formula.
plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
plot SpikePoints2 = if

this should use an average, not sessionVolume.
def rvolThreshold1 = rvolMultiplier1 * sessionVolume;

this will never be true, when sessionVolume is used in prev formula
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if absrvol >= rvolThreshold5 then Color.RED

this uses sessionvolume, so is too big
# Define Rvol Thresholds
#def rvolThreshold1 = rvolMultiplier1 * sessionVolume;

if the sessionVolume is replaced with the average volume, rvolThreshold1 will still be too big.
the change in volume will almost never be bigger than the average
i think the rvolMultiplier numbers need to be smaller

add a factor to make threshold numbers smaller
def f = 1/10000;
# Define Rvol Thresholds
def rvolThreshold1 = rvolMultiplier1 * rvol_avg * f;

rvolChange can be negative, so some values will be missed in this plot. use absvalue( ) on it.
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if rvolChange >= rvolThreshold5 then Color.RED

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

i didn't address your 3 questions. i didn't understand them. (fyi, i don't care if you call something exhaustion, that word doesn't describe what a formula has to do).
go ahead and experiment with this, clean it up. turn on the bubbles and look at variable values. learn what is going on.
then make a new post with clear questions as to what the next version will be.

Code:
``````#rvol_compare_first_xbars_01

#Dynamic Zero Line and Rvol Contraction
#hboogie  Nov 21, 2023

#Working through creating an rvol script to use for option premium charts. This is my current code and could use a hand on the following items:

#I don't want/need to plot a zero line with static values, would love for that to be dynamic and for it to adjust depending on the symbol.
#I introduced exhaustion logic such that points would only paint if the rvol change thresholds met AND prior "1" volume bar is >= 20% lower than total of cumulative volume of the first 15 bars of the session. The code as written ( courtesy of chatgpt, is not doing that )
#For good measure I would like to be able to create an input for that volume bar back number so that I can test with it during the day and see if the signals trigger better for 1-3 candles prior

# --------------------------------------------------------------
# Relative Volume Code with Price Exhaustion Logic
# hboogie
# --------------------------------------------------------------

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

def gd = getday();
def lastday = getlastday();
def currentday = gd == lastday;

def lastbar = (!isnan(close) and isnan(close[-1]));

# Define Rvol Thresholds
declare lower;

input rvolMultiplier1 = 1.5;
input rvolMultiplier2 = 2.0;
input rvolMultiplier3 = 3.0;
input rvolMultiplier4 = 5.0;
input rvolMultiplier5 = 8.0;

input maPeriod = 21;
input pctvolchg1 = 5;  # Percentage volume change
input pctvolchg2 = 10;

def period_bars = 15;

# find barnumber at day open, each day
#def startBar = secondsFromTime(0930) / secondsFromTime(1);  # 9:30 AM EST
def startBar = if secondsFromTime(0930) == 0 then bn else startbar[1];

def barcnt = if bn == 1 then 1 else if secondsFromTime(0930) == 0 then 1 else barcnt[1] + 1;

def endBar = startBar + period_bars - 1;  # First 15 bars

#def sessionVolume = TotalSum(if BarNumber() >= startBar and BarNumber() <= endBar then volume else 0);

def bars_en = (BarNumber() >= startBar and BarNumber() <= endBar);

# Calculate the total sum of volume from the first 15 bars, of each day ( except current bar
#def sessionVolume = TotalSum(if bars_en and !lastbar then volume else 0);

def sessionVolume =  if bars_en and !lastbar then sessionVolume[1] + volume else sessionVolume[1];
#if bn == 1 then 0 else

# get qty of bars, exclude last bar
def bar_qty = if bars_en and !lastbar then bar_qty[1] + 1 else bar_qty[1];

# rvol average
def rvol_avg = sessionVolume / bar_qty;

# session   v  needs to be divided by qty to get avg
#sessionVolume should be divided by a quantity of bars, to get an average, to be used in this,
#and sessionVolume should not include the volume from current bar

# Calculate the relative volume change
#def rvolChange = ((volume - sessionVolume) / sessionVolume) * 100;
#def rvolChange = ((sessionVolume - volume) / sessionVolume) * 100;
def rvolChange = ((rvol_avg - volume) / rvol_avg) * 100;

def n_bars = 500;
# Calculate the oscillator value
def oscillatorValue = Min(Max(rvolChange, -n_bars), n_bars);

# Choose the Moving Average type (Exponential)
def maValue = ExpAverage(oscillatorValue, maPeriod);

# Determine spike thresholds based on a % increase
def spikeThreshold1 = rvolChange > pctvolchg1;
def spikeThreshold2 = rvolChange > pctvolchg2;

# add a factor to make threshold numbers smaller, close to the vol change
def f = 1/10000;
# Define Rvol Thresholds
#def rvolThreshold1 = rvolMultiplier1 * sessionVolume;
#def rvolThreshold2 = rvolMultiplier2 * sessionVolume;
#def rvolThreshold3 = rvolMultiplier3 * sessionVolume;
#def rvolThreshold4 = rvolMultiplier4 * sessionVolume;
#def rvolThreshold5 = rvolMultiplier5 * sessionVolume;
def rvolThreshold1 = rvolMultiplier1 * rvol_avg * f;
def rvolThreshold2 = rvolMultiplier2 * rvol_avg * f;
def rvolThreshold3 = rvolMultiplier3 * rvol_avg * f;
def rvolThreshold4 = rvolMultiplier4 * rvol_avg * f;
def rvolThreshold5 = rvolMultiplier5 * rvol_avg * f;

# Define logic for volume contraction
def volumeContraction = rvolChange < (0.6 * AbsValue(rvolChange[1]));

# Plot the zero line
plot ZeroLine = 0;
ZeroLine.SetPaintingStrategy(PaintingStrategy.LINE);
ZeroLine.SetDefaultColor(Color.GRAY);

# Plot colored points for the spike thresholds
#plot SpikePoints1 = if spikeThreshold1 and volumeContraction then 0 else double.nan;
#SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
#SpikePoints1.AssignValueColor(Color.GREEN);
#SpikePoints1.setlineweight(3);
#SpikePoints1.hidebubble();

# Plot points
#plot SpikePoints2 = if spikeThreshold2 and volumeContraction then 0 else double.nan;
#SpikePoints2.SetPaintingStrategy(PaintingStrategy.POINTS);
#SpikePoints2.AssignValueColor(Color.VIOLET);
#SpikePoints2.setlineweight(3);
#SpikePoints2.hidebubble();

plot SpikePoints1 = if (spikeThreshold1 or spikeThreshold2) and volumeContraction then 0 else double.nan;
SpikePoints1.SetPaintingStrategy(PaintingStrategy.POINTS);
SpikePoints1.AssignValueColor(if spikeThreshold2 then color.magenta else if spikeThreshold1 then Color.GREEN else color.gray);
SpikePoints1.setlineweight(3);
SpikePoints1.hidebubble();

def absrvol = absvalue(rvolChange);

# Plot the oscillator in the lower pane (Exponential MA)
plot rel_vol_osc = maValue;
rel_vol_osc.AssignValueColor(
if absrvol >= rvolThreshold5 then Color.RED
else if absrvol >= rvolThreshold4 then Color.MAGENTA
else if absrvol >= rvolThreshold3 then Color.CYAN
else if absrvol >= rvolThreshold2 then Color.YELLOW
else if absrvol >= rvolThreshold1 then Color.GREEN
else Color.GRAY
);

rel_vol_osc.SetLineWeight(1);
rel_vol_osc.HideTitle();

bn + "\n" +
#startBar  + "\n" +
#bars_en + "\n" +
#barcnt
rvolChange + "\n" +
#sessionVolume + "\n" +
#sessionVolume2 + "\n" +
bar_qty + "\n" +
rvol_avg + "\n" +
#spikeThreshold1 + "\n" +
#spikeThreshold2
volume
#" "
, color.yellow, no);

absrvol + "\n" +
rvolThreshold5 + "\n" +
rvolThreshold4 + "\n" +
rvolThreshold3 + "\n" +
rvolThreshold2 + "\n" +
rvolThreshold1 + "\n"
, color.yellow, no);

#``````

Thank you for giving me a start and for your time. Truly appreciate it. Thank you

Thank you for giving me a start and for your time. Truly appreciate it. Thank you
welcome. keep asking questions, keep learning

unusual option volume with buy and sell strategy

Can someone help me refine the code where i can use it for mobile. My idea is that when there is massive options buying either call or put the premium of either one is overbought or oversold. next two days they will sell or buy. so i combine with the option volume scanner plus B4 indicator and RS percentile.

#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

#______________________________

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;

input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

##________________

# B4 Signal
#
# Free for use for non commercial. Header credits must be included when any form of the code included in this package is used.
# User assumes all risk. Author not responsible for errors or use of tool.
# Copyright (c) 2021 B4 Signals
#
# v3.0 - barbros / chuck - official release

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_sell && cluster ;
# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_up);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.green);
scanResults.HideBubble();

code : Selling
#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;
input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_down);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.red);
scanResults.HideBubble();

this codes itself can be use with thinkorswim platform but i can not use it on mobile and i would like to use it on Mobile app.
using this code alone "
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

will work on mobile but i want the combine strategy combine and it gives me the arrow. can someone help. thanks

Last edited by a moderator:
Can someone help me refine the code where i can use it for mobile. My idea is that when there is massive options buying either call or put the premium of either one is overbought or oversold. next two days they will sell or buy. so i combine with the option volume scanner plus B4 indicator and RS percentile.

#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

#______________________________

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;

input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

##________________

# B4 Signal
#
# Free for use for non commercial. Header credits must be included when any form of the code included in this package is used.
# User assumes all risk. Author not responsible for errors or use of tool.
# Copyright (c) 2021 B4 Signals
#
# Get support at: https://b4signals.com
#
#
# v3.0 - barbros / chuck - official release

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_sell && cluster ;
# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_up);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.green);
scanResults.HideBubble();

code : Selling
#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;
input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_down);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.red);
scanResults.HideBubble();

this codes itself can be use with thinkorswim platform but i can not use it on mobile and i would like to use it on Mobile app.
using this code alone "
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

will work on mobile but i want the combine strategy combine and it gives me the arrow. can someone help. thanks

View attachment 19684
hi, i tried adding this code but was unsuccessful. can you share a link or repaste so i can copy and paste.

Thanks!

Please help me correct this code so that the labels show the start and end in 12 hour format.

# Convierte los valores de tiempo a formato de horas
def inicioHora = if !IsNaN(inicio) then floor(inicio / 100) + (inicio % 100) / 60 else 0;
def finalHora = if !IsNaN(final) then floor(final / 100) + (final % 100) / 60 else 0;

# Convierte las horas y minutos a cadenas y agrega etiquetas
AddLabel(yes, "Inicio Hora de Trading Regular: " + (inicioHora * 60 + inicio % 100) + ":" + (inicio % 100));
AddLabel(yes, "Finalización Hora de Trading Regular: " + (finalHora * 60 + final % 100) + ":" + (final % 100));

Please help me correct this code so that the labels show the start and end in 12 hour format.

# Convierte los valores de tiempo a formato de horas
def inicioHora = if !IsNaN(inicio) then floor(inicio / 100) + (inicio % 100) / 60 else 0;
def finalHora = if !IsNaN(final) then floor(final / 100) + (final % 100) / 60 else 0;

# Convierte las horas y minutos a cadenas y agrega etiquetas
AddLabel(yes, "Inicio Hora de Trading Regular: " + (inicioHora * 60 + inicio % 100) + ":" + (inicio % 100));
AddLabel(yes, "Finalización Hora de Trading Regular: " + (finalHora * 60 + final % 100) + ":" + (final % 100));

something like this ?
need to have extended hours turned on

Code:
``````#twelve_hour_times

# Convierte los valores de tiempo a formato de horas
def inicioHora = if !IsNaN(inicio) then floor(inicio / 100) + (inicio % 100) / 60 else 0;
def finalHora = if !IsNaN(final) then floor(final / 100) + (final % 100) / 60 else 0;

# Convierte las horas y minutos a cadenas y agrega etiquetas
#AddLabel(yes, "Inicio Hora de Trading Regular: " + (inicioHora * 60 + inicio % 100) + ":" + (inicio % 100));
#AddLabel(yes, "Finalización Hora de Trading Regular: " + (finalHora * 60 + final % 100) + ":" + (final % 100));

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

def start = gettime() == RegularTradingStart(GetYYYYMMDD()) + 1;
def end = gettime() == RegularTradingend(GetYYYYMMDD()) + 1;

def mintotal = secondsfromTime(0) /60;
def hr = floor(mintotal / 60);

def mn2 = mintotal - (hr * 60);
def hr2 = if hr > 12 then hr - 12 else hr;
#def starthour = if start then

def starthr = if start then hr2 else starthr[1];
def startmin = if start then mn2 else startmin[1];

def endhr = if end then hr2 else endhr[1];
def endmin = if end then mn2 else endmin[1];

addlabel(1, "start " + starthr + ":" + (if startmin < 10 then "0" else "") + startmin, color.yellow);
addlabel(1, "end " + endhr + ":" + (if endmin < 10 then "0" else "") + endmin, color.yellow);

#--------------------------
gettime() + "\n" +
start + "\n" +
end + "\n" +
mintotal + "\n" +
hr + "\n" +
hr2 + "\n" +
mn2 + "\n" +
starthr + "\n" +
startmin
, color.yellow, no);
#``````

responder a la publicación 192

algo como esto ?
Es necesario tener activado el horario extendido.

[código]
#doce_horas_veces

# Convertir los valores de tiempo a formato de horas
def inicioHora = if !IsNaN(inicio) then piso(inicio / 100) + (inicio % 100) / 60 else 0;
def finalHora = if !IsNaN(final) entonces piso(final / 100) + (final % 100) / 60 else 0;

# Convierte las horas y minutos a cadenas y agrega etiquetas
#AddLabel(yes, "Inicio Hora de Trading Regular: " + (inicioHora * 60 + inicio % 100) + ":" + (inicio % 100));
#AddLabel(yes, "Finalización Hora de Trading Regular: " + (finalHora * 60 + final % 100) + ":" + (final % 100));

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

def inicio = gettime() == RegularTradingStart(GetAAAAMMDD()) + 1;
def fin = gettime() == RegularTradingend(GetAAAAMMDD()) + 1;

def mintotal = segundosdesdeTiempo(0) /60;
def hr = piso(mintotal / 60);

def mn2 = mintotal - (hora * 60);
def hr2 = si hr > 12 entonces hr - 12 en caso contrario hr;
#def horainicio = si comienza entonces

def starthr = si comienza entonces hr2 else starthr[1];
def startmin = si comienza entonces mn2 si no startmin[1];

def endhr = si finaliza entonces hr2 else endhr[1];
def endmin = si finaliza entonces mn2 sino endmin[1];

addlabel(1, "start " + starthr + ":" + (si startmin < 10 entonces "0" else "") + startmin, color.amarillo);
addlabel(1, "end " + endhr + ":" + (si endmin < 10 entonces "0" else "") + endmin, color.amarillo);

#--------------------------
gettime() + "\n" +
inicio + "\n" +
fin + "\n" +
total mínimo + "\n" +
hora + "\n" +
hora2 + "\n" +
mn2 + "\n" +
inicio + "\n" +
inicio
, color.amarillo, no);
#
[/código]

Thanks for the code.

Hello,

I'm struggling to make this work...can someone please be kind enough to help me fix this code please?
Much appreciated.

Last edited:
Hello,

I'm struggling to make this work...can someone please be kind enough to help me fix this code please?
Much appreciated.

you are using n to turn on a label, but didn't define n. could just replace n in label, with 1.
would have to add diff to label to display it.
here is something,

Code:
``````# compare_avgs

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

def data = close;

input avg1_type = AverageType.Simple;
#input avg1_type = AverageType.exponential;
input avg1_length = 10;
def avg1 = MovingAverage( avg1_type , data , avg1_length );
def diff1 = absvalue(close - avg1) * 100 / close;

input avg2_type = AverageType.Simple;
input avg2_length = 20;
def avg2 = MovingAverage( avg2_type , data , avg2_length );
def diff2 = absvalue(close - avg2) * 100 / close;

input show_labels = yes;
addlabel(show_labels, "price to avg1 " + round(diff1,2) + "%", color.yellow);
addlabel(show_labels, "price to avg2 " + round(diff2,2) + "%", color.yellow);

input show_average_lines = yes;
plot zavg1 = if show_average_lines then avg1 else na;
plot zavg2 = if show_average_lines then avg2 else na;
#``````

unusual option volume with buy and sell strategy

Can someone help me refine the code where i can use it for mobile. My idea is that when there is massive options buying either call or put the premium of either one is overbought or oversold. next two days they will sell or buy. so i combine with the option volume scanner plus B4 indicator and RS percentile.

#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

#______________________________

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;

input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

##________________

# B4 Signal
#
# Free for use for non commercial. Header credits must be included when any form of the code included in this package is used.
# User assumes all risk. Author not responsible for errors or use of tool.
# Copyright (c) 2021 B4 Signals
#
# Get support at: https://b4signals.com
#
#
# v3.0 - barbros / chuck - official release

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_sell && cluster ;
# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_up);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.green);
scanResults.HideBubble();

code : Selling
#```thinkscript
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

# RSpercentile

input OverBought = 95;
input OverSold = 10;
input Middle = 50;
input length = 7;

#def RS = if IsNan(relativeStrength("SPX")) then 0 else relativeStrength("SPX") ;
def RS = RelativeStrength("SPX");
def RSLow = Lowest(RS, length);
def RSHigh = Highest(RS, length);
def RSRank = 100 * (RS - RSLow) / (RSHigh - RSLow);
def RSRank_ = RSRank;

def rsrankall = rsrank_;
#AddLabel (yes, if RSRank >= 1 and RSRank < 100 then "000" + astext(RSRank) else astext( RSRank) );

def overbought_ = overbought;
def middle_ = middle;
def oversold_ = oversold;
#cluster
def cluster=if RSrankall >overbought then 100 else if rsrankall<oversold then 10 else double.nan;

### MACDBB

input MACDBB_FastLength = 12;
input MACDBB_SlowLength = 26;
input MACDBB_BandLength = 15;
input MACDBB_NumDev = 1.0;

def MACDBB_Data = MACD(fastLength = MACDBB_FastLength, slowLength = MACDBB_SlowLength, MACDLength = 5);
def MACDBB_Upper = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).UpperBand;;
def MACDBB_Lower = reference BollingerBands(price = MACDBB_Data, length = MACDBB_BandLength,
Num_Dev_Dn = -MACDBB_NumDev, Num_Dev_Up = MACDBB_NumDev).Lowerband;
def MACDBB_Buy = MACDBB_Data > MACDBB_Upper;
def MACDBB_Sell = MACDBB_Data <= MACDBB_Lower;

### RSI/STOCASTIC/MACD CONFLUENCE COMBO

def RSM_MACD_Diff = reference MACD(fastLength = 12, slowLength = 26, MACDLength = 9).Diff;
def RSM_MACD_ZeroLine = 0;
def RSM_RSI = reference RSI(length = 7).RSI;
def RSM_Stoch_Val = 100 * (close - lowest(low, 14)) / (highest(high, 14) - lowest(low, 14));
def RSM_StochSlowK = SimpleMovingAvg(SimpleMovingAvg(RSM_Stoch_Val,3),3);

def RSM_rsiGreen = RSM_RSI >= 50;
def RSM_rsiRed = RSM_RSI < 50;
def RSM_stochGreen = RSM_StochSlowK >= 50;
def RSM_stochRed = RSM_StochSlowK < 50;
def RSM_macdGreen = RSM_MACD_Diff >= 0;
def RSM_macdRed = RSM_MACD_Diff < 0;
def RSM_Buy = RSM_rsiGreen and RSM_stochGreen and RSM_macdGreen;
def RSM_Sell = RSM_rsiRed and RSM_stochRed and RSM_macdRed;

### RSI IFT

def RSI_IFT_R = reference RSI(5, close) - 50;
def RSI_IFT_AvgRSI = MovingAverage(AverageType.Exponential,RSI_IFT_R,9);
def RSI_IFT_InverseRSI = (Power(Double.E, 2 * RSI_IFT_AvgRSI) - 1) / (Power(Double.E, 2 * RSI_IFT_AvgRSI) + 1);
def RSI_IFT_Direction = if BarNumber() == 0 then 0
else if (RSI_IFT_InverseRSI[1] > 0) and (RSI_IFT_InverseRSI < 0) then -1
else if (RSI_IFT_InverseRSI > 0) and (RSI_IFT_InverseRSI[1] < 0) then 1
else RSI_IFT_Direction[1];

### Fibonacci SuperTrend

input FST_Length = 11;
input FST_Retrace = 23.6;
input FST_UseHighLow = yes;

def FST_h = if FST_UseHighLow then high else close;
def FST_l = if FST_UseHighLow then low else close;
def FST_minL = Lowest(FST_l, FST_Length);
def FST_maxH = Highest(FST_h, FST_Length);

def FST_hh = if FST_h > FST_maxH[1] then FST_h else FST_hh[1];
def FST_ll = if FST_l < FST_minL[1] then FST_l else FST_ll[1];
def FST_trend = if FST_h > FST_maxH[1] then 1 else if FST_l < FST_minL[1] then -1 else FST_trend[1];
def FST_Direction = if BarNumber() == 0 then 0
else if FST_trend != 1 then -1
else if FST_trend == 1 then 1
else FST_Direction[1];

### Strategy

input BullBear_Include_FST = yes; #hint BullBear_Include_FST: Include Fibonacci SuperTrend in the vertical line strategy
input BullBear_Include_RSI_IFT = yes; #hint BullBear_Include_RSI_IFT: Include RSI IFT in the vertical line strategy

def BullBear_Buy = (!BullBear_Include_FST or FST_Direction == 1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == 1);
def BullBear_Sell = (!BullBear_Include_FST or FST_Direction == -1) and
(!BullBear_Include_RSI_IFT or RSI_IFT_Direction == -1);

def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

# Customize the appearance of the scan results plot
scanResults.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_down);
scanResults.SetLineWeight(3);
scanResults.SetDefaultColor(Color.red);
scanResults.HideBubble();

this codes itself can be use with thinkorswim platform but i can not use it on mobile and i would like to use it on Mobile app.
using this code alone "
# Define the time period for the scan
input scanPeriod = 30; # Number of trading days to consider

# Calculate the average daily option volume
def avgOptionVolume = Average(volume(period = AggregationPeriod.DAY), scanPeriod);

# Calculate the average daily call option volume
def avgCallVolume = Average(volume(period = AggregationPeriod.DAY) * (close > open), scanPeriod);

# Calculate the average daily put option volume
def avgPutVolume = Average(volume(period = AggregationPeriod.DAY) * (close < open), scanPeriod);

# Calculate the current day's call option volume
def currentCallVolume = volume * (close > open);

# Calculate the current day's put option volume
def currentPutVolume = volume * (close < open);

# Calculate the ratio of current call option volume to average call option volume
def callVolumeRatio = currentCallVolume / avgCallVolume;

# Calculate the ratio of current put option volume to average put option volume
def putVolumeRatio = currentPutVolume / avgPutVolume;

# Define the threshold for unusual option buying activity
input threshold = 2.0;

# Scan for stocks with unusual call option buying activity
def unusualCallBuying = callVolumeRatio >= threshold;

# Scan for stocks with unusual put option buying activity
def unusualPutBuying = putVolumeRatio >= threshold;

# Combine the scan conditions to find stocks with either unusual call or put option buying activity

# Plot the scan results on the scan tab

will work on mobile but i want the combine strategy combine and it gives me the arrow. can someone help. thanks

sorry, i am not sure what needs to happen to make a study work on mobile. maybe someone else does.

when posting code, put it in a code window, especially when it is rediculously long like this.
in the header will be an icon </>

are you loading option symbols into the chart? if you are not, then there is no option data being used.

you are using n to turn on a label, but didn't define n. could just replace n in label, with 1.
would have to add diff to label to display it.
here is something,

Code:
``````# compare_avgs

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

def data = close;

input avg1_type = AverageType.Simple;
#input avg1_type = AverageType.exponential;
input avg1_length = 10;
def avg1 = MovingAverage( avg1_type , data , avg1_length );
def diff1 = absvalue(close - avg1) * 100 / close;

input avg2_type = AverageType.Simple;
input avg2_length = 20;
def avg2 = MovingAverage( avg2_type , data , avg2_length );
def diff2 = absvalue(close - avg2) * 100 / close;

input show_labels = yes;
addlabel(show_labels, "price to avg1 " + round(diff1,2) + "%", color.yellow);
addlabel(show_labels, "price to avg2 " + round(diff2,2) + "%", color.yellow);

input show_average_lines = yes;
plot zavg1 = if show_average_lines then avg1 else na;
plot zavg2 = if show_average_lines then avg2 else na;
#``````
Thank you so much! I tested it manually by using TOS Trendline tool and see a very minor % diff between the tool vs your study but I think overall this is perfect. Thank you so much again.

Thanks!

This is great! I tried , but sadly can't do it. Hoping to add the ATR, both daily and weekly, as a separate label that shows distance from chosen SMA/EMA. IF both VWAP and ATR can't be defined in the same script, I'd default to being able to see the % diff from SMA/EMA to ATR, either daily or weekly.

Thank you!!

Edit* I noticed in the code that you have logic/label to show "Average" but don't see that defined? Hoping you can change that to ATR, both daily and weekly. Adding a bit to the post, but being able for me to input the length of the ATR would be helpful too. The default is 14, but if i can change the input, it would help me see how far price is intraday and watch it move real-time to confirm trend direction. For say ES, I'd want to see an ATR (3) vs standard 14 where a stock I'd like to see the standard 14.

So below ma period would be ATR period. And above vwap timeframe there would be an: ATR timeframe (daily, weekly)

Thank you for the plot logic below for histogram. I'll enable it just to see how it looks. You rock!

View attachment 20319

Hope this is clear.

Thanks!!!
@halcyonguy When/if you're free would love to see if you can point in the direction to adding the ATR changes to the above.

Thank you!

#### Attachments

• Code Gold Futures.png
78.4 KB · Views: 125
Last edited by a moderator:
Build a scan tab, each separately:

1. VOULME greater than＞2 times the previous day

2. VOULME greater than＞2 times the previous five days

3. VOULME greater than＞2 times the previous quarter

Then on the SEARCH RESULT (in Scan tab or WATCHLIST tab) make EACH CODE appear as green background if meet the condition. Pink background if NOT meet the condition.

Code:
``````# Volume greater than 2 times the previous day
input multiple = 2;

def volCondition1 = volume > 2 * volume[1];
AddLabel(yes, if volCondition1 then "Volume > 2x Prev Day" else "", if volCondition1 then color.black else color.white);

# Volume greater than 2 times the previous five days
def volCondition2 = volume > 2 * average(volume, 5);
AddLabel(yes, if volCondition2 then "Volume > 2x Prev 5 Days" else "", if volCondition2 then color.black else color.white);

# Volume greater than 2 times the previous quarter
def volCondition3 = volume > 2 * average(volume, 63); # Assuming 63 trading days in a quarter
AddLabel(yes, if volCondition3 then "Volume > 2x Prev Quarter" else "", if volCondition3 then color.black else color.white);

# Background color based on condition
AssignBackgroundColor(if volCondition1 or volCondition2 or volCondition3 then color.green else color.pink);``````

Guys, have this code, but how to use this code to scan each of the condition, separately?

Last edited by a moderator:
CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);

Last edited by a moderator:
CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);

change capital formula to what i think you want
def capital = AccountNetLiq();

https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/A-B/AccountNetLiq

Code:
``````#chat203_fix

#Tonievanu  #203
#CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
#def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def capital = AccountNetLiq();

def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);

capital
, color.yellow, yes);
#``````

87k+ Posts
432 Online

## The Market Trading Game Changer

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

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?