# Open Interest Script
# Define the inputs
input symbol = "AAPL";
input expiration = 0;
input show_all_expirations = no;
# Determine the current date and time
def current_time = GetYYYYMMDD() * 10000 + GetTime() / 100;
# Get the option chain for the specified symbol and expiration date
def chain = OptionChain(symbol, expiration);
# Define the aggregation period
def aggregation_period = AggregationPeriod.DAY;
# Determine whether to use all expirations or just the specified one
def expirations = if show_all_expirations then GetExpirations(symbol) else expiration;
# Loop over each expiration date and display the open interest for each option
for exp in expirations do {
# Get the options for the current expiration date
def options = chain.GetOptions(exp, OptionClass.ALL);
# Loop over each option and display the open interest
for option in options do {
# Get the open interest for the current option
def oi = option.GetOpenInterest(aggregation_period);
# Display the open interest in a label on the chart
AddLabel(yes, "OI: " + oi, if current_time == option.GetExpirationDate() then Color.CYAN else Color.GRAY);
}
}
Join useThinkScript to post your question to a community of 21,000+ developers and traders.
Getting error as below
Invalid statement: for at 26:5
Invalid statement: } at 32:5
Code:# Open Interest Script # Define the inputs input symbol = "AAPL"; input expiration = 0; input show_all_expirations = no; # Determine the current date and time def current_time = GetYYYYMMDD() * 10000 + GetTime() / 100; # Get the option chain for the specified symbol and expiration date def chain = OptionChain(symbol, expiration); # Define the aggregation period def aggregation_period = AggregationPeriod.DAY; # Determine whether to use all expirations or just the specified one def expirations = if show_all_expirations then GetExpirations(symbol) else expiration; # Loop over each expiration date and display the open interest for each option for exp in expirations do { # Get the options for the current expiration date def options = chain.GetOptions(exp, OptionClass.ALL); # Loop over each option and display the open interest for option in options do { # Get the open interest for the current option def oi = option.GetOpenInterest(aggregation_period); # Display the open interest in a label on the chart AddLabel(yes, "OI: " + oi, if current_time == option.GetExpirationDate() then Color.CYAN else Color.GRAY); } }
Any other way who can help to modify this, do we need to check in discord?
on a given particular day I am looking for any indication or line where we have high open interest on puts and call options
If your intention is to loop through all the options for a particular instrument, please be aware that it cannot be done.Any other way who can help to modify this, do we need to check in discord?
As the ToS platform does not provide the ability to scan options for custom criteria, it is not possible.On a given particular day I am looking for any indication or line where we have high open interest on puts and call options
# Define the input parameters for the study
input length = 21;
input deviation = 2.0;
# Calculate the upper and lower bounds of the channel
def price = close;
def sdev = stdev(data = price, length = length);
def midLine = Average(price, length);
def upperLine = midLine + deviation * sdev;
def lowerLine = midLine - deviation * sdev;
# Check whether the current price is inside or outside the channel
def inChannel = high <= upperLine and low >= lowerLine;
def outOfChannel = (high > upperLine and close < upperLine) or (low < lowerLine and close > lowerLine);
# Add a custom watchlist column that displays the signal when the ticker is out of the channel
AddLabel(outOfChannel, "Out of Channel", Color.CYAN);
# Remove the ticker from the watchlist when it's back inside the channel
if inChannel {
RemoveFromWatchlist();
}
Hello,
I'm looking to create a watchlist where tickers are added if they're out of the StandardErrorChannel and removed when they're within it. I have this code below and I wanted to run it by you guys to confirm that this is what I should be using. Thank you!
Code:# Define the input parameters for the study input length = 21; input deviation = 2.0; # Calculate the upper and lower bounds of the channel def price = close; def sdev = stdev(data = price, length = length); def midLine = Average(price, length); def upperLine = midLine + deviation * sdev; def lowerLine = midLine - deviation * sdev; # Check whether the current price is inside or outside the channel def inChannel = high <= upperLine and low >= lowerLine; def outOfChannel = (high > upperLine and close < upperLine) or (low < lowerLine and close > lowerLine); # Add a custom watchlist column that displays the signal when the ticker is out of the channel AddLabel(outOfChannel, "Out of Channel", Color.CYAN); # Remove the ticker from the watchlist when it's back inside the channel if inChannel { RemoveFromWatchlist(); }
# scan_col_std_err_ch_00_lower
#chatgpt
#https://usethinkscript.com/threads/chatgpt.13822/page-2#post-120172
#Doc2b191
# #23
# I'm looking to create a watchlist where,
# tickers are added if they're out of the StandardErrorChannel
# and removed when they're within it.
# I have this code below and I wanted to run it by you guys to confirm that this is what I should be using. Thank you!
declare lower;
# Define the input parameters for the study
input length = 21;
input deviation = 2.0;
# Calculate the upper and lower bounds of the channel
def price = close;
def sdev = stdev(data = price, length = length);
def midLine = Average(price, length);
def upperLine = midLine + deviation * sdev;
def lowerLine = midLine - deviation * sdev;
# Check whether the current price is inside or outside the channel
def inChannel = high <= upperLine and low >= lowerLine;
#def outOfChannel = (high > upperLine and close < upperLine) or (low < lowerLine and close > lowerLine);
def outOfChannel = !inchannel;
plot z4 = outofchannel;
# Add a custom watchlist column that displays the signal when the ticker is out of the channel
#AddLabel(outOfChannel, "Out of Ch", Color.CYAN);
#AddLabel(1,
#if outOfChannel then "Out of Ch" else "-",
#if outOfChannel then Color.CYAN else color.gray);
# Remove the ticker from the watchlist when it's back inside the channel
#if inChannel {
# RemoveFromWatchlist();
#}
#
# scan_col_std_err_ch_00_upper
# scan_col_std_err_ch_00_lower
#chatgpt
#https://usethinkscript.com/threads/chatgpt.13822/page-2#post-120172
#Doc2b191
# #23
# I'm looking to create a watchlist where,
# tickers are added if they're out of the StandardErrorChannel
# and removed when they're within it.
# I have this code below and I wanted to run it by you guys to confirm that this is what I should be using. Thank you!
#declare lower;
# Define the input parameters for the study
input length = 21;
input deviation = 2.0;
# Calculate the upper and lower bounds of the channel
def price = close;
def sdev = stdev(data = price, length = length);
def midLine = Average(price, length);
def upperLine = midLine + deviation * sdev;
def lowerLine = midLine - deviation * sdev;
plot z1 = upperline;
plot z2 = midline;
plot z3 = lowerline;
#plot z4 = outofchannel;
# Check whether the current price is inside or outside the channel
def inChannel = high <= upperLine and low >= lowerLine;
#def outOfChannel = (high > upperLine and close < upperLine) or (low < lowerLine and close > lowerLine);
def outOfChannel = !inchannel;
# Add a custom watchlist column that displays the signal when the ticker is out of the channel
#AddLabel(outOfChannel, "Out of Ch", Color.CYAN);
AddLabel(1,
if outOfChannel then "Out of Ch" else "-",
if outOfChannel then Color.CYAN else color.gray);
# Remove the ticker from the watchlist when it's back inside the channel
#if inChannel {
# RemoveFromWatchlist();
#}
#
# zerrdev
#
# scan_col_std_err_ch_00_lower
#chatgpt
#https://usethinkscript.com/threads/chatgpt.13822/page-2#post-120172
#Doc2b191
# #23
# I'm looking to create a watchlist where,
# tickers are added if they're out of the StandardErrorChannel
# and removed when they're within it.
# I have this code below and I wanted to run it by you guys to confirm that this is what I should be using. Thank you!
#declare lower;
# Define the input parameters for the study
input length = 21;
input deviation = 2.0;
# Calculate the upper and lower bounds of the channel
def price = close;
def sdev = stdev(data = price, length = length);
def midLine = Average(price, length);
def upperLine = midLine + deviation * sdev;
def lowerLine = midLine - deviation * sdev;
# Check whether the current price is inside or outside the channel
def inChannel = high <= upperLine and low >= lowerLine;
#def outOfChannel = (high > upperLine and close < upperLine) or (low < lowerLine and close > lowerLine);
def outOfChannel = !inchannel;
# Add a custom watchlist column that displays the signal when the ticker is out of the channel
#AddLabel(outOfChannel, "Out of Ch", Color.CYAN);
AddLabel(1,
if outOfChannel then "Out of Ch" else "-",
color.black);
#if outOfChannel then Color.CYAN else color.gray);
assignbackgroundcolor( if outOfChannel then Color.CYAN else color.gray);
# Remove the ticker from the watchlist when it's back inside the channel
#if inChannel {
# RemoveFromWatchlist();
#}
#
oh my... thanks ? heh@halcyonguy
I hereby bestow upon you the title of the forum's in-house expert in ChatGPT.
While the title may be questionable, your contributions to this thread greatly assist ChatGPT users in finding the correct path.
# Ehler's Distant Coefficient Filter Strategy with Fast and Slow Lines
# Created by Christopher84 05/17/2022
# Updated by ChatGPT 02/19/2023
input fastLength = 10;
input slowLength = 34;
input coloredCandlesOn = yes;
def price = (high + low) / 2;
# Fast Line
def fastCoeff = fastLength * price * price - 2 * price * sum(price, fastLength)[1] + sum(price * price, fastLength)[1];
plot fastEhlers = sum(fastCoeff * price, fastLength) / sum(fastCoeff, fastLength);
fastEhlers.SetDefaultColor(GetColor(2));
# Slow Line
def slowCoeff = slowLength * price * price - 2 * price * sum(price, slowLength)[1] + sum(price * price, slowLength)[1];
plot slowEhlers = sum(slowCoeff * price, slowLength) / sum(slowCoeff, slowLength);
slowEhlers.SetDefaultColor(GetColor(1));
# Buy and Sell Conditions
def buyCond = close > slowEhlers and close > fastEhlers;
def sellCond = close < slowEhlers and close < fastEhlers;
# Buy and Sell Orders on Slow Line
AddOrder(OrderType.BUY_TO_OPEN, condition = buyCond, price = open[-1], tickcolor = GetColor(1), arrowcolor = Color.GREEN, name = "LE");
AddOrder(OrderType.SELL_TO_CLOSE, condition = buyCond, price = open[-1], tickcolor = GetColor(1), arrowcolor = Color.GREEN, name = "LX");
AddOrder(OrderType.SELL_TO_OPEN, condition = sellCond, price = open[-1], tickcolor = GetColor(2), arrowcolor = Color.RED, name = "SE");
AddOrder(OrderType.BUY_TO_CLOSE, condition = sellCond, price = open[-1], tickcolor = GetColor(2), arrowcolor = Color.RED, name = "SX");
# Buy and Sell Exit Conditions on Fast Line
def buyExitCond = close < fastEhlers;
def sellExitCond = close > fastEhlers;
AddOrder(OrderType.SELL_TO_CLOSE, condition = buyExitCond, price = open[-1], tickcolor = GetColor(1), arrowcolor = Color.MAGENTA, name = "FLX");
AddOrder(OrderType.BUY_TO_CLOSE, condition = sellExitCond, price = open[-1], tickcolor = GetColor(2), arrowcolor = Color.MAGENTA, name = "FSX");
# Coloring Candles based on Long or Short
def long = buyCond;
def short = sellCond;
AssignPriceColor(if coloredCandlesOn and long then Color.GREEN else if coloredCandlesOn and short then Color.RED else Color.GRAY);
# Daily Seasonality Averages
# Calculate the average of each day of the week over a specified period
input length = 252; # lookback period in trading days
input showLabels = yes; # toggle on/off day labels on the chart
# define the number of trading days in a week
def daysPerWeek = 5;
# define an array to hold the closing price for each day of the week
def dayClose = array.new_float(daysPerWeek, 0);
# loop through the data and populate the dayClose array
for i = 0 to length - 1 {
# get the day of the week for the current bar
def dayOfWeek = getDayOfWeek(GetYYYYMMDD());
# get the closing price for the current bar
def closePrice = close[i];
# add the closing price to the appropriate element in the dayClose array
array.set(dayClose, dayOfWeek - 1, array.get(dayClose, dayOfWeek - 1) + closePrice);
}
# calculate the average closing price for each day of the week
def avgClose = array.new_float(daysPerWeek, 0);
for i = 0 to daysPerWeek - 1 {
array.set(avgClose, i, array.get(dayClose, i) / (length / daysPerWeek));
}
# plot the average closing price for each day of the week
plot Monday = if showLabels then array.get(avgClose, 0) else double.nan;
plot Tuesday = if showLabels then array.get(avgClose, 1) else double.nan;
plot Wednesday = if showLabels then array.get(avgClose, 2) else double.nan;
plot Thursday = if showLabels then array.get(avgClose, 3) else double.nan;
plot Friday = if showLabels then array.get(avgClose, 4) else double.nan;
Monday.SetDefaultColor(Color.CYAN);
Tuesday.SetDefaultColor(Color.MAGENTA);
Wednesday.SetDefaultColor(Color.YELLOW);
Thursday.SetDefaultColor(Color.GREEN);
Friday.SetDefaultColor(Color.RED);
I used chatgpt to for seasonality to calculate average of each day of the week, but have some error in the array. Can anyone take a look and let me know how to correct them? Thank you!
Code:# Daily Seasonality Averages # Calculate the average of each day of the week over a specified period input length = 252; # lookback period in trading days input showLabels = yes; # toggle on/off day labels on the chart # define the number of trading days in a week def daysPerWeek = 5; # define an array to hold the closing price for each day of the week def dayClose = array.new_float(daysPerWeek, 0); # loop through the data and populate the dayClose array for i = 0 to length - 1 { # get the day of the week for the current bar def dayOfWeek = getDayOfWeek(GetYYYYMMDD()); # get the closing price for the current bar def closePrice = close[i]; # add the closing price to the appropriate element in the dayClose array array.set(dayClose, dayOfWeek - 1, array.get(dayClose, dayOfWeek - 1) + closePrice); } # calculate the average closing price for each day of the week def avgClose = array.new_float(daysPerWeek, 0); for i = 0 to daysPerWeek - 1 { array.set(avgClose, i, array.get(dayClose, i) / (length / daysPerWeek)); } # plot the average closing price for each day of the week plot Monday = if showLabels then array.get(avgClose, 0) else double.nan; plot Tuesday = if showLabels then array.get(avgClose, 1) else double.nan; plot Wednesday = if showLabels then array.get(avgClose, 2) else double.nan; plot Thursday = if showLabels then array.get(avgClose, 3) else double.nan; plot Friday = if showLabels then array.get(avgClose, 4) else double.nan; Monday.SetDefaultColor(Color.CYAN); Tuesday.SetDefaultColor(Color.MAGENTA); Wednesday.SetDefaultColor(Color.YELLOW); Thursday.SetDefaultColor(Color.GREEN); Friday.SetDefaultColor(Color.RED);
# chat_daily_seasonality_array_fix_00
#------------------------------
# each day,
# read the close price from all the bars during normal hours, and calc an average for past x days,
# plot a line at the avg
# display bubbles with the day average
#------------------------------
#https://usethinkscript.com/threads/chatgpt.13822/page-2#post-120235
#post29 BiggySmall 2/19
#I used chatgpt to for seasonality to calculate average of each day of the week, but have some error in the array. Can anyone take a look and let me know how to correct them? Thank you!
#--------------------------
def na = double.nan;
def bn = barnumber();
# -----------------------------------
# day count
def istoday = if GetLastDay() == GetDay() then 1 else 0;
def newday = if getday() != getday()[1] then 1 else 0;
def daycnt = if bn == 1 then 1 else if (!isnan(close) and newday) then daycnt[1] + 1 else daycnt[1];
def maxdays = highestall(daycnt);
def revdaycnt = maxdays - daycnt + 1;
input days_to_display = 5;
def daystoomany = if days_to_display < 1 or days_to_display > maxdays then 1 else 0;
addlabel(daystoomany, " ONLY " + MAXDAYS + " DAYS ON CHART. enter a different number for days back", color.cyan);
#----------------------
#----------------------
# https://usethinkscript.com/threads/finding-the-first-and-last-bar-of-the-day-in-thinkorswim.526/
# find last bar of day
# korygill
#def nan = Double.NaN;
def isRollover = GetYYYYMMDD() != GetYYYYMMDD()[1];
def beforeStart = GetTime() < RegularTradingStart(GetYYYYMMDD());
def afterEnd = GetTime() > RegularTradingEnd(GetYYYYMMDD());
def firstBarOfDay = if (beforeStart[1] == 1 and beforeStart == 0) or (isRollover and beforeStart == 0) then 1 else 0;
def lastBarOfDay = if
(afterEnd[-1] == 1 and afterEnd == 0) or
(isRollover[-1] and firstBarOfDay[-1])
then 1
else 0;
def rth = (GetTime() >= RegularTradingStart(GetYYYYMMDD()) and GetTime() < RegularTradingEnd(GetYYYYMMDD()) );
def ah = beforeStart or afterEnd;
#----------------------
# if first bar of day,
# read all bars of day, during RTH, calc an avg of close prices
# add up all, div by the qty of bars
def big = 99999;
def barz;
def davg2;
def lowz;
if (bn == 1 and !firstBarOfDay) or ah then {
barz = 1;
davg2 = 0;
lowz = 0;
} else if firstBarOfDay then {
# cnt bars during each day
barz = fold j = 0 to 500
with q
while !isnan(getvalue(close, -j)) and getvalue(rth, -j) == 1
# while !isnan(getvalue(close, -j)) and getvalue(lastBarOfDay, -j) == 0
do q + 1;
# calc an average
davg2 = (fold i = 0 to 500
with p
while !isnan(getvalue(close, -i)) and getvalue(rth, -i) == 1
do (p + getvalue(close, -i))) / barz;
# find low of day
lowz = fold k = 0 to 500
with r = big
# while !isnan(getvalue(close, -k)) and getvalue(rth, -k) == 1
while !isnan(getvalue(close, -k)) and getvalue(lastBarOfDay, -k) == 0
do min(r, getvalue(low, -k));
} else {
barz = barz[1];
davg2 = davg2[1];
lowz = lowz[1];
}
def dayz = (revdaycnt <= days_to_display and !isnan(close));
def davg = round(davg2,2);
# plot daily avg line
plot zdavg = if dayz and rth then davg else na;
zdavg.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
zdavg.SetDefaultColor(Color.light_gray);
#x.setlineweight(1);
zdavg.hidebubble();
input show_avg_bubble = yes;
AddChartBubble(show_avg_bubble and dayz and firstBarOfDay,
# low*0.995,
lowz,
"day avg\n" +
davg
# + "\n" +
# barz
, Color.yellow, no);
# Identify first bar of day and last bar of day on chart
input show_first_last_bubbles = no;
AddChartBubble(show_first_last_bubbles and firstBarOfDay, high,
"First"
, Color.GREEN, yes);
AddChartBubble(show_first_last_bubbles and lastBarOfDay, low,
"Last"
, Color.magenta, no);
#---------------------------------
# test stuff
input test2_rth_lines = no;
plot ahlines = if test2_rth_lines and ah then low*0.99 else na;
plot rthlines = if test2_rth_lines and rth then high*1.003 else na;
input test1 = no;
addchartbubble(test1, low,
newday + " new\n" +
daycnt + " cnt\n" +
revdaycnt + " rev\n" +
maxdays + " max\n"
, color.yellow, no);
#------------------------------------------
input test_show_revdaycnt = no;
addchartbubble( test_show_revdaycnt, low,
revdaycnt
, color.yellow, no);
#
This is what i got but it wont accept GetEventCount
# Define length of pre-market average
input length = 5;
# Define start and end time for pre-market volume
def start_time = 0400;
def end_time = 0930;
# Calculate pre-market volume and average
def preMarketVolume = if SecondsTillTime(start_time) >= 0 and SecondsTillTime(end_time) > 0 then volume(period = AggregationPeriod.DAY)[1] else double.NaN;
def preMarketAvgVolume = Average(if SecondsTillTime(start_time) >= 0 and SecondsTillTime(end_time) > 0 then volume(period = AggregationPeriod.DAY)[1] else double.NaN, length);
# Determine if pre-market volume is twice as much as the average
def twiceAvgVolume = preMarketVolume >= 2 * preMarketAvgVolume;
# Determine if there is breaking news
def breakingnews = GetEventCount() > 0;
# Create a scan for stocks with pre-market volume twice the 5 day pre-market average
plot signal = twiceAvgVolume and Breakingnews;
GetEventCount()
Thanks for the information it has been helped to check another script which was created by Sudoshu.when posting questions, start out by stating,
.. where you want to see something
.. what you want to see
when you have highlighted red regions of code, go to the online manual and look up the words
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/Color
you will find that OptionChain( ) isn't a valid function.
you will find that chatgpt does poorly at conversions.
it makes up functions that don't exist in thinkscript.
it is just a program , created by humans, that is far from perfect. if it was perfect, they could change a lot to use it.
-------------------------
this might be of interest. it plots rows, that represent OI for different strikes.
https://usethinkscript.com/threads/option-heatmap-and-oi-strikes.10664/page-4#post-94445
post67
i haven't read all the posts after this one to know if a newer version is available.
#RSI true swings indicator
declare lower;
input upthresh = 60;
input lwthresh = 40;
#volume criteria checkup
def volcheck = volume > SimpleMovingAvg(volume, 20);
def my_rsi = RSI(close, 14);
#Candle size must be above average
def bullbar_check = close > high[1] and (high - low) > SimpleMovingAvg(high - low, 20) and (close - low) > (high - close) and low <= high[1];
def bearbar_check = close < low[1] and (high - low) > SimpleMovingAvg(high - low, 20) and (high - close) > (close - low) and high >= low[1];
#RSI crossover/crossunder must fulfilling following criteria
def rsicrossover = Crosses(my_rsi, lwthresh) > 0 and volcheck and bullbar_check and volume > volume[1] and close > high[1] and open < close and close > high[2] and my_rsi[1] > lwthresh - 10;
def rsicrossunder = Crosses(my_rsi, upthresh) < 0 and volcheck and close < low[1] and bearbar_check and volume > volume[1] and open > close and close < low[2] and my_rsi[1] < upthresh + 10;
#Plotting the signal confirming
plotshape(rsicrossover, title="Short exit or Buy Entry", style=shape.labelup, location=LabelLocation.BELOW_BAR, color=color.green, size=size.tiny, text="BUY", textcolor=color.white);
plotshape(rsicrossunder, title="Bull exit or Short entry", style=shape.labeldown, location=LabelLocation.ABOVE_BAR, color=color.red, size=size.tiny, text="SELL", textcolor=color.white);
def rec_high = Highest(high, 5);
def rec_low = Lowest(low, 5);
if rsicrossover {
Alert(str.format("{0}: Exit SELL or BUY now\n Stoploss below {1}\n CMP {2}", GetSymbolName(), rec_low, close), Alert.freq_once_per_bar_close);
}
if rsicrossunder {
Alert(str.format("{0}: Exit BUY or SELL now\n Stoploss above {1}\n CMP {2}", GetSymbolName(), rec_high, close), Alert.freq_once_per_bar_close);
}
From "if rsicrossunder {" on, TOS doesn't accept the code.This works quite well on the 5min /m2k and whatnot. Its pine scirpt
https://www.tradingview.com/script/K6YXCogW-RSI-true-swings/
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeswithashish
//@version=5
indicator(title="RSI true swings indicator", shorttitle="RSI True swings", overlay=true)
upthresh=input.int(title="RSI Upper threshhold", defval=60, minval=50, step=5, maxval=90)
lwthresh=input.int(title="RSI Lower threshhold", defval=40, minval=10, step=5, maxval=50)
//volume criteria checkup
volcheck=volume>ta.sma(volume, 20)
my_rsi=ta.rsi(close, 14)
//Candle size must be above average
bullbar_check= close>high[1] and (high-low)>ta.sma(high-low, 20) and (close-low)>(high-close) and low<=high[1]
bearbar_check= close<low[1] and (high-low)>ta.sma(high-low, 20) and (high-close)>(close-low) and high>=low[1]
//RSI crossover/crossunder must fulfilling following criteria
rsicrossover=ta.crossover(my_rsi, lwthresh) and volcheck and bullbar_check and volume>volume[1] and close>high[1] and open<close and close>high[2] and my_rsi[1]>lwthresh-10
rsicrossunder=ta.crossunder(my_rsi, upthresh) and volcheck and close<low[1] and bearbar_check and volume>volume[1] and open>close and close<low[2] and my_rsi[1]<upthresh+10
//Plotting the signal confirming
plotshape(rsicrossover, title="Short exit or Buy Entry", style= shape.labelup, location=location.belowbar, color=color.green, size=size.tiny, text="BUY", textcolor=color.white)
plotshape(rsicrossunder, title="Bull exit or Short entry", style= shape.labeldown, location=location.abovebar, color=color.red, size=size.tiny, text="SELL", textcolor=color.white)
rec_high=ta.highest(high,5)
rec_low=ta.lowest(low, 5)
if rsicrossover
alert(str.tostring(syminfo.ticker)+": Exit SELL or BUY now"+"\n Stoploss below " + str.tostring(rec_low) + "\n CMP "+ str.tostring(close), alert.freq_once_per_bar_close)
if rsicrossunder
alert(str.tostring(syminfo.ticker)+": Exit BUY or SELL now \n Stoploss above"+ str.tostring(rec_high) + "\n CMP "+ str.tostring(close), alert.freq_once_per_bar_close)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Using chatgpt got this:
#RSI true swings indicator declare lower; input upthresh = 60; input lwthresh = 40; #volume criteria checkup def volcheck = volume > SimpleMovingAvg(volume, 20); def my_rsi = RSI(close, 14); #Candle size must be above average def bullbar_check = close > high[1] and (high - low) > SimpleMovingAvg(high - low, 20) and (close - low) > (high - close) and low <= high[1]; def bearbar_check = close < low[1] and (high - low) > SimpleMovingAvg(high - low, 20) and (high - close) > (close - low) and high >= low[1]; #RSI crossover/crossunder must fulfilling following criteria def rsicrossover = Crosses(my_rsi, lwthresh) > 0 and volcheck and bullbar_check and volume > volume[1] and close > high[1] and open < close and close > high[2] and my_rsi[1] > lwthresh - 10; def rsicrossunder = Crosses(my_rsi, upthresh) < 0 and volcheck and close < low[1] and bearbar_check and volume > volume[1] and open > close and close < low[2] and my_rsi[1] < upthresh + 10; #Plotting the signal confirming plotshape(rsicrossover, title="Short exit or Buy Entry", style=shape.labelup, location=LabelLocation.BELOW_BAR, color=color.green, size=size.tiny, text="BUY", textcolor=color.white); plotshape(rsicrossunder, title="Bull exit or Short entry", style=shape.labeldown, location=LabelLocation.ABOVE_BAR, color=color.red, size=size.tiny, text="SELL", textcolor=color.white); def rec_high = Highest(high, 5); def rec_low = Lowest(low, 5); if rsicrossover { Alert(str.format("{0}: Exit SELL or BUY now\n Stoploss below {1}\n CMP {2}", GetSymbolName(), rec_low, close), Alert.freq_once_per_bar_close); } if rsicrossunder { Alert(str.format("{0}: Exit BUY or SELL now\n Stoploss above {1}\n CMP {2}", GetSymbolName(), rec_high, close), Alert.freq_once_per_bar_close); }
chatGPT does not provide scripts that are useable.From "if rsicrossunder {" on, TOS doesn't accept the code.
@ThinkerThis works quite well on the 5min /m2k and whatnot. Its pine scirpt
https://www.tradingview.com/script/K6YXCogW-RSI-true-swings/
# Range Identifier
# This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
# © Mango2Juice
declare lower;
# Inputs
input i_maSource = close;
input i_maType = MovingAverageType.WMA;
input i_maLen1 = 3;
input i_maLen2 = 24;
input i_atrLen1 = 3;
input i_atrLen2 = 24;
input i_treshold = no;
input i_custom = 0.1;
input i_showBG = yes;
# Moving Averages
def ma(MovingAverageType type, input src, int len) {
def result = 0.0;
if (type == MovingAverageType.SIMPLE) { # Simple
result = SimpleMovingAvg(src, len);
} else if (type == MovingAverageType.EXPONENTIAL) { # Exponential
result = ExpAverage(src, len);
} else if (type == MovingAverageType.DOUBLE_EXPONENTIAL) { # Double Exponential
def e = ExpAverage(src, len);
result = 2 * e - ExpAverage(e, len);
} else if (type == MovingAverageType.TRIPLE_EXPONENTIAL) { # Triple Exponential
def e = ExpAverage(src, len);
result = 3 * (e - ExpAverage(e, len)) + ExpAverage(ExpAverage(e, len), len);
} else if (type == MovingAverageType.WEIGHTED) { # Weighted
result = WeightedMovingAvg(src, len);
} else if (type == MovingAverageType.VOLUME_WEIGHTED) { # Volume Weighted
result = VolumeWeightedMovingAvg(src, len);
} else if (type == MovingAverageType.SMMA) { # Smoothed
def w = WeightedMovingAvg(src, len);
result = if IsNaN(w[1]) then SimpleMovingAvg(src, len) else (w[1] * (len - 1) + src) / len;
} else if (type == MovingAverageType.HULL) { # Hull
result = WeightedMovingAvg(2 * WeightedMovingAvg(src, len / 2) - WeightedMovingAvg(src, len), Round(Sqrt(len)));
} else if (type == MovingAverageType.LEAST_SQUARES) { # Least Squares
result = Inertia(src, len, 0);
} else if (type == MovingAverageType.KIJUN) { # Kijun-sen
def kijun = (Lowest(len) + Highest(len)) / 2;
result = kijun;
} else if (type == MovingAverageType.MCGINLEY) {
def mg = if IsNaN(mg[1]) then ExpAverage(src, len) else mg[1] + (src - mg[1]) / (len * Pow(src / mg[1], 4));
result = mg;
}
result;
}
# Auto Set Treshold
def treshold;
switch (GetAggregationPeriod()) {
case AggregationPeriod.MONTH:
case AggregationPeriod.WEEK:
treshold = 0.5;
case AggregationPeriod.DAY:
treshold = 0.4;
case AggregationPeriod.HOUR:
treshold = 0.14;
case AggregationPeriod.MINUTE:
treshold = 0.08;
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mango2Juice
//@version=4
study("Range Identifier")
// Inputs
i_maSource = input(close, "Source", input.source)
i_maType = input("WMA", "MA Type", input.string, options = ["EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMA", "SMMA", "HMA", "LSMA", "Kijun", "McGinley"])
i_maLen1 = input(3, "MA Fast Length", input.integer)
i_maLen2 = input(24, "MA Slow Length", input.integer)
i_atrLen1 = input(3, "ATR Period 1", input.integer)
i_atrLen2 = input(24, "ATR Period 2", input.integer)
i_treshold = input(false, "Custom Treshold ? Default is Auto.", input.bool)
i_custom = input(0.1, "Custom Treshold", input.float, minval = 0.001)
i_showBG = input(true,"Show Background Color?")
// Moving Averages
ma(type, src, len) =>
float result = 0
if type=="SMA" // Simple
result := sma(src, len)
if type=="EMA" // Exponential
result := ema(src, len)
if type=="DEMA" // Double Exponential
e = ema(src, len)
result := 2 * e - ema(e, len)
if type=="TEMA" // Triple Exponential
e = ema(src, len)
result := 3 * (e - ema(e, len)) + ema(ema(e, len), len)
if type=="WMA" // Weighted
result := wma(src, len)
if type=="VWMA" // Volume Weighted
result := vwma(src, len)
if type=="SMMA" // Smoothed
w = wma(src, len)
result := na(w[1]) ? sma(src, len) : (w[1] * (len - 1) + src) / len
if type == "RMA"
result := rma(src, len)
if type=="HMA" // Hull
result := wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
if type=="LSMA" // Least Squares
result := linreg(src, len, 0)
if type=="Kijun" //Kijun-sen
kijun = avg(lowest(len), highest(len))
result :=kijun
if type=="McGinley"
mg = 0.0
mg := na(mg[1]) ? ema(src, len) : mg[1] + (src - mg[1]) / (len * pow(src/mg[1], 4))
result :=mg
result
// Auto Set Treshold
float treshold = na
if timeframe.period == "M" or timeframe.period == "W"
treshold := 0.5
else
if timeframe.period == "D"
treshold := 0.4
else
if timeframe.period == "240"
treshold := 0.14
else
if timeframe.period == "60"
treshold := 0.08
else
if timeframe.period == "30"
treshold := 0.05
else
if timeframe.period == "15"
treshold := 0.04
else
if timeframe.period == "5"
treshold := 0.02
else
if timeframe.period == "1"
treshold := 0.01
ma1 = 100 * (ma(i_maType, i_maSource, i_maLen1) - ma(i_maType, i_maSource, i_maLen2)) * atr(i_atrLen1) + 0.00001
ma2 = ma1 / ma(i_maType, i_maSource, i_maLen2) / atr(i_atrLen2)
range = (exp(2.0*ma2) - 1.0) / (exp(2.0 * ma2) + 1.0)
// Plots
c_range = range >= (i_treshold ? i_custom : treshold) ? color.lime : range <= -(i_treshold ? i_custom : treshold) ? color.red : color.gray
c_background = range >= (i_treshold ? i_custom : treshold) ? color.lime : range <= -(i_treshold ? i_custom : treshold) ? color.red : color.gray
plot(range, "Range", c_range, 4, plot.style_line)
plot((i_treshold ? i_custom : treshold), "Upper Treshold", color.gray, 1, plot.style_circles)
plot(-(i_treshold ? i_custom : treshold), "Lower Treshold", color.gray, 1, plot.style_circles)
bgcolor(i_showBG ? c_background : na)
I got this from ChatGPT but there is no price line:I'd like to scan the universe for when RSI is below X for X number of bars. I'm looking for stuff that is showing extreme weakness or strength.
Also I'd like a price line on the chart for when it first crossed this threshold. This line will provide support and resistance later.
Start a new thread and receive assistance from our community.
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.
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.