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:
Not sure if this is the right place for this thread, but I'll give it a try.

I've been reading Brian Shannon's Book "Anchored VWAP" and found it to be very helpful even for intraday trading. I began writing an AWAP thinkscript which is in the spirit of the book.

Objective: Create a thinkscript that draws 2 separate AVWAP lines, one anchored to the High-Of-Day and the other to the Low-Of-Day.
Potential issues: I'm not sure if thinkscript can redraw the AVWAP lines if the HOD/LOD changes.

Code snippet of something I tried
----
Ruby:
#for ETH to RTH crossover and day to day crossover.
def isCrossover = (isRTH and !isRTH[1]) or (GetYYYYMMDD() != GetYYYYMMDD()[1]);

#Get High Of Day
def hodValue = if isCrossover then high
    else if high > hodValue[1] then high
    else hodValue[1];

#Get the timestamp of the HOD - to be used for identifying bars past this time for VWAP calculation
def getHodTime = if high == HighestAll(hodValue) then GetTime() else getHodTime[1];

def postHod = if SecondsTillTime(getHodTime) <= 0 then 1 else 0;
#I get an error on this previous line due to getHodTime not being constant.
---
The thought was to get the timestamp of the HOD, the apply the following code to calculate AVWAP. The following is not my code but I've seen it on the forums and it works well.
---
Ruby:
input anchorTime = 1030;
def postAnchorTime = if SecondsTillTime(anchorTime) <= 0 and today then 1 else 0;

plot anchoredVWAP = TotalSum(if postAnchorTime then ((high+low+close+open)/4)*(volume) else 0)/TotalSum(if postAnchorTime then volume else 0);
---

How do i get AVWAP to anchor to the HOD and LOD?

The screenshot is what' i'm looking for. Note: the screenshot had anchor points set manually. I'm looking for auto anchor points attached to the HOD/LOD.

Thank you.
 

Attachments

  • 2023-06-04_16-24-55.png
    2023-06-04_16-24-55.png
    26.6 KB · Views: 233
Last edited:

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

# VWAP Bands Strategy with RSI Filter
# Buy when price crosses below VWAP LowerBand and RSI is below 30
# Sell when price crosses above VWAP UpperBand and RSI is above 70

input numDevDn = -2.0;
input numDevUp = 2.0;
input timeFrame = {default DAY, WEEK, MONTH};

def cap = GetAggregationPeriod();
def errorInAggregation =
timeFrame == timeFrame.DAY and cap >= AggregationPeriod.WEEK or
timeFrame == timeFrame.WEEK and cap >= AggregationPeriod.MONTH;
Assert(!errorInAggregation, "timeFrame should be not less than current chart aggregation period");

def yyyyMmDd = GetYYYYMMDD();
def periodIndx;
switch (timeFrame) {
case DAY:
periodIndx = yyyyMmDd;
case WEEK:
periodIndx = Floor((DaysFromDate(First(yyyyMmDd)) + GetDayOfWeek(First(yyyyMmDd))) / 7);
case MONTH:
periodIndx = RoundDown(yyyyMmDd / 100, 0);
}
def isPeriodRolled = CompoundValue(1, periodIndx != periodIndx[1], yes);

def volumeSum;
def volumeVwapSum;
def volumeVwap2Sum;

if (isPeriodRolled) {
volumeSum = volume;
volumeVwapSum = volume * vwap;
volumeVwap2Sum = volume * Sqr(vwap);
} else {
volumeSum = CompoundValue(1, volumeSum[1] + volume, volume);
volumeVwapSum = CompoundValue(1, volumeVwapSum[1] + volume * vwap, volume * vwap);
volumeVwap2Sum = CompoundValue(1, volumeVwap2Sum[1] + volume * Sqr(vwap), volume * Sqr(vwap));
}
def price = volumeVwapSum / volumeSum;
def deviation = Sqrt(Max(volumeVwap2Sum / volumeSum - Sqr(price), 0));

plot VWAP = price;
plot UpperBand = price + numDevUp * deviation;
plot LowerBand = price + numDevDn * deviation;

VWAP.SetDefaultColor(GetColor(0));
UpperBand.SetDefaultColor(GetColor(2));
LowerBand.SetDefaultColor(GetColor(4));

# RSI Calculation
def length = 14;
def NetChgAvg = MovingAverage(AverageType.EXPONENTIAL, close - close[1], length);
def TotChgAvg = MovingAverage(AverageType.EXPONENTIAL, AbsValue(close - close[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = Round(50 * (ChgRatio + 1), 0);

# Strategy
def buySignal = close crosses below LowerBand and RSI < 30;
def sellSignal = close crosses above UpperBand and RSI > 70;

# Plotting Buy and Sell signals on chart
plot BuySignal = if BuySignal then low else Double.NaN;
plot SellSignal = if SellSignal then high else Double.NaN;

BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
BuySignal.SetDefaultColor(Color.GREEN);
SellSignal.SetDefaultColor (Color.RED);
those area created error
plot BuySignal =
plot SellSignal =
I didn't know why
 
Hi everyone,

I was trying to write a code that calculates the distance from 9ema to the VWAP, but there is something wrong as the result is not correct, Can anyone take a look at this script to see what is the problem? Thanks for your help.

Here is the code:

# Calculate the 9EMA for the current chart time frame
input length = 9;
def ema9 = ExpAverage(close, length);

# Calculate the VWAP for the current chart time frame
def vwapValue = vwap;

# Calculate the distance between 9EMA and VWAP
def distance = ema9 - vwapValue;

# Calculate the percentage distance between 9EMA and VWAP
def percentageDistance = (distance / vwapValue) * 100;

# Display the percentage distance as a label on the chart
AddLabel(yes, "Distance from VWAP (%): " + AsPercent(percentageDistance / 100), Color.WHITE);
 
PLEASE HELP ME
Not sure if it's possible but, I need script so my watchlist will display EXACT LAST TRADED PRICE for stocks in afterhours session. Not Last closing price, not BID or ASK, no MARK price which is very misleading, but Last price of the stack value traded last - not always but should be betwen of BID ans ASK range.
I was able to find one for displaying EXACT LAST price on Chart, but I must have one in watchlist somehow. Is it anyone that can HELP?? Please.

P.S. This script for displaying last price on chart - but I need one in watchlist >

# After Hours Last Price
# Displays the exact last price of a stock during aftermarket trading session

declare lower;

# Define the aggregation period (e.g., 1 minute, 5 minutes, etc.)
input aggregationPeriod = AggregationPeriod.MIN;

# Calculate the aftermarket last price
def lastPrice = close(period = aggregationPeriod);
plot AfterHoursLastPrice = lastPrice;

# Customize the appearance of the plot
AfterHoursLastPrice.SetDefaultColor(color.white);
AfterHoursLastPrice.SetStyle(Curve.SHORT_DASH);
 
I've been currently running a Delta indicator similar to the MACD. Essentially I asked Chatgpt to code me a delta indicator along with a moving average line and took the histogram section of the MACD and applied it together. The issue Im running into is when the delta reaches an upper threshold and lower threshold. It double.nan and disables it from the chart. Can anyone help me fix this section of the script so that it doesn't double.nan and still plots the last known number?

Here's the script:
Line 32 is where my issue is and Im just not advanced enough to figure it out.
Ruby:
declare lower;

# Define the input parameters
input length = 20;
input showDeltaExp = yes;
input DexTrendLbl = yes;
input DexStrengthLbl = yes;
input DiffLbl = yes;

# Define the plot data
def delta = Delta();
def deltaExp = TEMA(delta - delta[length]);
def deltaAccum = Sum(deltaExp, length);

# Add a zero line to the chart
plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);
ZeroLine.SetStyle(Curve.SHORT_DASH);


# Calculate the smoothed line using a simple moving average
def smaDeltaExp = SimpleMovingAvg(deltaExp, length);


# Plot the smoothed line
plot SmoothedLine = smaDeltaExp;
SmoothedLine.AssignValueColor(if Smoothedline > zeroline then Color.green else color.dark_red);
SmoothedLine.HideBubble();
SmoothedLine.HideTitle();



# Plot The Diff
plot Diff = deltaExp - smoothedLine;
Diff.SetDefaultColor(GetColor(5));
Diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Diff.SetLineWeight(3);
Diff.DefineColor("Positive and Up", Color.GREEN);
Diff.DefineColor("Positive and Down", Color.DARK_GREEN);
Diff.DefineColor("Negative and Down", Color.RED);
Diff.DefineColor("Negative and Up", Color.dark_red);
Diff.AssignValueColor(if Diff >= 0 then if Diff > Diff[1] then Diff.color("Positive and Up") else Diff.color("Positive and Down") else if Diff < Diff[1] then Diff.color("Negative and Down") else Diff.color("Negative and Up"));


# Add a legend
AddLabel(DexTrendLbl, "DeXTrend: " + AsText(deltaExp, NumberFormat.TWO_DECIMAL_PLACES), if DeltaExpansion > 0 then Color.GREEN else Color.Yellow);


AddLabel(DiffLbl, "Diff: " + AsText(diff, NumberFormat.TwO_DECIMAL_PLACES),  if Diff < 0 then Color.Red else if Diff > .5 then color.dark_orange else if Diff < -.5 then color.dark_orange else color.green);

Here's a photo of what its suppose to look like when there is strength to the call side, as well as another indicator on the price chart that paintbars the magenta for entries. Has similar coding.
3zBMd91.png


This is what i get when it double.nan's. Which also removes the magenta paintbar.
oaYITA4.png


any help would be greatly appreciated and would further educate me in coding as well to fix the GWAP indicator as well when it Nan's out or zeros. Thank you!
 
Last edited:
that's great if it can provide something useful for your project.
i agree, new technology always seems to shift the job market, usually to something more automated related.
my beef with it is, people who don't know any thinkscript are asking it to generate a code, and expect it to work, and it doesn't. i think a tool shouldn't exist until it works.
i have no position to protect. i'm just a guy, doing a hobby. i have random pockets of free time, that i like to use to volunteer on this site, to help out others.
To be sure you have a knack at coding few of us do.

Curious, do you trade on TOS?
 
why is it i see Nothing on Using CHAT GPT in regards to what it can or cannot do
with ThinkScript . R there any working Prompts .what up with the silence .

Watch Tony Zhang of OptionsPlay's AI videos
He managed to get correction done on the errors. He apparently asked ChatGPT to correct the specific error and got the correction that worked. Good Luck.
 
Last edited by a moderator:
can one help please. this code from chat has error:
# Define input parameters
input underlyingSymbol = "SPX";
input volatility = imp_volatility(underlyingSymbol);

# Get option data
def optionChain = OptionChain(underlyingSymbol, GetYYYYMMDD());
def strikeCount = optionChain.GetStrikeCount();
def closePrice = close(underlyingSymbol);

# Loop through each strike and calculate gamma exposure for call and put options
for i = 0 to strikeCount - 1 {
def strike = optionChain.GetStrike(i);
def callOption = optionChain.GetCall(i);
def putOption = optionChain.GetPut(i);
def callBidPrice = bid(callOption);
def callAskPrice = ask(callOption);
def callMidPrice = (callBidPrice + callAskPrice) / 2;
def putBidPrice = bid(putOption);
def putAskPrice = ask(putOption);
def putMidPrice = (putBidPrice + putAskPrice) / 2;
def callGamma = Gamma(closePrice, volatility);
def callGammaExposure = callGamma * callMidPrice * 100;
def putGamma = Gamma(closePrice, volatility);
def putGammaExposure = putGamma * putMidPrice * 100;

# Plot gamma exposure as horizontal lines on the chart
plot CallGEXLine = if IsNaN(close) then Double.NaN else callGammaExposure;
CallGEXLine.SetDefaultColor(Color.GREEN);
CallGEXLine.SetStyle(Curve.FIRM);
CallGEXLine.SetLineWeight(1);
CallGEXLine.HideBubble();
plot PutGEXLine = if IsNaN(close) then Double.NaN else putGammaExposure;
PutGEXLine.SetDefaultColor(Color.RED);
PutGEXLine.SetStyle(Curve.FIRM);
PutGEXLine.SetLineWeight(1);
PutGEXLine.HideBubble();
 
Hello - I'm new to the forum and I'm hoping someone can help me fix this momentum indicator i've been working on. I can't get the momentum histogram to show at the same time as the Trend line. Can anyone help?

# Trend Momentum Indicator (TMI) for Thinkorswim
# Developed by Fluna
Declare Lower;
# Input parameters
input trendLength = 14;
input momentumLength = 12;
input volatilityLength = 20;
input momentumThreshold = 0.5;
input volatilityThreshold = 1.0;

# Calculate trend direction
def trend = if close > MovingAverage(AverageType.EXPONENTIAL, close, trendLength) then 1 else -1;

# Calculate momentum
def momentum = (close - close[momentumLength]) / close[momentumLength];

# Calculate volatility
def volatility = AbsValue(Log(high / low));

# Plot trend line
plot trendLine = trend;
trendLine.SetDefaultColor(Color.CYAN);

# Plot momentum histogram
plot momentumHistogram = momentum;
momentumHistogram.AssignValueColor(if momentum >= momentumThreshold then Color.GREEN else Color.RED);
momentumHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
momentumHistogram.SetLineWeight(2);

# Plot volatility line
plot volatilityLine = volatility;
volatilityLine.SetDefaultColor(Color.BLUE);
volatilityLine.SetStyle(Curve.SHORT_DASH);

# Add alerts
alert(trendLine crosses above 0, "Bullish Trend", Alert.BAR, Sound.Bell);
alert(trendLine crosses below 0, "Bearish Trend", Alert.BAR, Sound.Bell);
alert(momentumHistogram crosses above momentumThreshold, "Strong Momentum Up", Alert.BAR, Sound.Chimes);
alert(momentumHistogram crosses below -momentumThreshold, "Strong Momentum Down", Alert.BAR, Sound.Chimes);
alert(volatilityLine crosses above volatilityThreshold, "High Volatility", Alert.BAR, Sound.Ring);
alert(volatilityLine crosses below volatilityThreshold, "Low Volatility", Alert.BAR, Sound.Ring);
 
Can someone correct the errors for me
Error_TOS Code chatGPT Auto Trade Script_EMA cross + RSI,Macd

# Auto Trading Strategy with Time Frame Optimization

input rsiLength = 14;
input overboughtLevel = 70;
input oversoldLevel = 30;
input macdFastLength = 12;
input macdSlowLength = 26;
input macdLength = 9;

def optimalTimeFrame = OptimizeDataRange(5, 60, 5, "minutes"); # Time frame optimization range

def fastMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def slowMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def rsi = RSI(length = rsiLength);
def macdLine = MACD(close, macdFastLength, macdSlowLength, macdLength).Diff;

def bullishSignal = Crosses(fastMA, slowMA, CrossingDirection.ABOVE) && rsi < oversoldLevel && macdLine > 0;
def bearishSignal = Crosses(fastMA, slowMA, CrossingDirection.BELOW) && rsi > overboughtLevel && macdLine < 0;

# Entry and Exit Conditions
def entry = if bullishSignal then 1
else if bearishSignal then -1
else 0;

def exit = if bullishSignal then -1
else if bearishSignal then 1
else 0;

# Submit Orders
AddOrder(OrderType.BUY_TO_OPEN, entry > 0, 1, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, exit > 0, 1, tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "Sell");

# Plotting Moving Averages
plot FastMAPlot = fastMA;
FastMAPlot.SetDefaultColor(GetColor(1));
FastMAPlot.SetLineWeight(2);

plot SlowMAPlot = slowMA;
SlowMAPlot.SetDefaultColor(GetColor(2));
SlowMAPlot.SetLineWeight(2);

# Plotting RSI
plot RSILine = rsi;
RSILine.SetDefaultColor(GetColor(3));
RSILine.SetLineWeight(2);
RSILine.HideBubble();

# Plotting MACD
plot MACDLine = macdLine;
MACDLine.SetDefaultColor(GetColor(4));
MACDLine.SetLineWeight(2);
MACDLine.HideBubble();
 
Last edited by a moderator:
Hello - I'm new to the forum and I'm hoping someone can help me fix this momentum indicator i've been working on. I can't get the momentum histogram to show at the same time as the Trend line. Can anyone help?

# Trend Momentum Indicator (TMI) for Thinkorswim
# Developed by Fluna
Declare Lower;
# Input parameters
input trendLength = 14;
input momentumLength = 12;
input volatilityLength = 20;
input momentumThreshold = 0.5;
input volatilityThreshold = 1.0;

# Calculate trend direction
def trend = if close > MovingAverage(AverageType.EXPONENTIAL, close, trendLength) then 1 else -1;

# Calculate momentum
def momentum = (close - close[momentumLength]) / close[momentumLength];

# Calculate volatility
def volatility = AbsValue(Log(high / low));

# Plot trend line
plot trendLine = trend;
trendLine.SetDefaultColor(Color.CYAN);

# Plot momentum histogram
plot momentumHistogram = momentum;
momentumHistogram.AssignValueColor(if momentum >= momentumThreshold then Color.GREEN else Color.RED);
momentumHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
momentumHistogram.SetLineWeight(2);

# Plot volatility line
plot volatilityLine = volatility;
volatilityLine.SetDefaultColor(Color.BLUE);
volatilityLine.SetStyle(Curve.SHORT_DASH);

# Add alerts
alert(trendLine crosses above 0, "Bullish Trend", Alert.BAR, Sound.Bell);
alert(trendLine crosses below 0, "Bearish Trend", Alert.BAR, Sound.Bell);
alert(momentumHistogram crosses above momentumThreshold, "Strong Momentum Up", Alert.BAR, Sound.Chimes);
alert(momentumHistogram crosses below -momentumThreshold, "Strong Momentum Down", Alert.BAR, Sound.Chimes);
alert(volatilityLine crosses above volatilityThreshold, "High Volatility", Alert.BAR, Sound.Ring);
alert(volatilityLine crosses below volatilityThreshold, "Low Volatility", Alert.BAR, Sound.Ring);
All are plotting, the issue comes down to the mathematical results. Since your trend line will always be +1 or -1, the small values for your histogram and vol line results are much smaller values (.0011975 and .0044909, respectively, for 7/5/23) relative to the +/-1, so they're barely blips on the graph. Multiply the results of these by 10 or 100 to shift the decimal over and you'll now have results that will better show visual change in values against your +/-1 range.

Something like this is all you need:
plot momentumHistogram = momentum*10;
plot volatilityLine = volatility*10;
 
Can someone correct the errors for me
Error_TOS Code chatGPT Auto Trade Script_EMA cross + RSI,Macd

# Auto Trading Strategy with Time Frame Optimization

input rsiLength = 14;
input overboughtLevel = 70;
input oversoldLevel = 30;
input macdFastLength = 12;
input macdSlowLength = 26;
input macdLength = 9;

def optimalTimeFrame = OptimizeDataRange(5, 60, 5, "minutes"); # Time frame optimization range

def fastMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def slowMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def rsi = RSI(length = rsiLength);
def macdLine = MACD(close, macdFastLength, macdSlowLength, macdLength).Diff;

def bullishSignal = Crosses(fastMA, slowMA, CrossingDirection.ABOVE) && rsi < oversoldLevel && macdLine > 0;
def bearishSignal = Crosses(fastMA, slowMA, CrossingDirection.BELOW) && rsi > overboughtLevel && macdLine < 0;

# Entry and Exit Conditions
def entry = if bullishSignal then 1
else if bearishSignal then -1
else 0;

def exit = if bullishSignal then -1
else if bearishSignal then 1
else 0;

# Submit Orders
AddOrder(OrderType.BUY_TO_OPEN, entry > 0, 1, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, exit > 0, 1, tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "Sell");

# Plotting Moving Averages
plot FastMAPlot = fastMA;
FastMAPlot.SetDefaultColor(GetColor(1));
FastMAPlot.SetLineWeight(2);

plot SlowMAPlot = slowMA;
SlowMAPlot.SetDefaultColor(GetColor(2));
SlowMAPlot.SetLineWeight(2);

# Plotting RSI
plot RSILine = rsi;
RSILine.SetDefaultColor(GetColor(3));
RSILine.SetLineWeight(2);
RSILine.HideBubble();

# Plotting MACD
plot MACDLine = macdLine;
MACDLine.SetDefaultColor(GetColor(4));
MACDLine.SetLineWeight(2);
MACDLine.HideBubble();
reply to post137

you didn't describe what you are trying to do, so i can't fix this.
i can get rid of the errors, and have some lines draw, but i have no idea if it's what you want.


this is a strategy. it has addorder() functions.
this is plotting variations of what are normally lower studies, macd and rsi, on the main chart.


there is no function called OptimizeDataRange( ).
no idea what you want for this,
def optimalTimeFrame = OptimizeDataRange(5, 60, 5, "minutes"); # Time frame optimization range

verify average function parameters. using optimalTimeFrame as a length in average.
def fastMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);

MovingAverage ( averageType, data, length);
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Tech-Analysis/MovingAverage


parameters in macd function are wrong
def macdLine = MACD(close, macdFastLength, macdSlowLength, macdLength).Diff;
should be: length , length , length , type , yes/no
close isn't valid
https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD


can't have same variable on both sides of an equals sign
plot MACDLine = macdLine;
change to
plot MACDLine2 = macdLine;


Code:
#chat137_fix_macd_strat

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-7#post-127089
#prdgsdz  7/5  #137

#Can someone correct the errors for me
#Error_TOS Code chatGPT Auto Trade Script_EMA cross + RSI,Macd

# Auto Trading Strategy with Time Frame Optimization


input rsiLength = 14;
input overboughtLevel = 70;
input oversoldLevel = 30;
input macdFastLength = 12;
input macdSlowLength = 26;
input macdLength = 9;

#def optimalTimeFrame = OptimizeDataRange(5, 60, 5, "minutes"); # Time frame optimization range
input optimalTimeFrame = 5;

def fastMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def slowMA = MovingAverage(AverageType.EXPONENTIAL, close, optimalTimeFrame);
def rsi = RSI(length = rsiLength);
#def macdLine = MACD(close, macdFastLength, macdSlowLength, macdLength).Diff;
def macdLine = MACD(macdFastLength, macdSlowLength, macdLength).Diff;

def bullishSignal = Crosses(fastMA, slowMA, CrossingDirection.ABOVE) && rsi < oversoldLevel && macdLine > 0;
def bearishSignal = Crosses(fastMA, slowMA, CrossingDirection.BELOW) && rsi > overboughtLevel && macdLine < 0;

# Entry and Exit Conditions
def entry = if bullishSignal then 1
else if bearishSignal then -1
else 0;

def exit = if bullishSignal then -1
else if bearishSignal then 1
else 0;

# Submit Orders
AddOrder(OrderType.BUY_TO_OPEN, entry > 0, 1, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, exit > 0, 1, tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "Sell");

# Plotting Moving Averages
plot FastMAPlot = fastMA;
FastMAPlot.SetDefaultColor(GetColor(1));
FastMAPlot.SetLineWeight(2);

plot SlowMAPlot = slowMA;
SlowMAPlot.SetDefaultColor(GetColor(2));
SlowMAPlot.SetLineWeight(2);

# Plotting RSI
plot RSILine = rsi;
RSILine.SetDefaultColor(GetColor(3));
RSILine.SetLineWeight(2);
RSILine.HideBubble();

# Plotting MACD
plot MACDLine2 = macdLine;
MACDLine2.SetDefaultColor(GetColor(4));
MACDLine2.SetLineWeight(2);
MACDLine2.HideBubble();
#
 
Hello - I'm new to the forum and I'm hoping someone can help me fix this momentum indicator i've been working on. I can't get the momentum histogram to show at the same time as the Trend line. Can anyone help?

# Trend Momentum Indicator (TMI) for Thinkorswim
# Developed by Fluna
Declare Lower;
# Input parameters
input trendLength = 14;
input momentumLength = 12;
input volatilityLength = 20;
input momentumThreshold = 0.5;
input volatilityThreshold = 1.0;

# Calculate trend direction
def trend = if close > MovingAverage(AverageType.EXPONENTIAL, close, trendLength) then 1 else -1;

# Calculate momentum
def momentum = (close - close[momentumLength]) / close[momentumLength];

# Calculate volatility
def volatility = AbsValue(Log(high / low));

# Plot trend line
plot trendLine = trend;
trendLine.SetDefaultColor(Color.CYAN);

# Plot momentum histogram
plot momentumHistogram = momentum;
momentumHistogram.AssignValueColor(if momentum >= momentumThreshold then Color.GREEN else Color.RED);
momentumHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
momentumHistogram.SetLineWeight(2);

# Plot volatility line
plot volatilityLine = volatility;
volatilityLine.SetDefaultColor(Color.BLUE);
volatilityLine.SetStyle(Curve.SHORT_DASH);

# Add alerts
alert(trendLine crosses above 0, "Bullish Trend", Alert.BAR, Sound.Bell);
alert(trendLine crosses below 0, "Bearish Trend", Alert.BAR, Sound.Bell);
alert(momentumHistogram crosses above momentumThreshold, "Strong Momentum Up", Alert.BAR, Sound.Chimes);
alert(momentumHistogram crosses below -momentumThreshold, "Strong Momentum Down", Alert.BAR, Sound.Chimes);
alert(volatilityLine crosses above volatilityThreshold, "High Volatility", Alert.BAR, Sound.Ring);
alert(volatilityLine crosses below volatilityThreshold, "Low Volatility", Alert.BAR, Sound.Ring);

reply to post135

this has a scale factor, that auto adjusts the histogram, so it will always be at full scale of line plot, 1 to -1.
added a secondary factor (fudge , 1.1 ) to scale it to , 1.1 to -1.1. because very few bars are near the extreme limits.


Code:
#chat135_momentum_trend

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-7#post-127783
#fluna  #135
#I can't get the momentum histogram to show at the same time as the Trend line.


# Trend Momentum Indicator (TMI) for Thinkorswim
# Developed by Fluna
Declare Lower;

def bn = barnumber();

# Input parameters
input trendLength = 14;
input momentumLength = 12;
input volatilityLength = 20;
input momentumThreshold = 0.5;
input volatilityThreshold = 1.0;

# Calculate trend direction
def trend = if close > MovingAverage(AverageType.EXPONENTIAL, close, trendLength) then 1 else -1;

# Calculate momentum
#def momentum = (close - close[momentumLength]) / close[momentumLength];
def momentum2 = (close - close[momentumLength]) / close[momentumLength];

# create a scale factor on bar #1 , to fit the histo to  1 to -1
def scale = if bn == 1 then 1/highestall(absvalue(momentum2)) else scale[1];

#create a factor, so histo extends to 1.1 to -1.1
input fudge = 1.1;
def momentum = momentum2 * scale * fudge;

# Calculate volatility
def volatility = AbsValue(Log(high / low));

# Plot trend line
plot trendLine = trend;
trendLine.SetDefaultColor(Color.CYAN);

# Plot momentum histogram
plot momentumHistogram = momentum;
momentumHistogram.AssignValueColor(if momentum >= momentumThreshold then Color.GREEN else Color.RED);
momentumHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
momentumHistogram.SetLineWeight(2);

# Plot volatility line
plot volatilityLine = volatility;
volatilityLine.SetDefaultColor(Color.BLUE);
volatilityLine.SetStyle(Curve.SHORT_DASH);

# Add alerts
alert(trendLine crosses above 0, "Bullish Trend", Alert.BAR, Sound.Bell);
alert(trendLine crosses below 0, "Bearish Trend", Alert.BAR, Sound.Bell);
alert(momentumHistogram crosses above momentumThreshold, "Strong Momentum Up", Alert.BAR, Sound.Chimes);
alert(momentumHistogram crosses below -momentumThreshold, "Strong Momentum Down", Alert.BAR, Sound.Chimes);
alert(volatilityLine crosses above volatilityThreshold, "High Volatility", Alert.BAR, Sound.Ring);
alert(volatilityLine crosses below volatilityThreshold, "Low Volatility", Alert.BAR, Sound.Ring);
#

mGIHUvC.jpg
 
can one help please. this code from chat has error:
# Define input parameters
input underlyingSymbol = "SPX";
input volatility = imp_volatility(underlyingSymbol);

# Get option data
def optionChain = OptionChain(underlyingSymbol, GetYYYYMMDD());
def strikeCount = optionChain.GetStrikeCount();
def closePrice = close(underlyingSymbol);

# Loop through each strike and calculate gamma exposure for call and put options
for i = 0 to strikeCount - 1 {
def strike = optionChain.GetStrike(i);
def callOption = optionChain.GetCall(i);
def putOption = optionChain.GetPut(i);
def callBidPrice = bid(callOption);
def callAskPrice = ask(callOption);
def callMidPrice = (callBidPrice + callAskPrice) / 2;
def putBidPrice = bid(putOption);
def putAskPrice = ask(putOption);
def putMidPrice = (putBidPrice + putAskPrice) / 2;
def callGamma = Gamma(closePrice, volatility);
def callGammaExposure = callGamma * callMidPrice * 100;
def putGamma = Gamma(closePrice, volatility);
def putGammaExposure = putGamma * putMidPrice * 100;

# Plot gamma exposure as horizontal lines on the chart
plot CallGEXLine = if IsNaN(close) then Double.NaN else callGammaExposure;
CallGEXLine.SetDefaultColor(Color.GREEN);
CallGEXLine.SetStyle(Curve.FIRM);
CallGEXLine.SetLineWeight(1);
CallGEXLine.HideBubble();
plot PutGEXLine = if IsNaN(close) then Double.NaN else putGammaExposure;
PutGEXLine.SetDefaultColor(Color.RED);
PutGEXLine.SetStyle(Curve.FIRM);
PutGEXLine.SetLineWeight(1);
PutGEXLine.HideBubble();


reply to post134

no, i don't think anyone can help you.
posting just 'help please' tells us nothing.
there are too many problems with this and you didn't explain what it is supposed to do.

you told chatgpt something to make this code? then edit your post and add it.

but i will guess what you want isn't possible.


here is a study that calcs open interest for many strikes, to give you an idea of how long and complex it can be, dealing with option data.
https://usethinkscript.com/threads/option-heatmap-and-oi-strikes-for-thinkorswim.10664/

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

errors

can't use input with a function , formula
input volatility = imp_volatility(underlyingSymbol);

there is no function called OptionChain()
def optionChain = OptionChain(underlyingSymbol, GetYYYYMMDD());

likewise, this doesn't exist. no easy way to determine what are valid strikes
= optionChain.GetStrikeCount()

there are no 'for' loops
for i = 0 to strikeCount - 1 {
thinkscript has fold
https://tlc.thinkorswim.com/center/reference/thinkScript/Reserved-Words/fold

can't set variables within a fold loop, can't use def
fold can read many variables, but when finished, with hold 1 number.

can't save a symbol to a valiable ( i'm guessing that is what is intended here? )
def callOption = optionChain.GetCall(i);
 
PLEASE HELP ME
Not sure if it's possible but, I need script so my watchlist will display EXACT LAST TRADED PRICE for stocks in afterhours session. Not Last closing price, not BID or ASK, no MARK price which is very misleading, but Last price of the stack value traded last - not always but should be betwen of BID ans ASK range.
I was able to find one for displaying EXACT LAST price on Chart, but I must have one in watchlist somehow. Is it anyone that can HELP?? Please.

P.S. This script for displaying last price on chart - but I need one in watchlist >

# After Hours Last Price
# Displays the exact last price of a stock during aftermarket trading session

declare lower;

# Define the aggregation period (e.g., 1 minute, 5 minutes, etc.)
input aggregationPeriod = AggregationPeriod.MIN;

# Calculate the aftermarket last price
def lastPrice = close(period = aggregationPeriod);
plot AfterHoursLastPrice = lastPrice;

# Customize the appearance of the plot
AfterHoursLastPrice.SetDefaultColor(color.white);
AfterHoursLastPrice.SetStyle(Curve.SHORT_DASH);

reply to post128

all your code is doing is plotting close, which is the close price of current bar.

the watchlist column already has a built in function , LAST , to do this.


ARZOgHr.jpg
 
All are plotting, the issue comes down to the mathematical results. Since your trend line will always be +1 or -1, the small values for your histogram and vol line results are much smaller values (.0011975 and .0044909, respectively, for 7/5/23) relative to the +/-1, so they're barely blips on the graph. Multiply the results of these by 10 or 100 to shift the decimal over and you'll now have results that will better show visual change in values against your +/-1 range.

Something like this is all you need:
Thank you emaguireiv, super helpfull!
 
reply to post135

this has a scale factor, that auto adjusts the histogram, so it will always be at full scale of line plot, 1 to -1.
added a secondary factor (fudge , 1.1 ) to scale it to , 1.1 to -1.1. because very few bars are near the extreme limits.


Code:
#chat135_momentum_trend

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-7#post-127783
#fluna  #135
#I can't get the momentum histogram to show at the same time as the Trend line.


# Trend Momentum Indicator (TMI) for Thinkorswim
# Developed by Fluna
Declare Lower;

def bn = barnumber();

# Input parameters
input trendLength = 14;
input momentumLength = 12;
input volatilityLength = 20;
input momentumThreshold = 0.5;
input volatilityThreshold = 1.0;

# Calculate trend direction
def trend = if close > MovingAverage(AverageType.EXPONENTIAL, close, trendLength) then 1 else -1;

# Calculate momentum
#def momentum = (close - close[momentumLength]) / close[momentumLength];
def momentum2 = (close - close[momentumLength]) / close[momentumLength];

# create a scale factor on bar #1 , to fit the histo to  1 to -1
def scale = if bn == 1 then 1/highestall(absvalue(momentum2)) else scale[1];

#create a factor, so histo extends to 1.1 to -1.1
input fudge = 1.1;
def momentum = momentum2 * scale * fudge;

# Calculate volatility
def volatility = AbsValue(Log(high / low));

# Plot trend line
plot trendLine = trend;
trendLine.SetDefaultColor(Color.CYAN);

# Plot momentum histogram
plot momentumHistogram = momentum;
momentumHistogram.AssignValueColor(if momentum >= momentumThreshold then Color.GREEN else Color.RED);
momentumHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
momentumHistogram.SetLineWeight(2);

# Plot volatility line
plot volatilityLine = volatility;
volatilityLine.SetDefaultColor(Color.BLUE);
volatilityLine.SetStyle(Curve.SHORT_DASH);

# Add alerts
alert(trendLine crosses above 0, "Bullish Trend", Alert.BAR, Sound.Bell);
alert(trendLine crosses below 0, "Bearish Trend", Alert.BAR, Sound.Bell);
alert(momentumHistogram crosses above momentumThreshold, "Strong Momentum Up", Alert.BAR, Sound.Chimes);
alert(momentumHistogram crosses below -momentumThreshold, "Strong Momentum Down", Alert.BAR, Sound.Chimes);
alert(volatilityLine crosses above volatilityThreshold, "High Volatility", Alert.BAR, Sound.Ring);
alert(volatilityLine crosses below volatilityThreshold, "Low Volatility", Alert.BAR, Sound.Ring);
#

mGIHUvC.jpg
Thank you halcyonguy!
 
Stock Price Extension from 50-SMA via ATR% Multiple Measurement - open source available on Tos?
https://www.tradingview.com/script/...ion-from-50-SMA-via-ATR-Multiple-Measurement/

# ATR% from 50-SMA Scan

# Define variables
input atrMultiplierMin = 7;
input atrMultiplierMax = 10;

# Calculate ATR%
def atrPercentage = (ATR(14) / MovingAverage(AverageType.SIMPLE, close, 50)) * 100;

# Filter for ATR% within range
def scanResults = atrPercentage >= atrMultiplierMin and atrPercentage <= atrMultiplierMax;

# Output scan results
plot scan = scanResults;
 
Last edited by a moderator:
reply to #115
fairvaluegap is a made up word. it has no meaning. if you want a study to do something try listing out the rules that it should follow.
when close crosses this signal, do this.
if close is > 2 signals do this....

what is wrong with the code you posted?
what do you think needs to be changed?

i don't know what fairvaluegap is and i'm not going to go searching for definitions of it and guess i found the correct one. that is the job of the poster, you, to provide all the info you can, so that a stranger, not familiar with your request, can help.

you didn't tell us what 2 studies you looked at. what was wrong with them? why not use them?

you can get a link to a post, by clicking on the post number, then copy the web address.

reply to post122

here is something to find 4 patterns, that might help you figure out what you want.

i found a study of patterns, and copied 4 of them.
ref code - finds many patterns
https://usethinkscript.com/threads/candlestick-moving-avg-library-for-thinkorswim.14100/

i don't know what you want for 'key levels' , so i ignored that part.

referencePoints() isn't a valid function
def keyLevel = referencePoints(keyLevelPercent);

this draws,
white dot for hammer and shooting star,
yellow dot for bearish engulfing,
cyan dot for bullish engulfing

Code:
#chat122_patterns

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-7#post-125739
#jeditron  Jun 4, 2023  #122
#To ChatGPT: create a thinkorswim script that indicates buy and/or sell signals using price action candlestick reversal patterns at key levels or demand and supply zone areas


#I'm receiving an error message for this line: def keyLevel = referencePoints(keyLevelPercent);
#"No such function: referencePoints at 8:16"
#can anyone resolve this? Thanks in advance!

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

# Candlestick Reversal Patterns with Key Levels/Supply-Demand Zones
# Buy Signal: Reversal pattern bullish candlestick at key support or demand zone
# Sell Signal: Reversal pattern bearish candlestick at key resistance or supply zone
#--------------
# ref
# https://usethinkscript.com/threads/candlestick-moving-avg-library-for-thinkorswim.14100/
#-------------


addlabel(1, "-");

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

input keyLevelPercent = 1.0; 
# Percentage deviation from key levels/zones
input reversalPattern = {default "Bullish Engulfing", "Bearish Engulfing", "Hammer", "Shooting Star"};


#---------------------
#bullEngulf(float maxRejectWick = 0.0, bool mustEngulfWick = false) =>
script bullEngulf {
    input maxRejectWick = 0.0;
    input mustEngulfWick = no;
    def topWickSize = AbsValue(Max(close, open) - high);
    def bodySize       = AbsValue( close - open);
    def rejectionRule = maxRejectWick == 0.0 or topWickSize / bodySize < (maxRejectWick / 100);
    plot result = close[1] <= open[1] and close >= open[1] and open <= close[1] and rejectionRule and (!mustEngulfWick or close >= high[1]) and bodySize > 0;
}

#---------------------
#bearEngulf(float maxRejectWick = 0.0, bool mustEngulfWick = false) =>
script bearEngulf {
    input maxRejectWick = 0.0;
    input mustEngulfWick = no;
    def bottomWickSize = AbsValue(Min( close, open) - low);
    def bodySize       = AbsValue( close - open);
    def rejectionRule = maxRejectWick == 0.0 or bottomWickSize / bodySize < (maxRejectWick / 100);
    plot result = close[1] >= open[1] and close <= open[1] and open >= close[1] and rejectionRule and (!mustEngulfWick or close <= low[1]) and bodySize > 0;
}

#---------------------
#hammer(float ratio = 33, float shadowPercent = 5.0) =>
script hammer1 {
    input ratio = 33;
    input shadowPercent = 5.0;
    def topWickSize = AbsValue(Max(close, open) - high);
    def bodySize    = AbsValue( close - open);
    def bodyLow     = Min( close, open);
    def bullRatio = (low - high) * (ratio / 100) + high;
    def hasShadow = topWickSize > shadowPercent / 100 * bodySize;
    plot result   = bodySize > 0 and bodyLow >= bullRatio and !hasShadow;
}

#---------------------
# shooting star
#star(float ratio = 33, float shadowPercent = 5.0) =>
script star1 {
    input ratio = 33;
    input shadowPercent = 5.0;
    def bottomWickSize = AbsValue(Min( close, open) - low);
    def bodySize       = AbsValue( close - open);
    def bodyHigh       = Max( close, open);
    def bearRatio = (high - low) * (ratio / 100) + low;
    def hasShadow = bottomWickSize > shadowPercent / 100 * bodySize;
    plot result   = bodySize > 0 and bodyHigh <= bearRatio and !hasShadow;
}

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

# hammer function...  doesnt work
#input hammer_0 = 1;
# hammer()   inputs
#length    The number of candles used to calculate the average body height.
#trend setup    The number of preceding candles to check if the trend exists.
#body factor    The factor used when checking if a candle is short. A candle is considered short if its body height is lower than the average multiplied by this factor.
#shadow factor    The factor used when checking if a shadow is long. A shadow is considered long if its length exceeds body height multiplied by this factor.
#input hammer_len = 2;
#input trend_setup = 2;
#input body_factor = 1.0;
#input shadow_factor = 2.0;
#def h = hammer(hammer_len, trend_setup, body_factor, shadow_factor);


#-----------------------------
def v1 = 0.002;

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

input maxRejectWick = 0.0;
input mustEngulfWick = no;

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

def bear_en = bearEngulf(maxRejectWick, mustEngulfWick);
plot zbr = if bear_en then high * (1 + (1*v1)) else na;
zbr.SetPaintingStrategy(PaintingStrategy.POINTS);
zbr.SetDefaultColor(Color.yellow);
zbr.setlineweight(3);
zbr.hidebubble();

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

def bull_en = bullEngulf(maxRejectWick, mustEngulfWick);
plot zbl = if bull_en then low * (1 - (1*v1)) else na;
zbl.SetPaintingStrategy(PaintingStrategy.POINTS);
zbl.SetDefaultColor(Color.cyan);
zbl.setlineweight(3);
zbl.hidebubble();


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

input ratio = 30;
input shadowPercent = 5.0;

# hammer1
def ham = hammer1(ratio, shadowPercent);
plot zh = if ham then high * (1 + (2*v1)) else na;
zh.SetPaintingStrategy(PaintingStrategy.POINTS);
zh.SetDefaultColor(Color.white);
zh.setlineweight(3);
zh.hidebubble();

#-----------------------------
# shooting star
def star = star1(ratio, shadowPercent);
plot zs = if star then low * (1 - (2*v1)) else na;
zs.SetPaintingStrategy(PaintingStrategy.POINTS);
zs.SetDefaultColor(Color.white);
zs.setlineweight(3);
zs.hidebubble();

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


#def keyLevel = referencePoints(keyLevelPercent);
#def pattern;

#switch (reversalPattern) {
#case "Bullish Engulfing":
#    pattern = Engulfing().Bullish;
#case "Bearish Engulfing":
#    pattern = Engulfing().Bearish;
#case "Hammer":
#    pattern = Hammer();
#case "Shooting Star":
#    pattern = ShootingStar();
#}


#def bullishSignal = pattern and low <= keyLevel;
#def bearishSignal = pattern and high >= keyLevel;

#plot BuySignal = bullishSignal;
#plot SellSignal = bearishSignal;

#BuySignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SellSignal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#BuySignal.SetDefaultColor(Color.GREEN);
#SellSignal.SetDefaultColor(Color.RED);

#
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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