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:
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);
 
I'm trying to write a study where when I put the top of a rectangle drawing at where I want to get in at one point and the bottom of the rectangle for my stop loss at another point on the chart it will give me the number of shares I would need to buy risking x amount of money. I tried to use ChatGPT but I keep getting an error message for the first two lines of code. Here's the code:

study(title="Risk Calculator", shorttitle="Risk Calculator")

input riskAmount = 1000;
input commission = 5;

def entryPrice = draw.getSelectedRectangle().upper;
def stopPrice = draw.getSelectedRectangle().lower;

def totalCost = (entryPrice - stopPrice) * (1 + (commission / entryPrice));
def shares = riskAmount / totalCost;

plot data = shares;
 
I'm trying to write a study where when I put the top of a rectangle drawing at where I want to get in at one point and the bottom of the rectangle for my stop loss at another point on the chart it will give me the number of shares I would need to buy risking x amount of money. I tried to use ChatGPT but I keep getting an error message for the first two lines of code. Here's the code:

study(title="Risk Calculator", shorttitle="Risk Calculator")

input riskAmount = 1000;
input commission = 5;

def entryPrice = draw.getSelectedRectangle().upper;
def stopPrice = draw.getSelectedRectangle().lower;

def totalCost = (entryPrice - stopPrice) * (1 + (commission / entryPrice));
def shares = riskAmount / totalCost;

plot data = shares;

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
 
I asked ChatGPT to write a code that could identify what core sector etf is out performing and what one is underperforming. This is what I got. The code loaded without errors, but there was no functional input. Can anyone make this code work?

Sector performance script



# # Sources:

# https://siblisresearch.com/data/us-sector-weightings/

# https://seekingalpha.com/etfs-and-funds/etf-tables/sectors

# https://www.spglobal.com/spdji/en/indices/equity/sp-500/#data

# debug

declare lower;

declare once_per_bar;



input open_time = 930;

input ConsumerStaples = 5.88; #XLP

input Utilities = 2.5; #XLU

input Communications = 10.16; #XLC

input Financials = 10.69; #XLF

input Materials = 2.56; #XLB

input Industrials = 7.77; #XLI

input Energy = 2.67; #XLE

input RealEstate = 2.77; #XLRE

input HealthCare = 13.29; #XLV

input InformationTechnology = 29.17; #XLK

input ConsumerDiscretionary = 12.54; #XLY



input sticker = "SPX";



def SectorCount = 11;

def NewDay = SecondsFromTime(open_time) < SecondsFromTime(open_time)[1];



def xlkWeight = InformationTechnology;

def xlvWeight = HealthCare;

def xlyWeight = ConsumerDiscretionary;

def xlfWeight = Financials;

def xlcWeight = Communications;

def xliWeight = Industrials;

def xlpWeight = ConsumerStaples;

def xleWeight = Energy;

def xlreWeight = RealEstate;

def xlbWeight = Materials;

def xluWeight = Utilities;

def xlk = close("XLK");

def xlv = close("XLV");

def xly = close("XLY");

def xlf = close("XLF");

def xlc = close("XLC");

def xli = close("XLI");

def xlp = close("XLP");

def xle = close("XLE");

def xlre = close("XLRE");

def xlb = close("XLB");

def xlu = close("XLU");

def xlkprice = open("XLK");

def xlvprice = open("XLV");

def xlyprice = open("XLY");

def xlfprice = open("XLF");

def xlcprice = open("XLC");

def xliprice = open("XLI");

def xlpprice = open("XLP");

def xleprice = open("XLE");

def xlreprice = open("XLRE");

def xlbprice = open("XLB");

def xluprice = open("XLU");

def xlkChangePercent = (xlk - xlkprice) / xlkprice;

def xlvChangePercent = (xlv - xlvprice) / xlvprice;

def xlyChangePercent = (xly - xlyprice) / xlyprice;

def xlfChangePercent = (xlf - xlfprice) / xlfprice;

def xlcChangePercent = (xlc - xlcprice) / xlcprice;

def xliChangePercent = (xli - xliprice)
 
I asked ChatGPT to write a code that could identify what core sector etf is out performing and what one is underperforming. This is what I got. The code loaded without errors, but there was no functional input. Can anyone make this code work?
You "seem" to have lots of functional input.
Perhaps what you are trying to say, is that you don't have any functional output.

Output in ToS is defined by PLOT statements.
You are correct, you have no PLOT statements.

You did not say what you want your functional output to look like:
1. Are you trying to create chart output? If so what do you want to plot on your chart?
Something like this:​
z80QjdZ.png
or perhaps labels:​
2. Perhaps you are attempting to create a scanner.
What are the definitions of your filters?​
 
You "seem" to have lots of functional input.
Perhaps what you are trying to say, is that you don't have any functional output.

Output in ToS is defined by PLOT statements.
You are correct, you have no PLOT statements.

You did not say what you want your functional output to look like:
1. Are you trying to create chart output? If so what do you want to plot on your chart?
Something like this:​
z80QjdZ.png
or perhaps labels:​
2. Perhaps you are attempting to create a scanner.
What are the definitions of your filters?​
Thanks for the reply, I was looking for something that could give me what sector is out performing, and under performing in real time, on any timeframe. I went to the links you gave me and copied the scripts. I’ll try them out this week. I was also hoping that ChatGPT could write a functional script for me, since I can’t code myself. My hats off to all of you on this site who can. Your much appreciated
 
Hello kind forum. I am trying to write my first thinkscript and got the code from ChatGPT after describing what I wanted. Yet pasting it into the thinkScript editor gives me an error I don't know how to fix. My wife is a software engineer who is trying to assist and she's a little stumped as well. She suggested finding a forum of thinkScript experts so here I am.

I'm trying to write a study which I want to add as a column to a watchlist. The objective is to calculate the CAGR from a particular date that I can change. Here is the code:

Python:
input startDate = "2010-01-01";

def start = startDate;
def end = GetYYYYMMDD();
def days = DaysBetween(start, end);
def years = days / 365.0;
def lowPrice = low(start, start + 1);
def closePrice = close;

def cagr = if (closePrice / lowPrice > 0) then (closePrice / lowPrice)^(1/years) - 1 else 0;

def lastCAGR = if IsNaN(cagr[1]) then 0 else cagr[1];

def color = if lastCAGR >= 0 then Color.GREEN else Color.RED;

AddLabel(yes, "CAGR: " + Round(lastCAGR, 10), color = color);

def CalculateCAGR = lastCAGR;

RTD("tos.rtd", "LastCAGR", CalculateCAGR);

The error message in the editor is "Invalid statement: def at 10:1". That's the def cagr . . . line
My wife has tried rewriting this various ways but we're stuck! Any pointers would be so much appreciated. Thanks!
 
Hello kind forum. I am trying to write my first thinkscript and got the code from ChatGPT after describing what I wanted. Yet pasting it into the thinkScript editor gives me an error I don't know how to fix. My wife is a software engineer who is trying to assist and she's a little stumped as well. She suggested finding a forum of thinkScript experts so here I am.

I'm trying to write a study which I want to add as a column to a watchlist. The objective is to calculate the CAGR from a particular date that I can change. Here is the code:

Python:
input startDate = "2010-01-01";

def start = startDate;
def end = GetYYYYMMDD();
def days = DaysBetween(start, end);
def years = days / 365.0;
def lowPrice = low(start, start + 1);
def closePrice = close;

def cagr = if (closePrice / lowPrice > 0) then (closePrice / lowPrice)^(1/years) - 1 else 0;

def lastCAGR = if IsNaN(cagr[1]) then 0 else cagr[1];

def color = if lastCAGR >= 0 then Color.GREEN else Color.RED;

AddLabel(yes, "CAGR: " + Round(lastCAGR, 10), color = color);

def CalculateCAGR = lastCAGR;

RTD("tos.rtd", "LastCAGR", CalculateCAGR);

The error message in the editor is "Invalid statement: def at 10:1". That's the def cagr . . . line
My wife has tried rewriting this various ways but we're stuck! Any pointers would be so much appreciated. Thanks!

i started typing my response on my cell after a quick glance....
i should have waited and loaded this code, there are several things wrong...


please make another post and explain what a cagr is.

here are some fixes, but there are too many things wrong to spend any more time on this before i understand the task.
thinkscript won't highlight every error at first. it may find one and highlight it red. after you fix that, another could pop up. then another and....

-----

this is wrong. dashed date text won't be recognized.
input startDate = "2010-01-01";

should be a number , in yyyymmdd format.
input startDate = 20100101;

and make sure it is a date that has data... not a weekend.

---------

this is wrong
def lowPrice = low(start, start + 1);

do you want to find the lowest of 2 values?
could use min(a,b)
to read a value on a specific date, will require an if then to compare dates then assign low to a variable.

--------

the color formula is wrong.
generally only numbers can be assigned with def. there is an exception with bracketed data. def x = { default a, b, c};

def color = if lastCAGR >= 0 then Color.GREEN else Color.RED;

have to put the color formula inside the label

AddLabel(yes, "CAGR: " + Round(lastCAGR, 10), (if lastCAGR >= 0 then Color.GREEN else Color.RED));

---------
the last line is not thinkscript.
rtd() is an excel function.


here is a link to a function in the online manual. click on 3 lines top left and search for others
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYYYYMMDD

in a column, use this to change the color of the cell
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignBackgroundColor

^ isn't valid, use power()
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Power


next time, search this site for your topic. good chance someone already thought of it
https://usethinkscript.com/threads/how-to-use-ts-to-get-cagr-compounded-annual-growth-rates.5849/


https://www.investopedia.com/terms/c/cagr.asp

--------------------
oh, and hello and welcome.
as you will find out, chatgpt is not all it's hyped up to be. it may be able to create small code snippets , but the user should have knowledge of the code.
 
Last edited:
I wanted to see if Chat GPT would create a study that alerted me once the price closed above the daily high OR below the daily low on the 5 minute chart. I wanted an orange arrow to point at the candle that closed above the daily high, or below the daily low. I asked Chat GPT to only plot this arrow after 10am. Here's the script/code it created for me. I'm getting error messages for "input color = createColor(255, 165, 0);" that's on the 3rd line and for the "if" that starts the 7th line. Any idea why?

Code:
input startTime = 1015;
input endTime = 1600;
input color = createColor(255, 165, 0);

def dayHigh = high(period = "day");
def dayLow = low(period = "day");

def barTime = secondsFromTime(timeOfDay());

if (barTime >= secondsFromTime(startTime) and barTime <= secondsFromTime(endTime)) {
    plot ArrowAbove = if close > dayHigh and barNumber() != 0 then dayHigh else double.nan;
    ArrowAbove.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
    ArrowAbove.SetLineWeight(2);
    ArrowAbove.SetDefaultColor(color);

    plot ArrowBelow = if close < dayLow and barNumber() != 0 then dayLow else double.nan;
    ArrowBelow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
    ArrowBelow.SetLineWeight(2);
    ArrowBelow.SetDefaultColor(color);
}
 
i started typing my response on my cell after a quick glance....
i should have waited and loaded this code, there are several things wrong...


please make another post and explain what a cagr is.

here are some fixes, but there are too many things wrong to spend any more time on this before i understand the task.
thinkscript won't highlight every error at first. it may find one and highlight it red. after you fix that, another could pop up. then another and....

-----

this is wrong. dashed date text won't be recognized.
input startDate = "2010-01-01";

should be a number , in yyyymmdd format.
input startDate = 20100101;

and make sure it is a date that has data... not a weekend.

---------

this is wrong
def lowPrice = low(start, start + 1);

do you want to find the lowest of 2 values?
could use min(a,b)
to read a value on a specific date, will require an if then to compare dates then assign low to a variable.

--------

the color formula is wrong.
generally only numbers can be assigned with def. there is an exception with bracketed data. def x = { default a, b, c};

def color = if lastCAGR >= 0 then Color.GREEN else Color.RED;

have to put the color formula inside the label

AddLabel(yes, "CAGR: " + Round(lastCAGR, 10), (if lastCAGR >= 0 then Color.GREEN else Color.RED));

---------
the last line is not thinkscript.
rtd() is an excel function.


here is a link to a function in the online manual. click on 3 lines top left and search for others
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYYYYMMDD

in a column, use this to change the color of the cell
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignBackgroundColor

^ isn't valid, use power()
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Power


next time, search this site for your topic. good chance someone already thought of it
https://usethinkscript.com/threads/how-to-use-ts-to-get-cagr-compounded-annual-growth-rates.5849/


https://www.investopedia.com/terms/c/cagr.asp

--------------------
oh, and hello and welcome.
as you will find out, chatgpt is not all it's hyped up to be. it may be able to create small code snippets , but the user should have knowledge of the code.

Thank you so, so much for taking the time to provide such great feedback! I knew that code it might be a .
i started typing my response on my cell after a quick glance....
i should have waited and loaded this code, there are several things wrong...


please make another post and explain what a cagr is.

here are some fixes, but there are too many things wrong to spend any more time on this before i understand the task.
thinkscript won't highlight every error at first. it may find one and highlight it red. after you fix that, another could pop up. then another and....

-----

this is wrong. dashed date text won't be recognized.
input startDate = "2010-01-01";

should be a number , in yyyymmdd format.
input startDate = 20100101;

and make sure it is a date that has data... not a weekend.

---------

this is wrong
def lowPrice = low(start, start + 1);

do you want to find the lowest of 2 values?
could use min(a,b)
to read a value on a specific date, will require an if then to compare dates then assign low to a variable.

--------

the color formula is wrong.
generally only numbers can be assigned with def. there is an exception with bracketed data. def x = { default a, b, c};

def color = if lastCAGR >= 0 then Color.GREEN else Color.RED;

have to put the color formula inside the label

AddLabel(yes, "CAGR: " + Round(lastCAGR, 10), (if lastCAGR >= 0 then Color.GREEN else Color.RED));

---------
the last line is not thinkscript.
rtd() is an excel function.


here is a link to a function in the online manual. click on 3 lines top left and search for others
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Date---Time/GetYYYYMMDD

in a column, use this to change the color of the cell
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AssignBackgroundColor

^ isn't valid, use power()
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/Power


next time, search this site for your topic. good chance someone already thought of it
https://usethinkscript.com/threads/how-to-use-ts-to-get-cagr-compounded-annual-growth-rates.5849/


https://www.investopedia.com/terms/c/cagr.asp

--------------------
oh, and hello and welcome.
as you will find out, chatgpt is not all it's hyped up to be. it may be able to create small code snippets , but the user should have knowledge of the code.

Thank you so, so very much for taking the time to dissect this! Your answers definitely point me to all the areas I need to study further. I admit, as a non-developer there are basic foundational principles I just don't have yet and your answer shows me what to dig further into. Thank you so much! I did try searching initially but probably didn't know what words to use and didn't turn up anything that looked similar. Will continue to improve! Thanks again.
 
I appreciate any help, Im just trying to create a super simple script that counts 1 day back and finds any 1 minute candles that have a range of more than $1.99 (for example, say there were 16 one minute candles with a range of more than $1.99, then the result SHOULD show as "16"). But instead its only showing the result as "YES" in red, and thats only if I hover my mouse over it. If I move my mouse away, it just says "NO".

It's just not working how I want. Please help!

]Im super new to thinkscript and am hoping there is a veteran who can help me point out what im doing wrong, cause as far as i know, the syntax and everything should be fine right?
Untitled333.png
 
Last edited by a moderator:
I appreciate any help, Im just trying to create a super simple script that counts 1 day back and finds any 1 minute candles that have a range of more than $1.99 (for example, say there were 16 one minute candles with a range of more than $1.99, then the result SHOULD show as "16"). But instead its only showing the result as "YES" in red, and thats only if I hover my mouse over it. If I move my mouse away, it just says "NO".

It's just not working how I want. Please help!

]Im super new to thinkscript and am hoping there is a veteran who can help me point out what im doing wrong, cause as far as i know, the syntax and everything should be fine right?

in the future, don't post images of code. (unless you are showing some red highlighted errors)
please post the code , as text, in a code window.
in a new post, click on </> in the header.

compare bar heights to, dollars or a percent

if height is > than the minimum, a cyan arrow is drawn.
counts the big ranges each day and display the count in a bubble on last bar.

Code:
# min_bar_ht_00

#https://usethinkscript.com/threads/chatgpt.13822/#post-119061

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

def newday = getday() != getday()[1];
def dayend = getday() != getday()[-1];

def rng = (high - low);
def avg = average(close, 10);

input min_rng_dollar = 1.99;
input min_rng_percent = 1.3;

def minrng;
input range_type = { default dollar , percent};
switch (range_type) {
case dollar:
 minrng = min_rng_dollar;
case percent:
 minrng = avg * (min_rng_percent/100);
}


def rngx = (rng > minrng);

def rngxcnt = if bn == 1 then 0
 else if newday and rngx then 1
 else if newday then 0
 else if rngx then rngxcnt[1] + 1
 else rngxcnt[1];

plot z = if rngx then low*0.999 else na;
z.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
z.SetDefaultColor(Color.cyan);
z.setlineweight(2);
z.hidebubble();


input rng_cnt = yes;
addchartbubble(rng_cnt and dayend, high*1.001,
rngxcnt
, (if rngxcnt > 0 then color.yellow else color.gray), yes);


input test2 = no;
addchartbubble(test2, low*0.99,
(100 * rng / close)
, color.yellow, no);
#
 
Last edited by a moderator:
Is there a way to get A.I. to write custom code using thinkscript language?

from a few examples i have seen,
yes and no.
it seems to be able to create a program with some valid thinkscript functions.
but tends to include invalid functions also.
so, the output will probably not run as is, it will need fixing.
there is a saying, garbage in, garbage out. the more detailed the statement is, that is fed into AI, the better chances of something useful coming out.
 
Code for Rsi divergence. Please help me to correct it

input price = close;
input length = 14;
input overbought = 70;
input oversold = 30;

def diff = price - price[1];
def up = if diff > 0 then diff else 0;
def down = if diff < 0 then -diff else 0;
def avgUp = ExpAverage(up, length);
def avgDown = ExpAverage(down, length);
def rsi = 100 - (100 / (1 + avgUp / avgDown));

plot rsiLine = rsi;
rsiLine.SetDefaultColor(GetColor(5));
rsiLine.SetLineWeight(2);

def bullishDivergence = Cross(rsi, oversold) and price > price[1];
def bearishDivergence = Cross(overbought, rsi) and price < price[1];

plot bullish = bullishDivergence;
bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullish.SetDefaultColor(GetColor(6));
bullish.SetLineWeight(3);

plot bearish = bearishDivergence;
bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearish.SetDefaultColor(GetColor(1));
bearish.SetLineWeight(3);
 
Code for Rsi divergence. Please help me to correct it

input price = close;
input length = 14;
input overbought = 70;
input oversold = 30;

def diff = price - price[1];
def up = if diff > 0 then diff else 0;
def down = if diff < 0 then -diff else 0;
def avgUp = ExpAverage(up, length);
def avgDown = ExpAverage(down, length);
def rsi = 100 - (100 / (1 + avgUp / avgDown));

plot rsiLine = rsi;
rsiLine.SetDefaultColor(GetColor(5));
rsiLine.SetLineWeight(2);

def bullishDivergence = Cross(rsi, oversold) and price > price[1];
def bearishDivergence = Cross(overbought, rsi) and price < price[1];

plot bullish = bullishDivergence;
bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullish.SetDefaultColor(GetColor(6));
bullish.SetLineWeight(3);

plot bearish = bearishDivergence;
bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearish.SetDefaultColor(GetColor(1));
bearish.SetLineWeight(3);

cross() isn't a valid function

i changed it to be a lower study

Code:
# chat_rsi_diverg_00

#https://usethinkscript.com/threads/chatgpt.13822/#post-119427
# post15

declare lower;

def na = double.nan;

#songvicobac
# #15
#Code for Rsi divergence. Please help me to correct it

input price = close;
input length = 14;
input overbought = 70;
input oversold = 30;

def diff = price - price[1];
def up = if diff > 0 then diff else 0;
def down = if diff < 0 then -diff else 0;
def avgUp = ExpAverage(up, length);
def avgDown = ExpAverage(down, length);
def rsi = 100 - (100 / (1 + avgUp / avgDown));

plot rsiLine = rsi;
rsiLine.SetDefaultColor(GetColor(5));
rsiLine.SetLineWeight(2);

def bullishDivergence = Crosses(rsi, oversold) and price > price[1];
def bearishDivergence = Crosses(overbought, rsi) and price < price[1];

#plot bullish = bullishDivergence;
#bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
plot bullish = if bullishDivergence then rsi else na;
bullish.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
bullish.SetDefaultColor(GetColor(6));
bullish.SetLineWeight(3);

#plot bearish = bearishDivergence;
#bearish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot bearish = if bearishDivergence then rsi else na;
bearish.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
bearish.SetDefaultColor(GetColor(1));
bearish.SetLineWeight(3);

#

crosses
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/crosses
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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