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:
Lines at the last 3 highest volume vwap level within the last 52 weeks.
This is what i got from ChatGPT. Price is shown but no line is drawn on the chart. This is for just one line for the last highest vwap level.. I need it to draw 3 lines for the last 3 highest vwap level, add a number on each line in ascending order. Thank you for any help.



input lookbackPeriod = 52; # Lookback period in weeks

# Calculate the number of bars in the lookback period
def barsInPeriod = lookbackPeriod * 5;

# Find the highest volume day within the lookback period
def highestVolumeDay = Highest(volume, barsInPeriod);

# Calculate VWAP for the highest volume day
def vwapHighestVolumeDay = if volume == highestVolumeDay then reference VWAP() else Double.NaN;

# Plot horizontal line at the VWAP level of the highest volume day
plot VWAPLine = if !IsNaN(vwapHighestVolumeDay) then vwapHighestVolumeDay else Double.NaN;
VWAPLine.SetDefaultColor(Color.BLUE);
VWAPLine.SetLineWeight(1);

reply to #--
on each bar, this finds the 3 highest volumes, in the past x bars. then finds a VWAP for those 3 volume bars, and draws 3 lines.

Code:
#chat241_3hi_vwap_lines

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-13#post-140670
#elborsagy  #241
#Lines at the last 3 highest volume vwap level within the last 52 weeks.

def na = double.nan;
def bn = barnumber();
def m = 1000000;
def rnd = 2;

input lookbackPeriod = 52; # Lookback period in weeks

# Calculate the number of bars in the lookback period
def barsInPeriod = lookbackPeriod * 5;

# Find the highest volume day within the lookback period
def v1 = volume;
def v1hi = Highest(v1, barsInPeriod);

def v2hi = fold i = 0 to barsInPeriod
  with m2
  do if v1hi > GetValue(v1, i) then max(GetValue(v1, i), m2) else m2;

def v3hi = fold j = 0 to barsInPeriod
  with m3
  do if v2hi > GetValue(v1, j) then max(GetValue(v1, j), m3) else m3;


# Calculate VWAP for the highest volume day
def vwapHi1Vol = if bn == 1 then na
 else if v1 == v1hi then reference VWAP()
 else vwapHi1Vol[1];
plot VWAP1 = vwapHi1Vol;
VWAP1.SetDefaultColor(Color.BLUE);
VWAP1.SetLineWeight(1);
vwap1.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Calculate VWAP for the 2nd highest volume day
def vwapHi2Vol = if bn == 1 then na
 else if v1 == v2hi then reference VWAP()
 else vwapHi2Vol[1];
plot VWAP2 = vwapHi2Vol;
VWAP2.SetDefaultColor(Color.BLUE);
VWAP2.SetLineWeight(1);
vwap2.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

# Calculate VWAP for the 3rd highest volume day
def vwapHi3Vol = if bn == 1 then na
 else if v1 == v3hi then reference VWAP()
 else vwapHi3Vol[1];
plot VWAP3 = vwapHi3Vol;
VWAP3.SetDefaultColor(Color.BLUE);
VWAP3.SetLineWeight(1);
vwap3.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

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

# test stuff
def vr1 = round(v1/m, rnd);
def vr1hi = round(v1hi/m, rnd);
def vr2hi = round(v2hi/m, rnd);
def vr3hi = round(v3hi/m, rnd);

def x = (!isnan(close[-(barsInPeriod-1)]) and isnan(close[-(barsInPeriod)]));
addverticalline(x, "-",color.cyan);

addchartbubble(0, low*0.999,
 bn + "\n" +
 vr1 + "  \n" +
 " " + "\n" +
 vr1hi + " 1\n" +
 vr2hi + " 2\n" +
 vr3hi + " 3\n"
, color.yellow, no);

#addlabel(1, "len " +  barsInPeriod, color.cyan);
#


----------------------------
here is a volume study for testing
it displays the volume number, in millions, above the bars
Code:
#vol_nums
def v = volume;
def m = 1000000;
def rnd = 2;
def vr1 = round(v/m, rnd);
addchartbubble(1, v, vr1, color.yellow, yes);
 
Last edited:

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

Hey guys i'm new here and not a coder by any means, but will appreciate very much if somebody helps me in this.

I would like to build a scan in ToS for at least 3 consistant bar close higher than Upper Bollinger band
to show me intraday overextended stocks like DELL on 04/04/2024 View attachment 21700and CZOO on 04/24/2024 View attachment 21701When addressing this problem to ChatGPT it provided me with a code that don't work and idk why. The scan criteria are basically simple:

1. Stock should be above upper bollinger band intraday on 2-min chart.
2. Chart must have at least 3 consecutive 2min candles above Upper BB that closed higher one after previous ( so close of candle 3 > close of candle 2 > close of candle 1) and at least 3 consecutive 2min candles which lows are higher than previous two candles (low of candle3> low of candle2> low of candle1)

Below is the code that ChatGPT provided:
Code:
# Define variables
input length = 20;
input numCandles = 3;

# Calculate Bollinger Bands
def price = close;
def SD = StDev(price, length);
def upperBand = BollingerBands(price, length, 2.0, 2.0).UpperBand;

# Check condition
def aboveUpperBand = close > upperBand;

# Count consecutive candles above upper band
def count = if aboveUpperBand then count[1] + 1 else 0;

# Condition for scan
def signal = count >= numCandles;

# Output
plot scan = signal;

Any help or afdvice will be highly appreciated.

reply to 243
that is surprisingly close, coming from chatgpt.

it is missing the displace input parameter for BollingerBands.
because of this, the length 20 is applied as the displace (sideways shift), instead of 0.
then 2 is used as length, instead of 20.

replace this,
def upperBand = BollingerBands(price, length, 2.0, 2.0).UpperBand;

with this
def upperBand = BollingerBands(price, 0, length, 2.0, 2.0).UpperBand;
 
Last edited:
Greetings and Happy new month!
I have a new study inquiry - with an AI developed study.


The study draws lines for the OHLC on a defined time frame ( in the screenshot- the weekly is set).
The goal is to inquire if Clouds can be added as seen ( in between the High /Low and Open/Close).

The idea is to identify where there was buyer/seller pressure in any given time frame.
The study can be displaced ( in this example, it is ) and has some labels as well.
Thank you to the moderators and organizers of this site/page.
1714690583937.png

Here is the code :
Ruby:
# Define study parameters
input aggregationPeriod = AggregationPeriod.WEEK; # Set aggregation period to WEEK
input displacement = 1; # Set displacement to 1 to target the last completed week

# Calculate OHLC with displacement for the previous week
def openPrice = open(period = aggregationPeriod)[displacement];
def highPrice = high(period = aggregationPeriod)[displacement];
def lowPrice = low(period = aggregationPeriod)[displacement];
def closePrice = close(period = aggregationPeriod)[displacement];

# Determine if the previous week closed positively
def positiveWeek = closePrice > openPrice;
def negativeWeek = closePrice < openPrice;

# Current price retrieval (current close price)
def currClose = close;

# Plot OHLC lines
plot OpenLine = openPrice;
OpenLine.SetDefaultColor(Color.CYAN);

plot HighLine = highPrice;
HighLine.SetDefaultColor(Color.GREEN);

plot LowLine = lowPrice;
LowLine.SetDefaultColor(Color.RED);

plot CloseLine = closePrice;
CloseLine.SetDefaultColor(Color.YELLOW);

# Define price range conditions for labels
def sellCondition = (positiveWeek and currClose > closePrice and currClose <= highPrice) or
(negativeWeek and currClose > openPrice and currClose <= highPrice);

def buyCondition = (positiveWeek and currClose >= lowPrice and currClose < openPrice) or
(negativeWeek and currClose >= lowPrice and currClose < closePrice);

# Add Labels for trading signals
AddLabel(sellCondition, "Sell Press-WK", Color.RED);
AddLabel(buyCondition, "Buy Press-WK", Color.GREEN);

# Conditions for extreme price movements
def extremeUpCondition = currClose > highPrice;
def extremeDownCondition = currClose < lowPrice;

# Add Labels for extreme conditions
AddLabel(extremeUpCondition, "2U-W", Color.LimE);
AddLabel(extremeDownCondition, "2D-W", Color.MAGENTA);
 
Last edited by a moderator:
Greetings and Happy new month!
I have a new study inquiry - with an AI developed study.


The study draws lines for the OHLC on a defined time frame ( in the screenshot- the weekly is set).
The goal is to inquire if Clouds can be added as seen ( in between the High /Low and Open/Close).

The idea is to identify where there was buyer/seller pressure in any given time frame.
The study can be displaced ( in this example, it is ) and has some labels as well.
Thank you to the moderators and organizers of this site/page.

Here is the code :
Ruby:
# Define study parameters
input aggregationPeriod = AggregationPeriod.WEEK; # Set aggregation period to WEEK
input displacement = 1; # Set displacement to 1 to target the last completed week

# Calculate OHLC with displacement for the previous week
def openPrice = open(period = aggregationPeriod)[displacement];
def highPrice = high(period = aggregationPeriod)[displacement];
def lowPrice = low(period = aggregationPeriod)[displacement];
def closePrice = close(period = aggregationPeriod)[displacement];

# Determine if the previous week closed positively
def positiveWeek = closePrice > openPrice;
def negativeWeek = closePrice < openPrice;

# Current price retrieval (current close price)
def currClose = close;

# Plot OHLC lines
plot OpenLine = openPrice;
OpenLine.SetDefaultColor(Color.CYAN);

plot HighLine = highPrice;
HighLine.SetDefaultColor(Color.GREEN);

plot LowLine = lowPrice;
LowLine.SetDefaultColor(Color.RED);

plot CloseLine = closePrice;
CloseLine.SetDefaultColor(Color.YELLOW);

# Define price range conditions for labels
def sellCondition = (positiveWeek and currClose > closePrice and currClose <= highPrice) or
(negativeWeek and currClose > openPrice and currClose <= highPrice);

def buyCondition = (positiveWeek and currClose >= lowPrice and currClose < openPrice) or
(negativeWeek and currClose >= lowPrice and currClose < closePrice);

# Add Labels for trading signals
AddLabel(sellCondition, "Sell Press-WK", Color.RED);
AddLabel(buyCondition, "Buy Press-WK", Color.GREEN);

# Conditions for extreme price movements
def extremeUpCondition = currClose > highPrice;
def extremeDownCondition = currClose < lowPrice;

# Add Labels for extreme conditions
AddLabel(extremeUpCondition, "2U-W", Color.LimE);
AddLabel(extremeDownCondition, "2D-W", Color.MAGENTA);

next time, separate your rules into 2 separate statements.
don't write them combined like this, it's confusing
( in between the High /Low and Open/Close).

based on the picture, i assumed these rules and made this,

should have said,
between high and highest of open and close
between low and lowest of open and close

Code:
#chat246_ohlc_clouds

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-13#post-141165

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

# Define study parameters
input aggregationPeriod = AggregationPeriod.WEEK; # Set aggregation period to WEEK
input displacement = 1; # Set displacement to 1 to target the last completed week

# Calculate OHLC with displacement for the previous week
def openPrice = open(period = aggregationPeriod)[displacement];
def highPrice = high(period = aggregationPeriod)[displacement];
def lowPrice = low(period = aggregationPeriod)[displacement];
def closePrice = close(period = aggregationPeriod)[displacement];

# Determine if the previous week closed positively
def positiveWeek = closePrice > openPrice;
def negativeWeek = closePrice < openPrice;

# Current price retrieval (current close price)
def currClose = close;


# Plot OHLC lines
plot OpenLine = openPrice;
OpenLine.SetDefaultColor(Color.CYAN);
openline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot HighLine = highPrice;
HighLine.SetDefaultColor(Color.GREEN);
highline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot LowLine = lowPrice;
LowLine.SetDefaultColor(Color.RED);
lowline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot CloseLine = closePrice;
CloseLine.SetDefaultColor(Color.YELLOW);
closeline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

def bodytop = max(openline, closeline);
def bodybot = min(openline, closeline);

input clouds = yes;
def clduppertop = if clouds then highline else na;
def cldlowertop = if clouds then bodybot else na;

addcloud(clduppertop, bodytop, color.red);
addcloud(cldlowertop, lowline, color.green);


# Define price range conditions for labels
def sellCondition = (positiveWeek and currClose > closePrice and currClose <= highPrice) or
(negativeWeek and currClose > openPrice and currClose <= highPrice);

def buyCondition = (positiveWeek and currClose >= lowPrice and currClose < openPrice) or
(negativeWeek and currClose >= lowPrice and currClose < closePrice);

# Add Labels for trading signals
AddLabel(sellCondition, "Sell Press-WK", Color.RED);
AddLabel(buyCondition, "Buy Press-WK", Color.GREEN);

# Conditions for extreme price movements
def extremeUpCondition = currClose > highPrice;
def extremeDownCondition = currClose < lowPrice;

# Add Labels for extreme conditions
AddLabel(extremeUpCondition, "2U-W", Color.LimE);
AddLabel(extremeDownCondition, "2D-W", Color.MAGENTA);
#
 
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);
 
HOW TO IDENTIFY LONG BUILD UP, LONG UNWINDING, SHORT BUILDUP & SHORT COVERING USING OPTION CHAIN.

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

Getting error as below

Invalid statement: for at 26:5
Invalid statement: } at 32:5

Code:
# Open Interest Script

# Define the inputs
input symbol = "AAPL";
input expiration = 0;
input show_all_expirations = no;

# Determine the current date and time
def current_time = GetYYYYMMDD() * 10000 + GetTime() / 100;

# Get the option chain for the specified symbol and expiration date
def chain = OptionChain(symbol, expiration);

# Define the aggregation period
def aggregation_period = AggregationPeriod.DAY;

# Determine whether to use all expirations or just the specified one
def expirations = if show_all_expirations then GetExpirations(symbol) else expiration;

# Loop over each expiration date and display the open interest for each option
for exp in expirations do {
    # Get the options for the current expiration date
    def options = chain.GetOptions(exp, OptionClass.ALL);

    # Loop over each option and display the open interest
    for option in options do {
        # Get the open interest for the current option
        def oi = option.GetOpenInterest(aggregation_period);

        # Display the open interest in a label on the chart
        AddLabel(yes, "OI: " + oi, if current_time == option.GetExpirationDate() then Color.CYAN else Color.GRAY);
    }
}

B0PYN8R.png


Any other way who can help to modify this, do we need to check in discord?

on a given particular day I am looking for any indication or line where we have high open interest on puts and call options
 
Last edited by a moderator:
I need help with this script Iget an error

input aggregationPeriod = AggregationPeriod.DAY;
input showVolume = yes;
input showOpenInterest = yes;

def o = open;
def h = high;
def l = low;
def c = close;
def v = volume;
def oi = open_interest;

def isPeriodRolled = CompoundValue(1, (GetAggregationPeriod() <> GetAggregationPeriod()[1]), yes);

def volumeSum;
def oiSum;

if (isPeriodRolled) {
volumeSum = v;
oiSum = oi;
} else {
volumeSum = volumeSum[1] + v;
oiSum = oiSum[1] + oi;
}

def label = "OI: " + oiSum + "\n";
label = label + "P/C: " + Round((PutVolume() / CallVolume()) * 100, 0) + "%\n";
label = label + "Vol: " + volumeSum;

AddLabel(yes, label, Color.WHITE);

plot openInterest = showOpenInterest;
openInterest.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
openInterest.SetDefaultColor(Color.ORANGE);

def pcRatio = showVolume(PutVolume() / CallVolume())/
Double.NaN;

def volume = showVolume; (volumesum); Double.NaN;


AddCloud(volume, pcRatio, Color.GREEN, Color.RED);


reply to post62

you didn't explain what you are trying to do with this study, and almost every line is wrong, so i'm not going to guess at its purpose, and create a new study.
i will guess that you want a put call ratio thing, and show you this link, that might have something relevent.
https://usethinkscript.com/threads/put-call-ratio-pcr-indicator-for-thinkorswim.606/

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

i'll repeat this again, it is highly unlikely that chatgpt will create a working thinkscript study. it just doesn't know the language.

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

when i load your study, it shows just 1 error, with this line,

def volume = showVolume; (volumesum); Double.NaN;

but there are many errors. thinkscript is funny that way, sometimes it only shows 1 or 2 errors at a time. when they get fixed, more errors will show up.

i'm guessing it should be a if then statement, like this,

def volume = if showVolume then volumesum else Double.NaN;


after fixing that one, there are 5+ errors.

def isPeriodRolled = CompoundValue(1, (GetAggregationPeriod() <> GetAggregationPeriod()[1]), yes);

several things wrong here,
..don't use offset on GetAggregationPeriod()[1]
..the agg period isn't going to change, so comparing it to itself on a previous bar will be the same.
....i'm guessing this was supposed to determine a new day?


these 3 lines are wrong.

def label = "OI: " + oiSum + "\n";
label = label + "P/C: " + Round((PutVolume() / CallVolume()) * 100, 0) + "%\n";
label = label + "Vol: " + volumeSum;
AddLabel(yes, label, Color.WHITE);

can't assign text with a def.
can't create a text string and assign to a variable. have to use the text formula within addlabel().
can't use the same variable more than once.
can't use \n within a label. doesn't do anything. labels are all on one line. if \n is used in a bubble, then it starts a new line.

here are those lines as 3 labels,
AddLabel(yes, "OI: " + oiSum , Color.WHITE);
AddLabel(yes, "P/C: " + Round((PutVolume() / CallVolume()) * 100, 0) + "%", Color.WHITE);
AddLabel(yes, "Vol: " + volumeSum, Color.WHITE);

but one line still has an error because PutVolume() and CallVolume() are not valid.
they are not built in functions, they are not defined as a script, or not defined as variables.
so i can't create a working study.


this is wrong and probably should be a if then
def pcRatio = showVolume(PutVolume() / CallVolume()) / Double.NaN;

def pcRatio = if showVolume then (PutVolume / CallVolume) else Double.NaN;

but it has errors because PutVolume() and CallVolume() are not valid.


too many unknowns and errors to fix.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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