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:
Im getting symbol error

# Define the Volume Profile
input pricePerRowHeightMode = {default TICKSIZE, ATR, PERCENT};
input timePerProfile = {default CHART, MINUTE, HOUR, DAY, WEEK, MONTH, "OPT EXP", BAR};
input multiplier = 1;
input onExpansion = yes;
input profiles = 1;
input showPointOfControl = yes;
input showValueArea = yes;
input valueAreaPercent = 70;

def na = Double.NaN;
def bn = BarNumber();
def isNaN = IsNaN(close);
def profile = VolumeProfile("price per row height mode" = pricePerRowHeightMode, "time per profile" = timePerProfile, multiplier = multiplier, onExpansion = onExpansion, numberOfProfiles = profiles, "value area percent" = valueAreaPercent);
def poc = if showPointOfControl then GetValue(profile.GetPointOfControl(), 0) else na;
def vah = if showValueArea then GetValue(profile.GetHighestValueArea(), 0) else na;
def val = if showValueArea then GetValue(profile.GetLowestValueArea(), 0) else na;

# Plot the POC, VAH, and VAL
plot POC = poc;
plot VAH = vah;
plot VAL = val;

POC.SetDefaultColor(Color.RED);
VAH.SetDefaultColor(Color.GREEN);
VAL.SetDefaultColor(Color.BLUE);

# Define Buy and Sell Conditions
def buySignal = close > VAL and close crosses above VAL;
def sellSignal = close VAH and close crosses below VAH;

# Add Orders
AddOrder(OrderType.BUY_AUTO, buySignal, open[-1], 100, Color.CYAN, Color.CYAN, "Buy");
AddOrder(OrderType.SELL_AUTO, sellSignal, open[-1], 100, Color.MAGENTA, Color.MAGENTA, "Sell");
 

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

I created a Watchlist column to sort thru symbols faster,
for current number of closes within 1 range to the last close. Yet still wrong counts but closer.

Only the total # of closes near the last close (can be edited to last price), with a small buffer range of .0035 higher or lower.
(the very tiny range threshold can be edited,)

I asked both ChatGpt & Bard, & very much the same result, both were fails, so I actually wrote this piecemeal from the chart version.

My piecemeal code... still wrong counts but closer.
# Define a Range around LastClose !!
input lookbackPeriod = 10; #?!! I used to a long time ago but I'm too busy,
input threshold = 0.0035; # ranges + or - percent

def lastClose = if !isnan(close[-1]) then close[-1] else 0;
def increment = lastClose * threshold;

def range1Low = lastClose - increment;
def range1High = lastClose + increment;
def range = range1High - range1Low;

def candleCount = sum(if !isnan(close) and close >= range1Low and close <= range1High then 1 else 0, lookbackPeriod);

# Plot the result in the watchlist column
plot result = candleCount;
------------------------------------------------
:) Someday maybe adding an RSI:
Rsi w/3 different font colors upon conditions:
1) if the total #of bars near the last close were <6 with a low RSI (30% or less), "green font (buy)"
2) and if the total #of bars near the last close were >15 or <6, with a high RSI (60% or more). "red font (sell)"

Where a low bar count w/a low rsi would indicate an entry,
and a high bar count or extremely low bar count w/a high rsi would indicate an exit.
On some charts it looks like nice entry & exit.

My pretty font colored RSI for a Watchlist Column:
input VLow =35;
input Low = 42;
input High = 58;
input VHigh = 68;

plot RSI = Round(RSI(),0);

RSI.AssignValueColor(
if RSI < VLow then Color.GREEN
else if RSI >= VLow and RSI < Low then CreateColor(97, 155, 22)
else if RSI >= Low and RSI < High then CreateColor(209, 229, 182)
else if RSI >= High and RSI < VHigh then CreateColor(178, 109, 218)
else CreateColor(208, 43, 98)
);
----------------------------

here is a simplified lower version that should work as a watchlist

Code:
# cnt_closes_within_rng_0_lower

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

declare lower;

def na = Double.NaN;
def bn = BarNumber();

#def lastbn = HighestAll(If(IsNaN(close), 0, bn));
#def lastbar = if (bn == lastbn) then 1 else 0;
def lastbar = !IsNaN(close[0]) and IsNaN(close[-1]);
#def last_close = highestall(if lastbar then close else 0);

#------------------------
#https://usethinkscript.com/threads/current-price-line-indicator-for-thinkorswim.8793/
# Line At Price    Mobius
def barsBack = 1000;
def c = if !IsNaN(close) and IsNaN(close[-1])
       then close
       else c[1];
def line = if IsNaN(close[-barsBack])
       then c[-barsBack]
       else Double.NaN;
#------------------------

input range_percent = 1.0;
def upper1 = line * (1 + range_percent / 100);
def lower1 = line * (1 - range_percent / 100);
input look_back_period = 96;
def x = !IsNaN(close[-(look_back_period-1)]) and IsNaN(close[-(look_back_period+0)]);

def cnt;
if bn == 1 then {
  cnt = 0;
} else if lastbar then {
  cnt = fold a = 0 to look_back_period 
  with b
  do b + (if (upper1 > getvalue(close, a) and lower1 < getvalue(close, a)) then 1 else 0);
} else {
 cnt = cnt[1];
}

plot z = cnt;
z.setdefaultcolor(color.cyan);
#
 
Im getting symbol error

# Define the Volume Profile
input pricePerRowHeightMode = {default TICKSIZE, ATR, PERCENT};
input timePerProfile = {default CHART, MINUTE, HOUR, DAY, WEEK, MONTH, "OPT EXP", BAR};
input multiplier = 1;
input onExpansion = yes;
input profiles = 1;
input showPointOfControl = yes;
input showValueArea = yes;
input valueAreaPercent = 70;

def na = Double.NaN;
def bn = BarNumber();
def isNaN = IsNaN(close);
def profile = VolumeProfile("price per row height mode" = pricePerRowHeightMode, "time per profile" = timePerProfile, multiplier = multiplier, onExpansion = onExpansion, numberOfProfiles = profiles, "value area percent" = valueAreaPercent);
def poc = if showPointOfControl then GetValue(profile.GetPointOfControl(), 0) else na;
def vah = if showValueArea then GetValue(profile.GetHighestValueArea(), 0) else na;
def val = if showValueArea then GetValue(profile.GetLowestValueArea(), 0) else na;

# Plot the POC, VAH, and VAL
plot POC = poc;
plot VAH = vah;
plot VAL = val;

POC.SetDefaultColor(Color.RED);
VAH.SetDefaultColor(Color.GREEN);
VAL.SetDefaultColor(Color.BLUE);

# Define Buy and Sell Conditions
def buySignal = close > VAL and close crosses above VAL;
def sellSignal = close VAH and close crosses below VAH;

# Add Orders
AddOrder(OrderType.BUY_AUTO, buySignal, open[-1], 100, Color.CYAN, Color.CYAN, "Buy");
AddOrder(OrderType.SELL_AUTO, sellSignal, open[-1], 100, Color.MAGENTA, Color.MAGENTA, "Sell");

the error lists the line number

this line is missing a comparing symbol.
you have close vah,
missing something in between them.
def sellSignal = close VAH and close crosses below VAH;
 
here is a simplified lower version that should work as a watchlist

Code:
# cnt_closes_within_rng_0_lower

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

declare lower;

def na = Double.NaN;
def bn = BarNumber();

#def lastbn = HighestAll(If(IsNaN(close), 0, bn));
#def lastbar = if (bn == lastbn) then 1 else 0;
def lastbar = !IsNaN(close[0]) and IsNaN(close[-1]);
#def last_close = highestall(if lastbar then close else 0);

#------------------------
#https://usethinkscript.com/threads/current-price-line-indicator-for-thinkorswim.8793/
# Line At Price    Mobius
def barsBack = 1000;
def c = if !IsNaN(close) and IsNaN(close[-1])
       then close
       else c[1];
def line = if IsNaN(close[-barsBack])
       then c[-barsBack]
       else Double.NaN;
#------------------------

input range_percent = 1.0;
def upper1 = line * (1 + range_percent / 100);
def lower1 = line * (1 - range_percent / 100);
input look_back_period = 96;
def x = !IsNaN(close[-(look_back_period-1)]) and IsNaN(close[-(look_back_period+0)]);

def cnt;
if bn == 1 then {
  cnt = 0;
} else if lastbar then {
  cnt = fold a = 0 to look_back_period
  with b
  do b + (if (upper1 > getvalue(close, a) and lower1 < getvalue(close, a)) then 1 else 0);
} else {
 cnt = cnt[1];
}

plot z = cnt;
z.setdefaultcolor(color.cyan);
#
 
Trying a bot script and I have everything good to go BUT 1 thing. Can anyone tell me what I need to fix this?
(Red text)
# Close price, switchable to Heikin Ashi
def src = if useHeikinAshi then
HeikinAshiClose() else close;

Full script below:


# Bot Alerts Test

input a = 1; # Key Value (Sensitivity)
input c = 10; # ATR Period
input useHeikinAshi = no; # Option to switch between regular close and Heikin Ashi candles

# ATR Calculation
def xATR = ATR(c);
# Close price, switchable to Heikin Ashi
def src = if useHeikinAshi then HeikinAshiClose() else close;

# Calculate the trailing stop using ATR
def nLoss = a * xATR;
def xATRTrailingStop = if IsNaN(xATRTrailingStop[1]) then src - nLoss # Initialize the ATR trailing stop
else if src > xATRTrailingStop[1] and src[1] > xATRTrailingStop[1] then Max(xATRTrailingStop[1], src - nLoss)
else if src < xATRTrailingStop[1] and src[1] < xATRTrailingStop[1] then Min(xATRTrailingStop[1], src + nLoss)
else if src > xATRTrailingStop[1] then src - nLoss
else src + nLoss;

# Position state: 1 for long, -1 for short, 0 for neutral
def pos = if IsNaN(pos[1]) then 0 # Initialize position state
else if src[1] < xATRTrailingStop[1] and src > xATRTrailingStop[1] then 1
else if src[1] > xATRTrailingStop[1] and src < xATRTrailingStop[1] then -1
else pos[1];

# EMA Calculation for crossover logic
def ema = ExpAverage(src, 9); # You had '1' period, I adjusted to '9' for typical EMA smoothing
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

# Buy and Sell conditions
def buy = src > xATRTrailingStop and above;
def sell = src < xATRTrailingStop and below;

# Bar coloring conditions
def barbuy = src > xATRTrailingStop;
def barsell = src < xATRTrailingStop;

# Plot signals using arrows
AddChartBubble(buy, low, "Buy", Color.GREEN, yes);
AddChartBubble(sell, high, "Sell", Color.RED, no);

# Set bar colors for buy/sell conditions
AssignPriceColor(if barbuy then Color.GREEN else if barsell then Color.RED else Color.CURRENT);

# Alerts
Alert(buy, "UT Long", Alert.BAR, Sound.Ding);
Alert(sell, "UT Short", Alert.BAR, Sound.Ding);
 
Awesome, I'll let you know how it works, for now tho, I'm struggling with excel calc memory errors, every morning 1-2 hrs. Therefore switching to rtd, getting away from using stockhistory as much as possible. watch out though they could discontinue it, since I mentioned it.
Cheers!!

Update: Your script works like a charm. I'm spoiled now, thank you very much !! What a relief

I updated it to support an RSI (14) with colors for buy & sell signals. All for a watchlist:
-----------------------
# Candle Count & RSI: Watchlist Column study helper for buy/sell signals
(use RSI next to it in a 2nd column w/t/same colors to view actual RSI %'s,
something volume like a vwap could help it also).

def na = Double.NaN;
def bn = BarNumber();
def lastbar = !IsNaN(close[0]) and IsNaN(close[-1]);

input range_percent = 3;
input look_back_period = 96;

# Capture the last closing price within a range
def c = if !IsNaN(close) and IsNaN(close[-1])
then close
else c[1];

def line = if IsNaN(close[-look_back_period])
then c[-look_back_period]
else Double.NaN;

def upper1 = line * (1 + range_percent / 100);
def lower1 = line * (1 - range_percent / 100);

def cnt;
if bn == 1 then {
cnt = 0;
} else if lastbar then {
cnt = fold a = 0 to look_back_period
with b
do b + (if (upper1 > GetValue(close, a) and lower1 < GetValue(close, a)) then 1 else 0);
} else {
cnt = cnt[1];
}

# RSI Calculation
def RSIValue = RSI();

# Conditions
def buyCondition = cnt < 8 and RSIValue < 21;
def buymaybeCondition = cnt < 16 and RSIValue <40;
def sellmaybeCondition = (cnt <= 8 or cnt > 30) and (RSIValue >60 and RSIValue <70);
def sellCondition = (cnt <= 8 or cnt > 30) and RSIValue >= 70;


# Plot the candle count as the only value displayed
plot CandleCount = cnt;

# Assign color to the CandleCount plot based on conditions
CandleCount.AssignValueColor(
if buyCondition then Color.Green # Green for Buy
else if buymaybeCondition then CreateColor(97, 155, 22) # gr dk for buy maybe
else if sellmaybeCondition then CreateColor(178, 109, 218) # pink for Sell maybe
else if sellCondition then CreateColor(208, 43, 98) # Red for Sell
else CreateColor(164, 149, 111 ) # taupe for neutral
);

----
It does not really catch stocks that don't move, like many reit's.
This is a long term catch, rather than an intraday, & of course dud stocks are still included when they're falling out of orbit.
Shorter term intraday, that would be another challenge for this little column.
:)
 
Last edited:
I'm getting started with thinkscript and I would like to write a custom study that can be used in the scanner to find stocks which have a price range from 12pm-4pm EST which is greater than their 9:30am-12pm price range. I would of course run this scan at the end of the day (~3:50pm EST) so that the relevant data is available. It seems simple enough, but the results do not seem to match the criteria. Here is what I have so far:

Code:
# Define the start and end times for both periods
input morningStartTime = 0930;
input morningEndTime = 1200;
input afternoonStartTime = 1201;
input afternoonEndTime = 1530;

# Calculate the morning high and low within the specified time frame
def inMorningSession = SecondsFromTime(morningStartTime) >= 0 and SecondsTillTime(morningEndTime) >= 0;
def morningHigh = if inMorningSession then Max(morningHigh[1], high) else morningHigh[1];
def morningLow = if inMorningSession then Min(morningLow[1], low) else morningLow[1];

# Calculate the afternoon high and low within the specified time frame
def inAfternoonSession = SecondsFromTime(afternoonStartTime) >= 0 and SecondsTillTime(afternoonEndTime) >= 0;
def afternoonHigh = if inAfternoonSession then Max(afternoonHigh[1], high) else afternoonHigh[1];
def afternoonLow = if inAfternoonSession then Min(afternoonLow[1], low) else afternoonLow[1];

# Calculate the ranges for both periods
def morningRange = morningHigh - morningLow;
def afternoonRange = afternoonHigh - afternoonLow;

def isLastBar = SecondsTillTime(afternoonEndTime) <= 0;

# Compare the ranges and plot the condition
plot condition = if isLastBar and afternoonRange > morningRange then 1 else 0;

Apologies that I cannot ask a more specific question, because I've also not been able to figure out how to test or debug my code. I just run it against live data and get a list of stocks which do not meet the criteria I've described. Any point in the right direction would be greatly appreciated.
 
Trying a bot script and I have everything good to go BUT 1 thing. Can anyone tell me what I need to fix this?
(Red text)
# Close price, switchable to Heikin Ashi
def src = if useHeikinAshi then
HeikinAshiClose() else close;

Full script below:


# Bot Alerts Test

input a = 1; # Key Value (Sensitivity)
input c = 10; # ATR Period
input useHeikinAshi = no; # Option to switch between regular close and Heikin Ashi candles

# ATR Calculation
def xATR = ATR(c);
# Close price, switchable to Heikin Ashi
def src = if useHeikinAshi then HeikinAshiClose() else close;

# Calculate the trailing stop using ATR
def nLoss = a * xATR;
def xATRTrailingStop = if IsNaN(xATRTrailingStop[1]) then src - nLoss # Initialize the ATR trailing stop
else if src > xATRTrailingStop[1] and src[1] > xATRTrailingStop[1] then Max(xATRTrailingStop[1], src - nLoss)
else if src < xATRTrailingStop[1] and src[1] < xATRTrailingStop[1] then Min(xATRTrailingStop[1], src + nLoss)
else if src > xATRTrailingStop[1] then src - nLoss
else src + nLoss;

# Position state: 1 for long, -1 for short, 0 for neutral
def pos = if IsNaN(pos[1]) then 0 # Initialize position state
else if src[1] < xATRTrailingStop[1] and src > xATRTrailingStop[1] then 1
else if src[1] > xATRTrailingStop[1] and src < xATRTrailingStop[1] then -1
else pos[1];

# EMA Calculation for crossover logic
def ema = ExpAverage(src, 9); # You had '1' period, I adjusted to '9' for typical EMA smoothing
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

# Buy and Sell conditions
def buy = src > xATRTrailingStop and above;
def sell = src < xATRTrailingStop and below;

# Bar coloring conditions
def barbuy = src > xATRTrailingStop;
def barsell = src < xATRTrailingStop;

# Plot signals using arrows
AddChartBubble(buy, low, "Buy", Color.GREEN, yes);
AddChartBubble(sell, high, "Sell", Color.RED, no);

# Set bar colors for buy/sell conditions
AssignPriceColor(if barbuy then Color.GREEN else if barsell then Color.RED else Color.CURRENT);

# Alerts
Alert(buy, "UT Long", Alert.BAR, Sound.Ding);
Alert(sell, "UT Short", Alert.BAR, Sound.Ding);

no such thing as HeikinAshiClose()
have to use formulas to generate Heiken Ashi Candles

Code:
#chat307_heiken_ashi_choose

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

input a = 1; # Key Value (Sensitivity)
input c = 10; # ATR Period
input useHeikinAshi = no; # Option to switch between regular close and Heikin Ashi candles

#----------------------
#ref
#https://usethinkscript.com/threads/heiken-ashi-overlay-displaced.19472/#post-145865
#Heiken Ashi Candles
def HAclose = (open + high + low + close) / 4;
def HAopen = CompoundValue(1, (HAopen[1] + HAclose[1]) / 2, (open[1] + close[1]) / 2);
def HAhigh = Max(Max(high, HAopen), HAclose[1]);
def HAlow = Min(Min(low, HAopen), HAclose[1]);
#---------------------

def src;
if useHeikinAshi then {
 src  = haclose;
} else {
 src = close;
}


# ATR Calculation
def xATR = ATR(c);
# Close price, switchable to Heikin Ashi
#def src = if useHeikinAshi then HeikinAshiClose() else close;

# Calculate the trailing stop using ATR
def nLoss = a * xATR;
def xATRTrailingStop = if IsNaN(xATRTrailingStop[1]) then src - nLoss # Initialize the ATR trailing stop
else if src > xATRTrailingStop[1] and src[1] > xATRTrailingStop[1] then Max(xATRTrailingStop[1], src - nLoss)
else if src < xATRTrailingStop[1] and src[1] < xATRTrailingStop[1] then Min(xATRTrailingStop[1], src + nLoss)
else if src > xATRTrailingStop[1] then src - nLoss
else src + nLoss;

# Position state: 1 for long, -1 for short, 0 for neutral
def pos = if IsNaN(pos[1]) then 0 # Initialize position state
else if src[1] < xATRTrailingStop[1] and src > xATRTrailingStop[1] then 1
else if src[1] > xATRTrailingStop[1] and src < xATRTrailingStop[1] then -1
else pos[1];

# EMA Calculation for crossover logic
def ema = ExpAverage(src, 9); # You had '1' period, I adjusted to '9' for typical EMA smoothing
def above = Crosses(ema, xATRTrailingStop, CrossingDirection.ABOVE);
def below = Crosses(xATRTrailingStop, ema, CrossingDirection.ABOVE);

# Buy and Sell conditions
def buy = src > xATRTrailingStop and above;
def sell = src < xATRTrailingStop and below;

# Bar coloring conditions
def barbuy = src > xATRTrailingStop;
def barsell = src < xATRTrailingStop;

# Plot signals using arrows
AddChartBubble(buy, low, "Buy", Color.GREEN, no);
AddChartBubble(sell, high, "Sell", Color.RED, yes);

# Set bar colors for buy/sell conditions
AssignPriceColor(if barbuy then Color.GREEN else if barsell then Color.RED else Color.CURRENT);

# Alerts
Alert(buy, "UT Long", Alert.BAR, Sound.Ding);
Alert(sell, "UT Short", Alert.BAR, Sound.Ding);
#
 
I'm getting started with thinkscript and I would like to write a custom study that can be used in the scanner to find stocks which have a price range from 12pm-4pm EST which is greater than their 9:30am-12pm price range. I would of course run this scan at the end of the day (~3:50pm EST) so that the relevant data is available. It seems simple enough, but the results do not seem to match the criteria. Here is what I have so far:

Code:
# Define the start and end times for both periods
input morningStartTime = 0930;
input morningEndTime = 1200;
input afternoonStartTime = 1201;
input afternoonEndTime = 1530;

# Calculate the morning high and low within the specified time frame
def inMorningSession = SecondsFromTime(morningStartTime) >= 0 and SecondsTillTime(morningEndTime) >= 0;
def morningHigh = if inMorningSession then Max(morningHigh[1], high) else morningHigh[1];
def morningLow = if inMorningSession then Min(morningLow[1], low) else morningLow[1];

# Calculate the afternoon high and low within the specified time frame
def inAfternoonSession = SecondsFromTime(afternoonStartTime) >= 0 and SecondsTillTime(afternoonEndTime) >= 0;
def afternoonHigh = if inAfternoonSession then Max(afternoonHigh[1], high) else afternoonHigh[1];
def afternoonLow = if inAfternoonSession then Min(afternoonLow[1], low) else afternoonLow[1];

# Calculate the ranges for both periods
def morningRange = morningHigh - morningLow;
def afternoonRange = afternoonHigh - afternoonLow;

def isLastBar = SecondsTillTime(afternoonEndTime) <= 0;

# Compare the ranges and plot the condition
plot condition = if isLastBar and afternoonRange > morningRange then 1 else 0;

Apologies that I cannot ask a more specific question, because I've also not been able to figure out how to test or debug my code. I just run it against live data and get a list of stocks which do not meet the criteria I've described. Any point in the right direction would be greatly appreciated.

reply to 309


def morningHigh = if inMorningSession then Max(morningHigh[1], high) else morningHigh[1];
you aren't resetting the value. so if price is falling, it will save a price from days ago.


def inAfternoonSession = SecondsFromTime(afternoonStartTime) >= 0 and SecondsTillTime(afternoonEndTime) >= 0;
when using secondstilltime() , usually, just > is used.
then you can use the same number for stop and start.


#input afternoonEndTime = 1530;
i would change this to be 1600, so you run scan any time in afternoon or later.


here is a lower , for testing.
it plots a 1 whenever output is true in the afternoon.
it should work as a scan.

Code:
#chat309_day_2sections

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

declare lower;

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

# Define the start and end times for both periods
input morningStartTime = 0930;
input morningEndTime = 1200;
input afternoonStartTime = 1200;
#input afternoonEndTime = 1530;
input afternoonEndTime = 1600;

def inMorningSession = SecondsFromTime(morningStartTime) >= 0 and SecondsTillTime(morningEndTime) > 0;
def inAfternoonSession = SecondsFromTime(afternoonStartTime) >= 0 and SecondsTillTime(afternoonEndTime) > 0;

# Calculate the morning high and low within the specified time frame
def morningHigh = if (!inMorningSession[1] and inMorningSession) then high
 else if inMorningSession then Max(morningHigh[1], high)
 else morningHigh[1];
def morningLow = if (!inMorningSession[1] and inMorningSession) then low
 else if inMorningSession then Min(morningLow[1], low)
 else morningLow[1];

# Calculate the afternoon high and low within the specified time frame
def afternoonHigh = if inMorningSession then 0
 else if (!inAfternoonSession[1] and inAfternoonSession) then high
 else if inAfternoonSession then Max(afternoonHigh[1], high)
 else afternoonHigh[1];
def afternoonLow = if inMorningSession then big
 else if (!inAfternoonSession[1] and inAfternoonSession) then low
 else if inAfternoonSession then Min(afternoonLow[1], low)
 else afternoonLow[1];

# Calculate the ranges for both periods
def morningRange = morningHigh - morningLow;
def afternoonRange = afternoonHigh - afternoonLow;

def isLastBar = SecondsTillTime(afternoonEndTime) <= 0;

# Compare the ranges and plot the condition
#plot condition = if isLastBar and afternoonRange > morningRange then 1 else 0;
plot condition = if inAfternoonSession and afternoonRange > morningRange then 1 else 0;

#plot z1 =  morningRange;
#plot z2 = if afternoonRange == -big then 0 else afternoonRange;

addchartbubble(0, 0,
 morningRange + "\n" +
 afternoonRange
, color.yellow, yes);
#
 
I have been trying to play around with an existing strategy "PriceSwing" available in TOS. I created my own version of it using chatGPT so that it can work for day trading but for some reason it is not showing entry and exit signals. Help much appreciated.
Below is the code snippet -

# Enhanced Price Swing Indicator for Intraday Trading
input swingType = {default "Pivot High-Low", "Bollinger Bands Crossover", "RSI Crossover", "RSI + Higher Low / Lower High"};
input length = 9; # Shorter for more responsive RSI
input exitLength = 20;
input deviations = 1.5; # More sensitive Bollinger Bands for short time frames
input overbought = 60;
input oversold = 40;
input averageType = AverageType.ExPONENTIAL;

def rsi = reference RSI(length = length, "average type" = averageType);
def bbUpperBand = MovingAverage(averageType, close, length) + deviations * StDev(close, length);
def bbLowerBand = MovingAverage(averageType, close, length) - deviations * StDev(close, length);

def upSwing;
def downSwing;

switch (swingType) {
case "Pivot High-Low":
upSwing = low[1] < low[2] and low[1] < low;
downSwing = high[1] > high[2] and high[1] > high;
case "Bollinger Bands Crossover":
upSwing = close crosses above bbLowerBand;
downSwing = close crosses below bbUpperBand;
case "RSI Crossover":
upSwing = rsi crosses above oversold;
downSwing = rsi crosses below overbought;
case "RSI + Higher Low / Lower High":
upSwing = rsi < oversold and low > low[1];
downSwing = rsi > overbought and high < high[1];
}

# Dynamic exit with ATR Trailing Stop
def atr = reference ATR(14);
def entryPrice = EntryPrice();
def afterEntryCount = if IsNaN(entryPrice[1]) and !IsNaN(entryPrice) then 1 else if !IsNaN(entryPrice) then afterEntryCount[1] + 1 else Double.NaN;

# Trailing stop logic
def trailingStopBuy = if afterEntryCount == 1 then close - atr else Max(trailingStopBuy[1], close - atr);
def trailingStopSell = if afterEntryCount == 1 then close + atr else Min(trailingStopSell[1], close + atr);

# Entry Orders
AddOrder(OrderType.BUY_TO_OPEN, upSwing, tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "PriceSwingLE");
AddOrder(OrderType.SELL_TO_OPEN, downSwing, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "PriceSwingSE");

# Exit Orders using ATR Trailing Stop
AddOrder(OrderType.BUY_TO_CLOSE, close < trailingStopBuy, tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "PriceSwingLX");
AddOrder(OrderType.SELL_TO_CLOSE, close > trailingStopSell, tickcolor = GetColor(3), arrowcolor = GetColor(3), name = "PriceSwingSX");

# Visual feedback: Plot swing highs and lows
plot SwingHigh = if downSwing then high else Double.NaN;
plot SwingLow = if upSwing then low else Double.NaN;

SwingHigh.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SwingLow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);

SwingHigh.SetDefaultColor(Color.RED);
SwingLow.SetDefaultColor(Color.GREEN);
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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