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

#### MBF

##### Active member
2019 Donor
Hi all,
I have been trying to write this strategy script and I am new at strategy writing. I kind of have a grip but I've strayed from the path and am now confused.
The strategy is simple except for trying to figure out the two timeframe conundrum.
Strategy : Daily StochRSI KPeriod is above DPeriod.
4 Hour StochRSI DPeriod is below Oversold and RSI 2 Period is below Oversold.
If anyone can find some time to look at it, I would appreciate it.

Here is my attempt at the script for strategy:

Code:
``````#####
input tradetype = { "long"};

def timeFrame = GetAggregationPeriod();
def lowestAggregation;
def highestAggregation;

input timePeriods = { "day", default "Four" };

# RSI
input rsiLength = 2;
input rsiAverageType = AverageType.WILDERS;
input OverBought =  90;
input Oversold  = 10;

def R = rsiLength < 10;
def Q = rsiLength > 90;

# Stochastic
input KPeriod = 16;
input DPeriod = 10;
input RSILength2 = 14;
input Oversld = 10;
input OverBot = 90;
def T = KPeriod > DPeriod;
def S = KPeriod < DPeriod;
def OS = DPeriod < 10;
def OB = KPeriod > 90;

##Scan##
def Uptrend;

if timePeriods == timePeriods.day {
Uptrend = if T then 1 else 0;

} and if timePeriods == timePeriods.Four {
UpTrend1 = if OS  and R   then 1 else 0;
plot Uptrend;
if timePeriods {
day and fourHours == 1 then 1 else 0;

plot ExitUpTrend;

ExitUpTrend = if R  and OB then 1 else 0;

def LongBuy = if Uptrend and UpTrend1 == 1 then 1 else 0;
def LongExit = if R  and OB == 1 and ExitUpTrend[1] == 0 then 1 else 0;

##Labels##

AddLabel(yes, if Uptrend == 1 and ExitUpTrend == 0 then "::Go Long::" else if DownTrend == 1 and ExitDownTrend == 0 then "::Go Short::" else "::Do Nothing::", if Uptrend == 1 and ExitUpTrend == 0 then Color.CYAN else if DownTrend == 1 and ExitDownTrend == 0 then Color.MAGENTA else Color.GRAY);

def bar = BarNumber();

def longSignal = if Uptrend == 1 and ExitUpTrend == 0 then 1 else 0;

plot upArrow = if (LongBuy == 1 and (tradetype == tradetype.long))  or  (LongExit == 1) and  Active then low else Double.NaN;
upArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
upArrow.SetDefaultColor(Color.CYAN);

AddOrder(OrderType.BUY_AUTO, LongBuy == 1 and (tradetype == tradetype.long) and Active and testTimeFrames, price = close, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "BUY");
AddOrder(OrderType.SELL_TO_CLOSE, LongExit == 1 and (tradetype == tradetype.long) and testTimeFrames, price = open[-1], tickcolor = Color.MAGENTA, arrowcolor = Color.MAGENTA, name = "Sell To Close");

#### SteveDay

##### New member
Plus
After reading the OP's post I've been testing ChatGPT.

It can be very useful with converting known formulas and such, but it repeatedly uses functions/commands that don't exist. When I ask about any non-existent function it says "xxx() is a function in ThinkScript which does yyy". I then say "are you sure?" and it regurgitates, digging a deeper hole for itself. Only when I tell it that it's wrong and that does not exist in ThinkScript, does it finally say "You are right, xxx() does not exist in ThinkScript. I'm sorry for the confusion".

It also has a lot of difficulty when it thinks it can do something via Object-Oriented programming. Even if you tell it that ThinkScript is not an Object-Oriented language, it will apologize and agree with you, then recalculate the code, but more often than not it will still manage to squeeze OO behavior into the example. While I was trying something on Saturday (related to calculating Option prices), it managed to repeat that mistake recalculating the same script around 3 or 4 times before I finally got it to stop.

I tried a similar BS-detector test, this time unrelated to programming. I gave it a model of firearm that I knew about and asked it the differences between it and a similar sounding model (a model that appeared to be a model in the series from the same manufacturer). It gave a whole spec sheet on the non-existent model and did not own up to the lies until I explicitly told it that it did not exist. Even then it said it may have gotten the information from a typo somewhere. 🙄

It has incredible potential, but it lies like 5-year old caught doing something they shouldn't. I hate smoke being blow up my *** and ChatGPT has a great skill for doing just that. Maybe it's destined for politics? .😆

Last edited:

#### ttsdmagic

##### Member
I asked ChatGPT which settings have back-tested well on the MACD study. It gave me this response:

Yes, there are other settings for the MACD that have been backtested and found to perform well on the daily chart, depending on the market and trading strategy. Here are some alternative settings that traders have found to be effective:
1. 8, 17, 9: This setting uses a faster 8-period EMA and a shorter 17-period EMA, which can help to provide more responsive signals in trending markets.
2. 10, 20, 5: This setting uses a shorter 5-period EMA for the signal line, which can help to provide faster and more frequent trading signals.
3. 21, 55, 8: This setting uses longer EMA periods and a shorter signal line period, which can help to smooth out market noise and provide more reliable signals in longer-term trends.
4. 5, 35, 5: This setting uses a fast 5-period EMA and a longer 35-period EMA, which can help to capture short-term trends and identify potential reversals.
It's important to note that these settings are not guaranteed to work in all market conditions, and that traders should conduct their own backtesting and experimentation to determine the best settings for their individual needs and trading strategies. Additionally, the MACD should be used in conjunction with other indicators and tools to confirm trading signals and avoid false signals.

#### quantumomegallc

##### New member
VIP
I realized part way through with ChatGPT that it's converting into the API scripting code, not the Editor's function call. Pretty useless if you are on the app, but if you switch tot he Web Interface and somehow manage to plug in a Python interface it will work.

#### halcyonguy

##### Well-known member
VIP
After reading the OP's post I've been testing ChatGPT.

It can be very useful with converting known formulas and such, but it repeatedly uses functions/commands that don't exist. When I ask about any non-existent function it says "xxx() is a function in ThinkScript which does yyy". I then say "are you sure?" and it regurgitates, digging a deeper hole for itself. Only when I tell it that it's wrong and that does not exist in ThinkScript, does it finally say "You are right, xxx() does not exist in ThinkScript. I'm sorry for the confusion".

It also has a lot of difficulty when it thinks it can do something via Object-Oriented programming. Even if you tell it that ThinkScript is not an Object-Oriented language, it will apologize and agree with you, then recalculate the code, but more often than not it will still manage to squeeze OO behavior into the example. While I was trying something on Saturday (related to calculating Option prices), it managed to repeat that mistake recalculating the same script around 3 or 4 times before I finally got it to stop.

I tried a similar BS-detector test, this time unrelated to programming. I gave it a model of firearm that I knew about and asked it the differences between it and a similar sounding model (a model that appeared to be a model in the series from the same manufacturer). It gave a whole spec sheet on the non-existent model and did not own up to the lies until I explicitly told it that it did not exist. Even then it said it may have gotten the information from a typo somewhere. 🙄

It has incredible potential, but it lies like 5-year old caught doing something they shouldn't. I hate smoke being blow up my *** and ChatGPT has a great skill for doing just that. Maybe it's destined for politics? .😆

that is an interesting test. You would think it would just come out and say , I don't know about that model number.
the fact that it outright lies, tells me this whole chat thing is just garbage entertainment. just another tool for big tech to pull information from users.

#### MerryDay

Staff member
Staff
VIP
that is an interesting test. You would think it would just come out and say , I don't know about that model number.
the fact that it outright lies, tells me this whole chat thing is just garbage entertainment. just another tool for big tech to pull information from users.
It is interesting to watch as chatGPT is learning.
It is giving better explanations of why it uses the syntax that is does:

This doesn't generate anything. But it is getting better at Thinkscript syntax and the general logic of what it is supposed to do.

So yes, it is still garbage. But before, it was a 5yr old generating code. It's now a pre-teen; in a few short weeks. Who knows where it will be in a year.

Last edited:

#### halcyonguy

##### Well-known member
VIP

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

take a look at this post, looks like the same pine code

#### quantumomegallc

##### New member
VIP
After reading the OP's post I've been testing ChatGPT.

It can be very useful with converting known formulas and such, but it repeatedly uses functions/commands that don't exist. When I ask about any non-existent function it says "xxx() is a function in ThinkScript which does yyy". I then say "are you sure?" and it regurgitates, digging a deeper hole for itself. Only when I tell it that it's wrong and that does not exist in ThinkScript, does it finally say "You are right, xxx() does not exist in ThinkScript. I'm sorry for the confusion".

It also has a lot of difficulty when it thinks it can do something via Object-Oriented programming. Even if you tell it that ThinkScript is not an Object-Oriented language, it will apologize and agree with you, then recalculate the code, but more often than not it will still manage to squeeze OO behavior into the example. While I was trying something on Saturday (related to calculating Option prices), it managed to repeat that mistake recalculating the same script around 3 or 4 times before I finally got it to stop.

I tried a similar BS-detector test, this time unrelated to programming. I gave it a model of firearm that I knew about and asked it the differences between it and a similar sounding model (a model that appeared to be a model in the series from the same manufacturer). It gave a whole spec sheet on the non-existent model and did not own up to the lies until I explicitly told it that it did not exist. Even then it said it may have gotten the information from a typo somewhere. 🙄

It has incredible potential, but it lies like 5-year old caught doing something they shouldn't. I hate smoke being blow up my *** and ChatGPT has a great skill for doing just that. Maybe it's destined for politics? .😆
The functions are from the API, not Thinkscript itself.

#### JoeDV

##### Active member
VIP
I asked ChatGPT which settings have back-tested well on the MACD study. It gave me this response:

Yes, there are other settings for the MACD that have been backtested and found to perform well on the daily chart, depending on the market and trading strategy. Here are some alternative settings that traders have found to be effective:
1. 8, 17, 9: This setting uses a faster 8-period EMA and a shorter 17-period EMA, which can help to provide more responsive signals in trending markets.
2. 10, 20, 5: This setting uses a shorter 5-period EMA for the signal line, which can help to provide faster and more frequent trading signals.
3. 21, 55, 8: This setting uses longer EMA periods and a shorter signal line period, which can help to smooth out market noise and provide more reliable signals in longer-term trends.
4. 5, 35, 5: This setting uses a fast 5-period EMA and a longer 35-period EMA, which can help to capture short-term trends and identify potential reversals.
It's important to note that these settings are not guaranteed to work in all market conditions, and that traders should conduct their own backtesting and experimentation to determine the best settings for their individual needs and trading strategies. Additionally, the MACD should be used in conjunction with other indicators and tools to confirm trading signals and avoid false signals.

Just for the heck of it, I asked Google Bard the same question. Here's the response:

The following are some of the MACD settings that have back-tested well:
• (12,26,9): The default settings for the MACD indicator are: Slow moving average: 26 days. Fast moving average: 12 days. Signal line: 9-day moving average of the difference between fast and slow. All moving averages are exponential.
• (5,35,5): This setting is more sensitive than the default settings and might be better suited for weekly charts.
• (14,28,5): This setting is less sensitive than the default settings and might be better suited for daily charts.
• (14,28,9): This setting is a compromise between the (12,26,9) and (5,35,5) settings and might be a good all-around setting for most traders.
It is important to note that there is no single perfect set of MACD settings. The best settings for you will depend on your trading style, the markets you trade, and your risk tolerance. It is always best to experiment with different settings to find what works best for you.

#### BenTen

Staff member
Staff
VIP
@JoeDV You already got access to Google Bard? That was quick. I'm still on the waiting list, haha.

How is it compare to ChatGPT when it comes to thinkScripting?

#### JoeDV

##### Active member
VIP
@JoeDV You already got access to Google Bard? That was quick. I'm still on the waiting list, haha.

How is it compare to ChatGPT when it comes to thinkScripting?

Yeah I got access a few days ago, hang in there, the invites are coming out. That said, I'm all for Google/Android, a beta tester for the Pixel, etc but man, Bard doesn't come close to ChatGPT in so many ways. Thinkscript is absolutely awful!

Ok in fairness now, I did look through some of the help docs for Bard and it does say :

Can Bard help with coding?

Bard can't help you with coding just yet. Bard is still learning to code, and responses about code aren't officially supported for now.

The rest of it isn't as polished as Chatgpt yet either though.

Last edited:

#### Wenclarence

##### New member
Hi!

I am not a programmer and have almost no training in coding before. So when ChatGPT came around, it finally open the doors for me to utilise thinkscript in the options trading as well.

I tried to create a script that will help me identify the best credit spread pairing. And display it on the chart directly. By combining it with other criteria and indicators such as ichimouku cloud, i hope to be able to visually identify any potential credit spread set up directly from the chart, hence saving some time.

But unfortunately there are some error with the script and chatgpt was not able to resolved as well.

Below is the script, would appreciate if any expert will be able to resolve the error in the script?

Thank you!

Code:
``````# Define input variables
input expRangeDays = 25;
input expRangeDaysMax = 60;

# Define variables
def underlyingPrice = close;
def daysToExpiration = GetExpirationDate() - GetYYYYMMDD();
def expirationInRange = daysToExpiration >= expRangeDays and daysToExpiration <= expRangeDaysMax;

# Define functions
def GetOptionPrice(double strike) {
return (AskPrice(symbol = GetUnderlyingSymbol(), priceType = PriceType.ASK, useLastQuote = true) +
BidPrice(symbol = GetUnderlyingSymbol(), priceType = PriceType.BID, useLastQuote = true)) / 2.0;
}

def CalcCreditSpread(double strike, double moneyness, double creditSize) {
def callBuyStrike = Round(strike * (1 + moneyness), 2);
def callSellStrike = Round(callBuyStrike + creditSize, 2);
def putBuyStrike = Round(strike * (1 - moneyness), 2);
def putSellStrike = Round(putBuyStrike - creditSize, 2);
def callSellPrice = GetOptionPrice(callSellStrike);
def putSellPrice = GetOptionPrice(putSellStrike);
def maxGain = creditSize;
def maxLoss = (callSellStrike - callBuyStrike - creditSize) + (putSellStrike - putBuyStrike - creditSize);
def creditReceived = (callSellPrice - callBuyPrice) + (putSellPrice - putBuyPrice);
def roi = creditReceived / maxLoss * 100;
def probOfProfit = (creditSize / (callSellStrike - callBuyStrike)) * 100;
return if (probOfProfit >= 70 and roi >= 5) then [callBuyStrike, callSellStrike, putBuyStrike, putSellStrike, maxGain, maxLoss, roi, probOfProfit] else Double.NaN;
}

# Calculate optimal put and call credit spreads
def atmStrike = Round(underlyingPrice / 5.0, 0) * 5.0;
def optCallSpread = if (expirationInRange) then CalcCreditSpread(atmStrike, 0.05, underlyingPrice * 0.01) else Double.NaN;
def optPutSpread = if (expirationInRange) then CalcCreditSpread(atmStrike, 0.05, underlyingPrice * 0.01) else Double.NaN;

# Display optimal put and call credit spreads

#### zeek

##### Active member
2019 Donor
Edit: Request no longer needed

Last edited:

#### halcyonguy

##### Well-known member
VIP
Hi all,
I have been trying to write this strategy script and I am new at strategy writing. I kind of have a grip but I've strayed from the path and am now confused.
The strategy is simple except for trying to figure out the two timeframe conundrum.
Strategy : Daily StochRSI KPeriod is above DPeriod.
4 Hour StochRSI DPeriod is below Oversold and RSI 2 Period is below Oversold.
If anyone can find some time to look at it, I would appreciate it.

Here is my attempt at the script for strategy:

Code:
``````#####
input tradetype = { "long"};

def timeFrame = GetAggregationPeriod();
def lowestAggregation;
def highestAggregation;

input timePeriods = { "day", default "Four" };

# RSI
input rsiLength = 2;
input rsiAverageType = AverageType.WILDERS;
input OverBought =  90;
input Oversold  = 10;

def R = rsiLength < 10;
def Q = rsiLength > 90;

# Stochastic
input KPeriod = 16;
input DPeriod = 10;
input RSILength2 = 14;
input Oversld = 10;
input OverBot = 90;
def T = KPeriod > DPeriod;
def S = KPeriod < DPeriod;
def OS = DPeriod < 10;
def OB = KPeriod > 90;

##Scan##
def Uptrend;

if timePeriods == timePeriods.day {
Uptrend = if T then 1 else 0;

} and if timePeriods == timePeriods.Four {
UpTrend1 = if OS  and R   then 1 else 0;
plot Uptrend;
if timePeriods {
day and fourHours == 1 then 1 else 0;

plot ExitUpTrend;

ExitUpTrend = if R  and OB then 1 else 0;

def LongBuy = if Uptrend and UpTrend1 == 1 then 1 else 0;
def LongExit = if R  and OB == 1 and ExitUpTrend[1] == 0 then 1 else 0;

##Labels##

AddLabel(yes, if Uptrend == 1 and ExitUpTrend == 0 then "::Go Long::" else if DownTrend == 1 and ExitDownTrend == 0 then "::Go Short::" else "::Do Nothing::", if Uptrend == 1 and ExitUpTrend == 0 then Color.CYAN else if DownTrend == 1 and ExitDownTrend == 0 then Color.MAGENTA else Color.GRAY);

def bar = BarNumber();

def longSignal = if Uptrend == 1 and ExitUpTrend == 0 then 1 else 0;

plot upArrow = if (LongBuy == 1 and (tradetype == tradetype.long))  or  (LongExit == 1) and  Active then low else Double.NaN;
upArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
upArrow.SetDefaultColor(Color.CYAN);

AddOrder(OrderType.BUY_AUTO, LongBuy == 1 and (tradetype == tradetype.long) and Active and testTimeFrames, price = close, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "BUY");
AddOrder(OrderType.SELL_TO_CLOSE, LongExit == 1 and (tradetype == tradetype.long) and testTimeFrames, price = open[-1], tickcolor = Color.MAGENTA, arrowcolor = Color.MAGENTA, name = "Sell To Close");

this is a strategy, although the addorder codes are disabled.

most of your code is wrong, so i started over, guessing the best i could, with what i think you want.

your code has inputs in formulas instead of the function outputs.
ex. def T = KPeriod > DPeriod;
kperiod is an input , so the stochrsi function wouldn't have even been used.

i copied the codes for 2 studies, into 3 sections
rsi
stochrsi - daily
stochrsi - 4 hour

buy rules (i guessed that these are what you want)
..rsi - rsi(2) < over_Sold
..stochrsi - daily , fullk > fulld
..Stochrsi - 4 hour , fulld < st_oversold

each section has 1 true output.
i'm guessing if all 3 are true, then do a buy.
i plotted a shape for each of the 3 sections.

i disabled the original output formulas and addorders.

with overboughts at 90 and oversolds at 10, i didn't see bars with all 3 signals.

i changed all 6 overbought/oversold numbers, from 90/10 , to 80/20

then i saw a buy signal on a couple of stocks
F 1hour
NIO 1 hour

experiment with this and see if it is close to what you want.
then post back with observations and changes.

Code:
``````# chat41_strat_stochrsi_00

#MBF  Mar 4, 2023 #41

#I have been trying to write this strategy script and I am new at strategy writing. I kind of have a grip but I've strayed from the path and am now confused.
#The strategy is simple except for trying to figure out the two timeframe conundrum.

#Strategy :   wrong , this is comparing inputs
#  RSI 2 Period is below Oversold.
#  Daily StochRSI KPeriod is above DPeriod.
#  4 Hour StochRSI DPeriod is below Oversold

# rewritten , using outputs
#  rsi(2) < rsiover_Sold
#  daily - fullk > fulld
#  4 hr - fulld < st_oversold

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

#####
input tradetype = { default "long" , "short" };

def timeFrame = GetAggregationPeriod();
#def lowestAggregation;
#def highestAggregation;

input timePeriods = { "day", default "Four" };

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

#  rsi(2) < rsiover_Sold

# RSI
input rsiLength = 2;
input rsiAverageType = AverageType.WILDERS;
input rsiover_Bought = 90;
input rsiover_Sold = 10;
input price = close;

def NetChgAvg = MovingAverage(rsiAverageType, price - price[1], rsiLength);
def TotChgAvg = MovingAverage(rsiAverageType, AbsValue(price - price[1]), rsiLength);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;

def RSI = 50 * (ChgRatio + 1);

#  rsi(2) < rsiover_Sold
def rsi_os_below = rsi < rsiover_Sold;
def rsi_ob_above = rsi > rsiover_Bought;

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

# Stochrsi - daily , fullk > fulld

input agg1 = AggregationPeriod.day;
def agg1min = agg1/60000;

input st1KPeriod = 16;
input st1DPeriod = 10;
input st1RSI_length2 = 14;
input st1over_bought = 90;
input st1over_sold = 10;
input st1RSI_average_type = AverageType.WILDERS;
#input st1RSI_price = close;
def st1RSI_price = close(period = agg1);

input slowing_period = 1;
input st1averageType = AverageType.SIMPLE;
#input showBreakoutSignals = {default "No", "On FullK", "On FullD", "On FullK & FullD"};

def st1sRSI = RSI(price = st1RSI_price, length = st1RSI_length2, averageType = st1RSI_average_type);

def st1FullK = StochasticFull(st1over_bought, st1over_sold, st1KPeriod, st1DPeriod, st1sRSI, st1sRSI, st1sRSI, slowing_period, st1averageType).FullK;
def st1FullD = StochasticFull(st1over_bought, st1over_sold, st1KPeriod, st1DPeriod, st1sRSI, st1sRSI, st1sRSI, slowing_period, st1averageType).FullD;

def st1_kbelowd = st1fullk < st1fulld;
def st1_dbelowos = st1fulld < st1over_sold;
def st1_kaboveob = st1fullk > st1over_bought;

#  time1 - daily ,  fullk > fulld
def st1_koverd = st1fullk > st1fulld;

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

# Stochrsi - 4 hour , fulld < st_oversold

input agg2 = AggregationPeriod.four_hours;
def agg2min = agg2/60000;

input st2KPeriod = 16;
input st2DPeriod = 10;
input st2RSI_length2 = 14;
input st2over_bought = 90;
input st2over_sold = 10;
input st2RSI_average_type = AverageType.WILDERS;
#input st2RSI_price = close;
def st2RSI_price = close(period = agg2);

input st2slowing_period = 1;
input st2averageType = AverageType.SIMPLE;
#input showBreakoutSignals = {default "No", "On FullK", "On FullD", "On FullK & FullD"};

def st2sRSI = RSI(price = st2RSI_price, length = st2RSI_length2, averageType = st2RSI_average_type);

def st2FullK = StochasticFull(st2over_bought, st2over_sold, st2KPeriod, st2DPeriod, st2sRSI, st2sRSI, st2sRSI, slowing_period, st2averageType).FullK;
def st2FullD = StochasticFull(st2over_bought, st2over_sold, st2KPeriod, st2DPeriod, st2sRSI, st2sRSI, st2sRSI, slowing_period, st2averageType).FullD;

def st2_kaboved = st2fullk > st2fulld;
def st2_kbelowd = st2fullk < st2fulld;
def st2_kaboveob = st2fullk > st2over_bought;

#  4 hr - fulld < st_oversold
def st2_dbelowos = st2fulld < st2over_sold;

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

def buy1x = rsi_os_below and st1_koverd and st2_dbelowos;
#def buy1 = rsi_os_below or st1_koverd or st2_dbelowos;

plot buy1 = if rsi_os_below then low*0.99 else na;

plot buy2 = if st1_koverd then low*0.98 else na;

plot buy3 = if st2_dbelowos then low*0.97 else na;

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

# original code.  all disabled

##Scan##
#def Uptrend = if timePeriods == timePeriods.day and T then 1 else 0;
#def uptrend1 = if timePeriods == timePeriods.Four and OS and R then 1 else 0;
#def downtrend = 0;
#def downtrend1 = 0;
#def ExitUpTrend = if R and OB then 1 else 0;
#def LongBuy = if Uptrend and uptrend1 == 1 then 1 else 0;
#def LongExit = if R and OB == 1 and !ExitUpTrend[1] then 1 else 0;
#def ExitdownTrend = if Q and OS then 1 else 0;
#def shortbuy = if downtrend and downtrend1 == 1 then 1 else 0;
#def shortexit = if Q and OS and !ExitdownTrend[1] then 1 else 0;

# fix these
#def active = 0;
#def testTimeFrames = 0;

def uptrend = 0;
def ExitUpTrend = 0;
def downtrend = 0;
def ExitdownTrend = 0;
def LongBuy = 0;
def LongExit = 0;
def Active = 0;
def testTimeFrames = 0;

##Labels##
if Uptrend and !ExitUpTrend then "::Go Long::" else if downtrend and !ExitdownTrend then "::Go Short::" else "::Do Nothing::",
if Uptrend and !ExitUpTrend then Color.CYAN else if downtrend and !ExitdownTrend then Color.MAGENTA else Color.GRAY);

def longSignal = if Uptrend and !ExitUpTrend then 1 else 0;

plot upArrow = if (LongBuy == 1 and (tradetype == tradetype.long))  or  (LongExit == 1) and  Active then low else Double.NaN;
upArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
upArrow.SetDefaultColor(Color.CYAN);

AddOrder(OrderType.BUY_TO_OPEN, LongBuy == 1 and (tradetype == tradetype.long) and Active and testTimeFrames, price = close, tickcolor = Color.CYAN, arrowcolor = Color.CYAN, name = "BUY");

AddOrder(OrderType.SELL_TO_CLOSE, LongExit == 1 and (tradetype == tradetype.long) and testTimeFrames, price = open[-1], tickcolor = Color.MAGENTA, arrowcolor = Color.MAGENTA, name = "Sell To Close");

#``````

NIO 1hour 3/1

#### Wockets

##### Member
write a strategy code for thinkorswim that incorporates supply and demand and volume profile

As an AI language model, I can provide you with a sample code that incorporates both supply and demand and volume profile concepts for Thinkorswim. Please note that this is only an example code and you should always consult with a professional trader or financial advisor before implementing any trading strategies.

# Supply & Demand with Volume Profile Strategy for Thinkorswim
# Written by ChatGPT

declare lower;

# Supply and Demand Zones
input sdPeriod = 14;
input sdBuffer = 0.5;

def highs = highest(sdPeriod);
def lows = lowest(sdPeriod);
def range = max(highs - lows, 0.0000001);
def center = lows + range/2;

def supplyZone = center + range * sdBuffer;
def demandZone = center - range * sdBuffer;

def sdColor = highs > supplyZone ? color.red : lows < demandZone ? color.green : color.gray;
plot SupplyZone = supplyZone;
plot DemandZone = demandZone;
SupplyZone.SetDefaultColor(sdColor);
DemandZone.SetDefaultColor(sdColor);
AddCloud(demandZone, supplyZone, color.green, color.red);

# Volume Profile
input vpPeriod = 60;
input vpWidth = 10;

def vpData = VolumeProfile("startNewProfile" = yes, "onExpansion" = no, "numberOfProfiles" = vpPeriod, "pricePerRow" = 0.5, "showPointOfControl" = no, "showValueArea" = no);
def vpRange = Highest(vpData.Value[1], vpWidth);

plot VolumeProfile = vpData.Value[1];
plot VpRange = vpRange;
VolumeProfile.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
VolumeProfile.SetLineWeight(1);
VolumeProfile.SetDefaultColor(color.purple);
VolumeProfile.SetStyle(Curve.SHORT_DASH);
VpRange.SetDefaultColor(color.white);

# Signal
def buySignal = close > demandZone;
def sellSignal = close < supplyZone;

plot BuySignal = if buySignal then demandZone else Double.NaN;
plot SellSignal = if sellSignal then supplyZone else Double.NaN;
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(color.red);

This code uses Thinkorswim's built-in functions for volume profile and supply and demand analysis to plot zones on the chart where price may experience support or resistance. The script also generates signals when the price crosses these zones, and can alert you when these signals occur. Keep in mind that this is only one possible implementation of supply and demand and volume profile concepts, and you should always backtest and adjust the strategy to fit your personal trading style and risk tolerance.

When I copied and pasted in strategies ,

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

Hi tinfox,

Here is code that places an arrow whenever the RSI has been below the oversold line for 10 consecutive price bars (the same number of bars as shown in your original code). It works well and one can do stock scans where the RSI_ExtremeLow study is added and marked as true.

I did a scan tonight with minimum price \$5 and minimum volume 100,000 shares and "RSI_ExtremeLow is true" and got 42 hits. One of them, GPS, is shown below.

The major negative with this script is that I couldn't figure out how to make the number of price bars that RSI is below oversold be shown as an input, e.g., to change 10 consecutive bars with RSI below the oversold line to 15 bars, etc, by simply changing the number. This can be done with the code below by modifying the "plot RSIextreme" line, but it would really be better if it were an input.

Perhaps one of the more experienced individuals here will know how to make this adjustable in the inputs.

Code:
``````# RSI_ExtremeLow
# tinfox question 3-29-23

input price = close;
input length = 14;
input over_bought = 70;
input over_sold = 30;
input averageType = AverageType.WILDERS;

def NetChgAvg = MovingAverage(averageType, price - price[1], length);
def TotChgAvg = MovingAverage(averageType, AbsValue(price - price[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);

plot RSIextreme = RSI < over_sold and RSI[1] < over_sold and RSI[2] < over_sold and RSI[3] < over_sold and RSI[4] < over_sold and RSI[5] < over_sold and RSI[6] < over_sold and RSI[7] < over_sold and RSI[8] < over_sold and RSI[9] < over_sold;

RSIextreme.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
RSIextreme.SetDefaultColor(Color.RED);
RSIextreme.SetLineWeight(4);``````

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

Start a new thread and receive assistance from our community.

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