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:
Yes, I'm finding that it can be tricky to obtain ThinkScript code with out errors from ChatGPT3.5. I haven't subscribed to ChatGPT4 to see if its better at coding. Which version are you using, MerryDay?

I am fortunate to have been given the ChatGPT Enterprise to play with.
Yes, each version that comes out builds on the previous versions.
But ThinkScript has a tiny number of users relatively. I don't think you will see explosive growth differences in any version.
It has taken a year for AI to incorporate basic TS syntax. I expect it will take 2years or more for it to assimilate TS complex coding models.
 
Microsoft CoPilot is now a part of the WIndows 11 OS. You can upload images, then ask questions about the uploaded image. Yesterday, I uploaded a TOS chart, and asked it a few questions about the probable direction of the stock as illustrated by the chart. It did a pretty good job. Give it a try. CoPilot is based on ChatGPT 4, so it is the current version. And it's free.
 
Hello guys,

I'm new to the forum and new to coding. I came up with a script that would return stocks that traded more than 1RVOL yesterday, closed at the higher/lower 25% of the day range, and are trading near yesterday's high or low. This is a trend continuation set up. I am getting delays on the results. Stocks that meet my criteria at let's say 935EST are not showing on my dynamic watchlist until after 10am. Is there something wrong with my code?

# Inputs
input rvolThreshold = 1.5;
input atrLength = 14;
input longCloseRangePercentage = 75;
input shortCloseRangePercentage = 25;
input minATR = 1;

# Calculate RVOL
def dailyVolume = volume(period = "DAY")[0];
def avgDailyVolume = Average(volume, 20);
def rvol = dailyVolume / avgDailyVolume;

# Calculate ATR and Day Range
def atr = ATR(atrLength);
def dayRange = high - low;

# Check if ATR is greater than or equal to 1
def atrCondition = atr >= minATR;
# Long Side Conditions for Day 1
def longCloseAboveOpen = close[1] > open[1];
def longRvol = rvol[1] >= rvolThreshold;
def longDayRange = dayRange[1] > atr[1];
def longCloseRange = close[1] >= high[1] - (dayRange[1] * (1 - longCloseRangePercentage / 100));
def longDay1Condition = longCloseAboveOpen and longRvol and longDayRange and longCloseRange and atrCondition[1];

# Short Side Conditions for Day 1
def shortCloseBelowOpen = close[1] < open[1];
def shortRvol = rvol[1] >= rvolThreshold;
def shortDayRange = dayRange[1] > atr[1];
def shortCloseRange = close[1] <= low[1] + (dayRange[1] * (shortCloseRangePercentage / 100));
def shortDay1Condition = shortCloseBelowOpen and shortRvol and shortDayRange and shortCloseRange and atrCondition[1];


# Get previous day's high and low
def prevDayHigh = high(period = "DAY")[1];
def prevDayLow = low(period = "DAY")[1];

# Calculate Day 2 retracement levels for both Long and Short sides
def rangeDay2Long = (prevDayHigh - prevDayLow) * 0.51 + prevDayLow;
def rangeDay2Short = (prevDayHigh - prevDayLow) * 0.49 + prevDayLow;

# Initialize the retracement condition variables for both Long and Short sides
def retracementConditionLong;
def retracementConditionShort;
if !isNaN(close[1]) {
retracementConditionLong = CompoundValue(1, if low >= rangeDay2Long then 1 else 0, 1);
retracementConditionShort = CompoundValue(1, if high <= rangeDay2Short then 1 else 0, 1);
} else {
retracementConditionLong = Double.NaN;
retracementConditionShort = Double.NaN;
}

# Long Side Conditions for Day 2
def longCondition1 = high >= prevDayHigh * 0.99;
def longConditionDay2 = longCondition1 and retracementConditionLong;

# Short Side Conditions for Day 2
def shortCondition1 = low <= prevDayLow * 1.01;
def shortConditionDay2 = shortCondition1 and retracementConditionShort;

# Combine Day 1 and Day 2 Conditions for Long and Short sides
def combinedLongCondition = longDay1Condition and longConditionDay2;
def combinedShortCondition = shortDay1Condition and shortConditionDay2;

plot scan = combinedLongCondition or combinedShortCondition;
 
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: 90
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);

#
 

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