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:
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;
  Alert(Buy == 1,"Stoch Uptrend",Alert.BAR, Sound.Ring);


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

       
##BUY###
 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");
 AddOrder(OrderType.SELL_TO_CLOSE,
 

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

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


MsLFdZS.png


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:
https://www.tradingview.com/script/LgjsidVh-ATR-Stop-Loss-Finder/

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
https://usethinkscript.com/threads/average-true-range-stop-loss-finder-for-thinkorswim.14067/
 
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.
 
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.
 
@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:
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 callBuyPrice = GetOptionPrice(callBuyStrike);
    def callSellPrice = GetOptionPrice(callSellStrike);
    def putBuyPrice = GetOptionPrice(putBuyStrike);
    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
AddCloud(if !isNaN(optCallSpread[0]) then optCallSpread[0] else Double.NaN, if !isNaN(optCallSpread[1]) then optCallSpread[1] else Double.NaN, color.green, color.red);
AddCloud(if !isNaN(optPutSpread[2]) then optPutSpread[2] else Double.NaN, if !isNaN(optPutSpread[3]) then optPutSpread[3] else Double.NaN, color.red, color.green);
 
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;
  Alert(Buy == 1,"Stoch Uptrend",Alert.BAR, Sound.Ring);


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

       
##BUY###
 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");
 AddOrder(OrderType.SELL_TO_CLOSE,

reply to post41

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

#https://usethinkscript.com/threads/chatgpt-for-thinkorswim.13822/page-3#post-121184
#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;
addverticalline(buy1x, "buy", color.green);


plot buy1 = if rsi_os_below then low*0.99 else na;
buy1.SetPaintingStrategy(PaintingStrategy.POINTS);
buy1.SetDefaultColor(Color.yellow);
buy1.setlineweight(2);
buy1.hidebubble();

plot buy2 = if st1_koverd then low*0.98 else na;
buy2.SetPaintingStrategy(PaintingStrategy.SQUARES);
buy2.SetDefaultColor(Color.magenta);
buy2.setlineweight(2);
buy2.hidebubble();

plot buy3 = if st2_dbelowos then low*0.97 else na;
buy3.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
buy3.SetDefaultColor(Color.cyan);
buy3.setlineweight(2);
buy3.hidebubble();



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

# 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##
AddLabel(yes,
 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;

Alert(longSignal, "Stoch Uptrend", Alert.BAR, Sound.Ring);

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

      
##BUY###
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
BCRTVs8.jpg
 
write a strategy code for thinkorswim that incorporates supply and demand and volume profile

ChatGPT's reply :

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;
BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignal.SetDefaultColor(color.green);
SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SellSignal.SetDefaultColor(color.red);

# Alerts
alert(buySignal, "Buy Signal", Alert.BAR, Sound.Ding);
alert(sellSignal, "Sell Signal", Alert.BAR, Sound.Ding);

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 ,

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

tinfox-chart-3-29-23.png
 
I’ve created a version 2 of this indicator that allows the number of recent bars with the RSI under the oversold line to be an adjustable input and it works pretty well, but it isn’t a perfect mathematical expression of the desired outcome.

The problem has to do with the offset brackets. RSI[1] means the RSI one bar ago and RSI[2] means the RSI value two bars ago and RSI[3] means three bars ago, etc. But how does one indicate that each of the RSIs one and two and three bars ago must all be under the oversold line? RSA[1-3] doesn’t work and RSI[1,2,3] doesn’t work. (If perchance an employee at ThinkOrSwim happens to read this, it would be very helpful if the developers could enhance thinkscript to give us more options for this; or explain how it can be done using existing code words)

One can simply write out a requirement for each bar and that certainly works: RSA[1] < oversold and RSA[2] is oversold and RSA[3] is oversold works fine and it can be continued out for as many bars as one wants. However, this doesn’t allow the user to have an adjustable input number so they, for example, can easily compare requiring RSA to be less than the oversold line for each of the last 5 bars versus the last 10 bars.

I figured out that a little bit of math can be done inside the brackets. Thinkscript allows one to write something like RSI[Previousbars - 1] and RSI[Previousbars - 2], where Previousbars is the total number of past bars and is a variable defined by the user in the inputs.

So, one can input the Previousbars to be 10 and write the code as shown below, indicating that the current RSI must be under the oversold line AND the RSI 10 previous bars ago must be under oversold AND the RSI 10 minus 1 or 9 bars ago must be under oversold AND the RSI 10 minus 2 or 8 bars ago must be under oversold, and the RSI 10 minus 3 bars ago, etc. This approach means that not every single RSI value in the last 10 is absolutely required to be under the oversold line, but in practice most stock scans give the same results as when one requires all of the RSIs of the last 10 bars to be below the oversold line; and the big advantage of version 2 is that now one can choose 5 bars or 10 or 20 in the inputs and compare the results that each produces.

“plot RSIextreme = RSI < over_sold and RSI[Previousbars] < over_sold and RSI[Previousbars - 1] < over_sold and RSI[Previousbars - 2] < over_sold and RSI[Previousbars - 3] < over_sold and RSI[Previousbars - 4] < over_sold;”

A current chart of BABA is shown with Previousbars set to 7 in the inputs.

tinfox-rsiextreme-V2-chart-4-2-23.png



Code:
# RSI_ExtremeLow_v2
# tinfox question 4-1-23 - script that allows the number of recent bars that RSI is required to be below oversold to be changed in the inputs;
# The PreviousBars input should always be greater than or equal to 5. This script works well though it is not a perfect mathematical solution.

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

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[Previousbars] < over_sold and RSI[Previousbars - 1] < over_sold and RSI[Previousbars - 2] < over_sold and RSI[Previousbars - 3] < over_sold and RSI[Previousbars - 4] < over_sold;

RSIextreme.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
RSIextreme.SetDefaultColor(Color.BLUE);
RSIextreme.SetLineWeight(4);
 
I’ve created a version 2 of this indicator that allows the number of recent bars with the RSI under the oversold line to be an adjustable input and it works pretty well, but it isn’t a perfect mathematical expression of the desired outcome.

The problem has to do with the offset brackets. RSI[1] means the RSI one bar ago and RSI[2] means the RSI value two bars ago and RSI[3] means three bars ago, etc. But how does one indicate that each of the RSIs one and two and three bars ago must all be under the oversold line? RSA[1-3] doesn’t work and RSI[1,2,3] doesn’t work. (If perchance an employee at ThinkOrSwim happens to read this, it would be very helpful if the developers could enhance thinkscript to give us more options for this; or explain how it can be done using existing code words)

One can simply write out a requirement for each bar and that certainly works: RSA[1] < oversold and RSA[2] is oversold and RSA[3] is oversold works fine and it can be continued out for as many bars as one wants. However, this doesn’t allow the user to have an adjustable input number so they, for example, can easily compare requiring RSA to be less than the oversold line for each of the last 5 bars versus the last 10 bars.

I figured out that a little bit of math can be done inside the brackets. Thinkscript allows one to write something like RSI[Previousbars - 1] and RSI[Previousbars - 2], where Previousbars is the total number of past bars and is a variable defined by the user in the inputs.

So, one can input the Previousbars to be 10 and write the code as shown below, indicating that the current RSI must be under the oversold line AND the RSI 10 previous bars ago must be under oversold AND the RSI 10 minus 1 or 9 bars ago must be under oversold AND the RSI 10 minus 2 or 8 bars ago must be under oversold, and the RSI 10 minus 3 bars ago, etc. This approach means that not every single RSI value in the last 10 is absolutely required to be under the oversold line, but in practice most stock scans give the same results as when one requires all of the RSIs of the last 10 bars to be below the oversold line; and the big advantage of version 2 is that now one can choose 5 bars or 10 or 20 in the inputs and compare the results that each produces.

“plot RSIextreme = RSI < over_sold and RSI[Previousbars] < over_sold and RSI[Previousbars - 1] < over_sold and RSI[Previousbars - 2] < over_sold and RSI[Previousbars - 3] < over_sold and RSI[Previousbars - 4] < over_sold;”

A current chart of BABA is shown with Previousbars set to 7 in the inputs.

tinfox-rsiextreme-V2-chart-4-2-23.png



Code:
# RSI_ExtremeLow_v2
# tinfox question 4-1-23 - script that allows the number of recent bars that RSI is required to be below oversold to be changed in the inputs;
# The PreviousBars input should always be greater than or equal to 5. This script works well though it is not a perfect mathematical solution.

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

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[Previousbars] < over_sold and RSI[Previousbars - 1] < over_sold and RSI[Previousbars - 2] < over_sold and RSI[Previousbars - 3] < over_sold and RSI[Previousbars - 4] < over_sold;

RSIextreme.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
RSIextreme.SetDefaultColor(Color.BLUE);
RSIextreme.SetLineWeight(4);
hal_sum


check for values on multiple past bars
a , create a formula that evaluates to true/false.
b , add up several bars
c , compare the sum() to a number.
use a variable with an offset in sum() to start with a previous bar

Code:
input qty = 3;
def a = RSI < oversold;
def b = sum(a[1], qty);
def c = if (b == qty) then 1 else 0;

# test bubble to see the values
addchartbubble(1, low,
a + "\n" +
b + "\n" +
c
, color.yellow, no);
#
 
need help with Elliot wave coding

Code:
# Plotting Elliot Waves

declare lower;

# Define input variables
input price = close;
input length = 100;
input show_label = yes;
input show_line = yes;

# Define variables
def h = highest(price, length);
def l = lowest(price, length);
def range = h - l;
def midpoint = (h + l) / 2;
def wave_count = 0;
def wave_high = 0;
def wave_low = 0;
def wave_range = 0;
def wave_midpoint = 0;

# Define plot series
plot wave_high_plot;
plot wave_low_plot;
plot wave_range_plot;
plot wave_midpoint_plot;

# Configure plot series
wave_high_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_high_plot.SetDefaultColor(Color.BLUE);
wave_low_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_low_plot.SetDefaultColor(Color.RED);
wave_range_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_range_plot.SetDefaultColor(Color.BLACK);
wave_midpoint_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_midpoint_plot.SetDefaultColor(Color.BLACK);

# Calculate wave properties and plot series
for i = 1 to length {
    if (price[I] > h) {
        h = price[I];
    }
    if (price[I] < l) {
        l = price[I];
    }
    if (h - l >= range) {
        range = h - l;
        midpoint = (h + l) / 2;
        wave_count = wave_count + 1;
        wave_high = h;
        wave_low = l;
        wave_range = range;
        wave_midpoint = midpoint;
        if (show_label) {
            AddLabel(yes, "Wave " + wave_count + ": " + wave_low + " - " + wave_high, color.white);
        }
        if (show_line) {
            wave_high_plot.SetPrice(wave_high);
            wave_low_plot.SetPrice(wave_low);
            wave_range_plot.SetPrice(wave_range);
            wave_midpoint_plot.SetPrice(wave_midpoint);
        }
        h = price[I];
        l = price[I];
    }
}

# Hide plot series when not in use
if (!show_line) {
    wave_high_plot.Hide();
    wave_low_plot.Hide();
    wave_range_plot.Hide();
    wave_midpoint_plot.Hide();
}

This code is intended to plot Elliot Waves on a chart by identifying price waves based on the highest and lowest prices over a specified period of time. The code also includes options to show or hide labels and lines for each wave. 

Im getting errors and cant figure it out.

Invaild statement: for at 40:1
Invaild statement: } at 43:5
Invaild statement: } at 46:5
syntax error: An "else" block expected at 55:9
syntax error: Semicolon expected at 55:9
Invaild statement: } at 63:9
Invalid statement: } at 66:5[/I][/I][/I][/I][/I][/I]
 
Last edited by a moderator:
need help with Elliot wave coding

# Plotting Elliot Waves

declare lower;

# Define input variables
input price = close;
input length = 100;
input show_label = yes;
input show_line = yes;

# Define variables
def h = highest(price, length);
def l = lowest(price, length);
def range = h - l;
def midpoint = (h + l) / 2;
def wave_count = 0;
def wave_high = 0;
def wave_low = 0;
def wave_range = 0;
def wave_midpoint = 0;

# Define plot series
plot wave_high_plot;
plot wave_low_plot;
plot wave_range_plot;
plot wave_midpoint_plot;

# Configure plot series
wave_high_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_high_plot.SetDefaultColor(Color.BLUE);
wave_low_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_low_plot.SetDefaultColor(Color.RED);
wave_range_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_range_plot.SetDefaultColor(Color.BLACK);
wave_midpoint_plot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
wave_midpoint_plot.SetDefaultColor(Color.BLACK);

# Calculate wave properties and plot series
for i = 1 to length {
if (price > h) {
h = price;
}
if (price < l) {
l = price;
}
if (h - l >= range) {
range = h - l;
midpoint = (h + l) / 2;
wave_count = wave_count + 1;
wave_high = h;
wave_low = l;
wave_range = range;
wave_midpoint = midpoint;
if (show_label) {
AddLabel(yes, "Wave " + wave_count + ": " + wave_low + " - " + wave_high, color.white);
}
if (show_line) {
wave_high_plot.SetPrice(wave_high);
wave_low_plot.SetPrice(wave_low);
wave_range_plot.SetPrice(wave_range);
wave_midpoint_plot.SetPrice(wave_midpoint);
}
h = price;
l = price;
}
}

# Hide plot series when not in use
if (!show_line) {
wave_high_plot.Hide();
wave_low_plot.Hide();
wave_range_plot.Hide();
wave_midpoint_plot.Hide();
}

This code is intended to plot Elliot Waves on a chart by identifying price waves based on the highest and lowest prices over a specified period of time. The code also includes options to show or hide labels and lines for each wave.

Im getting errors and cant figure it out.

Invaild statement: for at 40:1
Invaild statement: } at 43:5
Invaild statement: } at 46:5
syntax error: An "else" block expected at 55:9
syntax error: Semicolon expected at 55:9
Invaild statement: } at 63:9
Invalid statement: } at 66:5


reply to post59


there are several things wrong with this.

the formulas don't look like elliot wave.

the code is so incomplete, there is no way to 'convert' this into an elliot study. the math to interpret elliot waves is complex, such that i don't think there is an elliot wave study on this site.
in other words, the couple dozen lines of gibberish code here are useless.

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

lines like this are wrong,

def wave_midpoint = 0;

you don't initialize variables in a separate formula.
it has to be done with an if then, in the same formula calculating the possible values.

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

thinkscript doesn't have 'for' loops, so this would have to be converted to a fold loop, but,

def h = highest(price, length);

for i = 1 to length {
if (price > h) {
h = price;
}

since h is the highest price , price will never be greater than h, so the first part of the loop will never be true... so the logic is wrong.

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

can't use output functions , like addlabel() and plot functions, within an if then

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

ref
https://school.stockcharts.com/doku.php?id=market_analysis:introduction_to_elliott_wave_theory
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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