# ChatGPT For ThinkOrSwim

#### MerryDay

Staff member
Staff
VIP
This is what chatGPT says about itself:

"Hello there! I am ChatGPT, your AI code-generating companion! While I do a pretty good job with definitions, I could use a little extra help with my syntax. You see, I might stumble a bit when it comes to creating functions, and sometimes I might even invent some on the fly. And I have to admit, generating output can be a bit of a difficulty for me."

We have a simple request:

We ask that you provide the words used to generate the chatGPT code.
We need this as a vital clue of what the script is supposed to be doing.
And we are curious how well it coverts from a description and how you described the problem.

Last edited:

#### sunil

##### New member
VIP
HOW TO IDENTIFY LONG BUILD UP, LONG UNWINDING, SHORT BUILDUP & SHORT COVERING USING OPTION CHAIN.

Any script we have in TOS to get these details in Optin chain.

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

Last edited by a moderator:

#### halcyonguy

##### Well-known member
VIP
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

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.

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

EDIT 3/2
some posts have been changed around in the thread.
post #1 now has the current version.

===============

this might be of interest. it plots rows, that represent OI for different strikes.
post67
i haven't read all the posts after this one to know if a newer version is available.

Last edited:

#### MerryDay

Staff member
Staff
VIP
Any other way who can help to modify this, do we need to check in discord?
If your intention is to loop through all the options for a particular instrument, please be aware that it cannot be done.

The ThinkScript on the ToS platform enables you to analyze one single individual option.
Unfortunately, there is no provision to compare or analyze a group of options.

On a given particular day I am looking for any indication or line where we have high open interest on puts and call options
As the ToS platform does not provide the ability to scan options for custom criteria, it is not possible.
Read more for what is available using standard filters:

Last edited:

#### Doc2b191

##### New member
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();
}``````

#### halcyonguy

##### Well-known member
VIP
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();
}``````

no. the last 4 lines are not thinkscript code

i think you want to modify this and save it as a scan study
.. change def outofchannel = .... to plot outofchannel = ....
.. disable the code lines after that line

then create a watchlist, that uses the scan study as a data source

====================

@Doc2b191 i edited my answer

i made a lower study for testing. i think it will work as a scan.

use this in a scan.
save the scan, as a watchlist.
go to watchlists and open it.

Code:
``````# scan_col_std_err_ch_00_lower

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

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

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

made an upper for testing

Code:
``````# scan_col_std_err_ch_00_upper

# scan_col_std_err_ch_00_lower

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

#``````

upper, lower, column

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

made a column study

Code:
``````# zerrdev
#

# scan_col_std_err_ch_00_lower

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

Last edited:

#### MerryDay

Staff member
Staff
VIP
@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.

#### halcyonguy

##### Well-known member
VIP
@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.
oh my... thanks ? heh

at first , i was against chatgpt. but if someone takes the time to go to a site ( even that one) and search a little and copy/paste some code with questions, i guess it's worth looking at and trying to answer. that is a little better than someone asking for a study to be made with no code.
my secret goal is to show that it is usually wrong and a long way from replacing someone studying and learning a topic.

#### METAL

##### Active member
So I have been experimenting with @Christopher84 Ehlers Distant Coefficient. I wanted to create a dual Ehlers with slow and fast and use the fast to exit trades while using the slow to buy/sell trades. I gave the info to Chat GPT and this is what it spit out. For some reason it also provided buy and sell exits for the slow line which you can jus turn off. I will try to remove them. This actually seems to be a pretty sound strategy. Take a look at it and let me know what your thought are.
Code:
``````# 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);``````

#### BiggySmall

##### New member
Sorry guys, I definitely did not think this question through nor explain it clearly.

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

Last edited:

#### halcyonguy

##### Well-known member
VIP
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);``````

people, if you are going to post this chat stuff, please post the words that you entered into it , to give others a clue of what it is supposed to be. also i'm curious how well it coverts from a description, and how well you described the problem.

short answer, thinkscript doesn't have array functions,
so we need a very good description of what you are trying to do, in order to 'fix' (completely rewrite) this

that thing generated mostly pine code, not thinkscript. so the code is worthless.

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

i started to look at this........ but i have no idea what you want

1. read the close from many candles during a day, and find an average of them ?

2. look at the last five days, read the close of the day, and calculate an average from those 5 ?

what time frame will the chart be set to , day ?

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

the following comments are just that. questions from what i come across. there is no emotion in my words, so don't add any. i am just trying to get you to describe the problem better.

these words were a big red flag, that your post would probably be confusing... and it was

...chatgpt to for seasonality...

if you can't compose a sentence, how is anyone going to help you?

seasonality ?? adding words that have no meaning, adds confusion.

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

EDIT
@BiggySmall

this version needs after hours turned on

i took a guess and made this , a study that finds the average each day, of all the closes on that day

Code:
``````# 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
#------------------------------

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

#----------------------
# 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;
newday + " new\n" +
daycnt + " cnt\n" +
revdaycnt + " rev\n" +
maxdays + " max\n"
, color.yellow, no);
#------------------------------------------

input test_show_revdaycnt = no;
revdaycnt
, color.yellow, no);

#``````

Last edited:

#### crscrs85

##### New member
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;

#### MerryDay

Staff member
Staff
VIP
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;

there is no:
GetEventCount()

The study that you are looking to create cannot be done within the ToS.
The ToS platform does not provide the ability to access news feeds, so we can not write scripts that act on news.

Last edited:

#### sunil

##### New member
VIP
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.
post67
i haven't read all the posts after this one to know if a newer version is available.
Thanks for the information it has been helped to check another script which was created by Sudoshu.

#### tinfox

##### Member
This works quite well on the 5min /m2k and whatnot. Its pine scirpt
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Using chatgpt got this failed attempt:

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

Last edited by a moderator:

#### Thinker

##### New member
VIP
This works quite well on the 5min /m2k and whatnot. Its pine scirpt

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@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); } ```
From "if rsicrossunder {" on, TOS doesn't accept the code.

#### halcyonguy

##### Well-known member
VIP
Last edited by a moderator:

##### Member
I keep getting error messages when I try to translate this code from PineScript.

I'll provide both scripts below, but can someone explain my mistake to me?

MY ATTEMPT
Code:
``````# Range Identifier
# This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

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;``````

PINESCRIPT CODE BELOW
Code:
``````// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@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)``````

Last edited by a moderator:

#### kelvin

##### Member

Original Pine Script as below:

/@version=4
study(title="Average True Range Stop Loss Finder", shorttitle="ATR", overlay=true)
length = input(title="Length", defval=14, minval=1)
smoothing = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
m = input(1.5, "Multiplier")
src1 = input(high)
src2 = input(low)
pline = input(true, "Show Price Lines")
col1 = input(color.blue, "ATR Text Color")
col2 = input(color.teal, "Low Text Color",inline ="1")
col3 = input(color.red, "High Text Color",inline ="2")
collong = input(color.teal, "Low Line Color",inline ="1")
colshort = input(color.red, "High Line Color",inline ="2")
ma_function(source, length) =>
if smoothing == "RMA"
rma(source, length)
else
if smoothing == "SMA"
sma(source, length)
else
if smoothing == "EMA"
ema(source, length)
else
wma(source, length)

a = ma_function(tr(true), length) * m
x = ma_function(tr(true), length) * m + src1
x2 = src2 - ma_function(tr(true), length) * m
p1 = plot(x, title = "ATR Short Stop Loss", color= colshort, transp=20, trackprice = pline ? true : false)
p2 = plot(x2, title = "ATR Long Stop Loss", color= collong, transp=20, trackprice = pline ? true : false)
var table Table = table.new(position.bottom_center, 3, 1, border_width = 3)
f_fillCell(_table, _column, _row, _value, _timeframe) =>
_cellText = _timeframe+ tostring(_value, "#.#")
table.cell(_table, _column, _row, _cellText, text_color = col1)
table.cell_set_text_color(Table, 1, 0, color.new(col3, transp = 0))
table.cell_set_text_color(Table, 2, 0, color.new(col2, transp = 0))

if barstate.islast
f_fillCell(Table, 0, 0, a, "ATR: " )
f_fillCell(Table, 1, 0, x, "H: " )
f_fillCell(Table, 2, 0, x2, "L: " )

I managed to convert by myself but failed, please see as below for what I got:

input length = 14;
input smoothing = {default "RMA", "SMA", "EMA", "WMA"};
input multiplier = 1.5;
input src1 = high;
input src2 = low;
input showPriceLines = yes;

def ma_function(source, len) {
switch (smoothing) {
case "RMA":
return RMA(source, len);
case "SMA":
return SimpleMovingAvg(source, len);
case "EMA":
return ExpAverage(source, len);
case "WMA":
return WMA(source, len);
}
}

def atr = AvgTrueRange(length = length);
def a = ma_function(atr, length) * multiplier;
def x = ma_function(atr, length) * multiplier + src1;
def x2 = src2 - ma_function(atr, length) * multiplier;

def shortStopLoss = plot(x, "ATR Short Stop Loss", color = Color.RED, transp = 20, trackPrice = showPriceLines);
def longStopLoss = plot(x2, "ATR Long Stop Loss", color = Color.GREEN, transp = 20, trackPrice = showPriceLines);

AddChartBubble(showPriceLines, a, "ATR: " + Round(a, 1), Color.BLUE);
AddChartBubble(showPriceLines, x, "H: " + Round(x, 1), Color.GREEN);
AddChartBubble(showPriceLines, x2, "L: " + Round(x2, 1), Color.RED);

Appreciate any legend could give a hand

#### tinfox

##### Member
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.

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.
I got this from ChatGPT but there is no price line:

# Define variables
input rsiLength = 14;
input overSold = 30;
input overBought = 70;
input lookBackBars = 10;

# Calculate RSI
def NetChgAvg = MovingAverage(AverageType.EXPONENTIAL, close - close[1], rsiLength);
def TotChgAvg = MovingAverage(AverageType.EXPONENTIAL, AbsValue(close - close[1]), rsiLength);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);

# Scan for RSI below 40 for 10 bars
def rsiBelow40 = Lowest(RSI, lookBackBars) < 40;
def rsiBelow40Count = if rsiBelow40 then rsiBelow40Count[1] + 1 else 0;
def scanCondition = rsiBelow40Count == lookBackBars;

# Plot price line when RSI first goes under 30 during the scan
def rsiBelow30 = RSI < overSold;
def rsiBelow30Count = if rsiBelow30 then rsiBelow30Count[1] + 1 else 0;
def plotCondition = scanCondition and rsiBelow30Count == 1;

plot priceLine = if plotCondition then low else Double.NaN;
priceLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
priceLine.SetLineWeight(2);
priceLine.SetDefaultColor(Color.CYAN);

Last edited by a moderator:

### Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
232 Online

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 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?