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 with this setup .
it does not generate any buy/sell orders

Code:
# Strategy for backtesting with specified conditions

input priceMin = 5;
input priceMax = 30;
input preMarketVolumeMin = 1000000;
input entryStartTime = 945;
input entryEndTime = 1000;
input riskPercent = 1.5; # Average of 1-2%
input profitLossRatio = 2.0;

def price = close;
def preMarketVolume = volume;
def currentTime = SecondsFromTime(entryStartTime) >= 0 and SecondsTillTime(entryEndTime) >= 0;

# Price range condition
def priceCondition = price >= priceMin and price <= priceMax;

# Pre-market volume condition
def preMarketVolumeCondition = preMarketVolume > preMarketVolumeMin;

# 15-minute trading range
def high15 = Highest(high, 15);
def low15 = Lowest(low, 15);
def range15 = high15 - low15;

# Entry conditions
def buySignal = priceCondition and preMarketVolumeCondition and currentTime and close > high15;
def sellSignal = priceCondition and preMarketVolumeCondition and currentTime and close < low15;

# Risk management
def riskAmount = close * (riskPercent / 100);
def profitTarget = close + (riskAmount * profitLossRatio);
def stopLoss = close - riskAmount;

# Add orders for backtesting
AddOrder(OrderType.BUY_AUTO, buySignal, open[-1], tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "Buy");
AddOrder(OrderType.SELL_TO_CLOSE, sellSignal, open[-1], tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "Sell");

# Profit target and stop loss
#AddOrder(OrderType.SELL_TO_CLOSE, close >= profitTarget, open[-1], tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "Profit Target");
#AddOrder(OrderType.SELL_TO_CLOSE, close <= stopLoss, open[-1], tickcolor = GetColor(3), arrowcolor = GetColor(3), name = "Stop Loss");

# Alerts
Alert(buySignal, "Buy Signal", Alert.BAR, Sound.Bell);
Alert(sellSignal, "Sell Signal", Alert.BAR, Sound.Ding);

# Labels for visibility
AddLabel(buySignal, "Buy Signal", Color.GREEN);
AddLabel(sellSignal, "Sell Signal", Color.RED);

reply to 316

if things don't work as expected, then look into the last formula and check the variable values.

this one drives the addorder,
def buySignal = priceCondition and preMarketVolumeCondition and currentTime and close > high15;

i added this to display the values, and all are 0.

Code:
addchartbubble(1, low,
 priceCondition + "\n" +
 preMarketVolumeCondition  + "\n" +
 currentTime + "\n" +
 high15 + "\n" +
 (close > high15) + "\n" +
 buySignal
, color.yellow, no);

repeat this process, looking back at previous formulas and display other variables, to see what is going on.


ps , your variable names add confusion.
preMarketVolume = volume; , this isn't pre market volume, its just volume.
def preMarketVolumeCondition = , not pre market
def currentTime = , this isn't current time, it is a specific time period
close > high15; , this will never be true. high15 is the highest value. close might = the highest, but it can't be greater

limiting a buy/sell time to just 15 minutes in a day, is just silly
def currentTime = SecondsFromTime(entryStartTime) >= 0 and SecondsTillTime(entryEndTime) >= 0;
 
Last edited:

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

Hello there

i am trying to get as part o the postions that i have to isplay next month monthly expiration for call and put delta around .20 or closest one... some how the belwo code is not working; apprecaite the help

#-- Code begin
# User-defined input for the target expiration (Third Friday of the target month)
input targetExpiration = 20241220; # Example: December 20, 2024 (Third Friday)

# Get Delta, Volume, Open Interest, and Bid Price
def delta = Delta();
def volume = if IsNaN(Volume()) then 0 else Volume();
def openInterest = if IsNaN(OpenInterest()) then 0 else OpenInterest();
def bidPrice = if IsNaN(Bid()) then 0 else Bid();

# Define Delta Range for Calls and Puts
def callCondition = delta >= 0.18 and delta <= 0.22; # Adjust delta range if needed
def putCondition = delta <= -0.18 and delta >= -0.22; # Adjust delta range if needed

# Directly use the target expiration as the expiration date
def isTargetExpiration = GetYYYYMMDD() == targetExpiration;

# Combine conditions for valid options
def isValidCall = callCondition and isTargetExpiration;
def isValidPut = putCondition and isTargetExpiration;

# Filter by Volume Threshold (Adjust as needed)
input minVolume = 10; # Minimum volume threshold
def meetsVolumeCondition = volume >= minVolume;

# Combine all filters for valid calls and puts
def isFilteredCall = isValidCall and meetsVolumeCondition;
def isFilteredPut = isValidPut and meetsVolumeCondition;

# Add Labels for Calls and Puts Meeting All Conditions
AddLabel(isFilteredCall, "Filtered Call | Vol: " + volume + " | OI: " + openInterest + " | Bid: " + bidPrice, Color.GREEN);
AddLabel(isFilteredPut, "Filtered Put | Vol: " + volume + " | OI: " + openInterest + " | Bid: " + bidPrice, Color.RED);

# Default Label for No Matches
AddLabel(!isFilteredCall and !isFilteredPut, "No Match Found | Exp: " + targetExpiration, Color.GRAY);

#--Code End



Thanks

Raj
 
I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

The conditions are as follows:

When all waves are below 0, and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
1732907129983.png



When all waves are above 0, and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.
1732907283044.png


I have tried below for first condition but is not working as expected. (Just to try I have selected value 5 but I am not looking at fix value. Is it possible to compare previous 2 waves length according to above conditions?
1732907339999.png



Below is ChatGPT answer, but still not correct. It is showing stock that has all waves above 0 line.

Ruby:
# Define TTM Wave Indicator
def TTMWave = TTM_Wave();

# Define the yellow wave (assumed to be the wave with a color of Yellow in the TTM_Wave study)
def yellowWave = TTMWave[1]; # For yellow wave detection, you may need to look for specific color logic if defined
# Identify when all waves are below 0
def allWavesBelowZero = TTMWave < 0;

# Check if the yellow wave's length is decreasing from the previous 2-3 bars
def yellowWaveDecreasing = yellowWave < yellowWave[1] and yellowWave[1] < yellowWave[2];

# The condition when all waves are below 0 and the yellow wave is decreasing
plot scan = allWavesBelowZero and yellowWaveDecreasing;
 
Last edited:
Trying to find out the 3rd Friday of current month and next month.
AI gave me some code, but I cannot make it work.
Can some figure out what went wrong here?

def currentMonth = GetMonth(); #(GetYYYYMMDD());
def currentYear = GetYear(); #(GetYYYYMMDD());
def nextMonth = if currentMonth == 12 then 1 else currentMonth + 1;
def nextYear = if currentMonth == 12 then currentYear + 1 else currentYear;

def firstDayOfMonth = GetDayOfWeek(currentYear * 10000 + currentMonth * 100 + 1);
def firstFriday = firstDayOfMonth + (5 - GetDayOfWeek(firstDayOfMonth) + 7) % 7;
def thirdFriday = firstFriday + 14;

def firstDayOfNextMonth = GetDayOfWeek(nextYear * 10000 + nextMonth * 100 + 1);
def firstFridayNextMonth = firstDayOfNextMonth + (5 - GetDayOfWeek(firstDayOfNextMonth) + 7) % 7;
def thirdFridayNextMonth = firstFridayNextMonth + 14;
 
QrPnM7K.png

In the context of this scan, the stocks identified would exhibit price action that aligns with the characteristics of Geometric Brownian Motion (GBM). Here’s a breakdown of what you could expect:

  1. Volatility: Stocks that pass the scan would exhibit relatively high volatility, as measured by the Average True Range (ATR). GBM assumes that volatility is a key factor, meaning the price fluctuates with a certain degree of randomness and uncertainty. This translates to price movements that have a higher chance of significant up or down swings in the short term. Stocks with higher volatility might exhibit wide daily price ranges.
  2. Trend Movement (Drift): The Rate of Change (ROC) filter ensures that stocks with an upward price trend (positive drift) are favored. This means you would see stocks with a noticeable increase in price over the lookback period. These stocks are likely trending upwards, though the movement may still follow a somewhat erratic path due to volatility.
  3. Mean Reversion and Oscillation: While GBM does not exhibit strict mean reversion, stocks with high volatility and drift, especially in combination with MACD momentum, can show oscillating behavior. This could mean that while prices are generally trending upwards (due to positive drift), you may still see pullbacks, sharp reversals, or consolidations as the price fluctuates within the volatility bounds.
  4. Volume Support: The filter for volume ensures that there’s significant market participation behind the price movements. Stocks with higher volume are more likely to see sustained price trends or volatility, as they reflect the involvement of institutional players or large retail groups. This helps provide liquidity for the erratic price moves suggested by a GBM-like process.

Expected Price Action from Scan Results:​

  • Short-Term Trends with High Fluctuations: Given that GBM reflects a random walk, you may see stocks with periods of strong upward movement (following the drift) but also with significant pullbacks or reversals, especially during high volatility periods.
  • Erratic Path with an Upward Bias: While the overall price movement may show an upward trend (positive drift), the path will not be smooth. The price will likely exhibit frequent oscillations, with higher highs and lower lows within the uptrend, characteristic of stocks with high volatility and momentum.
  • Potential for Sudden Price Movements: Due to the combination of volatility (ATR) and momentum (MACD and ROC), the price may move rapidly in short bursts, and you could experience sudden, sharp moves in either direction within the broader trend.

In Summary:​

You can expect stocks that meet the scan's criteria to show volatility-driven trends with a higher likelihood of price swings, in alignment with the GBM framework. This would mean that while the price generally follows an upward trend (drift), there will be frequent price fluctuations (randomness) along the way, with periods of both strong momentum and pullbacks.

I would love for someone to look at it by putting into a scan and just give feedback here is the script.
Code:
# Monte Carlo-Inspired Stock Scan with GBM Approximation and Enhancements

# Define Inputs
input RelativeVolatilityThreshold = 0.005;  # Minimum relative volatility threshold (e.g., 0.5%)
input ROCThreshold = 0.02;                  # Minimum rate of change threshold (2%)
input MACDThreshold = -0.5;                 # Allows for early momentum detection
input VolumeAvgPeriod = 20;                 # Period for average volume calculation
input VolumeMultiplier = 1.5;               # Current volume must be 150% of average
input lookbackPeriod = 14;                  # Period for ROC and volatility calculations
input ATRPeriod = 14;
input MACDFastLength = 12;
input MACDSlowLength = 26;
input MACDSignalLength = 9;
input MinPrice = 5;
input TrendDirection = {default Bullish, Bearish, Both};

# Calculate Relative Volatility using GBM approximation
def logReturns = Log(close / close[1]);
def historicalVolatility = StDev(logReturns, lookbackPeriod) * Sqrt(252);  # Annualized volatility
def meetsVolatility = historicalVolatility > RelativeVolatilityThreshold;

# Calculate Price Rate of Change (ROC)
def ROC = (close / close[lookbackPeriod]) - 1;

# Determine ROC condition based on Trend Direction
def meetsROC;
switch (TrendDirection) {
    case Bullish:
        meetsROC = ROC > ROCThreshold;
    case Bearish:
        meetsROC = ROC < -ROCThreshold;
    case Both:
        meetsROC = AbsValue(ROC) > ROCThreshold;
}

# Calculate MACD Histogram and Signal
def MACDLine = MACD(fastLength = MACDFastLength, slowLength = MACDSlowLength, MACDLength = MACDSignalLength)."Value";
def SignalLine = MACD(fastLength = MACDFastLength, slowLength = MACDSlowLength, MACDLength = MACDSignalLength)."Avg";
def MACDHistogram = MACDLine - SignalLine;
def MACDCross = MACDLine crosses above SignalLine;

# Use MACD Histogram Slope or Crossover
def meetsMACD = MACDHistogram > MACDThreshold;

# Calculate Volume Conditions
def avgVolume = Average(volume, VolumeAvgPeriod);
def relVolume = volume / avgVolume;
def meetsVolume = relVolume > VolumeMultiplier;

# Price Condition
def meetsPrice = close > MinPrice;

# Combine All Conditions
def meetsAllConditions = meetsVolatility and meetsROC and meetsMACD and meetsVolume and meetsPrice;

# Plot for Potential Trend
plot TrendPotential = meetsAllConditions;
TrendPotential.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
TrendPotential.SetDefaultColor(Color.GREEN);
TrendPotential.SetLineWeight(2);

# Plot Individual Conditions (Optional)
plot VolatilityCondition = if meetsVolatility then 1 else 0;
VolatilityCondition.SetDefaultColor(Color.RED);
VolatilityCondition.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
VolatilityCondition.Hide();

plot ROCCondition = if meetsROC then 1 else 0;
ROCCondition.SetDefaultColor(Color.BLUE);
ROCCondition.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
ROCCondition.Hide();

plot MACDCondition = if meetsMACD then 1 else 0;
MACDCondition.SetDefaultColor(Color.ORANGE);
MACDCondition.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
MACDCondition.Hide();

plot VolumeCondition = if meetsVolume then 1 else 0;
VolumeCondition.SetDefaultColor(Color.PINK);
VolumeCondition.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
VolumeCondition.Hide();

plot PriceCondition = if meetsPrice then 1 else 0;
PriceCondition.SetDefaultColor(Color.CYAN);
PriceCondition.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
PriceCondition.Hide();

# Alerts
Alert(meetsAllConditions, "Potential Trend Detected", Alert.BAR, Sound.Ding);
 
Last edited by a moderator:
Trying to find out the 3rd Friday of current month and next month.
AI gave me some code, but I cannot make it work.
Can some figure out what went wrong here?

def currentMonth = GetMonth(); #(GetYYYYMMDD());
def currentYear = GetYear(); #(GetYYYYMMDD());
def nextMonth = if currentMonth == 12 then 1 else currentMonth + 1;
def nextYear = if currentMonth == 12 then currentYear + 1 else currentYear;

def firstDayOfMonth = GetDayOfWeek(currentYear * 10000 + currentMonth * 100 + 1);
def firstFriday = firstDayOfMonth + (5 - GetDayOfWeek(firstDayOfMonth) + 7) % 7;
def thirdFriday = firstFriday + 14;

def firstDayOfNextMonth = GetDayOfWeek(nextYear * 10000 + nextMonth * 100 + 1);
def firstFridayNextMonth = firstDayOfNextMonth + (5 - GetDayOfWeek(firstDayOfNextMonth) + 7) % 7;
def thirdFridayNextMonth = firstFridayNextMonth + 14;

reply to 327

as is , there is no error because there is no output.
when i add a bubble to display firstFriday, an error appears.

sometimes an error causes this to appear,
in the top left corner of the chart, under the symbol field, there is a flashing white circle on the chart, with an exclamation point

click on it,
it says date value can't be less than 19020101

start at the end of study and disable a code line and save, until error goes away

firstDayOfMonth , this is a number 1 to 7. 1 = monday, 7 = sunday
dec/2024 = 7 , 1st is on sunday


this causes an error
GetDayOfWeek() wants a date code number, YYYYMMDD , not a number < 10
def firstFriday = firstDayOfMonth + (5 - GetDayOfWeek(firstDayOfMonth) + 7) % 7;

this produces a number, but i think its wrong.
def firstFriday = firstDayOfMonth + (5 - firstDayOfMonth + 7) % 7;

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

here is a code to experiment with
it has bubbles to display some values
vertical lines on 1st and 3rd fridays

Code:
#third_friday_00b

#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-17#post-147937
#timing
#12/02
#327
#Trying to find out the 3rd Friday of current month and next month.
#AI gave me some code, but I cannot make it work.
#Can some figure out what went wrong here?

def dat = GetYYYYMMDD();

def currentMonth = GetMonth(); #(GetYYYYMMDD());
def currentYear = GetYear(); #(GetYYYYMMDD());
def nextMonth = if currentMonth == 12 then 1 else currentMonth + 1;
def nextYear = if currentMonth == 12 then currentYear + 1 else currentYear;

#def firstDayOfMonth = GetDayOfWeek(currentYear * 10000 + currentMonth * 100 + 1);
#def firstDayOfMonth = GetDayOfWeek((currentYear * 10000) + (currentMonth * 100) + 1);

def date1 = ((currentYear * 10000) + (currentMonth * 100) + 1);
def firstDayOfMonth = GetDayOfWeek(date1);


#input day_of_week = {default Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
#AddChartBubble(GetDayofWeek(GetYYYYMMDD()) == day_of_week + 1, high, "Here it is");


#bad
#def firstFriday = firstDayOfMonth + (5 - GetDayOfWeek(firstDayOfMonth) + 7) % 7;
#wrong
#def firstFriday = firstDayOfMonth + (5 - firstDayOfMonth + 7) % 7;


# 1st friday , day of month
def firstfriday_dom = 
    (if firstDayOfMonth == 1 then 5
else if firstDayOfMonth == 2 then 4
else if firstDayOfMonth == 3 then 3
else if firstDayOfMonth == 4 then 2
else if firstDayOfMonth == 5 then 1
else if firstDayOfMonth == 6 then 7 
else if firstDayOfMonth == 7 then 6
else 0);


#def thirdFriday = firstFriday + 14;
def thirdFriday_dom = firstfriday_dom + 14;


def isfirstfriday = dat == ((currentYear * 10000) + (currentMonth * 100) + firstfriday_dom);
addverticalline( isfirstfriday , "FIRST  FRIDAY  " + asprice((currentYear * 10000) + (currentMonth * 100) + firstfriday_dom), color.cyan);

def isthirdfriday = dat == ((currentYear * 10000) + (currentMonth * 100) + thirdFriday_dom);
addverticalline( isthirdfriday , "THIRD  FRIDAY  " + asprice((currentYear * 10000) + (currentMonth * 100) + thirdFriday_dom), color.magenta);


#def firstDayOfNextMonth = GetDayOfWeek(nextYear * 10000 + nextMonth * 100 + 1);
#def firstFridayNextMonth = firstDayOfNextMonth + (5 - GetDayOfWeek(firstDayOfNextMonth) + 7) % 7;
#def thirdFridayNextMonth = firstFridayNextMonth + 14;


def y = 0.02;
addchartbubble(1, high*(1+y),
(currentMonth + "/1\n" +
 "DOW= " + firstDayOfMonth + "\n" + 
    (if firstDayOfMonth == 1 then "Monday"
else if firstDayOfMonth == 2 then "Tuesday"
else if firstDayOfMonth == 3 then "Wednesday"
else if firstDayOfMonth == 4 then "Thursday"
else if firstDayOfMonth == 5 then "Friday"
else if firstDayOfMonth == 6 then "Saturday" 
else if firstDayOfMonth == 7 then "Sunday"
else "-")),
color.yellow, yes);



addchartbubble(1, high*(1+y),
 "1st friday\n" +
 currentMonth + "/" + firstfriday_dom
, color.yellow, yes);


addchartbubble(1, high*(1+y),
 "3rd friday\n" +
 currentMonth + "/" +  thirdFriday_dom
, color.yellow, yes);


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

addchartbubble(0, low*(1-y),
currentMonth + "\n" +
date1 + "\n" +
firstDayOfMonth + "\n" +
#firstFriday + "\n" +
firstfriday_dom + "\n" 
, color.yellow, no);

#


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


there is a built in study called
Next3rdFriday
that calculates the days to the 3rd friday
 

Attachments

  • img1.JPG
    img1.JPG
    105 KB · Views: 26
I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

The conditions are as follows:

When all waves are below 0, and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.



When all waves are above 0, and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.


I have tried below for first condition but is not working as expected. (Just to try I have selected value 5 but I am not looking at fix value. Is it possible to compare previous 2 waves length according to above conditions?



Below is ChatGPT answer, but still not correct. It is showing stock that has all waves above 0 line.

Ruby:
# Define TTM Wave Indicator
def TTMWave = TTM_Wave();

# Define the yellow wave (assumed to be the wave with a color of Yellow in the TTM_Wave study)
def yellowWave = TTMWave[1]; # For yellow wave detection, you may need to look for specific color logic if defined
# Identify when all waves are below 0
def allWavesBelowZero = TTMWave < 0;

# Check if the yellow wave's length is decreasing from the previous 2-3 bars
def yellowWaveDecreasing = yellowWave < yellowWave[1] and yellowWave[1] < yellowWave[2];

# The condition when all waves are below 0 and the yellow wave is decreasing
plot scan = allWavesBelowZero and yellowWaveDecreasing;

reply to 325

another example of chatgpt not knowing how to create a study.
the study only reads 1 plot from the study. there are 3 signals and zero.
just take the time to learn thinkscript.

since the original study is hidden, i had to make some guesses and start experimenting.
i loaded the original study, ttm_wave.

i read the plot values from the original study, and plotted lines.
def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

the lines are pretty flat, so its hard to tell when they change direction.
i made a bubble to display the plot values.
i stared at the histogram colors and my bubble values.
i guessed if the change in w1 is positive, there are yellow histogram bars. if negative then brown. then changed the bubble color to follow that rule. it matched the histogram.

next i found the change in w2 histogram bar height. if positive then cyan. if negative then blue.

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


scan code

Code:
#ttm_wave_crossings_01_scan



#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-17#post-148286
#AlwaysLearning
#11/29
#325
#I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

#The conditions are as follows:
# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.


declare lower;

def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

def wavesabove = w1 > 0 and w2hi > 0 and w2lo > 0;
def wavesbelow = w1 < 0 and w2hi < 0 and w2lo < 0;

input min_sequential_bars = 2;

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

def w1chg = w1 - w1[1];
# if w1chg > 0 then yellow.  if < 0 then  brown(red)

# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
def yellowdecrease = wavesbelow and w1chg > 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.
def browndecrease = wavesabove and w1chg < 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

#-------------------
def w2chg = (w2hi - w2lo) - (w2hi[1] - w2lo[1]);
# if w2chg > 0 then cyan.   if < 0 then  blue
#-------------------

plot z = yellowdecrease or  browndecrease;

#

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


lower test code

Code:
#ttm_wave_crossings_lower



#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-17#post-148286
#AlwaysLearning
#11/29
#325
#I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

#The conditions are as follows:
# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.





# ttm_wave
#plot Wave1 = Double.NaN;
#plot Wave2High = Double.NaN;
#plot Wave2Low = Double.NaN;
#plot ZeroLine = Double.NaN;


declare lower;

def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

def wavesabove = w1 > 0 and w2hi > 0 and w2lo > 0;
def wavesbelow = w1 < 0 and w2hi < 0 and w2lo < 0;

input min_sequential_bars = 2;

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

def w1chg = w1 - w1[1];
# if w1chg > 0 then yellow.  if < 0 then  brown(red)

# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
def yellowdecrease = wavesbelow and w1chg > 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.
def browndecrease = wavesabove and w1chg < 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

#-------------------
def w2chg = (w2hi - w2lo) - (w2hi[1] - w2lo[1]);
# if w2chg > 0 then cyan.   if < 0 then  blue
#-------------------

plot z = yellowdecrease or  browndecrease;

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

# outputs

addverticalline(yellowdecrease, "Yellow", color.yellow);
addverticalline(browndecrease, "Brown", color.red);

plot z1 = w1;
plot z2 = w2hi;
plot z3 = w2lo;
plot z4 = 0;

z1.SetDefaultColor(Color.cyan);
z2.SetDefaultColor(Color.green);
z3.SetDefaultColor(Color.red);
z4.SetDefaultColor(Color.white);
z4.setlineweight(2);



addchartbubble(1 or wavesbelow, 1,
# w1 + "\n" +
 w1chg
# w2hi + "\n" +
# w2lo + "\n" +
# w2chg
, (if w1chg > 0 then color.yellow else color.red), yes);
#, (if w2chg > 0 then color.cyan else color.blue), yes);
#, color.yellow, yes);



addchartbubble(1 or wavesbelow, 1,
# w1 + "\n" +
# w1chg
# w2hi + "\n" +
# w2lo + "\n" +
w2chg
#, (if w1chg > 0 then color.yellow else color.red), yes);
, (if w2chg > 0 then color.cyan else color.blue), yes);
#, color.yellow, yes);

#
 

Attachments

  • img2 - AIG 1hr.JPG
    img2 - AIG 1hr.JPG
    218.3 KB · Views: 33
reply to 325

another example of chatgpt not knowing how to create a study.
the study only reads 1 plot from the study. there are 3 signals and zero.
just take the time to learn thinkscript.

since the original study is hidden, i had to make some guesses and start experimenting.
i loaded the original study, ttm_wave.

i read the plot values from the original study, and plotted lines.
def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

the lines are pretty flat, so its hard to tell when they change direction.
i made a bubble to display the plot values.
i stared at the histogram colors and my bubble values.
i guessed if the change in w1 is positive, there are yellow histogram bars. if negative then brown. then changed the bubble color to follow that rule. it matched the histogram.

next i found the change in w2 histogram bar height. if positive then cyan. if negative then blue.

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


scan code

Code:
#ttm_wave_crossings_01_scan



#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-17#post-148286
#AlwaysLearning
#11/29
#325
#I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

#The conditions are as follows:
# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.


declare lower;

def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

def wavesabove = w1 > 0 and w2hi > 0 and w2lo > 0;
def wavesbelow = w1 < 0 and w2hi < 0 and w2lo < 0;

input min_sequential_bars = 2;

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

def w1chg = w1 - w1[1];
# if w1chg > 0 then yellow.  if < 0 then  brown(red)

# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
def yellowdecrease = wavesbelow and w1chg > 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.
def browndecrease = wavesabove and w1chg < 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

#-------------------
def w2chg = (w2hi - w2lo) - (w2hi[1] - w2lo[1]);
# if w2chg > 0 then cyan.   if < 0 then  blue
#-------------------

plot z = yellowdecrease or  browndecrease;

#

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


lower test code

Code:
#ttm_wave_crossings_lower



#https://usethinkscript.com/threads/chatgpt-bard-other-ai-scripts-which-cant-be-used-in-thinkorswim.13822/page-17#post-148286
#AlwaysLearning
#11/29
#325
#I want to configure a scanner that detects when the TTM_Waves cross the 0 line, if any of the condition is true I want to see that stock in scanner list.

#The conditions are as follows:
# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.





# ttm_wave
#plot Wave1 = Double.NaN;
#plot Wave2High = Double.NaN;
#plot Wave2Low = Double.NaN;
#plot ZeroLine = Double.NaN;


declare lower;

def w1 = ttm_wave().Wave1;
def w2hi = ttm_wave().Wave2High;
def w2lo = ttm_wave().Wave2Low;
#def z0 = ttm_wave().ZeroLine;

def wavesabove = w1 > 0 and w2hi > 0 and w2lo > 0;
def wavesbelow = w1 < 0 and w2hi < 0 and w2lo < 0;

input min_sequential_bars = 2;

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

def w1chg = w1 - w1[1];
# if w1chg > 0 then yellow.  if < 0 then  brown(red)

# When all waves are below 0,
#  and a yellow wave appears, with its length decreasing over the last 2-3 consecutive bars.
def yellowdecrease = wavesbelow and w1chg > 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

# When all waves are above 0,
#  and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.
def browndecrease = wavesabove and w1chg < 0 and (sum((w1chg<w1chg[1]), min_sequential_bars) ==  min_sequential_bars);

#-------------------
def w2chg = (w2hi - w2lo) - (w2hi[1] - w2lo[1]);
# if w2chg > 0 then cyan.   if < 0 then  blue
#-------------------

plot z = yellowdecrease or  browndecrease;

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

# outputs

addverticalline(yellowdecrease, "Yellow", color.yellow);
addverticalline(browndecrease, "Brown", color.red);

plot z1 = w1;
plot z2 = w2hi;
plot z3 = w2lo;
plot z4 = 0;

z1.SetDefaultColor(Color.cyan);
z2.SetDefaultColor(Color.green);
z3.SetDefaultColor(Color.red);
z4.SetDefaultColor(Color.white);
z4.setlineweight(2);



addchartbubble(1 or wavesbelow, 1,
# w1 + "\n" +
 w1chg
# w2hi + "\n" +
# w2lo + "\n" +
# w2chg
, (if w1chg > 0 then color.yellow else color.red), yes);
#, (if w2chg > 0 then color.cyan else color.blue), yes);
#, color.yellow, yes);



addchartbubble(1 or wavesbelow, 1,
# w1 + "\n" +
# w1chg
# w2hi + "\n" +
# w2lo + "\n" +
w2chg
#, (if w1chg > 0 then color.yellow else color.red), yes);
, (if w2chg > 0 then color.cyan else color.blue), yes);
#, color.yellow, yes);

#
Thank you @halcyonguy, appreciate your response.

I ran your scan code, it returned below result for daily time frame,
1733292632835.png



When I checked couple of them, looks like they are returning even lines are above 0 for uptrend and below 0 in downtrend.

Example - SHW
Expected TTM Wave - Brown lines should be below 0 line.
1733292718038.png


Same for ALLY
1733292798337.png


But thanks for the script, I will try to modify it according my understanding, I am new to thinkscript so it will be good learning too.
 
Thank you @halcyonguy, appreciate your response.

I ran your scan code, it returned below result for daily time frame,



When I checked couple of them, looks like they are returning even lines are above 0 for uptrend and below 0 in downtrend.

Example - SHW
Expected TTM Wave - Brown lines should be below 0 line.


Same for ALLY


But thanks for the script, I will try to modify it according my understanding, I am new to thinkscript so it will be good learning too.

sorry, your words are confusing.
returns even lines? what is an even line?
i have no idea what i am supposed to look at in your images.
1st pic , what study did you use in the column?
2nd pic , where sis those horizontal lines come from? you are showing things and not explaining where they cam from.
3rd pic, same no idea where the lines came from


from #325
you didn't specify what the rules mean, so i didn't know what was up or down.

why do you want brown lines below zero when you said the opposite , above
'When all waves are above 0, and brown wave appears and its length is decreasing over the last 2-3 consecutive bars.'

instead of saying brown lines. say the name of the plot , w1 , w2hi , w2lo
brown is the color of a histogram bar, not lines

you wanted 2 conditions to trigger an output, so if the 'up' rule or 'down' rule is true, the output is true
 
Hello All,
I am sorry if this has been covered already. I attempted to read all the discussions and finally called it quits at page 5. I was hoping to create a new column in the Equities and Equity Options tab (Monitor tabActivity and Positions tab→Position Statement tab→Unallocated tab→Equity and Equity Options tab) that lists the number of days that has transpired since the trade was opened. Not till expiration but just days opened. I attempted to create the Thinkscript via Chat and surprise surprise it was a flop.
Is there anyone that could look at the Thinkscript Chat spit out, and perhaps tell me what I am missing? ...

def entryDate = if IsNaN(EntryDate()) then Double.NaN else EntryDate();def daysOpen = if IsNaN(entryDate) then Double.NaN else GetYYYYMMDD() - entryDate;# If position is not open, display NaNAddLabel(yes, if IsNaN(daysOpen) then "N/A" else daysOpen + " Days", Color.CYAN);plot data = daysOpen;

the following errors came up...
entryDate at 1:26
No such function: entryDate at 1:60
No such function: entryDate at 1:60
Expected double at 1:20



Thank You,
Mark Armstrong
 
Hello, I am looking for a simple code that plots EMA8 and EMA 23 cross over with SL and target lines extended untill the levels are breached. But running into below issue. Can anyone help to fix this pls?

1) Not able to stop subsequent signals from appearing
2) Not able to show the SL, target extentions untill the levels are breached.

Code:
# Define the EMAs
input length1 = 8; # Length for the first EMA
input length2 = 23; # Length for the second EMA
input candleCount = 5; # User-defined input for the number of previous candles

# Calculate the EMAs
def ema8 = ExpAverage(close, length1);
def ema23 = ExpAverage(close, length2);

# Plot the EMAs
plot EMA8Line = ema8;
EMA8Line.SetDefaultColor(Color.GREEN);
plot EMA23Line = ema23;
EMA23Line.SetDefaultColor(Color.RED);

# Define crossover conditions
def buySignal = ema8 crosses above ema23;
def sellSignal = ema8 crosses below ema23;

# Define NY trading hours using SecondsFromTime and SecondsTillTime
def isInNYTime = SecondsFromTime(930) >= 0 and SecondsTillTime(1600) >= 0;

# Plot buy and sell signals only during NY trading hours
plot BuyArrow = if buySignal and isInNYTime then low - 0.02 else Double.NaN;
BuyArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuyArrow.SetDefaultColor(Color.GREEN);
BuyArrow.SetLineWeight(3);

plot SellArrow = if sellSignal and isInNYTime then high + 0.02 else Double.NaN;
SellArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellArrow.SetDefaultColor(Color.RED);
SellArrow.SetLineWeight(3);

# Calculate stop loss and target levels
def stopLossBuy = if buySignal then Lowest(low[1], candleCount) else Double.NaN;
def targetBuy = if buySignal then close + (1.5 * (close - stopLossBuy)) else Double.NaN;

def stopLossSell = if sellSignal then Highest(high[1], candleCount) else Double.NaN;
def targetSell = if sellSignal then close - (1.5 * (stopLossSell - close)) else Double.NaN;

# Check if stop loss or target has been breached
def stopLossBreachedBuy = close < stopLossBuy;
def targetBreachedBuy = close >= targetBuy;

def stopLossBreachedSell = close > stopLossSell;
def targetBreachedSell = close <= targetSell;

# Plot stop loss and target levels only during NY trading hours and if not breached
plot StopLossBuyPlot = if isInNYTime and !stopLossBreachedBuy and !targetBreachedBuy then stopLossBuy else Double.NaN;
StopLossBuyPlot.SetDefaultColor(Color.RED);
StopLossBuyPlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot TargetBuyPlot = if isInNYTime and !stopLossBreachedBuy and !targetBreachedBuy then targetBuy else Double.NaN;
TargetBuyPlot.SetDefaultColor(Color.GREEN);
TargetBuyPlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot StopLossSellPlot = if isInNYTime and !stopLossBreachedSell and !targetBreachedSell then stopLossSell else Double.NaN;
StopLossSellPlot.SetDefaultColor(Color.RED);
StopLossSellPlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

plot TargetSellPlot = if isInNYTime and !stopLossBreachedSell and !targetBreachedSell then targetSell else Double.NaN;
TargetSellPlot.SetDefaultColor(Color.GREEN);
TargetSellPlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Last edited by a moderator:
New Highs count Watchlist Custom Column. Trying to use as scanner filter but having trouble setting condition to certain amount anything over 100.

I asked ChatGPT to make a script that counts new highs within the day and that's what it gave me. Sorry not an actual programmer more like a household mechanic. I think it converted to pennies to lessen the money count of stock price? Not sure like I said I'm not a programmer.

Then I asked usethinkscript to make a scanner that only allows certain amount of new highs within the day. Example: Anything over 100 new high of day. ChatGPT wasn't to helpful with that.

# Custom Watchlist Column: New High Incremental Count

def newDay = GetYYYYMMDD() != GetYYYYMMDD()[1];

def lowestLow = if newDay then low else Min(lowestLow[1], low);

def highestHigh = if newDay then high else Max(highestHigh[1], high);

def highDifference = highestHigh - lowestLow;

def increment = 0.01; # Set the increment to 1 cent

def highCount = Round(highDifference / increment, 0);

plot count = highCount;

# End script


newHigh1.jpg
 
Last edited by a moderator:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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