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:
Build a scan tab, each separately:

1. VOULME greater than>2 times the previous day

2. VOULME greater than>2 times the previous five days

3. VOULME greater than>2 times the previous quarter

Then on the SEARCH RESULT (in Scan tab or WATCHLIST tab) make EACH CODE appear as green background if meet the condition. Pink background if NOT meet the condition.

Code:
# Volume greater than 2 times the previous day
input multiple = 2;

def volCondition1 = volume > 2 * volume[1];
AddLabel(yes, if volCondition1 then "Volume > 2x Prev Day" else "", if volCondition1 then color.black else color.white);

# Volume greater than 2 times the previous five days
def volCondition2 = volume > 2 * average(volume, 5);
AddLabel(yes, if volCondition2 then "Volume > 2x Prev 5 Days" else "", if volCondition2 then color.black else color.white);

# Volume greater than 2 times the previous quarter
def volCondition3 = volume > 2 * average(volume, 63); # Assuming 63 trading days in a quarter
AddLabel(yes, if volCondition3 then "Volume > 2x Prev Quarter" else "", if volCondition3 then color.black else color.white);

# Background color based on condition
AssignBackgroundColor(if volCondition1 or volCondition2 or volCondition3 then color.green else color.pink);

Guys, have this code, but how to use this code to scan each of the condition, separately?
 
Last edited by a moderator:
CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;
input riskPerTrade = 1.0; # Risk percentage per trade

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot BuySignal = longEntry;
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
BuySignal.SetDefaultColor(Color.GREEN);
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);
 
Last edited by a moderator:
CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;
input riskPerTrade = 1.0; # Risk percentage per trade

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot BuySignal = longEntry;
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
BuySignal.SetDefaultColor(Color.GREEN);
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);

reply to #203

change capital formula to what i think you want
def capital = AccountNetLiq();

https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/A-B/AccountNetLiq

Code:
#chat203_fix

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

#Tonievanu  #203
#CAN SOMEONE FIX THIS ERROR CODE
# Example Trading Strategy with Consolidation and Breakout Detection

declare lower;

# Inputs
input atrLength = 14;
input consolidationMultiplier = 1.5;
input breakoutMultiplier = 2.0;
input riskPerTrade = 1.0; # Risk percentage per trade

# Average True Range (ATR) for volatility measurement
def atr = ATR(atrLength);

# Calculate consolidation and breakout levels
def consolidationLevel = consolidationMultiplier * atr;
def breakoutLevel = breakoutMultiplier * atr;

# Calculate risk per trade in dollars
#def capital = GetLastEquity(); # Use GetLastEquity to get the account's net liquidating value
def capital = AccountNetLiq();

def riskAmount = capital * (riskPerTrade / 100);

# Calculate position size based on risk and distance to stop loss
def positionSize = if (atr != 0) then Round(riskAmount / atr, 0) else 1;

# Market state detection
def isConsolidating = atr <= consolidationLevel;
def isBreakingOut = atr > breakoutLevel;

# Entry conditions
def longEntry = close > high[1] and isBreakingOut;
def shortEntry = close < low[1] and isBreakingOut;

# Exit conditions
def longExit = close < low[1] or isConsolidating;
def shortExit = close > high[1] or isConsolidating;

# Plotting signals on chart
plot BuySignal = longEntry;
plot SellSignal = shortEntry;
plot CoverSignal = longExit;
plot ShortSignal = shortExit;

# Visualization
BuySignal.SetDefaultColor(Color.GREEN);
SellSignal.SetDefaultColor(Color.RED);
CoverSignal.SetDefaultColor(Color.GREEN);
ShortSignal.SetDefaultColor(Color.RED);


addchartbubble(0, 0,
capital
, color.yellow, yes);
#
 
halcyonguy , The time code is not working correctly with Gold Futures, what could it be?

reply to 201 , 192
https://usethinkscript.com/threads/...used-in-thinkorswim.13822/page-10#post-134251

you didn't say anything about futures in your post.
it seems like RegularTradingStart(GetYYYYMMDD()) doesn't read the correct value with futures. i'm not sure why, i don't trade futures. i loaded the built in futures watchlist, and looked at some symbols. turn on extended hours.
i added this to put a colored bubble at the start and end of the trading period. it doesn't seem to work.
it does work with normal stocks, 9;30 to 4pm

Code:
def start = gettime() == RegularTradingStart(GetYYYYMMDD()) + 1;
def end = gettime() == RegularTradingend(GetYYYYMMDD()) + 1;

addchartbubble(1, low,
start + " S\n" +
end + " E"
, (if start then color.green else if end then color.red else color.gray), no);
 
cross() isn't a valid function

i changed it to be a lower study

Code:
# chat_rsi_diverg_00

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

declare lower;

def na = double.nan;

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

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

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

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

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

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

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

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

#

crosses
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/crosses
Can you tell me what i am doing wrong to get this code to work?
I have both created a study, and strategy but nothing shows up on my chart. The study name is in red, and i'm having trouble troubleshooting to get this indicator to work. tia.
 
Can you tell me what i am doing wrong to get this code to work?
I have both created a study, and strategy but nothing shows up on my chart. The study name is in red, and i'm having trouble troubleshooting to get this indicator to work. tia.
No, it won't work in the strategy tab.
The strategy tab is ONLY for scripts with ADDORDER statements used in backtesting.

You did not include a screen grab, therefore it is not possible to say where you went astray.
1. Many times, it is a cut & paste error. Consider re-pasting the script into your study tab.
2. Click on the script in the study tab, scroll to the bottom, you will see your errors.
3. If you are still having issues, cut & paste your script into your post, so contributors can review it for syntax errors.
 
Last edited:
Hi folks, can I get a little help making the script below work with tick timeframe. The script appears to work fine in all minute time frames. However, when I try to set it to 133 tick time frame nothing shows up. Doesn't seem to show up on any tick time frame. See screen shots below

1min chart:
1min.jpg


3min chart:
3min.png


133 Tick Chart:
133tick chart.png


declare lower;

input symbol1 = "SPY"; # SPY
input symbol2 = "UVXY"; # UVXY
input length = 14; # Normalization period length, adjust based on preference. Represents ticks in a tick chart.

# Fetching the closing price data for both symbols
def price1 = close(symbol1);
def price2 = close(symbol2);

# Normalizing the price data to make them comparable and centered around zero
def minPrice1 = Lowest(price1, length);
def maxPrice1 = Highest(price1, length);
def normalizedPrice1 = ((price1 - minPrice1) / (maxPrice1 - minPrice1)) - 0.5; # Centered around zero

def minPrice2 = Lowest(price2, length);
def maxPrice2 = Highest(price2, length);
def normalizedPrice2 = ((price2 - minPrice2) / (maxPrice2 - minPrice2)) - 0.5; # Centered around zero

# Plotting the normalized prices
plot NormPrice1 = normalizedPrice1;
plot NormPrice2 = normalizedPrice2;

# Plotting the zero line for reference
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.WHITE);
ZeroLine.SetStyle(Curve.SHORT_DASH);

# Setting the plot attributes for better visualization
NormPrice1.SetDefaultColor(Color.CYAN);
NormPrice1.SetLineWeight(2);
NormPrice1.SetPaintingStrategy(PaintingStrategy.LINE);

NormPrice2.SetDefaultColor(Color.MAGENTA);
NormPrice2.SetLineWeight(2);
NormPrice2.SetPaintingStrategy(PaintingStrategy.LINE);
 
Last edited:
Hi folks, can I get a little help making the script below work with tick timeframe. Thanks.

declare lower;

input symbol1 = "SPY"; # SPY
input symbol2 = "UVXY"; # UVXY
input length = 14; # Normalization period length, adjust based on preference. Represents ticks in a tick chart.

# Fetching the closing price data for both symbols
def price1 = close(symbol1);
def price2 = close(symbol2);

# Normalizing the price data to make them comparable and centered around zero
def minPrice1 = Lowest(price1, length);
def maxPrice1 = Highest(price1, length);
def normalizedPrice1 = ((price1 - minPrice1) / (maxPrice1 - minPrice1)) - 0.5; # Centered around zero

def minPrice2 = Lowest(price2, length);
def maxPrice2 = Highest(price2, length);
def normalizedPrice2 = ((price2 - minPrice2) / (maxPrice2 - minPrice2)) - 0.5; # Centered around zero

# Plotting the normalized prices
plot NormPrice1 = normalizedPrice1;
plot NormPrice2 = normalizedPrice2;

# Plotting the zero line for reference
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.WHITE);
ZeroLine.SetStyle(Curve.SHORT_DASH);

# Setting the plot attributes for better visualization
NormPrice1.SetDefaultColor(Color.CYAN);
NormPrice1.SetLineWeight(2);
NormPrice1.SetPaintingStrategy(PaintingStrategy.LINE);

NormPrice2.SetDefaultColor(Color.MAGENTA);
NormPrice2.SetLineWeight(2);
NormPrice2.SetPaintingStrategy(PaintingStrategy.LINE);
go back and edit your post,

tell us what it does on a time chart and what it doesn't do on a tick chart.

never say 'it doesn't work'.
i'm not going to load it on different charts and guess at what the issue might be.
 
Hello team, I'm new to thinkscript world, so I asked ChatGPT: Write a ThinkScript for AddLabel for CurrentBar volume, with change LabelColor to Green when volume of the CurrentBar is greater than or equal to 100,000.

ChatGPT:

declare lower;

# Define the volume of the current bar
def currentVolume = volume;

# Define label color based on volume
def labelColor = if currentVolume >= 100000 then Color.GREEN else Color.GRAY;

# Add a label displaying the volume of the current bar
AddLabel(yes, "Current Bar Volume: " + AsText(currentVolume), labelColor);


---but the script generated following errors:
Expected double at 7:5
Incompatible parameter: labelColor at 7:5
Expected class com.devexperts.tos.thinkscript.data.CustomColor at 10:1
Expected double at 7:5
Incompatible parameter: labelColor at 7:5
Expected class com.devexperts.tos.thinkscript.data.CustomColor at 10:1

I pasted the errors to ChatGPT, but it gave me another set of script with more errors, I'm sure this is an easy fix. Can you assist. Thanks in advanced guys.
 
Hello team, I'm new to thinkscript world, so I asked ChatGPT: Write a ThinkScript for AddLabel for CurrentBar volume, with change LabelColor to Green when volume of the CurrentBar is greater than or equal to 100,000.

ChatGPT:

declare lower;

# Define the volume of the current bar
def currentVolume = volume;

# Define label color based on volume
def labelColor = if currentVolume >= 100000 then Color.GREEN else Color.GRAY;

# Add a label displaying the volume of the current bar
AddLabel(yes, "Current Bar Volume: " + AsText(currentVolume), labelColor);


---but the script generated following errors:
Expected double at 7:5
Incompatible parameter: labelColor at 7:5
Expected class com.devexperts.tos.thinkscript.data.CustomColor at 10:1
Expected double at 7:5
Incompatible parameter: labelColor at 7:5
Expected class com.devexperts.tos.thinkscript.data.CustomColor at 10:1

I pasted the errors to ChatGPT, but it gave me another set of script with more errors, I'm sure this is an easy fix. Can you assist. Thanks in advanced guys.

reply to 211

can't set a color to a variable.
have to put the color if-then formula inside the label.

don't need astext(currentVolume). it actually adds .00 to end of number
asprice() formats number with no commas
just use currentVolume as it is.

i removed declare lower, so it will appear in the volume chart.
need to turn on volume sub graph


Code:
#chat211_label_vol

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-11#post-138686
#orac2920  3/11  #211
#AddLabel for CurrentBar volume, with change LabelColor to Green when volume of the CurrentBar is greater than or equal to 100,000.

# Define the volume of the current bar
def currentVolume = volume;

# Add a label displaying the volume of the current bar
AddLabel(yes, 
#"Current Bar Volume: " + AsText(currentVolume), 
#"Current Bar Volume: " + Asprice(currentVolume), 
"Current Bar Volume: " + currentVolume, 
if currentVolume >= 100000 then Color.GREEN else Color.GRAY);
#
 
Hi folks, can I get a little help making the script below work with tick timeframe. The script appears to work fine in all minute time frames. However, when I try to set it to 133 tick time frame nothing shows up. Doesn't seem to show up on any tick time frame. See screen shots below

1min chart:


3min chart:


133 Tick Chart:


declare lower;

input symbol1 = "SPY"; # SPY
input symbol2 = "UVXY"; # UVXY
input length = 14; # Normalization period length, adjust based on preference. Represents ticks in a tick chart.

# Fetching the closing price data for both symbols
def price1 = close(symbol1);
def price2 = close(symbol2);

# Normalizing the price data to make them comparable and centered around zero
def minPrice1 = Lowest(price1, length);
def maxPrice1 = Highest(price1, length);
def normalizedPrice1 = ((price1 - minPrice1) / (maxPrice1 - minPrice1)) - 0.5; # Centered around zero

def minPrice2 = Lowest(price2, length);
def maxPrice2 = Highest(price2, length);
def normalizedPrice2 = ((price2 - minPrice2) / (maxPrice2 - minPrice2)) - 0.5; # Centered around zero

# Plotting the normalized prices
plot NormPrice1 = normalizedPrice1;
plot NormPrice2 = normalizedPrice2;

# Plotting the zero line for reference
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.WHITE);
ZeroLine.SetStyle(Curve.SHORT_DASH);

# Setting the plot attributes for better visualization
NormPrice1.SetDefaultColor(Color.CYAN);
NormPrice1.SetLineWeight(2);
NormPrice1.SetPaintingStrategy(PaintingStrategy.LINE);

NormPrice2.SetDefaultColor(Color.MAGENTA);
NormPrice2.SetLineWeight(2);
NormPrice2.SetPaintingStrategy(PaintingStrategy.LINE);

reply to #208

thanks for reposting. i don't use tick charts so was hoping for more clues, because i had none.
after loading the study, it shows a ! in the top left corner. clicking on it says
can't use secondary periods less than 1 day on tick charts.
92P0Ls7.png


unfortunately, this doesn't help. TOS is good at creating useless error messages.

so... when something doesn't work, try simple things, then simplify it.

i tried changing the symbols. nothing.
i started at the end and started disabling code lines.

when i disabled this line
price1 = close(symbol1);
then something plotted

so i guess , tick charts don't like reading data from a different symbol...?


maybe @MerryDay can explain why this happens

Code:
#chat208_tick

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

#1min chart:
#1min.jpg

#3min chart:
#3min.png


# no chart
#133 Tick Chart:
#133tick chart.png

declare lower;

input symbol1 = "SPY"; # SPY
input symbol2 = "UVXY"; # UVXY
#input symbol2 = "WMT"; # UVXY

input length = 14; # Normalization period length, adjust based on preference. Represents ticks in a tick chart.

# Fetching the closing price data for both symbols
#def price1 = close(symbol1);
#def price2 = close(symbol2);

def price1 = close;

# Normalizing the price data to make them comparable and centered around zero
#def minPrice1 = Lowest(price1, length);
#def maxPrice1 = Highest(price1, length);
#def normalizedPrice1 = ((price1 - minPrice1) / (maxPrice1 - minPrice1)) - 0.5; # Centered around zero

#def minPrice2 = Lowest(price2, length);
#def maxPrice2 = Highest(price2, length);
#def normalizedPrice2 = ((price2 - minPrice2) / (maxPrice2 - minPrice2)) - 0.5; # Centered around zero

# Plotting the normalized prices
#plot NormPrice1 = normalizedPrice1;
#plot NormPrice2 = normalizedPrice2;

#plot NormPrice1 = minprice1;
#plot NormPrice2 = minprice2;

plot NormPrice1 = price1;
#plot NormPrice2 = price2;


# Plotting the zero line for reference
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.WHITE);
ZeroLine.SetStyle(Curve.SHORT_DASH);

# Setting the plot attributes for better visualization
NormPrice1.SetDefaultColor(Color.CYAN);
NormPrice1.SetLineWeight(2);
#NormPrice1.SetPaintingStrategy(PaintingStrategy.LINE);

#NormPrice2.SetDefaultColor(Color.MAGENTA);
#NormPrice2.SetLineWeight(2);
#NormPrice2.SetPaintingStrategy(PaintingStrategy.LINE);
#
 
Hello everyone,
I am no expert in script languages and converting languages into others. The goal to create this seemed simple until I was staying up all night(s). Maybe I'm going about it the wrong way thinking I can do it all by myself.
I'm trying to recreate an indicator I saw on TradingView and convert it into ThinkScript.

My definition: The indicator takes the company's EPS TTM and you multiply the EPS TTM by 15 (PE Ratio) to calculate the market price per share at 15 times earnings.

I do not know if he birthed this idea but Peter Lynch introduced me to idea and in all of his books that I have display that indicator overlapping the current trading price.

I've completed about one-third of the indicator and I am hoping that someone on these forums would help guide me to the finish line. Please, Thank you.

Concept: https://www.gurufocus.com/news/1471569/behind-the-numbers-peter-lynch-and-fair-value

Original code: https://www.tradingview.com/script/Y5bvwFfr-Peter-Lynch-Value/

Current code (Formatted by ChatGPT):
# Calculate Earnings Per Share (EPS) using financial data
def EPS = EarningsPerShareTTM();

#PERatio = input(15, title="P/E Ratio", step=1)
def PERatio = close / EarningsPerShareTTM();
input PE = 15;

# Calculate Fair Price based on EPS and P/E Ratio
#fairprice = EPS > 0 ? PERatio * EPS : na
#plot(fairprice, color=color.green)

# Calculate Earnings Estimate for the fiscal year
#earningestimate = financial(syminfo.tickerid, "EARNINGS_ESTIMATE", "FY")

# Calculate Fair Price Estimate based on Earnings Estimate and P/E Ratio
#fairpriceestimate = earningestimate > 0 ? PERatio * earningestimate : na

# Plot fairprice and fairpriceestimate on the chart.
 
reply to #208

thanks for reposting. i don't use tick charts so was hoping for more clues, because i had none.
after loading the study, it shows a ! in the top left corner. clicking on it says
can't use secondary periods less than 1 day on tick charts.
92P0Ls7.png


unfortunately, this doesn't help. TOS is good at creating useless error messages.

so... when something doesn't work, try simple things, then simplify it.

i tried changing the symbols. nothing.
i started at the end and started disabling code lines.

when i disabled this line
price1 = close(symbol1);
then something plotted

so i guess , tick charts don't like reading data from a different symbol...?


maybe @MerryDay can explain why this happens

Code:
#chat208_tick

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

#1min chart:
#1min.jpg

#3min chart:
#3min.png


# no chart
#133 Tick Chart:
#133tick chart.png

declare lower;

input symbol1 = "SPY"; # SPY
input symbol2 = "UVXY"; # UVXY
#input symbol2 = "WMT"; # UVXY

input length = 14; # Normalization period length, adjust based on preference. Represents ticks in a tick chart.

# Fetching the closing price data for both symbols
#def price1 = close(symbol1);
#def price2 = close(symbol2);

def price1 = close;

# Normalizing the price data to make them comparable and centered around zero
#def minPrice1 = Lowest(price1, length);
#def maxPrice1 = Highest(price1, length);
#def normalizedPrice1 = ((price1 - minPrice1) / (maxPrice1 - minPrice1)) - 0.5; # Centered around zero

#def minPrice2 = Lowest(price2, length);
#def maxPrice2 = Highest(price2, length);
#def normalizedPrice2 = ((price2 - minPrice2) / (maxPrice2 - minPrice2)) - 0.5; # Centered around zero

# Plotting the normalized prices
#plot NormPrice1 = normalizedPrice1;
#plot NormPrice2 = normalizedPrice2;

#plot NormPrice1 = minprice1;
#plot NormPrice2 = minprice2;

plot NormPrice1 = price1;
#plot NormPrice2 = price2;


# Plotting the zero line for reference
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.WHITE);
ZeroLine.SetStyle(Curve.SHORT_DASH);

# Setting the plot attributes for better visualization
NormPrice1.SetDefaultColor(Color.CYAN);
NormPrice1.SetLineWeight(2);
#NormPrice1.SetPaintingStrategy(PaintingStrategy.LINE);

#NormPrice2.SetDefaultColor(Color.MAGENTA);
#NormPrice2.SetLineWeight(2);
#NormPrice2.SetPaintingStrategy(PaintingStrategy.LINE);
#

Why some scripts and some syntax works on tick charts and some don't; is one of those mysteries of the ages.

Support's canned answer:
The core of the ToS app is based on time-based charts. Tick Charts were introduced to provide real-time price action, however support of custom studies is limited.

The forum's canned answer:
We know that scripts that have any time-based calculations will, by default, not work on tick / range/ renko charts.
Beyond that, what works and doesn't work tends to be a crap shoot. It should be noted that members have reported having sporadic success with running custom studies on tick charts with extended hours enabled.


Hope this helps.
@fluna
 
Last edited:
I have been stalking this site for a while and took the leap in writing my first scanner code.

I have looked at posts about extended hours here but did not find any that adds both premarket and post market. I decided to write one.

My objective is to add up yesterday's post market and today's premarket volume to identify stocks that have volume greater than day before. I would run this scanner during post market and premarket.

I tested this code on the charts and found it to be working as expected but the scanner doesn't seem to produce the desired results. I am getting results for all stocks with extended hour volume instead of just ones with volume greater than day before. Any pointers in the right direction will be extremely helpful.


Code:
## Trading day for stock market cycles betweeen Pre (04:00-09:29EST), Regular (09:30-03:59EST) and Post trading hours (04:00-08:00)
### On July 3rd, Black Friday and December 24th, regular is (09:30-12:59EST) and post is (01:00-05:00EST) .
### Thinkorswim can have zero or more bars for Pre and post hours based on trades. There are missing bars during regular trading hour

def V =  volume;

# % change threshold (>) required from previous day
def minChange = 0;

# Returns the date of the current bar in the YYYYMMDD format. This date corresponds to the day whose trading session contains the current bar.
def date = GetYYYYMMDD();

# Returns the number of the current bar day in the CST timezone. The output is returned in the range from 1 through 365 (366 for leap years).
def day = GetDay();

# Returns the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT) for the begining of current bar.
def time = GetTime();

# Returns the number of milliseconds elapsed since the epoch (January 1, 1970, 00:00:00 GMT) till the start of the regular trading hours on a given
# day for the current symbol. The trading day is to be specified using the YYYYMMDD format.
def RTHStart = RegularTradingStart(date);

# Returns the number of milliseconds elapsed since the epoch (January 1, 1970, 00:00:00 GMT) till the end of the regular trading hours on a given
# day for the current symbol. The trading day is to be specified using the YYYYMMDD format.
def RTHEnd = RegularTradingEnd(date);

# The GetAggregationPeriod function returns the current aggregation period in milliseconds for time charts
def Agg = GetaggregationPeriod();

# Is it regular trading hours?
def isRTH =
    time >= RTHStart
    and time <= RTHEnd
;

# Is last bar of RTH?
def IsRTHEnd =
    time == (RTHEnd - Agg + 1) # For situations where there is a last bar in regular hours
    or isRTH and !isRTH[-1] # For situations where there is no last bar in regular hours
    or (isRTH and day != day[-1]); # For situations there is no last bar in regular hours and no extended hours;

# Extended Hour Volume
def extendedHourVolume =
    if IsRTHEnd[1] and isRTH then 0 # 1st bar after RTH is a new RTH means no extended, reset to 0
    else if IsRTHEnd[1] then V # 1st bar after RTH is extended hour, reset to current bar volume
    else if !isRTH then extendedHourVolume[1] + V # Extended hour bars, add current bar volume
    else extendedHourVolume[1] # RTH bars, carry over previous extended hour volume
;

# Previous day extended hour volume
def previousDayExtVolume =
    if IsRTHEnd[1] then extendedHourVolume[1] # RTH last bar, store previous extended hour volume
    else previousDayExtVolume[1] # All other bars, carry over previous day extended hour volume
;

# Scan condition
plot Scan =
    !isRTH and # This scan works only in extended hours
    (extendedHourVolume / previousDayExtVolume) - 1 > minChange # Extended hour volume so far is greater than yesterday's extended hour volume
;
 
Hey everyone, I'm in the process of teaching myself ThinkScript and figured it'd be helpful to use ChatGPT (version 4) as a kind of virtual tutor. I asked it a simple question about how to add arrows to a chart and this is the answer it gave me:
In ThinkScript, you can add arrows with text on your charts to highlight specific conditions or signals. Typically, you'd use this feature to mark important points on the price chart, like potential buy or sell signals. Here’s how you can do it:

Adding Arrows in ThinkScript​

To add arrows, you'll use the AddChartBubble or AddChartArrow function in your script. However, it's important to note that while you can add text labels to chart bubbles, arrows themselves cannot directly display text beside them. You'd typically use arrows to point out specific price points and use bubbles to add explanatory text.

Here's a basic example of how to use both:
Code:
script ShowSignal {
    input condition = yes;
    input price = close;
    input text = "Signal";
    def showBubble = condition;
    
    # Add arrow pointing up for a buy signal
    AddChartArrow(condition, price, "Up", Color.GREEN, yes);
    
    # Add text bubble near the arrow
    AddChartBubble(showBubble, price, text, Color.GREEN, yes);
}

# Example usage
ShowSignal(condition = close crosses above SMA(close, 20), price = low, text = "Buy Signal");

As far as I can tell however, the AddChartArrow function does not exist in ThinkScript and never has! Is this a legit LLM hallucination?

Thanks
 
Hello everyone,
I am no expert in script languages and converting languages into others. The goal to create this seemed simple until I was staying up all night(s). Maybe I'm going about it the wrong way thinking I can do it all by myself.
I'm trying to recreate an indicator I saw on TradingView and convert it into ThinkScript.

My definition: The indicator takes the company's EPS TTM and you multiply the EPS TTM by 15 (PE Ratio) to calculate the market price per share at 15 times earnings.

I do not know if he birthed this idea but Peter Lynch introduced me to idea and in all of his books that I have display that indicator overlapping the current trading price.

I've completed about one-third of the indicator and I am hoping that someone on these forums would help guide me to the finish line. Please, Thank you.

Concept: https://www.gurufocus.com/news/1471569/behind-the-numbers-peter-lynch-and-fair-value

Original code: https://www.tradingview.com/script/Y5bvwFfr-Peter-Lynch-Value/

Current code (Formatted by ChatGPT):
# Calculate Earnings Per Share (EPS) using financial data
def EPS = EarningsPerShareTTM();

#PERatio = input(15, title="P/E Ratio", step=1)
def PERatio = close / EarningsPerShareTTM();
input PE = 15;

# Calculate Fair Price based on EPS and P/E Ratio
#fairprice = EPS > 0 ? PERatio * EPS : na
#plot(fairprice, color=color.green)

# Calculate Earnings Estimate for the fiscal year
#earningestimate = financial(syminfo.tickerid, "EARNINGS_ESTIMATE", "FY")

# Calculate Fair Price Estimate based on Earnings Estimate and P/E Ratio
#fairpriceestimate = earningestimate > 0 ? PERatio * earningestimate : na

# Plot fairprice and fairpriceestimate on the chart.

here is a lower study to experiment with.
it draws bubbles with some variable values

some financial functions have a value on just 1 bar out of 3 months. so you have to save the value till the next value comes along.

Code:
#chat214_convert_lyncg_eps_pe

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/p#age-11#post-138729
#Concept: https://www.gurufocus.com/news/1471569/behind-the-numbers-peter-lynch-and-fair-value
#Original code: https://www.tradingview.com/script/Y5bvwFfr-Peter-Lynch-Value/

declare lower;

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

# Calculate Earnings Per Share (EPS) using financial data
def EPS = if bn == 1 then 0
  else if isnan(EarningsPerShareTTM()) then eps[1]
  else round(EarningsPerShareTTM(),2);

def PERatio = if eps != 0 then (close / Eps) else 0;

#PERatio = input(15, title="P/E Ratio", step=1)
input PE = 15;

# Calculate Fair Price based on EPS and P/E Ratio
#fairprice = EPS > 0 ? PERatio * EPS : na
def fairprice = if eps != 0 then peratio * eps
  else 0;

# Calculate Earnings Estimate for the fiscal year
#earningestimate = financial(syminfo.tickerid, "EARNINGS_ESTIMATE", "FY")
# earnings are on 1 bar in 3 months. the other bars are N/A. this will keep previous value
def earningestimate = if bn == 1 then 0
  else if isnan(GetEstimatedEarnings()) then earningestimate[1]
  else round(GetEstimatedEarnings(),2);

# Calculate Fair Price Estimate based on Earnings Estimate and P/E Ratio
#fairpriceestimate = earningestimate > 0 ? PERatio * earningestimate : na
def fairpriceestimate = if earningestimate > 0 then round(PERatio * earningestimate,2) else 0;

# Plot fairprice and fairpriceestimate on the chart.

#plot(fairprice, color=color.green)
plot z1 = if fairprice > 0 then fairprice else na;
plot z2 = if fairpriceestimate != 0 then fairpriceestimate else na;
z1.setdefaultcolor(color.yellow);
z2.setdefaultcolor(color.cyan);

plot z = if isnan(close) then na else 0;

addlabel(1, "Fair price: " + fairprice , z1.TakeValueColor());
addlabel(1, "Fair price estimate: " + fairpriceestimate, z2.TakeValueColor());

def epsen = !isnan(eps);
def epsdiff = eps != eps[1];

input test_bubble1 = yes;
addchartbubble(test_bubble1 and !isnan(close), 0,
eps + " EPS\n" +
fairprice + " fair\n" +
 earningestimate + " Est\n" +
fairpriceestimate + " f est"
, color.yellow, no);
#, (if !isnan(eps) then color.yellow else color.gray), no);
#
 
Hello everyone, I have little understanding of thinkscript programming. I am needing your help to debug a code that you gave me, in order to have a script that does a retrospective test of buying and selling operations, every time two Hull moving averages (10 and 20 periods respectively) cross each other and at the end sample the import in $ obtained (starting, for example, from an initial capital of $1,000).

I add the code below.-


# Get the symbol of the instrument on screen
symbol = symbol;

# Variables to store signals and data
buySignal = false;
sellSignal = false;
buyPrice = 0.0;
sellPrice = 0.0;
currentBalance = initialCapital;
totalProfit = 0.0;
totalTrades = 0;

# Calculate Hull moving averages
hullMA1 = hullMA(symbol, periodMA1);
hullMA2 = hullMA(symbol, periodMA2);

# Iterate through the defined time period
for (i = 0; i < barCount(symbol); i++) {
# Get the current data bar
bar = bar(symbol, i);

# Generate buy/sell signals
if (hullMA1 > hullMA2 and not buySignal) {
buySignal = true;
sellSignal = false;
buyPrice = bar.close;
log("Buy: " + bar.close + " - " + bar.date);
} else if (hullMA1 < hullMA2 and not sellSignal) {
buySignal = false;
sellSignal = true;
sellPrice = bar.close;
log("Sell: " + bar.close + " - " + bar.date);

# Calculate and record profit/loss
profit = sellPrice - buyPrice;
totalProfit += profit;
totalTrades++;

# Reinvest profit in the next buy
currentBalance += profit;
buyPrice = 0.0;
}
}

# Display results
plot("Hull MA1", hullMA1, color.blue);
plot("Hull MA2", hullMA2, color.orange);
plot("Close Price", bar.close, color.black);

# Display trade summary
log("Final Balance: $" + currentBalance);
log("Total Profit: $" + totalProfit);
log("Total Trades: " + totalTrades);

# Display summary message
if (totalProfit > 0) {
alert("Congratulations! You made a total profit of $" + totalProfit + " in " + totalTrades + " trades.");
} else if (totalProfit < 0) {
alert("Sorry, you had a total loss of $" + totalProfit + " in " + totalTrades + " trades.");
} else {
alert("No profit or loss was made in " + totalTrades + " trades.");
}

# Adjust parameters
def periodMA1 = 10;
def periodMA2 = 20;
def initialCapital = 1000.0;

strategy(periodMA1, periodMA2, initialCapital);
# END CODE

I greatly appreciate your contributions.-
 
Last edited:
Hey everyone, I'm in the process of teaching myself ThinkScript and figured it'd be helpful to use ChatGPT (version 4) as a kind of virtual tutor. I asked it a simple question about how to add arrows to a chart and this is the answer it gave me:


As far as I can tell however, the AddChartArrow function does not exist in ThinkScript and never has! Is this a legit LLM hallucination?

Thanks
hello and welcome.
you have found out that chatgpt is worthless when it comes to thinkscript. it confused pine functions as thinkscript, or just makes up things.

the best way to learn is read the manual and type in the examples and change them to see what happens.
https://tlc.thinkorswim.com/center/reference/thinkScript

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

here is a code that draws arrows
it compares the current high to the high several bars ago. if higher then draw an arrow

the plot formula makes a comparison, then assigns a price level for the arrow

Code:
# test_arrow
input bars_back = 10;
# compare the current high to the high several bars ago. if higher then draw an arrow
plot z = if high > high[bars_back] then low else double.nan;
z.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
z.SetDefaultColor(Color.cyan);
z.setlineweight(3);
z.hidebubble();
#
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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