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

MerryDay

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

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

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

The above video, explains the basics of providing good specifications to AI which results in better scripts.
AOzhl05.png
 
Last edited:
Hello,

I wrote the following stock screener code but found that it gives me a few results that break just about every condition in my script. I am new to ThinkScript so believe I may be doing something wrong.

Code:
#Variables
def minPrice = 1.00;     # Define minimum stock price.
def minAboveLow = 0.30;  # Define minimum % above 52 week low.
def maxBelowHigh = 0.25; # Define maximum % below 52 week high.
def ma50CloseDays = 10;  # Define number of days for stock to close above the 50 day moving average.
def minVol = 500000;     # Define the minimum 50 day average volume.

#Define stock price for screening.
def price = close;

#Define moving averages
def ma50 = SimpleMovingAvg(price, 50);   #50 day price SMA.
def ma150 = SimpleMovingAvg(price, 150); #150 day price SMA.
def ma200 = SimpleMovingAvg(price, 200); #200 day price SMA.

#Define moving average trends
def ma50Trend = SimpleMovingAvg(price, 50) [21];   #50 day price SMA from 21 bars ago.
def ma150Trend = SimpleMovingAvg(price, 150) [21]; #150 day price SMA from 21 bars ago.
def ma200Trend = SimpleMovingAvg(price, 200)[63];  #200 day price SMA from 63 bars ago.

#Define average volume
def avgVol = SimpleMovingAvg(volume, 50); #50 day volume SMA.

#Define days closing above SMA (50)
def ma50Close = Sum("data" = price > SimpleMovingAvg(close, 50), "length" = ma50CloseDays);

#Define 52 week high and low
def low52 = Lowest(price,252);   #Lowest close from teh past 252 bars.
def high52 = Highest(price,252); #Highest close from the past 252 bars.

def condition1 = price > ma50 and price > ma150 and price > ma200;
def condition2 = ma50 > ma150;                                 
def condition3 = ma150 > ma200;
def condition4 = ma200 > ma200Trend;
def condition5 = price >= (1 + minAboveLow) * low52;
def condition6 = price >= (1 - maxBelowHigh) * high52;

#Require price to be greater than $1.00 to avoid penny stocks.
def condition7 = price >= minPrice;

#Require volume SMA (50) to be greater than X to avoid thinly traded stocks.
def condition8 = avgVol >= minVol;

#Require the price to be greater than SMA (50) for the past X days to avoid volative stocks.
def condition9 = ma50Close >= ma50CloseDays;

#Require the 50 and 150 day SMAs to be trending positive for the past 21 bars.
def condition10 = ma50 > ma50Trend;
def condition11 = ma150 > ma150Trend;

#Plot results
plot scan = condition1 and condition2 and condition3 and condition4 and condition5 and condition6 and condition7 and condition8 and condition9 and condition10 and condition11;

The scan provides the following results:


The top 5 results are way below my threshold of within 25% of a 52 week high and when looking at the charts the 200 day SMA is greater than the 150 day SMA and the 150 day SMA is greater than the 50 day SMA - basically the exact opposite of what I'm looking for.

Any help is greatly appreciated!

reply to post180

i don't have a good answer for you.
maybe the combined lengths are too long, trying to access data that isn't available. i forget how far back a scan can read data.
https://usethinkscript.com/threads/fib-scan-watchlist.9857/#post-126493

change the average lengths to 10,20,30 and compare the results, and see if the results are good.


here is a lower study for testing.
it plots rows of dots of the 11 true/false conditions.


Code:
#chat180_conditions

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-9#post-133775
#Kevinabrahamson  #180

#I wrote the following stock screener code but found that it gives me a few results that break just about every condition in my script. I am new to ThinkScript so believe I may be doing something wrong.


declare lower;

DefineGlobalColor("true", color.green);
DefineGlobalColor("false", color.red);
DefineGlobalColor("all", color.cyan);
DefineGlobalColor("none", color.orange);
# GlobalColor("x")

#Variables
def minPrice = 1.00;     # Define minimum stock price.
def minAboveLow = 0.30;  # Define minimum % above 52 week low.
def maxBelowHigh = 0.25; # Define maximum % below 52 week high.
def ma50CloseDays = 10;  # Define number of days for stock to close above the 50 day moving average.
def minVol = 500000;     # Define the minimum 50 day average volume.

#Define stock price for screening.
def price = close;

#Define moving averages
def ma50 = SimpleMovingAvg(price, 50);   #50 day price SMA.
def ma150 = SimpleMovingAvg(price, 150); #150 day price SMA.
def ma200 = SimpleMovingAvg(price, 200); #200 day price SMA.

#Define moving average trends
def ma50Trend = SimpleMovingAvg(price, 50)[21];   #50 day price SMA from 21 bars ago.
def ma150Trend = SimpleMovingAvg(price, 150)[21]; #150 day price SMA from 21 bars ago.
def ma200Trend = SimpleMovingAvg(price, 200)[63];  #200 day price SMA from 63 bars ago.

#Define average volume
def avgVol = SimpleMovingAvg(volume, 50); #50 day volume SMA.

#Define days closing above SMA (50)
def ma50Close = Sum("data" = price > SimpleMovingAvg(close, 50), "length" = ma50CloseDays);

#Define 52 week high and low
def low52 = Lowest(price, 252);   #Lowest close from teh past 252 bars.
def high52 = Highest(price, 252); #Highest close from the past 252 bars.

def condition1 = price > ma50 and price > ma150 and price > ma200;
def condition2 = ma50 > ma150;
def condition3 = ma150 > ma200;
def condition4 = ma200 > ma200Trend;
def condition5 = price >= (1 + minAboveLow) * low52;
def condition6 = price >= (1 - maxBelowHigh) * high52;

#Require price to be greater than $1.00 to avoid penny stocks.
def condition7 = price >= minPrice;

#Require volume SMA (50) to be greater than X to avoid thinly traded stocks.
def condition8 = avgVol >= minVol;

#Require the price to be greater than SMA (50) for the past X days to avoid volative stocks.
def condition9 = ma50Close >= ma50CloseDays;

#Require the 50 and 150 day SMAs to be trending positive for the past 21 bars.
def condition10 = ma50 > ma50Trend;
def condition11 = ma150 > ma150Trend;


addchartbubble(0, 0,
ma50Close
, color.yellow, no);




#Plot results
def all = condition1 and condition2 and condition3 and condition4 and condition5 and condition6 and condition7 and condition8 and condition9 and condition10 and condition11;

def none = !condition1 and !condition2 and !condition3 and !condition4 and !condition5 and !condition6 and !condition7 and !condition8 and !condition9 and !condition10 and !condition11;

plot scan = all;
scan.setdefaultcolor(color.cyan);
scan.SetLineWeight(3);

#The scan provides the following results:
# The top 5 results are way below my threshold of within 25% of a 52 week high
# and when looking at the charts the 200 day SMA is greater than the 150 day SMA and the 150 day SMA is greater than the 50 day SMA - basically the exact opposite of what I'm looking for.

# plot dot rows for conditions
input all_same_color = yes;
def all2 = (all_same_color and all);
def none2 = (all_same_color and none);

def space = 0.08;
def na = double.nan;
plot z1 = if isnan(close) then na else (1 * space);
plot z2 = if isnan(close) then na else (2 * space);
plot z3 = if isnan(close) then na else (3 * space);
plot z4 = if isnan(close) then na else (4 * space);
plot z5 = if isnan(close) then na else (5 * space);
plot z6 = if isnan(close) then na else (6 * space);
plot z7 = if isnan(close) then na else (7 * space);
plot z8 = if isnan(close) then na else (8 * space);
plot z9 = if isnan(close) then na else (9 * space);
plot z10 = if isnan(close) then na else (10 * space);
plot z11 = if isnan(close) then na else (11 * space);

def size = 4;
z1.SetPaintingStrategy(PaintingStrategy.POINTS);
z1.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition1 then GlobalColor("true") else GlobalColor("false"));
z1.SetLineWeight(size);
z1.HideBubble();

z2.SetPaintingStrategy(PaintingStrategy.POINTS);
z2.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition2 then GlobalColor("true") else GlobalColor("false"));
z2.SetLineWeight(size);
z2.HideBubble();

z3.SetPaintingStrategy(PaintingStrategy.POINTS);
z3.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition3 then GlobalColor("true") else GlobalColor("false"));
z3.SetLineWeight(size);
z3.HideBubble();

z4.SetPaintingStrategy(PaintingStrategy.POINTS);
z4.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition4 then GlobalColor("true") else GlobalColor("false"));
z4.SetLineWeight(size);
z4.HideBubble();

z5.SetPaintingStrategy(PaintingStrategy.POINTS);
z5.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition5 then GlobalColor("true") else GlobalColor("false"));
z5.SetLineWeight(size);
z5.HideBubble();

z6.SetPaintingStrategy(PaintingStrategy.POINTS);
z6.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition6 then GlobalColor("true") else GlobalColor("false"));
z6.SetLineWeight(size);
z6.HideBubble();

z7.SetPaintingStrategy(PaintingStrategy.POINTS);
z7.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition7 then GlobalColor("true") else GlobalColor("false"));
z7.SetLineWeight(size);
z7.HideBubble();

z8.SetPaintingStrategy(PaintingStrategy.POINTS);
z8.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition8 then GlobalColor("true") else GlobalColor("false"));
z8.SetLineWeight(size);
z8.HideBubble();

z9.SetPaintingStrategy(PaintingStrategy.POINTS);
z9.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition9 then GlobalColor("true") else GlobalColor("false"));
z9.SetLineWeight(size);
z9.HideBubble();

z10.SetPaintingStrategy(PaintingStrategy.POINTS);
z10.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition10 then GlobalColor("true") else GlobalColor("false"));
z10.SetLineWeight(size);
z10.HideBubble();

z11.SetPaintingStrategy(PaintingStrategy.POINTS);
z11.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition11 then GlobalColor("true") else GlobalColor("false"));
z11.SetLineWeight(size);
z1.HideBubble();

plot zz = 1;
zz.setdefaultcolor(color.gray);

#

P5rFknr.jpg
 

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

there are several things wrong with your question.

there is no draw function.
there is no study function.

learn some of the basic functions in thinkscript, then you will have an idea of what is possible.
https://tlc.thinkorswim.com/center/reference/thinkScript/tutorials



thinkscript can't read data points from objects manually drawn on a chart. i assume that is what you want to have happen, since you didn't provide any rules or conditions, to define the start and stop times of the rectangle.


if you define your buy conditions, they might be able to be added to one of these studies.

https://usethinkscript.com/threads/dynamic-risk-reward-study-for-thinkorswim.8615/#post-80068

https://usethinkscript.com/threads/thinkorswim-risk-reward-indicator.7210/page-2#post-74034

https://usethinkscript.com/threads/intraday-position-size-calculator-help.7077/#post-68449


or search for risk reward
or position size
Thanks for this. Now I know where to begin on how to Learn Thinkscript. Perfect !!!!
 
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
AddReferenceLine(0, "Zero Line", Color.GRAY);
 
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
AddReferenceLine(0, "Zero Line", Color.GRAY);

reply to post183

Code:
#chat183_dist_from_avg

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

#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, " ", color.black);
addlabel(show_avg, "Average", za.TakeValueColor());
addlabel(show_avg, "VWAP", zv.TakeValueColor());
addlabel(1, " ", color.black);
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);
#
 
reply to post183

Code:
#chat183_dist_from_avg

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

#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, " ", color.black);
addlabel(show_avg, "Average", za.TakeValueColor());
addlabel(show_avg, "VWAP", zv.TakeValueColor());
addlabel(1, " ", color.black);
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!

1701400440095.png


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

#https://usethinkscript.com/threads/dynamic-zero-line-and-rvol-contraction.17238/
#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

#addchartbubble(1, 0, startBar , color.yellow

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


addchartbubble(0, 1,
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);


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

#

eu4Gp6f.jpg
 
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

#https://usethinkscript.com/threads/dynamic-zero-line-and-rvol-contraction.17238/
#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

#addchartbubble(1, 0, startBar , color.yellow

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


addchartbubble(0, 1,
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);


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

#

eu4Gp6f.jpg
Thank you for giving me a start and for your time. Truly appreciate it. Thank you
 
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.

code: Buying
#```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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;




#______________________________

#rsspx
# RSpercentile
#-------------------- Header End ----------------------------

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
# Join us at: https://discord.gg/kD3pKE2CQd
#
#
# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualcallBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;





# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_BUY && cluster ;
# 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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;"""""

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

1694282434903.png
 
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.

code: Buying
#```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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;




#______________________________

#rsspx
# RSpercentile
#-------------------- Header End ----------------------------

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
# Join us at: https://discord.gg/kD3pKE2CQd
#
#
# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualcallBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;





# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_BUY && cluster ;
# 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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;"""""

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.
def inicio = RegularTradingStart(GetYYYYMMDD());
def final = RegularTradingEnd(GetYYYYMMDD());

# 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.
def inicio = RegularTradingStart(GetYYYYMMDD());
def final = RegularTradingEnd(GetYYYYMMDD());

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

reply to post 192

something like this ?
need to have extended hours turned on

Code:
#twelve_hour_times

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

def inicio = RegularTradingStart(GetYYYYMMDD());
def final = RegularTradingEnd(GetYYYYMMDD());

# 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, " ", color.black);
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);


#--------------------------
addchartbubble(0, low,
gettime() + "\n" +
RegularTradingStart(GetYYYYMMDD()) + "\n" +
start + "\n" +
end + "\n" +
mintotal + "\n" +
hr + "\n" +
hr2 + "\n" +
mn2 + "\n" +
starthr + "\n" +
startmin
, color.yellow, no);
#

CgwdKPy.jpg
 
responder a la publicación 192

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

[código]
#doce_horas_veces

#https://usethinkscript.com/threads/...used-in-thinkorswim.13822/page-10#post-134251

def inicio = RegularTradingStart(GetAAAAMMDD());
def final = RegularTradingEnd(GetAAAAMMDD());

# 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, " ", color.negro);
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);


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

CgwdKPy.jpg
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?
If possible, can you also add another AddLabel for 20 SMA?
Much appreciated.

1700497720130.png
 
Last edited:
Hello,

I'm struggling to make this work...can someone please be kind enough to help me fix this code please?
If possible, can you also add another AddLabel for 20 SMA?
Much appreciated.

reply to #195
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, " ", color.black);
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.

code: Buying
#```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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;




#______________________________

#rsspx
# RSpercentile
#-------------------- Header End ----------------------------

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
# Join us at: https://discord.gg/kD3pKE2CQd
#
#
# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualcallBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;





# 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_Buy = BullBear_Buy and MACDBB_Buy and RSM_Buy;
def Strategy_Sell = BullBear_Sell and MACDBB_Sell and RSM_Sell;

plot scanResults = unusualOptionBuying && strategy_BUY && cluster ;
# 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
#def unusualOptionBuying = unusualCallBuying or unusualPutBuying;
def unusualOptionBuying = unusualputBuying;

# Plot the scan results on the scan tab
#plot scanResults = unusualOptionBuying;"""""

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.
 
reply to #195
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, " ", color.black);
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!
 
I found this pretty fascinating as AI is starting to get more prevalent. Just to preface this, I'm not a coder by any stretch so my knowledge is limited in this respect to Thinkscript/Pinescript. I had input the Pinescript code (first block of code) into Chat GPT and asked it to convert it to Thinkscript which is the second block of code below.
I did try the code and it showed some errors. I was curious if it was way off or this could be an easier way to do conversions.
Just wanted to lighten the load for all that help us out here.
Website: Open AI


Code:
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
indicator("Signal Moving Average [LuxAlgo]", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(50)

src = input(close)

//------------------------------------------------------------------------------
//Signal moving average
//-----------------------------------------------------------------------------{
var ma = 0.
var os = 0.

target = ta.sma(src, length)
abs_diff = math.abs(target - target[1])

r2 = math.pow(ta.correlation(close, bar_index, length), 2)

os := r2 > 0.5 ? math.sign(src[1] - target[1]) : os

ma := r2 > 0.5 ? r2 * target + (1 - r2) * nz(ma[1], target)
  : ma[1] - abs_diff * os
 
 
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot0 = plot(src, display = display.none, editable = false)

css = os == 1 ? #0cb51a : #ff1100
plot1 = plot(ma, 'Signal MA'
  , css)
 
fill_css = src > ma ? color.new(#0cb51a, 80) : color.new(#ff1100, 80)
fill(plot0, plot1, fill_css, 'Fill')


//-----------------------------------------------------------------------------}

Results from Chat GPT:
Code:
input length = 50;
input src = close;

def ma;
def os;

def target = SimpleMovingAvg(src, length);
def abs_diff = AbsValue(target - target[1]);
def bar = BarNumber();

def r2 = Power(Correlation(src, bar, length), 2);

def osCond = if r2 > 0.5 then Sign(src[1] - target[1]) else os;

def oc = osCond;
oc.AssignValueColor(if osCond == 1 then osCond else Double.NaN, color.green, color.red);

def nz = if IsNaN(ma[1]) then target else ma[1];

def maCond = if r2 > 0.5 then r2 * target + (1 - r2) * nz else ma[1] - abs_diff * os;

plot srcPlot = src;
plot signalMA = maCond;
AddCloud(if src > ma then src else Double.NaN, color.light_green, color.light_red);
using CHAT GPT i have come up with a few scripts i am testing on small but real trades .and seem to be working but still testing these are not simple scripts .
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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