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:
Need help. Made an attempt to convert TV pine script for Volume Composition.
https://www.tradingview.com/script/d4TDeuRU-Volume-composition-Buy-sell-active-passive/

No syntax errors returned but having problems making it a lower study. The converted script also does not produce any visible output on the chart.
#Begin Script
# Fetch volume data
def volume = volume;
def closePrice = close;

# Calculate buy and sell volume
def buyVol;
def sellVol;

if closePrice > closePrice[1] {
buyVol = volume;
sellVol = 0;
} else if closePrice < closePrice[1] {
buyVol = 0;
sellVol = volume;
} else {
buyVol = 0;
sellVol = 0;
}

# Calculate total buy and sell volume
def length = 20; # You can adjust this as needed
def totalBuyVol = Sum(buyVol, length);
def totalSellVol = Sum(sellVol, length);

# Calculate buy and sell volume percentages
def totalVol = totalBuyVol + totalSellVol;
def buyVolPerc = (totalBuyVol / totalVol) * 100;
def sellVolPerc = (totalSellVol / totalVol) * 100;

# Define conditions for high volume
input volThreshold = 70;
def highBuyVolCondition = buyVolPerc >= volThreshold;
def highSellVolCondition = sellVolPerc >= volThreshold;

# Define conditions for high active volume
input volAThreshold = 70;
def highBuyVolACondition = buyVolPerc >= volAThreshold;
def highSellVolACondition = sellVolPerc >= volAThreshold;

# Plot high volume conditions as bubbles
plot highBuyVolBubble = highBuyVolCondition;
plot highSellVolBubble = highSellVolCondition;

highBuyVolBubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
highBuyVolBubble.SetDefaultColor(Color.GREEN);
highBuyVolBubble.SetLineWeight(1);

highSellVolBubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
highSellVolBubble.SetDefaultColor(Color.RED);
highSellVolBubble.SetLineWeight(1);

# Plot high active volume conditions as bubbles
plot highBuyVolABubble = highBuyVolACondition;
plot highSellVolABubble = highSellVolACondition;

highBuyVolABubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
highBuyVolABubble.SetDefaultColor(Color.BLUE);
highBuyVolABubble.SetLineWeight(1);

highSellVolABubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
highSellVolABubble.SetDefaultColor(Color.ORANGE);
highSellVolABubble.SetLineWeight(1);

#End Script
 
Last edited by a moderator:
I am tyring to fix this particular line that is highlighted in red in the TOS script as an error
plot bbUpper = bb.upperband;

Here is the script:

# Define length for calculations
input length = 14; # RSI length

# Calculate Bollinger Bands
def bb = BollingerBands(price = close, length = length, numDevDn = -2, numDevUp = 2);

# Plot Bollinger Bands Upper
plot bbUpper = bb.upperband;

# Calculate RSI
def rsi = RSI(length = length);

# Calculate lower highs and lower lows
def lowerHighs = high < high[1];
def lowerLows = low < low[1];

# Bearish condition 1: RSI above 70 in the last 7 days but now below 70
def condition1 = Highest(rsi, 7) > 70;
def condition2 = rsi < 70;

# Bearish condition 2: Price candles showing lower highs and lower lows
def condition3 = lowerHighs and lowerLows;

# Bearish condition 3: Price at or near the upper Bollinger Band
def condition4 = close >= bbUpper * 0.98; # Adjust the threshold as needed

# Combine conditions for bearish setup
def bearishSetup = condition1 and condition2 and condition3 and condition4;

# Plot scan results
plot bearishScan = bearishSetup;
bearishScan.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearishScan.SetLineWeight(1);
bearishScan.SetDefaultColor(Color.RED);

And I get the following errors in the addendum:
No such constant: bb.upperband at 9:16
No such constant: bb.upperband at 9:16
Expected double at 9:6
No such constant: bb.upperband at 9:16
No such constant: bb.upperband at 9:16
Expected double at 9:6

Any help would be appreciated
 
I am tyring to fix this particular line that is highlighted in red in the TOS script as an error
plot bbUpper = bb.upperband;

Here is the script:

# Define length for calculations
input length = 14; # RSI length

# Calculate Bollinger Bands
def bb = BollingerBands(price = close, length = length, numDevDn = -2, numDevUp = 2);

# Plot Bollinger Bands Upper
plot bbUpper = bb.upperband;

# Calculate RSI
def rsi = RSI(length = length);

# Calculate lower highs and lower lows
def lowerHighs = high < high[1];
def lowerLows = low < low[1];

# Bearish condition 1: RSI above 70 in the last 7 days but now below 70
def condition1 = Highest(rsi, 7) > 70;
def condition2 = rsi < 70;

# Bearish condition 2: Price candles showing lower highs and lower lows
def condition3 = lowerHighs and lowerLows;

# Bearish condition 3: Price at or near the upper Bollinger Band
def condition4 = close >= bbUpper * 0.98; # Adjust the threshold as needed

# Combine conditions for bearish setup
def bearishSetup = condition1 and condition2 and condition3 and condition4;

# Plot scan results
plot bearishScan = bearishSetup;
bearishScan.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearishScan.SetLineWeight(1);
bearishScan.SetDefaultColor(Color.RED);

And I get the following errors in the addendum:
No such constant: bb.upperband at 9:16
No such constant: bb.upperband at 9:16
Expected double at 9:6
No such constant: bb.upperband at 9:16
No such constant: bb.upperband at 9:16
Expected double at 9:6

Any help would be appreciated

reply to post167

should have had the .upperband on the end of the bb formula , not the variable
def bb = BollingerBands(price = close, length = length, numDevDn = -2, numDevUp = 2);

def bb = BollingerBands(price = close, length = length, numDevDn = -2, numDevUp = 2).upperband;


bb is just a variable, not a function, so can't use .upperband
plot bbUpper = bb.upperband;
if it was a function, would need ()


Code:
# chat167_bb

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-9#post-132136
#omzense  10/14  #167

#I am tyring to fix this particular line that is highlighted in red in the TOS script as an error
# plot bbUpper = bb.upperband;


input price = close;
input length = 14; # RSI length
input numDevDn = -2;
input numDevUp = 2;

# Calculate Bollinger Bands
def bb_ub = BollingerBands(price = price, length = length, numDevDn = numDevDn, numDevUp = numDevup).UpperBand;
def bb_mid = BollingerBands(price = price, length = length, numDevDn = numDevDn, numDevUp = numDevup).midline;
def bb_lb = BollingerBands(price = price, length = length, numDevDn = numDevDn, numDevUp = numDevup).lowerBand;

# Plot Bollinger Bands Upper
plot bbUpper = bb_ub;

# Calculate RSI
def rsi = RSI(length = length);

# Calculate lower highs and lower lows
def lowerHighs = high < high[1];
def lowerLows = low < low[1];

# Bearish condition 1: RSI above 70 in the last 7 days but now below 70
def condition1 = Highest(rsi, 7) > 70;
def condition2 = rsi < 70;

# Bearish condition 2: Price candles showing lower highs and lower lows
def condition3 = lowerHighs and lowerLows;

# Bearish condition 3: Price at or near the upper Bollinger Band
def condition4 = close >= bbUpper * 0.98; # Adjust the threshold as needed

# Combine conditions for bearish setup
def bearishSetup = condition1 and condition2 and condition3 and condition4;

# Plot scan results
plot bearishScan = bearishSetup;
bearishScan.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearishScan.SetLineWeight(1);
bearishScan.SetDefaultColor(Color.RED);
#
 
Last edited:
Need help. Made an attempt to convert TV pine script for Volume Composition.
https://www.tradingview.com/script/d4TDeuRU-Volume-composition-Buy-sell-active-passive/

No syntax errors returned but having problems making it a lower study. The converted script also does not produce any visible output on the chart.
#Begin Script
# Fetch volume data
def volume = volume;
def closePrice = close;

# Calculate buy and sell volume
def buyVol;
def sellVol;

if closePrice > closePrice[1] {
buyVol = volume;
sellVol = 0;
} else if closePrice < closePrice[1] {
buyVol = 0;
sellVol = volume;
} else {
buyVol = 0;
sellVol = 0;
}

# Calculate total buy and sell volume
def length = 20; # You can adjust this as needed
def totalBuyVol = Sum(buyVol, length);
def totalSellVol = Sum(sellVol, length);

# Calculate buy and sell volume percentages
def totalVol = totalBuyVol + totalSellVol;
def buyVolPerc = (totalBuyVol / totalVol) * 100;
def sellVolPerc = (totalSellVol / totalVol) * 100;

# Define conditions for high volume
input volThreshold = 70;
def highBuyVolCondition = buyVolPerc >= volThreshold;
def highSellVolCondition = sellVolPerc >= volThreshold;

# Define conditions for high active volume
input volAThreshold = 70;
def highBuyVolACondition = buyVolPerc >= volAThreshold;
def highSellVolACondition = sellVolPerc >= volAThreshold;

# Plot high volume conditions as bubbles
plot highBuyVolBubble = highBuyVolCondition;
plot highSellVolBubble = highSellVolCondition;

highBuyVolBubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
highBuyVolBubble.SetDefaultColor(Color.GREEN);
highBuyVolBubble.SetLineWeight(1);

highSellVolBubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
highSellVolBubble.SetDefaultColor(Color.RED);
highSellVolBubble.SetLineWeight(1);

# Plot high active volume conditions as bubbles
plot highBuyVolABubble = highBuyVolACondition;
plot highSellVolABubble = highSellVolACondition;

highBuyVolABubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
highBuyVolABubble.SetDefaultColor(Color.BLUE);
highBuyVolABubble.SetLineWeight(1);

highSellVolABubble.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
highSellVolABubble.SetDefaultColor(Color.ORANGE);
highSellVolABubble.SetLineWeight(1);

#End Script

reply to post166

there is an error
there is a ! in the top left of chart

trying to self assign volume
def volume = volume;

why would you do this ?
delete that line and it will plot arrows

why do people use variable names of commonly used constants , functions......

ps , to make a stacked volume bar chart, look for example codes that use addchart()
https://usethinkscript.com/search/1333833/?q=addchart(&o=date
 
Last edited:
Hi - Can someone help me with the following script. I would like the UpTrend and DownTrend EMA lines/plots to be equally centered on a zero plane or center line. Haven't been able to get ChatGPT to figure it out. Any help would be appreciated. Thanks.

declare lower;

input price = close;
input length = 20;
input displace = -10; # Adjusted displace to center the lines
input showBreakoutSignals = no;
input scale = 1.0;
input smoothLength = 12;
input combinedTrendSmoothLength = 12;
input weightByROC = yes;
input smootheningRatio = 1.0;

def Avg = Average(price[-displace], length);
def SMA = (price - Avg) * scale;

def ROC = (price / price[length]) - 1;

def CumulativeUpTrend = fold i = 0 to length with totalUp = 0 do totalUp + if SMA > 0 then SMA * ROC else 0;
def CumulativeDownTrend = fold j = 0 to length with totalDown = 0 do totalDown + if SMA < 0 then SMA * ROC else 0;

def EMAUpTrendRaw = CumulativeUpTrend;
def EMADownTrendRaw = CumulativeDownTrend;

def EMAUpTrend = ExpAverage(EMAUpTrendRaw, smoothLength) * smootheningRatio;
def EMADownTrend = ExpAverage(EMADownTrendRaw, smoothLength) * smootheningRatio;

plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);

plot UpTrend = EMAUpTrend;
UpTrend.SetDefaultColor(Color.GREEN);
UpTrend.SetLineWeight(2);

plot DownTrend = EMADownTrend;
DownTrend.SetDefaultColor(Color.RED);
DownTrend.SetLineWeight(2);

def CombinedTrendRaw = SMA;
def CombinedTrendSmoothed = ExpAverage(CombinedTrendRaw, combinedTrendSmoothLength);

def SmoothOscillator = ExpAverage(CombinedTrendSmoothed, smoothLength);

plot SmoothOscillatorNeutral = if SmoothOscillator == 0 then SmoothOscillator else Double.NaN;
SmoothOscillatorNeutral.SetDefaultColor(Color.ORANGE);
SmoothOscillatorNeutral.SetLineWeight(2);

plot UpSignal = price crosses above Avg;
plot DownSignal = price crosses below Avg;

UpSignal.SetHiding(!showBreakoutSignals);
DownSignal.SetHiding(!showBreakoutSignals);

AddLabel(UpTrend > 0.2, "Bullish", if UpTrend > 0.2 then Color.GREEN else Color.RED);
AddLabel(DownTrend < -0.2, "Bearish", if DownTrend < -0.2 then Color.GREEN else Color.RED);

AddLabel(SmoothOscillator > 0, "Smooth Bullish", Color.GREEN);
AddLabel(SmoothOscillator < 0, "Smooth Bearish", Color.RED);

AddLabel(UpTrend, "UpTrend ROC: " + AsPercent(ROC), if UpTrend > 0.2 then Color.GREEN else Color.RED);
 
Hi @halcyonguy - When you get a chance can you help me with a post I made to the ChatGPT, BARD, thread #170?
i started to look at it. i get interupted a lot.. sorry. i I think it has 2 lines that are above 0 . do you want each line centered around 0? or did you want one of them flipped to be an inverse and on the negative side??
 
Hi - Can someone help me with the following script. I would like the UpTrend and DownTrend EMA lines/plots to be equally centered on a zero plane or center line. Haven't been able to get ChatGPT to figure it out. Any help would be appreciated. Thanks.

declare lower;

input price = close;
input length = 20;
input displace = -10; # Adjusted displace to center the lines
input showBreakoutSignals = no;
input scale = 1.0;
input smoothLength = 12;
input combinedTrendSmoothLength = 12;
input weightByROC = yes;
input smootheningRatio = 1.0;

def Avg = Average(price[-displace], length);
def SMA = (price - Avg) * scale;

def ROC = (price / price[length]) - 1;

def CumulativeUpTrend = fold i = 0 to length with totalUp = 0 do totalUp + if SMA > 0 then SMA * ROC else 0;
def CumulativeDownTrend = fold j = 0 to length with totalDown = 0 do totalDown + if SMA < 0 then SMA * ROC else 0;

def EMAUpTrendRaw = CumulativeUpTrend;
def EMADownTrendRaw = CumulativeDownTrend;

def EMAUpTrend = ExpAverage(EMAUpTrendRaw, smoothLength) * smootheningRatio;
def EMADownTrend = ExpAverage(EMADownTrendRaw, smoothLength) * smootheningRatio;

plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);

plot UpTrend = EMAUpTrend;
UpTrend.SetDefaultColor(Color.GREEN);
UpTrend.SetLineWeight(2);

plot DownTrend = EMADownTrend;
DownTrend.SetDefaultColor(Color.RED);
DownTrend.SetLineWeight(2);

def CombinedTrendRaw = SMA;
def CombinedTrendSmoothed = ExpAverage(CombinedTrendRaw, combinedTrendSmoothLength);

def SmoothOscillator = ExpAverage(CombinedTrendSmoothed, smoothLength);

plot SmoothOscillatorNeutral = if SmoothOscillator == 0 then SmoothOscillator else Double.NaN;
SmoothOscillatorNeutral.SetDefaultColor(Color.ORANGE);
SmoothOscillatorNeutral.SetLineWeight(2);

plot UpSignal = price crosses above Avg;
plot DownSignal = price crosses below Avg;

UpSignal.SetHiding(!showBreakoutSignals);
DownSignal.SetHiding(!showBreakoutSignals);

AddLabel(UpTrend > 0.2, "Bullish", if UpTrend > 0.2 then Color.GREEN else Color.RED);
AddLabel(DownTrend < -0.2, "Bearish", if DownTrend < -0.2 then Color.GREEN else Color.RED);

AddLabel(SmoothOscillator > 0, "Smooth Bullish", Color.GREEN);
AddLabel(SmoothOscillator < 0, "Smooth Bearish", Color.RED);

AddLabel(UpTrend, "UpTrend ROC: " + AsPercent(ROC), if UpTrend > 0.2 then Color.GREEN else Color.RED);

reply to post168

this finds the highest and lowest value of each line. then shifts them down, to be centered around the zero line

Code:
#chat170_lines_centered_00b

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-9#post-132875
#fluna  #170

declare lower;

input price = close;
input length = 20;
input displace = -10; # Adjusted displace to center the lines
input showBreakoutSignals = no;
input scale = 1.0;
input smoothLength = 12;
input combinedTrendSmoothLength = 12;
input weightByROC = yes;
input smootheningRatio = 1.0;

def Avg = Average(price[-displace], length);
def SMA = (price - Avg) * scale;

def ROC = (price / price[length]) - 1;

def CumulativeUpTrend = fold i = 0 to length
 with totalUp = 0
 do totalUp + if SMA > 0 then SMA * ROC else 0;

def CumulativeDownTrend = fold j = 0 to length
 with totalDown = 0
 do totalDown + if SMA < 0 then SMA * ROC else 0;


def EMAUpTrendRaw = CumulativeUpTrend;
def EMADownTrendRaw = CumulativeDownTrend;

def EMAUpTrend = ExpAverage(EMAUpTrendRaw, smoothLength) * smootheningRatio;
def EMADownTrend = ExpAverage(EMADownTrendRaw, smoothLength) * smootheningRatio;


def EMAUpTrend2hi = highestall(EMAUpTrend);
def EMAUpTrend2lo = lowestall(EMAUpTrend);
def EMADownTrend2hi = highestall(EMADownTrend);
def EMADownTrend2lo = lowestall(EMADownTrend);

def euphalf = (EMAUpTrend2hi - EMAUpTrend2lo)/2;
def edwnhalf = (EMAdownTrend2hi - EMAdownTrend2lo)/2;


addchartbubble(0, 0,
roc
, (if roc < 0 then color.yellow else color.cyan), yes);


plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);

#plot UpTrend = EMAUpTrend;
plot UpTrend = EMAUpTrend - euphalf;
UpTrend.SetDefaultColor(Color.GREEN);
UpTrend.SetLineWeight(2);

#plot DownTrend = EMADownTrend;
plot DownTrend = EMADownTrend - edwnhalf;
DownTrend.SetDefaultColor(Color.RED);
DownTrend.SetLineWeight(2);

def CombinedTrendRaw = SMA;
def CombinedTrendSmoothed = ExpAverage(CombinedTrendRaw, combinedTrendSmoothLength);

def SmoothOscillator = ExpAverage(CombinedTrendSmoothed, smoothLength);

plot SmoothOscillatorNeutral = if SmoothOscillator == 0 then SmoothOscillator else Double.NaN;
SmoothOscillatorNeutral.SetDefaultColor(Color.ORANGE);
SmoothOscillatorNeutral.SetLineWeight(2);

plot UpSignal = price crosses above Avg;
plot DownSignal = price crosses below Avg;

UpSignal.SetHiding(!showBreakoutSignals);
DownSignal.SetHiding(!showBreakoutSignals);

#upsignal.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
#downsignal.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

AddLabel(UpTrend > 0.2, "Bullish", if UpTrend > 0.2 then Color.GREEN else Color.RED);
AddLabel(DownTrend < -0.2, "Bearish", if DownTrend < -0.2 then Color.GREEN else Color.RED);

AddLabel(SmoothOscillator > 0, "Smooth Bullish", Color.GREEN);
AddLabel(SmoothOscillator < 0, "Smooth Bearish", Color.RED);

AddLabel(UpTrend, "UpTrend ROC: " + AsPercent(ROC), if UpTrend > 0.2 then Color.GREEN else Color.RED);
#
 
Last edited:
I don't understand thinkScript yet, I just trade... but I was trying to have ChatGPT make a script for me that would allow me to get in and out of trades quicker because I often have to react right as a trendline is created with my strategy.

My strategy is pretty simple, I just combined the 9/20 cross with an ABC trendline retracement strategy that I saw online from SMB Capital;

When the 9 SMA is above the 20, I look for a very recent trendline of 3+ consecutive candles trending down, to be broken to the upside by 5-10 cents depending on my judgement about the steepness of the trendline. When the 9 is below the 20, I look for the break of an uptrend to the downside. Sometimes there's a retracement right there, sometimes I have to wait for the retracement to occur. I just wanted a thinkScript that would draw the up or downtrend lines depending on where the 9 is in relation to the 20, and be looking to update it at every candle close. So that I can focus on executing trades, and making sure any of my other rules are met (I don't enter when I perceive there to be a "bubble" e.g. prolonged trend without any recent crosses and the 9/20 are quite far from each other - unless price retraces back into the fishtail between or behind the SMAs and then breaks that retracement line).

There's also a quirk that if the first and third candle are connected (this is a must), but the second candle is "contained" e.g. it's floating and doesn't touch the TL, then it's valid. However, if the second candle breaks below an uptrend line (or above a downtrend line) - THEN I keep the angle of the trendline from candles 1 and 3, but simply "float" it up or down (slide it after drawing it) until it makes contact with the second candle's low or high point (high for 9/20 up with down retracement line, low for 9/20 down with up retracement line).

Here's the script Chat GPT wrote me, and syntax errors from TOS at the bottom:

# Trendline Drawing Study for Thinkorswim
# Automatically draws trendlines based on specified criteria

declare lower;

input smaLength1 = 9;
input smaLength2 = 20;
input trendlineOffset = 1; # Offset for drawing the trendlines

# Calculate SMAs
def sma1 = SimpleMovingAvg(close, smaLength1);
def sma2 = SimpleMovingAvg(close, smaLength2);

# Check if we have enough data for the SMAs
def validData = !IsNaN(sma1) and !IsNaN(sma2);

# Define uptrend and downtrend conditions
def uptrend = sma1 < sma2 and close > close[1] and close[1] > close[2];
def downtrend = sma1 > sma2 and close < close[1] and close[1] < close[2];

# Initialize trendline points
plot startTrendLine = Double.NaN;
plot endTrendLine = Double.NaN;

# Check for uptrend and downtrend conditions
if (uptrend and validData) {
startTrendLine = Min(low, low[2]);
endTrendLine = Min(low[1], low[2]);
if close < startTrendLine {
startTrendLine = startTrendLine - trendlineOffset;
endTrendLine = endTrendLine - trendlineOffset;
}
} else if (downtrend and validData) {
startTrendLine = Max(high, high[2]);
endTrendLine = Max(high[1], high[2]);
if close > startTrendLine {
startTrendLine = startTrendLine + trendlineOffset;
endTrendLine = endTrendLine + trendlineOffset;
}
}

# Plot the trendlines
plot uptrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
uptrendLine.SetDefaultColor(Color.GREEN);
uptrendLine.SetStyle(Curve.FIRM);
uptrendLine.SetLineWeight(1);

plot downtrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
downtrendLine.SetDefaultColor(Color.RED);
downtrendLine.SetStyle(Curve.FIRM);
downtrendLine.SetLineWeight(1);

SYNTAX ERRORS:
Syntax error: An 'else' block expected at 29:5
Syntax error: Semicolon expected at 26:1
Syntax error: An 'else' block expected at 36:5
Syntax error: Semicolon expected at 36:5

I asked ChatGPT to try and fix the errors but ended up just going back and forth having it create new errors and not know how to fix them. If you can get this working I'll be your BFF. Happy to exchange it for my full trade plan too there might be a few other helpful rules in there.

Thanks.
 
Hello -

I have another script that I could use some help with. The indicator below is a volume histogram with an aggregation period of 3min. The bars on the histogram move 3 bars at a time. Is it possible to keep the aggregation period at 3min or more but have the bars move one bar at a time/1min etc. if on 1min chart? See image below. Thanks.

declare lower;

input useTickData = no;
input displayLabels = no;
input dataSmoothingType = {default Exponential, Simple};
input smoothingLength = 3;
input dataTimeframe = AggregationPeriod.THREE_MIN; # 3 minutes for data aggregation
input volumeTimeframe = AggregationPeriod.MIN; # 1 minute for volume

# Data processing for price
def price;
if (useTickData) {
price = close;
} else {
price = close(period = dataTimeframe);
}

# Data processing for volume (updated every 1 minute)
def volumeData;
if (useTickData) {
volumeData = volume;
} else {
volumeData = volume(period = volumeTimeframe);
}

# Applying smoothing to the data line
plot Data;
switch (dataSmoothingType) {
case Simple:
Data = Average(price, smoothingLength) - Average(Average(price, smoothingLength), smoothingLength);
case Exponential:
Data = ExpAverage(price, smoothingLength) - ExpAverage(ExpAverage(price, smoothingLength), smoothingLength);
}
Data.SetDefaultColor(Color.WHITE);
Data.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

# Defining buy and sell volume
def buyVolume = if close > close[1] then volumeData else 0;
def sellVolume = if close < close[1] then volumeData else 0;

# Resetting the volume calculation each day
def isNewDay = GetDay() != GetDay()[1];
def intradayBuyVolume = if isNewDay then buyVolume else intradayBuyVolume[1] + buyVolume;
def intradaySellVolume = if isNewDay then sellVolume else intradaySellVolume[1] + sellVolume;

# Adding a label to display the intraday volumes
AddLabel(displayLabels, "Buy Vol: " + intradayBuyVolume + " | Sell Vol: " + intradaySellVolume,
if intradayBuyVolume > intradaySellVolume then Color.GREEN else Color.RED);
 

Attachments

  • Aggregate Volume indicator.JPG
    Aggregate Volume indicator.JPG
    62.2 KB · Views: 167
Hi Folks - I posted in ChatGPT, BARD, Other AI Scripts Which Can't Be Used In ThinkOrSwim. Post #173. Can someone please help me with that? Thank you for anyone that can help!

its only been a day. be patient. no need to repost. when someone has the time and knowledge , they will look at it. there are some very talented people here.

no, i don't think it can be changed to how you asked. when using 2nd aggregation data, the data has the same value for several bars, there's no getting around that..
Maybe instead of using second aggregation. You could use an average of close, with a length of 3, and use that as your data source. Then it will be smoother...??
 
its only been a day. be patient. no need to repost. when someone has the time and knowledge , they will look at it. there are some very talented people here.

no, i don't think it can be changed to how you asked. when using 2nd aggregation data, the data has the same value for several bars, there's no getting around that..
Maybe instead of using second aggregation. You could use an average of close, with a length of 3, and use that as your data source. Then it will be smoother...??
Thank you, may bad. I would like to maintain the stepped appearance, rather than transitioning to a smoothed representation. Additionally, I'd like to adjust how the bars move in the histogram visualization. Currently, when set to a 3-minute aggregate, three bars move together. Instead, I would prefer if each bar could move independently, updating at 1-minute intervals while maintaining the higher aggregate period.
 
Thank you, may bad. I would like to maintain the stepped appearance, rather than transitioning to a smoothed representation. Additionally, I'd like to adjust how the bars move in the histogram visualization. Currently, when set to a 3-minute aggregate, three bars move together. Instead, I would prefer if each bar could move independently, updating at 1-minute intervals while maintaining the higher aggregate period.

can't do it. if using 2nd aggregation, formulas will have stepped outputs. the same data exists on several bars.
 
can't do it. if using 2nd aggregation, formulas will have stepped outputs. the same data exists on several bars.
I tried making the following modifications, not the stepped pattern I was hoping for. Would it be possible to infill the missing bars by extrapolating the rate of change so that they infill at 1min or chart setting?

declare lower;

input smoothingLength = 15;
input aggregationPeriod = 2; # User-defined aggregation period

input momentumLength = 2; # Adjustable momentum length
input momentumMultiplier = 1; # Adjustable momentum multiplier

# Calculate bar index for aggregation
def barNumber = BarNumber();
def isAggregationBar = barNumber % aggregationPeriod == 0;

# Obtain current price
def price = close;

# Calculate simple or exponential smoothing for 1-minute data
def dataOneMin = ExpAverage(price, smoothingLength);

# Aggregate or summarize data based on user-defined period
def aggregatedData = if isAggregationBar then dataOneMin else aggregatedData[1];

# Calculate the momentum
def momentum = (aggregatedData - aggregatedData[momentumLength]) / aggregationPeriod;

# Initialize a variable to hold the infilled data
def infilledData;
if isAggregationBar {
infilledData = aggregatedData;
} else {
# Calculate the value for non-aggregated bars
infilledData = infilledData[1] + momentum * momentumMultiplier;
}

# Centering the plot around a zero plane
plot Data = infilledData - infilledData[1];
Data.SetDefaultColor(Color.WHITE);
Data.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
 
Hello,

I wrote the following stock screener code but found that it gives me a few results that break just about every condition in my script. I am new to ThinkScript so believe I may be doing something wrong.

Code:
#Variables
def minPrice = 1.00;     # Define minimum stock price.
def minAboveLow = 0.30;  # Define minimum % above 52 week low.
def maxBelowHigh = 0.25; # Define maximum % below 52 week high.
def ma50CloseDays = 10;  # Define number of days for stock to close above the 50 day moving average.
def minVol = 500000;     # Define the minimum 50 day average volume.

#Define stock price for screening.
def price = close;

#Define moving averages
def ma50 = SimpleMovingAvg(price, 50);   #50 day price SMA.
def ma150 = SimpleMovingAvg(price, 150); #150 day price SMA.
def ma200 = SimpleMovingAvg(price, 200); #200 day price SMA.

#Define moving average trends
def ma50Trend = SimpleMovingAvg(price, 50) [21];   #50 day price SMA from 21 bars ago.
def ma150Trend = SimpleMovingAvg(price, 150) [21]; #150 day price SMA from 21 bars ago.
def ma200Trend = SimpleMovingAvg(price, 200)[63];  #200 day price SMA from 63 bars ago.

#Define average volume
def avgVol = SimpleMovingAvg(volume, 50); #50 day volume SMA.

#Define days closing above SMA (50)
def ma50Close = Sum("data" = price > SimpleMovingAvg(close, 50), "length" = ma50CloseDays);

#Define 52 week high and low
def low52 = Lowest(price,252);   #Lowest close from teh past 252 bars.
def high52 = Highest(price,252); #Highest close from the past 252 bars.

def condition1 = price > ma50 and price > ma150 and price > ma200;
def condition2 = ma50 > ma150;                                   
def condition3 = ma150 > ma200;
def condition4 = ma200 > ma200Trend;
def condition5 = price >= (1 + minAboveLow) * low52;
def condition6 = price >= (1 - maxBelowHigh) * high52;

#Require price to be greater than $1.00 to avoid penny stocks.
def condition7 = price >= minPrice;

#Require volume SMA (50) to be greater than X to avoid thinly traded stocks.
def condition8 = avgVol >= minVol;

#Require the price to be greater than SMA (50) for the past X days to avoid volative stocks.
def condition9 = ma50Close >= ma50CloseDays;

#Require the 50 and 150 day SMAs to be trending positive for the past 21 bars.
def condition10 = ma50 > ma50Trend;
def condition11 = ma150 > ma150Trend;

#Plot results
plot scan = condition1 and condition2 and condition3 and condition4 and condition5 and condition6 and condition7 and condition8 and condition9 and condition10 and condition11;

The scan provides the following results:

1699311387495.png


The top 5 results are way below my threshold of within 25% of a 52 week high and when looking at the charts the 200 day SMA is greater than the 150 day SMA and the 150 day SMA is greater than the 50 day SMA - basically the exact opposite of what I'm looking for.

Any help is greatly appreciated!
 
I don't understand thinkScript yet, I just trade... but I was trying to have ChatGPT make a script for me that would allow me to get in and out of trades quicker because I often have to react right as a trendline is created with my strategy.

My strategy is pretty simple, I just combined the 9/20 cross with an ABC trendline retracement strategy that I saw online from SMB Capital;

When the 9 SMA is above the 20, I look for a very recent trendline of 3+ consecutive candles trending down, to be broken to the upside by 5-10 cents depending on my judgement about the steepness of the trendline. When the 9 is below the 20, I look for the break of an uptrend to the downside. Sometimes there's a retracement right there, sometimes I have to wait for the retracement to occur. I just wanted a thinkScript that would draw the up or downtrend lines depending on where the 9 is in relation to the 20, and be looking to update it at every candle close. So that I can focus on executing trades, and making sure any of my other rules are met (I don't enter when I perceive there to be a "bubble" e.g. prolonged trend without any recent crosses and the 9/20 are quite far from each other - unless price retraces back into the fishtail between or behind the SMAs and then breaks that retracement line).

There's also a quirk that if the first and third candle are connected (this is a must), but the second candle is "contained" e.g. it's floating and doesn't touch the TL, then it's valid. However, if the second candle breaks below an uptrend line (or above a downtrend line) - THEN I keep the angle of the trendline from candles 1 and 3, but simply "float" it up or down (slide it after drawing it) until it makes contact with the second candle's low or high point (high for 9/20 up with down retracement line, low for 9/20 down with up retracement line).

Here's the script Chat GPT wrote me, and syntax errors from TOS at the bottom:

# Trendline Drawing Study for Thinkorswim
# Automatically draws trendlines based on specified criteria

declare lower;

input smaLength1 = 9;
input smaLength2 = 20;
input trendlineOffset = 1; # Offset for drawing the trendlines

# Calculate SMAs
def sma1 = SimpleMovingAvg(close, smaLength1);
def sma2 = SimpleMovingAvg(close, smaLength2);

# Check if we have enough data for the SMAs
def validData = !IsNaN(sma1) and !IsNaN(sma2);

# Define uptrend and downtrend conditions
def uptrend = sma1 < sma2 and close > close[1] and close[1] > close[2];
def downtrend = sma1 > sma2 and close < close[1] and close[1] < close[2];

# Initialize trendline points
plot startTrendLine = Double.NaN;
plot endTrendLine = Double.NaN;

# Check for uptrend and downtrend conditions
if (uptrend and validData) {
startTrendLine = Min(low, low[2]);
endTrendLine = Min(low[1], low[2]);
if close < startTrendLine {
startTrendLine = startTrendLine - trendlineOffset;
endTrendLine = endTrendLine - trendlineOffset;
}
} else if (downtrend and validData) {
startTrendLine = Max(high, high[2]);
endTrendLine = Max(high[1], high[2]);
if close > startTrendLine {
startTrendLine = startTrendLine + trendlineOffset;
endTrendLine = endTrendLine + trendlineOffset;
}
}

# Plot the trendlines
plot uptrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
uptrendLine.SetDefaultColor(Color.GREEN);
uptrendLine.SetStyle(Curve.FIRM);
uptrendLine.SetLineWeight(1);

plot downtrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
downtrendLine.SetDefaultColor(Color.RED);
downtrendLine.SetStyle(Curve.FIRM);
downtrendLine.SetLineWeight(1);

SYNTAX ERRORS:
Syntax error: An 'else' block expected at 29:5
Syntax error: Semicolon expected at 26:1
Syntax error: An 'else' block expected at 36:5
Syntax error: Semicolon expected at 36:5

I asked ChatGPT to try and fix the errors but ended up just going back and forth having it create new errors and not know how to fix them. If you can get this working I'll be your BFF. Happy to exchange it for my full trade plan too there might be a few other helpful rules in there.

Thanks.

reply to post172

i haven't analized all your words. i just made the study plot something.
will study your rules later.

can't do this, and use formulas within if thens
plot startTrendLine = Double.NaN;
plot endTrendLine = Double.NaN;

you just put semi colon after the variable....
plot startTrendLine;
plot endTrendLine;

but, you can't use plot with formulas with recursive variables ( read previous values of same variable)
have to change plot to def, then plot later.


i changed the structure of the if then , and added [1] to some variables on the right side of =.
can't have the same variable of both sides of =.

Code:
#chat172_sma_trend

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

# Trendline Drawing Study for Thinkorswim
# Automatically draws trendlines based on specified criteria

declare lower;

input smaLength1 = 9;
input smaLength2 = 20;
input trendlineOffset = 1; # Offset for drawing the trendlines

# Calculate SMAs
def sma1 = SimpleMovingAvg(close, smaLength1);
def sma2 = SimpleMovingAvg(close, smaLength2);

# Check if we have enough data for the SMAs
def validData = !IsNaN(sma1) and !IsNaN(sma2);

# Define uptrend and downtrend conditions
def uptrend = sma1 < sma2 and close > close[1] and close[1] > close[2];
def downtrend = sma1 > sma2 and close < close[1] and close[1] < close[2];

# Initialize trendline points
def startTrendLine;
def endTrendLine;

# Check for uptrend and downtrend conditions
if (uptrend and validData) {
    startTrendLine = Min(low, low[2]);
    endTrendLine = Min(low[1], low[2]);
 } else if close < startTrendLine[1] {
    startTrendLine = startTrendLine[1] - trendlineOffset;
    endTrendLine = endTrendLine[1] - trendlineOffset;
 } else if (downtrend and validData) {
   startTrendLine = Max(high, high[2]);
   endTrendLine = Max(high[1], high[2]);
 } else if close > startTrendLine[1] {
   startTrendLine = startTrendLine[1] + trendlineOffset;
   endTrendLine = endTrendLine[1] + trendlineOffset;
 } else {
   startTrendLine = startTrendLine[1];
   endTrendLine = endTrendLine[1];
}

plot z1 = startTrendLine;
plot z2 = endTrendLine;

# Plot the trendlines
plot uptrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
            uptrendLine.SetDefaultColor(Color.GREEN);
            uptrendLine.SetStyle(Curve.FIRM);
            uptrendLine.SetLineWeight(1);

            plot downtrendLine = if !IsNaN(startTrendLine) then startTrendLine else Double.NaN;
            downtrendLine.SetDefaultColor(Color.RED);
            downtrendLine.SetStyle(Curve.FIRM);
            downtrendLine.SetLineWeight(1);

#
 
Hello,

I wrote the following stock screener code but found that it gives me a few results that break just about every condition in my script. I am new to ThinkScript so believe I may be doing something wrong.

Code:
#Variables
def minPrice = 1.00;     # Define minimum stock price.
def minAboveLow = 0.30;  # Define minimum % above 52 week low.
def maxBelowHigh = 0.25; # Define maximum % below 52 week high.
def ma50CloseDays = 10;  # Define number of days for stock to close above the 50 day moving average.
def minVol = 500000;     # Define the minimum 50 day average volume.

#Define stock price for screening.
def price = close;

#Define moving averages
def ma50 = SimpleMovingAvg(price, 50);   #50 day price SMA.
def ma150 = SimpleMovingAvg(price, 150); #150 day price SMA.
def ma200 = SimpleMovingAvg(price, 200); #200 day price SMA.

#Define moving average trends
def ma50Trend = SimpleMovingAvg(price, 50) [21];   #50 day price SMA from 21 bars ago.
def ma150Trend = SimpleMovingAvg(price, 150) [21]; #150 day price SMA from 21 bars ago.
def ma200Trend = SimpleMovingAvg(price, 200)[63];  #200 day price SMA from 63 bars ago.

#Define average volume
def avgVol = SimpleMovingAvg(volume, 50); #50 day volume SMA.

#Define days closing above SMA (50)
def ma50Close = Sum("data" = price > SimpleMovingAvg(close, 50), "length" = ma50CloseDays);

#Define 52 week high and low
def low52 = Lowest(price,252);   #Lowest close from teh past 252 bars.
def high52 = Highest(price,252); #Highest close from the past 252 bars.

def condition1 = price > ma50 and price > ma150 and price > ma200;
def condition2 = ma50 > ma150;                                 
def condition3 = ma150 > ma200;
def condition4 = ma200 > ma200Trend;
def condition5 = price >= (1 + minAboveLow) * low52;
def condition6 = price >= (1 - maxBelowHigh) * high52;

#Require price to be greater than $1.00 to avoid penny stocks.
def condition7 = price >= minPrice;

#Require volume SMA (50) to be greater than X to avoid thinly traded stocks.
def condition8 = avgVol >= minVol;

#Require the price to be greater than SMA (50) for the past X days to avoid volative stocks.
def condition9 = ma50Close >= ma50CloseDays;

#Require the 50 and 150 day SMAs to be trending positive for the past 21 bars.
def condition10 = ma50 > ma50Trend;
def condition11 = ma150 > ma150Trend;

#Plot results
plot scan = condition1 and condition2 and condition3 and condition4 and condition5 and condition6 and condition7 and condition8 and condition9 and condition10 and condition11;

The scan provides the following results:


The top 5 results are way below my threshold of within 25% of a 52 week high and when looking at the charts the 200 day SMA is greater than the 150 day SMA and the 150 day SMA is greater than the 50 day SMA - basically the exact opposite of what I'm looking for.

Any help is greatly appreciated!

reply to post180

i don't have a good answer for you.
maybe the combined lengths are too long, trying to access data that isn't available. i forget how far back a scan can read data.
https://usethinkscript.com/threads/fib-scan-watchlist.9857/#post-126493

change the average lengths to 10,20,30 and compare the results, and see if the results are good.


here is a lower study for testing.
it plots rows of dots of the 11 true/false conditions.


Code:
#chat180_conditions

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-9#post-133775
#Kevinabrahamson  #180

#I wrote the following stock screener code but found that it gives me a few results that break just about every condition in my script. I am new to ThinkScript so believe I may be doing something wrong.


declare lower;

DefineGlobalColor("true", color.green);
DefineGlobalColor("false", color.red);
DefineGlobalColor("all", color.cyan);
DefineGlobalColor("none", color.orange);
# GlobalColor("x")

#Variables
def minPrice = 1.00;     # Define minimum stock price.
def minAboveLow = 0.30;  # Define minimum % above 52 week low.
def maxBelowHigh = 0.25; # Define maximum % below 52 week high.
def ma50CloseDays = 10;  # Define number of days for stock to close above the 50 day moving average.
def minVol = 500000;     # Define the minimum 50 day average volume.

#Define stock price for screening.
def price = close;

#Define moving averages
def ma50 = SimpleMovingAvg(price, 50);   #50 day price SMA.
def ma150 = SimpleMovingAvg(price, 150); #150 day price SMA.
def ma200 = SimpleMovingAvg(price, 200); #200 day price SMA.

#Define moving average trends
def ma50Trend = SimpleMovingAvg(price, 50)[21];   #50 day price SMA from 21 bars ago.
def ma150Trend = SimpleMovingAvg(price, 150)[21]; #150 day price SMA from 21 bars ago.
def ma200Trend = SimpleMovingAvg(price, 200)[63];  #200 day price SMA from 63 bars ago.

#Define average volume
def avgVol = SimpleMovingAvg(volume, 50); #50 day volume SMA.

#Define days closing above SMA (50)
def ma50Close = Sum("data" = price > SimpleMovingAvg(close, 50), "length" = ma50CloseDays);

#Define 52 week high and low
def low52 = Lowest(price, 252);   #Lowest close from teh past 252 bars.
def high52 = Highest(price, 252); #Highest close from the past 252 bars.

def condition1 = price > ma50 and price > ma150 and price > ma200;
def condition2 = ma50 > ma150;
def condition3 = ma150 > ma200;
def condition4 = ma200 > ma200Trend;
def condition5 = price >= (1 + minAboveLow) * low52;
def condition6 = price >= (1 - maxBelowHigh) * high52;

#Require price to be greater than $1.00 to avoid penny stocks.
def condition7 = price >= minPrice;

#Require volume SMA (50) to be greater than X to avoid thinly traded stocks.
def condition8 = avgVol >= minVol;

#Require the price to be greater than SMA (50) for the past X days to avoid volative stocks.
def condition9 = ma50Close >= ma50CloseDays;

#Require the 50 and 150 day SMAs to be trending positive for the past 21 bars.
def condition10 = ma50 > ma50Trend;
def condition11 = ma150 > ma150Trend;


addchartbubble(0, 0,
ma50Close
, color.yellow, no);




#Plot results
def all = condition1 and condition2 and condition3 and condition4 and condition5 and condition6 and condition7 and condition8 and condition9 and condition10 and condition11;

def none = !condition1 and !condition2 and !condition3 and !condition4 and !condition5 and !condition6 and !condition7 and !condition8 and !condition9 and !condition10 and !condition11;

plot scan = all;
scan.setdefaultcolor(color.cyan);
scan.SetLineWeight(3);

#The scan provides the following results:
# The top 5 results are way below my threshold of within 25% of a 52 week high
# and when looking at the charts the 200 day SMA is greater than the 150 day SMA and the 150 day SMA is greater than the 50 day SMA - basically the exact opposite of what I'm looking for.

# plot dot rows for conditions
input all_same_color = yes;
def all2 = (all_same_color and all);
def none2 = (all_same_color and none);

def space = 0.08;
def na = double.nan;
plot z1 = if isnan(close) then na else (1 * space);
plot z2 = if isnan(close) then na else (2 * space);
plot z3 = if isnan(close) then na else (3 * space);
plot z4 = if isnan(close) then na else (4 * space);
plot z5 = if isnan(close) then na else (5 * space);
plot z6 = if isnan(close) then na else (6 * space);
plot z7 = if isnan(close) then na else (7 * space);
plot z8 = if isnan(close) then na else (8 * space);
plot z9 = if isnan(close) then na else (9 * space);
plot z10 = if isnan(close) then na else (10 * space);
plot z11 = if isnan(close) then na else (11 * space);

def size = 4;
z1.SetPaintingStrategy(PaintingStrategy.POINTS);
z1.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition1 then GlobalColor("true") else GlobalColor("false"));
z1.SetLineWeight(size);
z1.HideBubble();

z2.SetPaintingStrategy(PaintingStrategy.POINTS);
z2.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition2 then GlobalColor("true") else GlobalColor("false"));
z2.SetLineWeight(size);
z2.HideBubble();

z3.SetPaintingStrategy(PaintingStrategy.POINTS);
z3.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition3 then GlobalColor("true") else GlobalColor("false"));
z3.SetLineWeight(size);
z3.HideBubble();

z4.SetPaintingStrategy(PaintingStrategy.POINTS);
z4.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition4 then GlobalColor("true") else GlobalColor("false"));
z4.SetLineWeight(size);
z4.HideBubble();

z5.SetPaintingStrategy(PaintingStrategy.POINTS);
z5.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition5 then GlobalColor("true") else GlobalColor("false"));
z5.SetLineWeight(size);
z5.HideBubble();

z6.SetPaintingStrategy(PaintingStrategy.POINTS);
z6.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition6 then GlobalColor("true") else GlobalColor("false"));
z6.SetLineWeight(size);
z6.HideBubble();

z7.SetPaintingStrategy(PaintingStrategy.POINTS);
z7.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition7 then GlobalColor("true") else GlobalColor("false"));
z7.SetLineWeight(size);
z7.HideBubble();

z8.SetPaintingStrategy(PaintingStrategy.POINTS);
z8.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition8 then GlobalColor("true") else GlobalColor("false"));
z8.SetLineWeight(size);
z8.HideBubble();

z9.SetPaintingStrategy(PaintingStrategy.POINTS);
z9.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition9 then GlobalColor("true") else GlobalColor("false"));
z9.SetLineWeight(size);
z9.HideBubble();

z10.SetPaintingStrategy(PaintingStrategy.POINTS);
z10.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition10 then GlobalColor("true") else GlobalColor("false"));
z10.SetLineWeight(size);
z10.HideBubble();

z11.SetPaintingStrategy(PaintingStrategy.POINTS);
z11.AssignValueColor(if all2 then GlobalColor("all") else if none2 then GlobalColor("none") else if condition11 then GlobalColor("true") else GlobalColor("false"));
z11.SetLineWeight(size);
z1.HideBubble();

plot zz = 1;
zz.setdefaultcolor(color.gray);

#

P5rFknr.jpg
 
there are several things wrong with your question.

there is no draw function.
there is no study function.

learn some of the basic functions in thinkscript, then you will have an idea of what is possible.
https://tlc.thinkorswim.com/center/reference/thinkScript/tutorials



thinkscript can't read data points from objects manually drawn on a chart. i assume that is what you want to have happen, since you didn't provide any rules or conditions, to define the start and stop times of the rectangle.


if you define your buy conditions, they might be able to be added to one of these studies.

https://usethinkscript.com/threads/dynamic-risk-reward-study-for-thinkorswim.8615/#post-80068

https://usethinkscript.com/threads/thinkorswim-risk-reward-indicator.7210/page-2#post-74034

https://usethinkscript.com/threads/intraday-position-size-calculator-help.7077/#post-68449


or search for risk reward
or position size
Thanks for this. Now I know where to begin on how to Learn Thinkscript. Perfect !!!!
 
Hi,

Could someone help me with the code to show the distance in % terms between a chosen SMA/EMA and the daily ATR and/or Weekly/Session/Monthly VWAP ?

ChatGPT gave me start, but I don't want it to plot, I'd like for it to show as seperate labels. First label would be % away from ATR and second label would be % away from selected VWAP. And the EMA/SMA is adjustable (both the period and the type)

Code:
# Input for Moving Average Type
input maType = {default "SMA", "EMA"};

# Input for Moving Average Period
input maPeriod = 20;

# Input for VWAP Timeframe
input vwapTimeframe = {default "Daily", "Weekly", "Monthly"};

# Calculate Moving Average
def ma;
switch (maType) {
    case "SMA":
        ma = SimpleMovingAvg(close, maPeriod);
    case "EMA":
        ma = ExpAverage(close, maPeriod);
}

# Calculate VWAP based on selected timeframe
def vwap;
switch (vwapTimeframe) {
    case "Daily":
        vwap = VWAP();
    case "Weekly":
        vwap = VWAP(overlap = "WEEK");
    case "Monthly":
        vwap = VWAP(overlap = "MONTH");
}

# Calculate Percentage Difference between MA and VWAP
def percentDifference = (ma - vwap) / ma * 100;

# Plot the Percentage Difference
plot PercentDiffPlot = percentDifference;
PercentDiffPlot.SetDefaultColor(GetColor(1));  # Adjust color as needed
PercentDiffPlot.SetLineWeight(2);
PercentDiffPlot.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
PercentDiffPlot.AssignValueColor(if percentDifference > 0 then Color.GREEN else Color.RED);
PercentDiffPlot.SetLineWeight(2);
PercentDiffPlot.SetDefaultColor(Color.GRAY);

# Add a reference line at zero
AddReferenceLine(0, "Zero Line", Color.GRAY);
 
Last edited:

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
251 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