Indicators
SMA / EMA / WMA / HMA #
(series, length)
Various Moving Averages (Simple, Exponential, Weighted, Hull).
SMA 200 Trend Filter Strategy
Demonstrates trend filtering using SMA 200.
# ==================================================
# SMA 200 Trend Filter Strategy
# Demonstrates trend filtering using SMA 200
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Calculate the 200-period Simple Moving Average.
#
# SMA 200 is one of the most widely used
# long-term trend indicators.
sma_200 = SMA(close, 200)
# Market is considered bullish when
# price is trading above the SMA 200.
uptrend = close > sma_200
# Buy only when:
#
# 1. Price crosses above SMA 200
# 2. Market is in an uptrend
buy_signal = crossover(close, sma_200) & uptrend
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when price falls below SMA 200.
#
# This suggests the long-term trend
# may be weakening.
sell_signal = close < sma_200
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Calculate SMA 200 again for chart display.
sma_200 = SMA(close, 200)
# Determine trend direction.
uptrend = close > sma_200
# Plot SMA 200 on the chart.
#
# Many traders use this line to determine
# whether a market is bullish or bearish.
draw(
sma_200,
title="SMA 200",
frame=0,
color="yellow"
)
# Mark buy signals.
#
# Green triangles appear when price
# crosses above the SMA 200.
drawshape(
condition=crossover(close, sma_200),
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Mark sell signals.
#
# Red triangles appear when price
# falls below the SMA 200.
drawshape(
condition=close < sma_200,
shape="triangle_down",
location="AboveBar",
color="red",
size="normal"
)
# Display trend information.
marker_text(
frame=0,
text="SMA 200 Trend Filter",
anchor="top_right"
)
# Display strategy statistics.
marker_table(
frame=0,
data=[
["Trend Filter", "SMA 200"],
["Uptrend", uptrend]
],
position="bottom_right"
)
# Show completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
EMA Crossover Strategy
Demonstrates crossover entry and crossunder exit using two EMAs.
# =================================================
# EMA Crossover Strategy
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Calculate the fast EMA.
#
# EMA 9 reacts quickly to recent
# price movements.
fast_ema = EMA(close, 9)
# Calculate the slow EMA.
#
# EMA 21 reacts more slowly and helps
# identify the broader trend.
slow_ema = EMA(close, 21)
# Bullish crossover occurs when the
# fast EMA crosses above the slow EMA.
#
# This suggests bullish momentum may
# be starting.
bullish_cross = crossover(fast_ema, slow_ema)
# Enter a long position when a
# bullish crossover occurs.
Entry(
index=1,
logic=bullish_cross,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when the fast EMA crosses
# below the slow EMA.
#
# This suggests bullish momentum
# is weakening.
bearish_cross = crossunder(fast_ema, slow_ema)
Exit(
index=1,
logic=bearish_cross,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Calculate the fast EMA.
fast_ema = EMA(close, 9)
# Calculate the slow EMA.
slow_ema = EMA(close, 21)
# Bullish crossover signal.
bullish_cross = crossover(fast_ema, slow_ema)
# Bearish crossover signal.
bearish_cross = crossunder(fast_ema, slow_ema)
# Plot the fast EMA.
#
# Green line follows price more closely.
draw(
fast_ema,
title="EMA 9",
frame=0,
color="green"
)
# Plot the slow EMA.
#
# Red line reacts more slowly and
# filters market noise.
draw(
slow_ema,
title="EMA 21",
frame=0,
color="red"
)
# Draw a green triangle whenever
# a bullish crossover occurs.
drawshape(
condition=bullish_cross,
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Draw a red triangle whenever
# a bearish crossover occurs.
drawshape(
condition=bearish_cross,
shape="triangle_down",
location="AboveBar",
color="red",
size="normal"
)
# Display strategy name.
marker_text(
frame=0,
text="EMA Crossover Strategy",
anchor="top_right"
)
# Show current EMA values.
marker_table(
frame=0,
data=[
["EMA 9", round(fast_ema, 2)],
["EMA 21", round(slow_ema, 2)]
],
position="bottom_right"
)
# Display completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
WMA Rejection Strategy
Demonstrates WMA() based rejection strategy.
# ==================================================
# WMA Rejection Strategy
# Demonstrates WMA()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Calculate the 30-period Weighted Moving Average.
#
# WMA gives more importance to recent prices
# compared to a Simple Moving Average.
wma_30 = WMA(close, 30)
# Price rejection above WMA.
#
# Condition becomes TRUE when the entire candle
# remains above the WMA.
#
# This suggests buyers are defending the trend.
bullish = low > wma_30
# Enter a long position whenever
# the bullish condition is satisfied.
Entry(
index=1,
logic=bullish,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when price falls below WMA.
#
# This suggests trend strength may be weakening.
sell_signal = close < wma_30
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Calculate WMA 30 again for visualization.
wma_30 = WMA(close, 30)
# Plot the WMA on the chart.
#
# The line reacts faster than an SMA
# because recent prices receive more weight.
draw(
wma_30,
title="WMA 30",
frame=0,
color="orange"
)
# Bullish rejection condition.
#
# Entire candle remains above WMA.
bullish = low > wma_30
# Bearish condition.
#
# Price closes below WMA.
bearish = close < wma_30
# Mark bullish rejection candles.
drawshape(
condition=bullish,
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Mark bearish candles.
drawshape(
condition=bearish,
shape="triangle_down",
location="AboveBar",
color="red",
size="normal"
)
# Display strategy name.
marker_text(
frame=0,
text="WMA 30 Rejection Strategy",
anchor="top_right"
)
# Display WMA information.
marker_table(
frame=0,
data=[
["WMA 30", round(wma_30, 2)],
["Bullish", bullish]
],
position="bottom_right"
)
# Display completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
RSI #
(series, period)
Relative Strength Index.
RSI Bullish Momentum Strategy
Buy when RSI crosses above 50, indicating bullish momentum.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate 14-period RSI
rsi_val = RSI(close, 14)
# Buy when RSI crosses above 50, indicating bullish momentum
buy_signal = crossover(rsi_val, 50)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when RSI crosses below 50, indicating bearish momentum
sell_signal = crossunder(rsi_val, 50)
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot RSI in a separate panel
draw(
rsi_val,
title="RSI (14)",
frame=1,
color="blue",
y_range=[0,100]
)
# Display Entry and Exit markers on the chart
marker_trades(
frame=0,
show_pnl=True
)
RSI Bearish Momentum Strategy
Sell when RSI crosses below 50, indicating bearish momentum.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate 14-period RSI
rsi_val = RSI(close, 14)
# Sell when RSI crosses below 50, indicating bearish momentum
sell_signal = crossunder(rsi_val, 50)
Entry(
index=1,
logic=sell_signal,
timeframe=5,
script=RELIANCE,
action=Sell,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when RSI crosses above 50, indicating bullish momentum
buy_signal = crossover(rsi_val, 50)
Exit(
index=1,
logic=buy_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot RSI in a separate panel
draw(
rsi_val,
title="RSI (14)",
frame=1,
color="blue",
y_range=[0,100]
)
# Display Entry and Exit markers on the chart
marker_trades(
frame=0,
show_pnl=True
)
Volume RSI Strategy
Use volume instead of price to calculate RSI.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate 14-period RSI using Volume instead of Price
rsi_volume = RSI(volume, 14)
# Buy when Volume RSI crosses above 50, indicating increasing buying activity
buy_signal = crossover(rsi_volume, 50)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when Volume RSI crosses below 50, indicating weakening buying activity
sell_signal = crossunder(rsi_volume, 50)
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot Volume RSI
draw(
rsi_volume,
title="RSI Volume",
frame=1,
color="red"
)
# Overbought level
draw(
80,
title="Overbought",
frame=1,
color="red"
)
# Midline
draw(
50,
title="Midline",
frame=1,
color="white"
)
# Oversold level
draw(
20,
title="Oversold",
frame=1,
color="green"
)
# Display Entry and Exit markers
marker_trades(
frame=0,
show_pnl=True
)
MACD #
(source, fastlen, slowlen, siglen)
Moving Average Convergence Divergence. Returns [macd, signal, hist].
RSI Snapshot Strategy
Capture indicator values exactly when RSI crosses 70.
# ==================================================
# RSI Snapshot Strategy | entry_logic.ta
# ==================================================
ema20 = EMA(close, 20)
rsi14 = RSI(close, 14)
atr14 = ATR(14)
trend_up = close > ema20
rsi_entry = crossover(rsi14, 50)
buy_signal = trend_up & rsi_entry
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
overbought = crossover(rsi14, 70)
# Capture indicator values exactly when RSI crosses 70
log_snapshot_on_event(
overbought,
close_price=close,
ema20=ema20,
rsi_value=rsi14,
atr_value=atr14,
open_profit=open_pnl,
bars_held=bars_in_trade
)
exit_signal = overbought | DayLastBar
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
draw(
rsi14,
title="RSI 14",
frame=1,
color="purple"
)
draw(
70,
title="Overbought",
frame=1,
color="red"
)
marker_trades(
frame=0,
show_pnl=True
)
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
MACD Snapshot Strategy
Capture market state at exit using log_snapshot_on_event with MACD.
# ==================================================
# MACD Snapshot Strategy | entry_logic.ta
# ==================================================
# Indicators
macd_line, signal_line, histogram = MACD(close, 12, 26, 9)
ema50 = EMA(close, 50)
# Entry Conditions
trend_up = close > ema50
macd_bull = crossover(macd_line, signal_line)
long_entry = trend_up & macd_bull
Entry(
index=1,
logic=long_entry,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
# Exit Condition
macd_bear = crossunder(macd_line, signal_line)
# Capture market state at exit
log_snapshot_on_event(
macd_bear,
close_price=close,
macd=macd_line,
signal=signal_line,
histogram=histogram,
ema50=ema50,
pnl=open_pnl,
bars=bars_in_trade
)
Exit(
index=1,
logic=macd_bear,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
ema50,
title="EMA 50",
frame=0,
color="orange"
)
draw(
macd_line,
title="MACD",
frame=1,
color="blue"
)
draw(
signal_line,
title="Signal",
frame=1,
color="red"
)
marker_trades(
frame=0,
show_pnl=True
)
drawshape(
condition=long_entry,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
bb #
(series, length, mult)
Bollinger Bands. Returns [mid, upper, lower].
Bollinger Bands Breakout Strategy
Buy when price breaks above the Upper Band.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Bollinger Bands (20 Period, 2 Standard Deviations)
upper_band, middle_band, lower_band = bb(close, 20, 2)
# Buy when price breaks above the Upper Band,
# indicating a bullish breakout
buy_signal = crossover(close, upper_band)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below the Middle Band,
# indicating bullish momentum is weakening
exit_signal = crossunder(close, middle_band)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot Bollinger Bands
draw(
upper_band,
title="BB Upper",
frame=0,
color="red"
)
draw(
middle_band,
title="BB Middle",
frame=0,
color="white"
)
draw(
lower_band,
title="BB Lower",
frame=0,
color="green"
)
# Highlight the Bollinger Band range
marker_fill(
frame=0,
line1=upper_band,
line2=lower_band,
color="rgba(0,150,255,0.08)"
)
# Mark Buy signals
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Display executed trades
marker_trades(
frame=0,
show_pnl=True
)
Bollinger Bands Reversal Strategy
Buy when price crosses back above the Lower Band.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Bollinger Bands (20 Period, 2 Standard Deviations)
upper_band, middle_band, lower_band = bb(close, 20, 2)
# Buy when price crosses back above the Lower Band,
# indicating a potential reversal from an oversold condition
buy_signal = crossover(close, lower_band)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price reaches the Middle Band,
# which acts as the mean of the Bollinger Bands
exit_signal = crossover(close, middle_band)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# Bollinger Bands Indicator
# Displays the Upper, Middle, and Lower Bollinger Bands.
# ==================================================
draw(
upper_band,
title="BB Upper",
frame=0,
color="red"
)
draw(
middle_band,
title="BB Middle",
frame=0,
color="white"
)
draw(
lower_band,
title="BB Lower",
frame=0,
color="green"
)
marker_trades(
frame=0,
show_pnl=True
)
SuperTrend #
(atrPeriod=10, factor=3.0)
SuperTrend indicator. Returns (trend, dir).
SuperTrend Strategy 1
Buy when SuperTrend turns bullish.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate SuperTrend
st_val, st_dir = SuperTrend(atrPeriod=10, factor=3.0)
# Buy when SuperTrend turns bullish
buy_signal = st_dir == 1
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when SuperTrend turns bearish
exit_signal = st_dir == -1
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot SuperTrend
draw(
st_val,
title="SuperTrend",
frame=0,
color="green"
)
# Display Entry and Exit markers
marker_trades(
frame=0,
show_pnl=True
)
SuperTrend Strategy 2
Buy when SuperTrend changes from bearish to bullish.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate SuperTrend
st_val, st_dir = SuperTrend(
atrPeriod=10,
factor=3.0
)
# Buy when SuperTrend changes from bearish to bullish
buy_signal = crossover(st_dir, 0)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when SuperTrend changes from bullish to bearish
exit_signal = crossunder(st_dir, 0)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot SuperTrend
draw(
st_val,
title="SuperTrend",
frame=0,
color="green"
)
# Mark Buy signals
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Strategy name
marker_text(
frame=0,
text="SuperTrend Strategy",
anchor="top_right"
)
# Display Entry and Exit markers
marker_trades(
frame=0,
show_pnl=True
)
VWAP #
(source=hlc3)
Volume-Weighted Average Price.
VWAP Strategy 1
Buy when price crosses above VWAP.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate VWAP
vwap_line = VWAP(ohlc4)
# Buy when price crosses above VWAP,
# indicating bullish momentum
buy_signal = crossover(close, vwap_line)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below VWAP,
# indicating weakening bullish momentum
exit_signal = crossunder(close, vwap_line)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# VWAP Indicator
# Displays Volume Weighted Average Price (VWAP).
# ==================================================
draw(
vwap_line,
title="VWAP",
frame=0,
color="yellow"
)
marker_text(
frame=0,
text="VWAP Indicator",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
VWAP Strategy 2
Buy when price crosses above VWAP.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate VWAP
vwap_val = VWAP(hlc3)
# Buy when price crosses above VWAP,
# indicating bullish momentum
buy_signal = crossover(close, vwap_val)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below VWAP,
# indicating bearish momentum
exit_signal = crossunder(close, vwap_val)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot VWAP
draw(
vwap_val,
title="VWAP",
frame=0,
color="yellow"
)
# Mark Buy signals
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Display Entry and Exit markers
marker_trades(
frame=0,
show_pnl=True
)
Ichimoku #
(conversionLinePeriod, baseLinePeriod, ...)
Returns [tenkan, kijun, senkou_a, senkou_b, chikou].
Tenkan & Kijun Crossover Strategy
Buy when the Tenkan Line crosses above the Kijun Line.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Ichimoku Cloud
tenkan, kijun, senkou_a, senkou_b, chikou = Ichimoku(
9,
26,
52,
26
)
# Buy when the Tenkan Line crosses above the Kijun Line,
# indicating a bullish trend reversal
buy_signal = crossover(tenkan, kijun)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when the Tenkan Line crosses below the Kijun Line,
# indicating a bearish trend reversal
exit_signal = crossunder(tenkan, kijun)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# Ichimoku Cloud Indicator
# Displays all Ichimoku Cloud components.
# ==================================================
draw(
tenkan,
title="Tenkan",
frame=0,
color="red"
)
draw(
kijun,
title="Kijun",
frame=0,
color="blue"
)
draw(
senkou_a,
title="Senkou A",
frame=0,
color="green"
)
draw(
senkou_b,
title="Senkou B",
frame=0,
color="orange"
)
draw(
chikou,
title="Chikou",
frame=0,
color="purple"
)
# Cloud Area
marker_fill(
frame=0,
line1=senkou_a,
line2=senkou_b,
color="rgba(0,255,0,0.08)"
)
marker_text(
frame=0,
text="Ichimoku Cloud",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Cloud Breakout Strategy
Buy when price breaks above the Ichimoku Cloud.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Ichimoku Cloud
tenkan, kijun, senkou_a, senkou_b, chikou = Ichimoku(
9,
26,
52,
26
)
# Buy when price breaks above the Ichimoku Cloud,
# indicating a strong bullish trend
buy_signal = crossover(close, senkou_a)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the Kijun Line,
# indicating the bullish trend is weakening
exit_signal = crossunder(close, kijun)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Ichimoku Cloud Indicator
# Displays all Ichimoku Cloud components.
# ============================================================
draw(
tenkan,
title="Tenkan",
frame=0,
color="red"
)
draw(
kijun,
title="Kijun",
frame=0,
color="blue"
)
draw(
senkou_a,
title="Senkou A",
frame=0,
color="green"
)
draw(
senkou_b,
title="Senkou B",
frame=0,
color="orange"
)
draw(
chikou,
title="Chikou",
frame=0,
color="purple"
)
marker_fill(
frame=0,
line1=senkou_a,
line2=senkou_b,
color="rgba(0,255,0,0.08)"
)
marker_trades(
frame=0,
show_pnl=True
)
ATR / STDDEV #
(length)
Average True Range and Standard Deviation volatility indicators.
High Volatility ATR Strategy
Buy when current ATR is greater than the 50-period ATR.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate ATR
atr_val = ATR(14)
# Buy when current ATR is greater than the 50-period ATR,
# indicating increasing market volatility
buy_signal = atr_val > ATR(50)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when current ATR falls below the 50-period ATR,
# indicating volatility is decreasing
exit_signal = atr_val < ATR(50)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ATR Indicator
# Displays the current ATR and the 50-period ATR.
# ============================================================
draw(
atr_val,
title="ATR (14)",
frame=1,
color="orange"
)
draw(
ATR(50),
title="ATR (50)",
frame=1,
color="blue"
)
marker_trades(
frame=0,
show_pnl=True
)
Volatility Expansion STDDEV Strategy
Buy when volatility increases above its recent average.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Standard Deviation
std_20 = STDDEV(close, 20)
# Buy when volatility increases above its recent average
buy_signal = crossover(std_20, SMA(std_20, 10))
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when volatility falls below its recent average
exit_signal = crossunder(std_20, SMA(std_20, 10))
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Standard Deviation Indicator
# ============================================================
draw(
std_20,
title="STDDEV 20",
frame=1,
color="orange"
)
draw(
SMA(std_20, 10),
title="STDDEV SMA",
frame=1,
color="blue"
)
marker_text(
frame=1,
text="STDDEV Indicator",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
ATR Trend Filter Strategy
Buy when price crosses above the EMA during high volatility.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate EMA and ATR
ema20 = EMA(close, 20)
atr14 = ATR(14)
# Buy when price crosses above the EMA during high volatility
buy_signal = crossover(close, ema20) & (atr14 > 10)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the EMA
exit_signal = crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ATR Trend Filter Strategy
# ============================================================
# EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
# ATR
draw(
atr14,
title="ATR 14",
frame=1,
color="orange"
)
# ATR Threshold
draw(
10,
title="Volatility Threshold",
frame=1,
color="red"
)
# Display trades
marker_trades(
frame=0,
show_pnl=True
)
marker_text(
frame=0,
text="ATR Trend Filter",
anchor="top_right"
)
Stochastic #
(source, high, low, length)
Stochastic Oscillator momentum indicator.
Stochastic Overbought / Oversold Reversal Strategy
Buy when %K crosses above %D in the oversold zone.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Stochastic
k_line, d_line = Stochastic(close, high, low, 14, 3, 3)
# Buy when %K crosses above %D in the oversold zone
buy_zone = (k_line < 20) | (d_line < 20)
buy_signal = crossover(k_line, d_line) & buy_zone
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Calculate Stochastic
k_line, d_line = Stochastic(close, high, low, 14, 3, 3)
# Exit when %K crosses below %D in the overbought zone
sell_zone = (k_line > 80) | (d_line > 80)
exit_signal = crossunder(k_line, d_line) & sell_zone
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate Stochastic
k_line, d_line = Stochastic(close, high, low, 14, 3, 3)
# Overbought / Oversold Levels
ob_line = k_line * 0 + 80
os_line = k_line * 0 + 20
# Plot %K and %D
draw(
k_line,
title="%K Line",
frame=1,
color="#00FFFF"
)
draw(
d_line,
title="%D Line",
frame=1,
color="#FFA500"
)
draw(
ob_line,
title="Overbought",
frame=1,
color="#FF3333"
)
draw(
os_line,
title="Oversold",
frame=1,
color="#33FF33"
)
marker_trades(
frame=0,
show_pnl=True
)
Stochastic Bullish Momentum Strategy
Buy when %K crosses above %D while both are above 50.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Stochastic
k_line, d_line = Stochastic(close, high, low, 14, 3, 3)
# Buy when %K crosses above %D while both are above 50,
# indicating bullish momentum
buy_signal = crossover(k_line, d_line) & (k_line > 50)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when %K crosses below %D or falls below 50,
# indicating weakening momentum
exit_signal = crossunder(k_line, d_line) | (k_line < 50)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot %K and %D
draw(
k_line,
title="%K Line",
frame=1,
color="#00FFFF"
)
draw(
d_line,
title="%D Line",
frame=1,
color="#FFA500"
)
# Midline
draw(
50,
title="Midline",
frame=1,
color="white"
)
# Overbought
draw(
80,
title="Overbought",
frame=1,
color="#FF3333"
)
# Oversold
draw(
20,
title="Oversold",
frame=1,
color="#33FF33"
)
marker_trades(
frame=0,
show_pnl=True
)
DMI #
(diLength=14, adxSmoothing=14)
Directional Movement Index. Returns [di_plus, di_minus, adx].
DMI Crossover Strategy
Buy when +DI crosses above -DI.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate DMI Components
di_plus, di_minus, adx = DMI(14, 14)
# Buy when +DI crosses above -DI,
# indicating buyers are gaining strength
buy_signal = crossover(di_plus, di_minus)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when -DI crosses above +DI,
# indicating sellers are gaining strength
exit_signal = crossover(di_minus, di_plus)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot +DI
draw(
di_plus,
title="+DI",
frame=1,
color="green"
)
# Plot -DI
draw(
di_minus,
title="-DI",
frame=1,
color="red"
)
# Plot ADX
draw(
adx,
title="ADX",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="DMI Indicator",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Strong Trend DMI Strategy
Buy when ADX rises above 25 and DI+ is greater than DI-.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate DMI Components
di_plus, di_minus, adx = DMI(
diLength=14,
adxSmoothing=14
)
# Buy when ADX rises above 25 and DI+ is greater than DI-,
# indicating a strong bullish trend
buy_signal = crossover(adx, 25) & (di_plus > di_minus)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when DI- becomes greater than DI+,
# indicating bearish strength
exit_signal = di_minus > di_plus
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# DMI Indicator
# Displays DI+, DI-, and ADX trend strength lines.
# ==================================================
di_plus, di_minus, adx = DMI(
diLength=14,
adxSmoothing=14
)
draw(
di_plus,
title="DI+",
frame=1,
color="green"
)
draw(
di_minus,
title="DI-",
frame=1,
color="red"
)
draw(
adx,
title="ADX",
frame=1,
color="yellow"
)
draw(
25,
title="Trend Strength",
frame=1,
color="white"
)
marker_text(
frame=1,
text="DMI Indicator",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
PSAR #
(start_af=0.02, step_af=0.02, max_af=0.20)
Parabolic Stop and Reverse.
PSAR Trend Reversal Strategy
Buy when PSAR flips below the price.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate PSAR
psar_val = PSAR(0.02, 0.02, 0.20)
# Buy when PSAR flips below the price,
# indicating the start of an uptrend
buy_signal = psar_val < close
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when PSAR moves above the price,
# indicating a possible trend reversal
exit_signal = psar_val > close
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Parabolic SAR Indicator
# Displays trend reversal levels.
# ============================================================
psar_val = PSAR(0.02, 0.02, 0.20)
draw(
psar_val,
title="PSAR",
frame=0,
color="orange"
)
marker_text(
frame=0,
text="PSAR Indicator",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
PSAR + EMA Trend Filter Strategy
Buy when price crosses above the 20 EMA while remaining above the PSAR.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate PSAR and EMA
psar_val = PSAR(0.02, 0.02, 0.20)
ema20 = EMA(close, 20)
# Buy when price crosses above the 20 EMA
# while remaining above the PSAR
buy_signal = crossover(close, ema20) & (close > psar_val)
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price closes below the PSAR
exit_signal = crossunder(close, psar_val)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate PSAR and EMA
psar_val = PSAR(0.02, 0.02, 0.20)
ema20 = EMA(close, 20)
# Plot PSAR
draw(
psar_val,
title="PSAR",
frame=0,
color="orange"
)
# Plot EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
marker_text(
frame=0,
text="PSAR + EMA Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
CCI #
(source=hlc3, length=20)
Commodity Channel Index.
CCI Oversold Recovery Strategy
Buy when CCI crosses above -100.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate CCI
cci_val = CCI(hlc3, 20)
# Buy when CCI crosses above -100,
# indicating recovery from an oversold condition
buy_signal = crossover(cci_val, -100)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when CCI enters the overbought zone
exit_signal = cci_val > 100
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# CCI Indicator
# ============================================================
# Plot CCI
draw(
cci_val,
title="CCI (20)",
frame=1,
color="orange"
)
# Overbought Level
draw(
100,
title="Overbought",
frame=1,
color="red"
)
# Oversold Level
draw(
-100,
title="Oversold",
frame=1,
color="green"
)
# Zero Line
draw(
0,
title="Zero Line",
frame=1,
color="white"
)
marker_trades(
frame=0,
show_pnl=True
)
CCI Zero Line Crossover Strategy
Buy when CCI crosses above the Zero Line.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate CCI
cci_val = CCI(hlc3, 20)
# Buy when CCI crosses above the Zero Line,
# indicating bullish momentum
buy_signal = crossover(cci_val, 0)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when CCI crosses below the Zero Line,
# indicating bearish momentum
exit_signal = crossunder(cci_val, 0)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# CCI Indicator
# ============================================================
draw(
cci_val,
title="CCI (20)",
frame=1,
color="orange"
)
draw(
100,
title="Overbought",
frame=1,
color="red"
)
draw(
0,
title="Zero Line",
frame=1,
color="white"
)
draw(
-100,
title="Oversold",
frame=1,
color="green"
)
marker_trades(
frame=0,
show_pnl=True
)
PivotPoints #
()
Returns [P, BC, TC, R1, S1, R2, S2, R3, S3].
Pivot Crossover Strategy
Buy when price crosses above the Pivot Point.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Pivot Points
P, BC, TC, R1, S1, R2, S2, R3, S3 = PivotPoints()
# Buy when price crosses above the Pivot Point,
# indicating bullish momentum
buy_signal = crossover(close, P)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price reaches the first resistance level
exit_signal = crossover(close, R1)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Pivot Point Indicator
# ============================================================
P, BC, TC, R1, S1, R2, S2, R3, S3 = PivotPoints()
draw(
P,
title="Pivot",
frame=0,
color="white"
)
draw(
BC,
title="Bottom Central",
frame=0,
color="cyan"
)
draw(
TC,
title="Top Central",
frame=0,
color="cyan"
)
draw(
R1,
title="Resistance 1",
frame=0,
color="red"
)
draw(
S1,
title="Support 1",
frame=0,
color="green"
)
draw(
R2,
title="Resistance 2",
frame=0,
color="#FF8800"
)
draw(
S2,
title="Support 2",
frame=0,
color="#00AA00"
)
marker_text(
frame=0,
text="Pivot Point Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Pivot Support Bounce Strategy
Buy when price bounces above Support 1.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Pivot Points
P, BC, TC, R1, S1, R2, S2, R3, S3 = PivotPoints()
# Buy when price bounces above Support 1,
# indicating buyers are defending the support level
buy_signal = crossover(close, S1)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price reaches the Pivot Point
exit_signal = crossover(close, P)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Pivot Point Indicator
# ============================================================
P, BC, TC, R1, S1, R2, S2, R3, S3 = PivotPoints()
draw(P, title="Pivot", frame=0, color="white")
draw(BC, title="BC", frame=0, color="cyan")
draw(TC, title="TC", frame=0, color="cyan")
draw(R1, title="R1", frame=0, color="red")
draw(S1, title="S1", frame=0, color="green")
draw(R2, title="R2", frame=0, color="#FF8800")
draw(S2, title="S2", frame=0, color="#00AA00")
draw(R3, title="R3", frame=0, color="#FF4444")
draw(S3, title="S3", frame=0, color="#008800")
marker_text(
frame=0,
text="Pivot Support Bounce",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
DonchianChannels #
(length=20)
Returns [upper, mid, lower].
Donchian Channel Breakout Strategy
Buy when price breaks above the Upper Channel.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Donchian Channels
dc_upper, dc_mid, dc_lower = DonchianChannels(20)
# Buy when price breaks above the Upper Channel,
# indicating a bullish breakout
buy_signal = crossover(close, dc_upper)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the Middle Channel,
# indicating the trend is weakening
exit_signal = crossunder(close, dc_mid)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Donchian Channels Indicator
# ============================================================
dc_upper, dc_mid, dc_lower = DonchianChannels(20)
draw(
dc_upper,
title="DC Upper",
frame=0,
color="red"
)
draw(
dc_mid,
title="DC Middle",
frame=0,
color="white"
)
draw(
dc_lower,
title="DC Lower",
frame=0,
color="green"
)
marker_fill(
frame=0,
line1=dc_upper,
line2=dc_lower,
color="rgba(0,150,255,0.08)"
)
marker_text(
frame=0,
text="Donchian Breakout",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Donchian Midline Strategy
Buy when price crosses above the Middle Channel.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate Donchian Channels
dc_upper, dc_mid, dc_lower = DonchianChannels(30)
# Buy when price crosses above the Middle Channel,
# indicating bullish momentum
buy_signal = crossover(close, dc_mid)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below the Lower Channel,
# indicating a bearish breakout
exit_signal = crossunder(close, dc_lower)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# Donchian Channels Indicator
# Displays upper, middle and lower channel bands.
# ============================================================
dc_upper, dc_mid, dc_lower = DonchianChannels(30)
draw(
dc_upper,
title="Upper",
frame=0,
color="red"
)
draw(
dc_mid,
title="Middle",
frame=0,
color="white"
)
draw(
dc_lower,
title="Lower",
frame=0,
color="green"
)
marker_trades(
frame=0,
show_pnl=True
)
Logic & State
crossover / crossunder #
(series1, series2)
True if series1 just crossed above or below series2.
VWAP Crossover Strategy
Buy when price crosses above VWAP.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate VWAP
vwap_val = VWAP(hlc3)
# Buy when price crosses above VWAP,
# indicating bullish momentum
buy_signal = crossover(close, vwap_val)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Calculate VWAP
vwap_val = VWAP(hlc3)
# Exit when price crosses below VWAP,
# indicating bearish momentum
exit_signal = crossunder(close, vwap_val)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate VWAP
vwap_val = VWAP(hlc3)
# Plot VWAP
draw(
vwap_val,
title="VWAP",
frame=0,
color="yellow"
)
marker_trades(
frame=0,
show_pnl=True
)
RSI Crossover Strategy
Buy when RSI crosses above 50.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate RSI
rsi_14 = RSI(close, 14)
# Buy when RSI crosses above 50,
# indicating bullish momentum
buy_signal = crossover(rsi_14, 50)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when RSI crosses below 50,
# indicating bearish momentum
exit_signal = crossunder(rsi_14, 50)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate RSI
rsi_14 = RSI(close, 14)
# Plot RSI
draw(
rsi_14,
title="RSI (14)",
frame=1,
color="blue"
)
# Overbought Level
draw(
70,
title="Overbought",
frame=1,
color="red"
)
# Midline
draw(
50,
title="Midline",
frame=1,
color="white"
)
# Oversold Level
draw(
30,
title="Oversold",
frame=1,
color="green"
)
marker_trades(
frame=0,
show_pnl=True
)
iff #
(condition, true_val, false_val)
Vectorized if. Returns true_val if condition is true, else false_val.
IFF Strategy (Dynamic EMA)
Use iff to dynamically select between EMA 20 and EMA 50 based on volatility.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate ATR and EMAs
atr14 = ATR(14)
atr50 = ATR(50)
ema20 = EMA(close, 20)
ema50 = EMA(close, 50)
# If volatility is high, use EMA 20.
# Otherwise, use EMA 50.
trend_line = iff(atr14 > atr50, ema20, ema50)
# Buy when price crosses above the selected trend line
buy_signal = crossover(close, trend_line)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below the selected trend line
exit_signal = crossunder(close, trend_line)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
draw(
trend_line,
title="Dynamic EMA",
frame=0,
color="yellow"
)
draw(
ema20,
title="EMA 20",
frame=0,
color="green"
)
draw(
ema50,
title="EMA 50",
frame=0,
color="red"
)
marker_text(
frame=0,
text="IFF Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
IFF Score Strategy
Build a numeric signal score based on multiple conditions using nested iff.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate RSI and EMAs
rsi_14 = RSI(close, 14)
ema20 = EMA(close, 20)
ema50 = EMA(close, 50)
# Trend Filter
trend_ok = ema20 > ema50
# Assign a score based on trend and RSI strength
# 2 = Strong Bullish
# 1 = Moderate Bullish
# 0 = Neutral
# -1 = Bearish
score = iff(
trend_ok & (rsi_14 > 60),
2,
iff(
trend_ok & (rsi_14 > 50),
1,
iff(
rsi_14 < 40,
-1,
0
)
)
)
# Buy only when the score is strongly bullish
buy_signal = score == 2
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when the score becomes neutral or bearish
exit_signal = score <= 0
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMAs
draw(
ema20,
title="EMA 20",
frame=0,
color="green"
)
draw(
ema50,
title="EMA 50",
frame=0,
color="red"
)
# Plot Score
draw(
score,
title="Trend Score",
frame=1,
color="blue"
)
marker_text(
frame=1,
text="IFF Score Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
IFF Time-Based Strategy
Select different RSI thresholds depending on the time of day.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate RSI
rsi_14 = RSI(close, 14)
# Morning session uses a lower RSI threshold,
# while the afternoon requires stronger momentum.
morning = time < 1130
threshold = iff(
morning,
55,
62
)
# Buy when RSI is above the selected threshold
buy_signal = rsi_14 > threshold
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=BANKNIFTY,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when RSI falls below the active threshold
exit_signal = rsi_14 < threshold
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot RSI
draw(
rsi_14,
title="RSI (14)",
frame=1,
color="blue"
)
# Plot Dynamic Threshold
draw(
threshold,
title="Dynamic RSI Threshold",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="IFF Time-Based Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
valuewhen #
(condition, source, occurrence=0)
Gets the value of source when the n-th condition occurred.
ValueWhen Strategy
Retrieve the close price at the moment of the most recent buy signal.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate EMAs
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
# Buy when the fast EMA crosses above the slow EMA
buy_signal = crossover(fast_ema, slow_ema)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Store the price where the last buy signal occurred
entry_price = valuewhen(buy_signal, close, 0)
# Calculate profit from the entry price
unrealised_move = close - entry_price
# Exit after gaining 100 points
exit_signal = unrealised_move >= 100
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate EMAs
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
# Plot EMAs
draw(
fast_ema,
title="EMA 9",
frame=0,
color="green"
)
draw(
slow_ema,
title="EMA 21",
frame=0,
color="red"
)
# Plot Entry Price
draw(
entry_price,
title="Entry Price",
frame=0,
color="yellow"
)
marker_text(
frame=0,
text="ValueWhen Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Pivot Breakout Strategy
Get the high value at the last pivot peak — useful for resistance tracking.
# ============================================================
# entry_logic.ta
# ============================================================
# Detect Pivot High
pivot_peak = peak(high, 5, 2)
# Get the High of the most recent Pivot
last_swing_high = valuewhen(pivot_peak, high, 0)
# Buy when price breaks above the last Pivot High
buy_signal = close > last_swing_high
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the 20 EMA
ema20 = EMA(close, 20)
exit_signal = crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Detect Pivot High
pivot_peak = peak(high, 5, 2)
# Get the High of the most recent Pivot
last_swing_high = valuewhen(pivot_peak, high, 0)
# Plot Last Swing High
draw(
last_swing_high,
title="Last Swing High",
frame=0,
color="red"
)
# Plot EMA
draw(
EMA(close, 20),
title="EMA 20",
frame=0,
color="blue"
)
marker_text(
frame=0,
text="Pivot Breakout Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
highest / lowest #
(source, length)
Highest/Lowest value over a lookback period.
Example
# 20-day High and Low
high_20 = highest(high, 20)
low_20 = lowest(low, 20)
# Donchian Channel logic
breakout_high = close > high_20[1]
Range Squeeze Strategy
Buy when price breaks above the 5-bar High after a squeeze.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate the short-term and long-term trading ranges
range_5 = highest(high, 5) - lowest(low, 5)
range_20 = highest(high, 20) - lowest(low, 20)
# A squeeze occurs when the recent range is much
# smaller than the longer-term range
squeeze = range_5 < (range_20 * 0.30)
# Buy when price breaks above the 5-bar High
# after a squeeze
buy_signal = squeeze & crossover(close, highest(high, 5))
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the 5-bar Low
exit_signal = crossunder(close, lowest(low, 5))
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot the trading ranges
draw(
range_5,
title="5-Bar Range",
frame=1,
color="green"
)
draw(
range_20,
title="20-Bar Range",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="Range Squeeze Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Lowest Recovery Strategy
Buy when price recovers above the previous 20-bar Low after testing it.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate the 20-bar Low
low_20 = lowest(low, 20)
# Buy when price recovers above the previous
# 20-bar Low after testing it
buy_signal = crossover(close, low_20)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price reaches the 20 EMA
ema20 = EMA(close, 20)
exit_signal = crossover(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
low_20 = lowest(low, 20)
ema20 = EMA(close, 20)
draw(
low_20,
title="20-Bar Low",
frame=0,
color="green"
)
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
marker_text(
frame=0,
text="Lowest Recovery Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
highestbars / lowestbars #
(source, length)
Bar offset to the highest/lowest value over a lookback period.
Example
# Find how many bars ago the highest high occurred
offset_high = highestbars(high, 50)
# If offset is 0, the current bar is the highest
is_new_high = offset_high == 0
HighestBars Strategy
Check if the current bar has the highest High of the last 20 bars.
# ============================================================
# entry_logic.ta
# ============================================================
# Check if the current bar has the highest High
# of the last 20 bars
is_new_20_high = highestbars(high, 20) == 0
Entry(
index=1,
logic=is_new_20_high,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when the current bar has the lowest Low
# of the last 20 bars
exit_signal = lowestbars(low, 20) == 0
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot the 20-bar Highest High
draw(
highest(high, 20),
title="20-Bar High",
frame=0,
color="red"
)
# Plot the 20-bar Lowest Low
draw(
lowest(low, 20),
title="20-Bar Low",
frame=0,
color="green"
)
marker_text(
frame=0,
text="HighestBars Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
LowestBars Reversal
Buy when the current candle makes a new 20-bar low, indicating a potential reversal zone.
# ============================================================
# entry_logic.ta
# ============================================================
# Find how many bars ago the lowest Low occurred
offset_low = lowestbars(low, 20)
# Buy when the current candle makes a new 20-bar low,
# indicating a potential reversal zone
buy_signal = offset_low == 0
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price reaches the 20 EMA
ema20 = EMA(close, 20)
exit_signal = crossover(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate EMA
ema20 = EMA(close, 20)
# Plot EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
# Plot Lowest Low of the last 20 bars
draw(
lowest(low, 20),
title="20-Bar Low",
frame=0,
color="green"
)
marker_text(
frame=0,
text="LowestBars Reversal",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Market Structure Strategy
If the last High is old but a new Low has formed recently, the market structure is turning bearish.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate EMA
ema20 = EMA(close, 20)
# Buy when price crosses above the 20 EMA
buy_signal = crossover(close, ema20)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Find the age of the highest High and lowest Low
age_high = highestbars(high, 30)
age_low = lowestbars(low, 30)
# If the last High is old but a new Low has formed recently,
# the market structure is turning bearish
bearish_struct = (age_high > 10) & (age_low < 3)
Exit(
index=1,
logic=bearish_struct,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
# Plot Age of Highest High
draw(
age_high,
title="High Age",
frame=1,
color="red"
)
# Plot Age of Lowest Low
draw(
age_low,
title="Low Age",
frame=1,
color="green"
)
marker_text(
frame=1,
text="Market Structure Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
increasing / decreasing #
(source, length)
Checks if a series has been consistently rising or falling.
Example
# Check if RSI has been rising for 3 bars
rsi_rising = increasing(rsi_14, 3)
# Check if volume is falling
vol_falling = decreasing(volume, 5)
Increasing EMA Strategy
Enter only when EMA 20 has been consistently rising for 3 bars — confirmed trend.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate EMA and RSI
ema20 = EMA(close, 20)
rsi_14 = RSI(close, 14)
# EMA has been rising for the last 3 bars
ema_rising = increasing(ema20, 3)
# RSI confirms bullish momentum
rsi_bull = rsi_14 > 55
# Buy when both conditions are satisfied
buy_signal = ema_rising & rsi_bull
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when the EMA starts falling for 2 consecutive bars
ema_falling = decreasing(ema20, 2)
Exit(
index=1,
logic=ema_falling,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
# Plot RSI
draw(
rsi_14,
title="RSI (14)",
frame=1,
color="orange"
)
# RSI Confirmation Level
draw(
55,
title="RSI 55",
frame=1,
color="green"
)
marker_text(
frame=1,
text="Increasing EMA Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Volume Contraction Strategy
Detect when volume has been decreasing for 4 bars — potential breakout setup.
# ============================================================
# entry_logic.ta
# ============================================================
# Volume has been decreasing for the last 4 bars
vol_contracting = decreasing(volume, 4)
# Price range is tight relative to ATR
range_tight = (high - low) < (ATR(14) * 0.5)
# Coil setup
coil_setup = vol_contracting & range_tight
# Buy when price breaks above the current High
# after a coil setup
buy_signal = coil_setup & crossover(close, high)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the 10 EMA
ema10 = EMA(close, 10)
exit_signal = crossunder(close, ema10)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMA
draw(
ema10,
title="EMA 10",
frame=0,
color="blue"
)
# Plot ATR
draw(
ATR(14),
title="ATR (14)",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="Volume Contraction Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
RSI Momentum Fade Strategy
Exit when RSI has been falling for 2 consecutive bars — momentum weakening.
# ============================================================
# entry_logic.ta
# ============================================================
# Calculate RSI
rsi_14 = RSI(close, 14)
# Buy when RSI crosses above 50,
# indicating bullish momentum
buy_signal = crossover(rsi_14, 50)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# RSI has been falling for 2 consecutive bars
rsi_fading = decreasing(rsi_14, 2)
# Exit only if RSI is still in the strong momentum zone
above_65 = rsi_14 > 65
exit_signal = rsi_fading & above_65
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot RSI
draw(
rsi_14,
title="RSI (14)",
frame=1,
color="blue"
)
# Overbought Level
draw(
65,
title="RSI 65",
frame=1,
color="red"
)
# Midline
draw(
50,
title="RSI 50",
frame=1,
color="white"
)
marker_text(
frame=1,
text="RSI Momentum Fade Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
for_loop #
(logic_func, args, initial_state, reset)
Executes a multi-line procedural block bar-by-bar.
Example
# Define a custom logic function
def my_accumulator(acc, val):
return acc + val
# Run the loop
# args must be a list of series
total_volume = for_loop(my_accumulator, [volume], 0)
For Loop Volume Strategy
Accumulate volume bar-by-bar and buy when cumulative volume crosses a threshold.
# ============================================================
# entry_logic.ta
# ============================================================
# Function to accumulate volume
def vol_accumulator(acc, vol):
return acc + vol
# Cumulative volume
daily_vol = for_loop(
vol_accumulator,
[volume],
0
)
# Buy when cumulative volume crosses the threshold
buy_signal = crossover(daily_vol, 1000000)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
ema20 = EMA(close, 20)
exit_signal = crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
draw(
daily_vol,
title="Accumulated Volume",
frame=1,
color="blue"
)
draw(
1000000,
title="Volume Threshold",
frame=1,
color="red"
)
marker_text(
frame=1,
text="For Loop Volume Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Running High Strategy
Keep track of the highest High seen so far and buy when price makes a new running High.
# ============================================================
# entry_logic.ta
# ============================================================
# Function to keep track of the highest High seen so far
def running_max(acc, h):
return h if h > acc else acc
# Running maximum High
session_high = for_loop(
running_max,
[high],
0
)
# Buy when price makes a new running High
buy_signal = high >= session_high
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price crosses below EMA 20
ema20 = EMA(close, 20)
exit_signal = crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot Running High
draw(
session_high,
title="Running High",
frame=0,
color="red"
)
# Plot EMA 20
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
marker_text(
frame=0,
text="Running High Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Bullish Candle Count Strategy
Count consecutive bullish candles and enter after 4 consecutive bullish candles.
# ============================================================
# entry_logic.ta
# ============================================================
# Function to count consecutive bullish candles
def bullish_counter(count, o, c):
if c > o:
return count + 1
return 0
# Count consecutive bullish candles
bull_count = for_loop(
bullish_counter,
[open, close],
0
)
# Buy after 4 consecutive bullish candles
buy_signal = bull_count >= 4
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit on the first bearish candle
exit_signal = close < open
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot consecutive bullish candle count
draw(
bull_count,
title="Bullish Candle Count",
frame=1,
color="green"
)
# Entry threshold
draw(
4,
title="Threshold",
frame=1,
color="red"
)
marker_text(
frame=1,
text="Bullish Candle Count Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
state #
(initial_series, update_condition, update_value, reset_condition)
Computes a path-dependent state series.
Example
# Track the highest high since a buy signal
# Initialize with 0
# Update when high > current_state
# Reset when sell_signal is True
trailing_stop = state(0, high > trailing_stop, high, sell_signal)
State Counter Strategy
Reset a counter whenever a new buy signal occurs, and exit after 15 bars.
# ============================================================
# entry_logic.ta
# ============================================================
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
buy_signal = crossover(fast_ema, slow_ema)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Reset whenever a new buy signal occurs
bars_in_trade = state(
0,
buy_signal,
0,
1
)
# Exit after the state reaches 15 bars
exit_signal = bars_in_trade >= 15
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
draw(
fast_ema,
title="EMA 9",
frame=0,
color="green"
)
draw(
slow_ema,
title="EMA 21",
frame=0,
color="red"
)
draw(
bars_in_trade,
title="State Counter",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="State Counter Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Session Open Strategy
Store the session opening price and use it as a reference for entry and exit.
# ============================================================
# entry_logic.ta
# ============================================================
# Store the session opening price
session_open = state(
open,
close > open,
open,
DayFirstBar
)
# Buy when price is above the stored session open
buy_signal = close > session_open
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when price falls below the session open
exit_signal = close < session_open
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
draw(
session_open,
title="Session Open",
frame=0,
color="orange"
)
marker_text(
frame=0,
text="Session Open Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Track Drawdown Strategy
Track the current drawdown from entry and exit if it exceeds a panic limit.
# ============================================================
# entry_logic.ta
# Track Drawdown Strategy
# ============================================================
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
buy_signal = crossover(fast_ema, slow_ema)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
sell_signal = crossunder(fast_ema, slow_ema)
# Entry price
entry_close = valuewhen(buy_signal, close, 0)
# Current drawdown from entry
drawdown = ((entry_close - close) / entry_close) * 100
# Exit if drawdown exceeds 3%
panic_exit = drawdown >= 3
Exit(
index=1,
logic=panic_exit,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
entry_close = valuewhen(crossover(fast_ema, slow_ema), close, 0)
drawdown = ((entry_close - close) / entry_close) * 100
draw(
fast_ema,
title="EMA 9",
frame=0,
color="green"
)
draw(
slow_ema,
title="EMA 21",
frame=0,
color="red"
)
draw(
drawdown,
title="Drawdown %",
frame=1,
color="orange"
)
draw(
3,
title="3% Limit",
frame=1,
color="red"
)
marker_text(
frame=1,
text="Drawdown Exit Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
evolve #
(initial_value, update_expression_str, series_args, reset_condition)
Computes a recursive series bar-by-bar via a string expression.
Example
# Exponential Moving Average calculation manually
# "p" refers to previous value
# "args[0]" refers to the first series in the list (close)
my_ema = evolve(close[0], "0.2 * args[0] + 0.8 * p", [close])
Custom Momentum Decay Strategy
Create a smoothed momentum line using exponential decay.
# ============================================================
# entry_logic.ta
# Custom Momentum Decay Strategy
# ============================================================
# Calculate the 14-period RSI to measure market momentum.
rsi_14 = RSI(close, 14)
# Create a smoothed momentum line using exponential decay.
momentum_decay = evolve(
rsi_14.shift(1),
"0.1 * args[0] + 0.9 * p",
[rsi_14]
)
# Generate a Buy signal when the Momentum Decay line crosses above the RSI.
buy_signal = crossover(momentum_decay, rsi_14)
# Execute the Buy order.
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Calculate the 14-period RSI.
rsi_14 = RSI(close, 14)
# Recalculate the Momentum Decay line.
momentum_decay = evolve(
rsi_14.shift(1),
"0.1 * args[0] + 0.9 * p",
[rsi_14]
)
# Exit the trade when Momentum Decay crosses below the RSI.
exit_signal = crossunder(momentum_decay, rsi_14)
# Execute the Exit order.
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate the 14-period RSI.
rsi_14 = RSI(close, 14)
# Calculate the Momentum Decay line using the evolve() function.
momentum_decay = evolve(
rsi_14.shift(1),
"0.1 * args[0] + 0.9 * p",
[rsi_14]
)
# Plot the Momentum Decay line.
draw(
momentum_decay,
title="Momentum Decay",
frame=1,
color="orange"
)
# Plot the RSI for comparison.
draw(
rsi_14,
title="RSI (14)",
frame=1,
color="blue"
)
# Display the strategy title on the chart.
marker_text(
frame=1,
text="Momentum Decay Strategy",
anchor="top_right"
)
# Display buy, sell and PnL trade markers.
marker_trades(
frame=0,
show_pnl=True
)
Adaptive Trend Score Strategy
Demonstrates an adaptive score calculated via evolve().
# ============================================================
# entry_logic.ta
# Adaptive Trend Score Strategy
# ============================================================
# Calculate Fast and Slow EMA
fast_ema = EMA(close, 20)
# Fast trend moving average
slow_ema = EMA(close, 50)
# Trend direction
trend_up = fast_ema > slow_ema
# Adaptive Trend Score
# Increases by 1 while bullish
# Decreases by 1 while bearish
# Score is limited between -10 and +10
trend_score = evolve(
0,
"args[0] ? min(p + 1, 10) : max(p - 1, -10)",
[trend_up]
)
# Buy after sustained bullish momentum
buy_signal = crossover(trend_score, 5)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Calculate Fast and Slow EMA
fast_ema = EMA(close, 20)
slow_ema = EMA(close, 50)
# Trend direction
trend_up = fast_ema > slow_ema
# Adaptive Trend Score
trend_score = evolve(
0,
"args[0] ? min(p + 1, 10) : max(p - 1, -10)",
[trend_up]
)
# Exit when bullish momentum weakens
exit_signal = crossunder(trend_score, 0)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Calculate Fast and Slow EMA
fast_ema = EMA(close, 20)
slow_ema = EMA(close, 50)
# Trend direction
trend_up = fast_ema > slow_ema
# Adaptive Trend Score
trend_score = evolve(
0,
"args[0] ? min(p + 1, 10) : max(p - 1, -10)",
[trend_up]
)
# Plot Fast EMA
draw(
fast_ema,
title="EMA 20",
frame=0,
color="blue"
)
# Plot Slow EMA
draw(
slow_ema,
title="EMA 50",
frame=0,
color="orange"
)
# Plot Adaptive Trend Score
draw(
trend_score,
title="Adaptive Trend Score",
frame=1,
color="green"
)
# Strategy Title
marker_text(
frame=1,
text="Adaptive Trend Score Strategy",
anchor="top_right"
)
# Show Trade Markers
marker_trades(
frame=0,
show_pnl=True
)
consecutive #
(condition)
Counts consecutive bars where a condition is true.
Example
# Count consecutive green candles
green_streak = consecutive(close > open)
# Buy if 3 green candles in a row
buy = green_streak == 3
High Volume Confirmation Strategy
Require at least 2 consecutive high-volume candles and a trend filter before buying.
# ============================================================
# entry_logic.ta
# High Volume Confirmation Strategy
# ============================================================
# Average Volume
avg_vol = SMA(volume, 20)
# Count consecutive high-volume bars
vol_streak = consecutive(volume > avg_vol * 1.5)
# Require at least 2 consecutive high-volume candles
vol_confirm = vol_streak >= 2
# Trend filter
ema20 = EMA(close, 20)
# Buy only when volume confirms and price is above EMA
buy_signal = vol_confirm & (close > ema20)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when volume streak ends or price falls below EMA
exit_signal = (vol_streak == 0) | crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMA
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
# Plot consecutive high-volume count
draw(
vol_streak,
title="High Volume Streak",
frame=1,
color="green"
)
# Confirmation threshold
draw(
2,
title="Confirmation Level",
frame=1,
color="red"
)
marker_text(
frame=1,
text="Volume Streak Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Green Candle Continuation Strategy
Buy after 3 consecutive green candles and exit after 2 consecutive red candles.
# ============================================================
# entry_logic.ta
# Green Candle Continuation Strategy
# ============================================================
# Count consecutive green candles
green_streak = consecutive(close > open)
# Buy after 3 consecutive green candles
buy_signal = green_streak >= 3
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Count consecutive red candles
red_streak = consecutive(close < open)
# Exit after 2 consecutive red candles
exit_signal = red_streak >= 2
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot Green Candle Streak
draw(
green_streak,
title="Green Streak",
frame=1,
color="green"
)
# Plot Red Candle Streak
draw(
red_streak,
title="Red Streak",
frame=1,
color="red"
)
# Entry Threshold
draw(
3,
title="Entry Level",
frame=1,
color="blue"
)
# Exit Threshold
draw(
2,
title="Exit Level",
frame=1,
color="orange"
)
marker_text(
frame=1,
text="Consecutive Candle Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
NotOthers #
(trigger_series, reset_series)
Utility function for exclusive signal generation.
Example
# Ensure only one signal is active at a time
# If buy is True, it stays True until sell becomes True
in_long = NotOthers(buy_signal, sell_signal)
EMA Trend State Strategy
Stay in a long state after a Buy signal until a Sell signal occurs.
# ============================================================
# entry_logic.ta
# EMA Trend State Strategy
# ============================================================
# Calculate EMAs
fast_ema = EMA(close, 9)
slow_ema = EMA(close, 21)
# Buy and Sell Signals
buy_signal = crossover(fast_ema, slow_ema)
sell_signal = crossunder(fast_ema, slow_ema)
# Stay in a long state after a Buy signal
# until a Sell signal occurs
in_long = NotOthers(buy_signal, sell_signal)
# Enter only when a new Buy signal occurs
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit on EMA bearish crossover
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot EMAs
draw(
fast_ema,
title="EMA 9",
frame=0,
color="green"
)
draw(
slow_ema,
title="EMA 21",
frame=0,
color="red"
)
# Plot Long State (1 = Long, 0 = Flat)
draw(
in_long,
title="In Long State",
frame=1,
color="blue"
)
marker_text(
frame=1,
text="NotOthers Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Bull Market Regime Strategy
Stay in Bull Regime until a Death Cross occurs, and take trades only during this regime.
# ============================================================
# entry_logic.ta
# Bull Market Regime Strategy
# ============================================================
# Calculate Moving Averages
sma_50 = SMA(close, 50)
sma_200 = SMA(close, 200)
# Market regime signals
bull_start = crossover(sma_50, sma_200)
bear_start = crossunder(sma_50, sma_200)
# Stay in Bull Regime until a Death Cross occurs
bull_regime = NotOthers(bull_start, bear_start)
# Momentum confirmation
rsi_14 = RSI(close, 14)
# Buy only when RSI is strong during a Bull Regime
buy_signal = (rsi_14 > 55) & bull_regime
Entry(
index=1,
logic=buy_signal,
timeframe=60,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ============================================================
# exit_logic.ta
# ============================================================
# Exit when the market leaves the Bull Regime
exit_signal = bear_start
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ============================================================
# canvas.ta
# ============================================================
# Plot Moving Averages
draw(
sma_50,
title="SMA 50",
frame=0,
color="green"
)
draw(
sma_200,
title="SMA 200",
frame=0,
color="red"
)
# Plot Bull Regime State
draw(
bull_regime,
title="Bull Regime",
frame=1,
color="blue"
)
marker_text(
frame=1,
text="Bull Regime Strategy",
anchor="top_right"
)
marker_trades(
frame=0,
show_pnl=True
)
Pattern Recognition
is_doji #
(max_body_perc=0.05)
Identifies Doji candles.
Example
# Detect Doji
doji = is_doji(0.05)
# Filter for high volume Dojis
valid_doji = doji & (volume > avg(volume, 20))
Doji Candle Strategy
Demonstrates is_doji()
# ==================================================
# Doji Candle Strategy
# Demonstrates is_doji()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Doji candles.
# A Doji forms when the opening and closing
# prices are nearly equal.
#
# This indicates market indecision because
# neither buyers nor sellers gained control.
doji = is_doji()
# Enter a trade whenever a Doji appears.
#
# This simple example is intended to
# demonstrate how pattern detection
# functions can be used inside Entry().
Entry(
index=1,
logic=doji,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when a bearish candle appears.
#
# A bearish candle closes below its opening price,
# indicating that sellers have gained control.
Exit(
index=1,
logic=close < open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Doji candles again for visualization.
doji = is_doji()
# Draw a yellow diamond above every Doji candle.
#
# This makes it easy to visually verify
# where the pattern occurred on the chart.
drawshape(
condition=doji,
shape="diamond",
location="AboveBar",
color="yellow",
size="small"
)
# Display the strategy name.
#
# The text appears in the top-right corner
# of the chart so users know which example
# is currently running.
marker_text(
frame=0,
text="Doji Pattern Strategy",
anchor="top_right"
)
# Display completed trades and PnL.
#
# This helps users see exactly which
# Doji candles generated entries and exits.
marker_trades(
frame=0,
show_pnl=True
)
Advanced Doji Strategy
Demonstrates is_doji(threshold)
# ==================================================
# Advanced Doji Strategy
# Demonstrates is_doji(threshold)
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Doji candles using a custom threshold.
#
# The threshold controls how close the open
# and close prices must be to qualify as a Doji.
#
# Smaller value = Stricter Doji detection.
# Larger value = More Doji candles detected.
doji = is_doji(0.05)
# Bullish Doji condition.
#
# A Doji candle forms and the candle closes
# above its opening price.
#
# This suggests buyers gained a slight advantage.
long_entry = doji & (close > open)
# Bearish Doji condition.
#
# A Doji candle forms and the candle closes
# below its opening price.
#
# This suggests sellers gained a slight advantage.
short_entry = doji & (close < open)
# Enter a long trade when a bullish
# Doji pattern appears.
Entry(
index=1,
logic=long_entry,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# Enter a short trade when a bearish
# Doji pattern appears.
Entry(
index=2,
logic=short_entry,
timeframe=5,
script=RELIANCE,
action=Sell,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit long positions when a bearish candle appears.
#
# This suggests buyers are losing control.
long_exit = close < open
# Exit short positions when a bullish candle appears.
#
# This suggests sellers are losing control.
short_exit = close > open
# Close long trades.
Exit(
index=1,
logic=long_exit,
exit_type="MARKET"
)
# Close short trades.
Exit(
index=2,
logic=short_exit,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Doji candles again for visualization.
doji = is_doji(0.05)
# Draw a yellow diamond above every
# detected Doji candle.
#
# This allows users to visually verify
# where the pattern occurred.
drawshape(
condition=doji,
shape="diamond",
location="AboveBar",
color="yellow",
size="small"
)
# Display strategy name.
#
# Appears in the top-right corner
# of the chart.
marker_text(
frame=0,
text="Doji Strategy",
anchor="top_right"
)
# Display completed trades.
#
# Entry points, exit points and PnL
# are shown directly on the chart.
marker_trades(
frame=0,
show_pnl=True
)
is_hammer #
(max_body_perc=0.3)
Identifies the Hammer candle shape.
Example
# Detect Hammer pattern
hammer = is_hammer(0.3)
# Confirm with next candle
confirmed = hammer[1] & (close > high[1])
Hammer Pattern Strategy
Demonstrates is_hammer()
# ==================================================
# Hammer Pattern Strategy
# Demonstrates is_hammer()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Hammer candlestick patterns.
#
# A Hammer candle usually appears after a decline
# and signals that buyers stepped in aggressively
# after sellers pushed prices lower.
#
# Characteristics:
# - Small real body
# - Long lower shadow
# - Little or no upper shadow
hammer = is_hammer()
# Enter a long trade whenever
# a Hammer pattern is detected.
#
# This strategy assumes the Hammer may
# signal a bullish reversal.
Entry(
index=1,
logic=hammer,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when a bearish candle appears.
#
# A bearish candle closes below its open,
# indicating sellers may be regaining control.
Exit(
index=1,
logic=close < open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Hammer patterns again for visualization.
hammer = is_hammer()
# Draw a green triangle below every
# Hammer candle detected.
#
# This helps traders quickly identify
# potential bullish reversal areas.
drawshape(
condition=hammer,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Display strategy name on the chart.
#
# Appears in the top-right corner
# for easy identification.
marker_text(
frame=0,
text="Hammer Pattern Strategy",
anchor="top_right"
)
# Display completed trades and PnL.
#
# Shows:
# - Entry points
# - Exit points
# - Profit/Loss for each trade
marker_trades(
frame=0,
show_pnl=True
)
Advanced Hammer Strategy
Demonstrates is_hammer(threshold)
# ==================================================
# Advanced Hammer Strategy
# Demonstrates is_hammer(threshold)
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Hammer candles using a custom threshold.
#
# The threshold controls how strict the
# Hammer pattern detection should be.
#
# Lower values:
# - Fewer Hammer candles detected
# - Stricter pattern requirements
#
# Higher values:
# - More Hammer candles detected
# - Looser pattern requirements
hammer = is_hammer(0.3)
# Bullish Hammer setup.
#
# Conditions:
# 1. Hammer pattern detected
# 2. Candle closes above its opening price
#
# This suggests buyers were able to push
# the candle higher before the close.
long_entry = hammer & (close > open)
# Bearish Hammer setup.
#
# Conditions:
# 1. Hammer pattern detected
# 2. Candle closes below its opening price
#
# This suggests sellers maintained slight
# control despite the Hammer structure.
short_entry = hammer & (close < open)
# Open a long trade when the bullish
# Hammer setup is detected.
Entry(
index=1,
logic=long_entry,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# Open a short trade when the bearish
# Hammer setup is detected.
Entry(
index=2,
logic=short_entry,
timeframe=5,
script=RELIANCE,
action=Sell,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit long trades when a bearish candle appears.
#
# This suggests buyers may be losing control.
long_exit = close < open
# Exit short trades when a bullish candle appears.
#
# This suggests sellers may be losing control.
short_exit = close > open
# Close long trades.
Exit(
index=1,
logic=long_exit,
exit_type="MARKET"
)
# Close short trades.
Exit(
index=2,
logic=short_exit,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Hammer patterns again for chart display.
hammer = is_hammer(0.3)
# Draw a green triangle below every
# detected Hammer candle.
#
# This helps visually verify where
# the pattern appeared.
drawshape(
condition=hammer,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Display strategy name.
#
# Appears in the top-right corner
# of the chart.
marker_text(
frame=0,
text="Hammer Strategy",
anchor="top_right"
)
# Display all completed trades.
#
# Shows:
# - Entry points
# - Exit points
# - Profit/Loss values
marker_trades(
frame=0,
show_pnl=True
)
is_bullish_engulfing / is_bearish_engulfing #
()
Identifies the two-bar engulfing patterns.
Example
# Engulfing patterns
bull_eng = is_bullish_engulfing()
bear_eng = is_bearish_engulfing()
# Trade on pattern
Entry(1, bull_eng, "5m", banknifty, Buy, "MARKET")
Bearish Engulfing Strategy
Demonstrates is_bearish_engulfing()
# ==================================================
# Bearish Engulfing Strategy
# Demonstrates is_bearish_engulfing()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Bearish Engulfing candlestick patterns.
#
# A Bearish Engulfing pattern occurs when:
#
# 1. The previous candle is bullish.
# 2. The current candle is bearish.
# 3. The body of the bearish candle completely
# engulfs the body of the previous bullish candle.
#
# This pattern is commonly interpreted as
# a potential bearish reversal signal.
bearish_engulfing = is_bearish_engulfing()
# Enter a short trade whenever a
# Bearish Engulfing pattern is detected.
#
# A Sell action opens a bearish position,
# allowing the strategy to profit from
# falling prices.
Entry(
index=1,
logic=bearish_engulfing,
timeframe=5,
script=RELIANCE,
action=Sell,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit the short position when a
# bullish candle appears.
#
# A bullish candle closes above its opening price,
# suggesting buyers may be regaining control.
Exit(
index=1,
logic=close > open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Bearish Engulfing patterns again
# for visualization purposes.
bearish_engulfing = is_bearish_engulfing()
# Draw a red triangle above every
# Bearish Engulfing pattern.
#
# This helps traders quickly identify
# potential bearish reversal signals.
drawshape(
condition=bearish_engulfing,
shape="triangle_down",
location="AboveBar",
color="red",
size="normal"
)
# Display the strategy name.
#
# Appears in the top-right corner
# of the chart.
marker_text(
frame=0,
text="Bearish Engulfing",
anchor="top_right"
)
# Display completed trades.
#
# Shows:
# - Entry points
# - Exit points
# - Profit/Loss values
marker_trades(
frame=0,
show_pnl=True
)
Bullish Engulfing Strategy
Demonstrates is_bullish_engulfing()
# ==================================================
# Bullish Engulfing Strategy
# Demonstrates is_bullish_engulfing()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect a Bullish Engulfing candlestick pattern.
# Returns True when the current bullish candle completely engulfs
# the body of the previous bearish candle, indicating a potential
# bullish reversal.
bullish_engulfing = is_bullish_engulfing()
Entry(
index=1,
logic=bullish_engulfing,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit the Buy position when the current candle closes below its open,
# indicating bearish price action.
Exit(
index=1,
logic=close < open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect the same Bullish Engulfing pattern for visualization.
bullish_engulfing = is_bullish_engulfing()
# Plot a green upward triangle below every Bullish Engulfing candle.
drawshape(
condition=bullish_engulfing,
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Display the strategy name on the chart.
marker_text(
frame=0,
text="Bullish Engulfing",
anchor="top_right"
)
# Display executed trades and their profit/loss.
marker_trades(
frame=0,
show_pnl=True
)
is_morning_star / is_evening_star #
(star_max_body_perc=0.3)
Identifies three-bar star reversal patterns.
Example
# Star patterns
m_star = is_morning_star(0.3)
e_star = is_evening_star(0.3)
Morning Star Strategy
Demonstrates is_morning_star(threshold)
# ==================================================
# Morning Star Strategy
# Demonstrates is_morning_star(threshold)
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Morning Star candlestick patterns.
#
# The Morning Star is a bullish reversal pattern
# consisting of three candles.
#
# The threshold parameter controls how strict
# the pattern recognition should be.
#
# Lower values:
# - Stricter pattern matching
# - Fewer signals
#
# Higher values:
# - Looser pattern matching
# - More signals
morning_star = is_morning_star(0.3)
# Enter a long trade whenever a
# Morning Star pattern is detected.
#
# The pattern suggests that bearish momentum
# may be ending and buyers may be taking control.
Entry(
index=1,
logic=morning_star,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when a bearish candle appears.
#
# A bearish candle closes below its opening price,
# which may indicate weakening bullish momentum.
Exit(
index=1,
logic=close < open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Morning Star patterns again
# for chart visualization.
morning_star = is_morning_star(0.3)
# Draw a green triangle below every
# detected Morning Star pattern.
#
# This makes it easy to identify
# bullish reversal zones on the chart.
drawshape(
condition=morning_star,
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Display strategy name.
#
# Appears in the top-right corner
# of the chart.
marker_text(
frame=0,
text="Morning Star",
anchor="top_right"
)
# Display completed trades and PnL.
#
# Shows:
# - Entry points
# - Exit points
# - Profit/Loss values
marker_trades(
frame=0,
show_pnl=True
)
Evening Star Strategy
Demonstrates is_evening_star(threshold)
# ==================================================
# Evening Star Strategy
# Demonstrates is_evening_star(threshold)
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Detect Evening Star candlestick patterns.
#
# The Evening Star is a bearish reversal pattern
# consisting of three candles.
#
# The threshold parameter controls how strict
# the pattern recognition should be.
#
# Lower values:
# - Stricter pattern matching
# - Fewer signals
#
# Higher values:
# - Looser pattern matching
# - More signals
evening_star = is_evening_star(0.3)
# Enter a short trade whenever an
# Evening Star pattern is detected.
#
# The pattern suggests that bullish momentum
# may be ending and sellers may be taking control.
Entry(
index=1,
logic=evening_star,
timeframe=5,
script=RELIANCE,
action=Sell,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit the short trade when a bullish candle appears.
#
# A bullish candle closes above its opening price,
# suggesting buyers may be regaining control.
Exit(
index=1,
logic=close > open,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Detect Evening Star patterns again
# for chart visualization.
evening_star = is_evening_star(0.3)
# Draw a red triangle above every
# detected Evening Star pattern.
#
# This makes it easy to identify
# bearish reversal zones on the chart.
drawshape(
condition=evening_star,
shape="triangle_down",
location="AboveBar",
color="red",
size="normal"
)
# Display strategy name.
#
# Appears in the top-right corner
# of the chart.
marker_text(
frame=0,
text="Evening Star",
anchor="top_right"
)
# Display completed trades and PnL.
#
# Shows:
# - Entry points
# - Exit points
# - Profit/Loss values
marker_trades(
frame=0,
show_pnl=True
)
Morning Star + SMA 50 Trend Filter
Demonstrates candlestick patterns with trend filtering
# ==================================================
# Morning Star + SMA 50 Trend Filter Strategy
# Demonstrates candlestick patterns with trend filtering
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Calculate the 50-period Simple Moving Average.
#
# SMA 50 is commonly used as a trend filter.
# Price above SMA 50 suggests an uptrend.
sma_50 = SMA(close, 50)
# Detect Morning Star pattern.
#
# Morning Star is a bullish reversal pattern
# consisting of three candles.
morning_star = is_morning_star(0.3)
# Buy only when:
#
# 1. Morning Star appears
# 2. Price is above SMA 50
#
# This helps filter out weak reversal signals
# that occur against the prevailing trend.
buy_signal = morning_star & (close > sma_50)
# Open a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Exit when price falls below SMA 50.
#
# This suggests the uptrend may be weakening
# or reversing.
Exit(
index=1,
logic=close < sma_50,
exit_type="MARKET"
)
# ==================================================
# Canvas
# ==================================================
# Calculate SMA 50 for visualization.
sma_50 = SMA(close, 50)
# Plot SMA 50 on the chart.
#
# This allows traders to easily identify
# the overall market trend.
draw(
sma_50,
title="SMA 50",
frame=0,
color="yellow"
)
# Mark all Morning Star patterns.
#
# Green triangles appear below candles
# where the pattern is detected.
drawshape(
condition=is_morning_star(0.3),
shape="triangle_up",
location="BelowBar",
color="lime",
size="normal"
)
# Display strategy title.
marker_text(
frame=0,
text="Morning Star + SMA 50",
anchor="top_right"
)
# Show completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
is_GapUp / is_GapDown #
(percentage=None)
Identifies percentage gaps in price.
Utility Tools
input #
(defval, title, tooltip, group, min, max, options)
Creates a user-configurable setting for the strategy.
Example
# User inputs
rsi_len = input(14, title="RSI Length", min=1)
ma_type = input("SMA", title="MA Type", options=["SMA", "EMA"])
Configurable SMA Strategy
Demonstrates input().
# ==================================================
# Configurable SMA Strategy
# Demonstrates input()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Create a user-configurable SMA length.
# Users can change this value from the
# strategy settings panel.
ma_length = input(
20,
title="SMA Length",
min=1
)
# Calculate the SMA using the selected length.
ma = SMA(close, ma_length)
# Buy when price crosses above the SMA.
# This suggests a potential bullish trend.
buy_signal = crossover(close, ma)
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Use the same configurable SMA length.
ma_length = input(
20,
title="SMA Length",
min=1
)
# Recalculate SMA.
ma = SMA(close, ma_length)
# Exit when price crosses below SMA.
# This suggests weakening momentum.
sell_signal = crossunder(close, ma)
# Close the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# Demonstrates input()
# ==================================================
# Create a user-configurable SMA length.
# Users can modify the moving average period
# without changing the strategy code.
ma_length = input(
20,
title="SMA Length",
min=1
)
# Calculate the SMA using the selected value.
ma = SMA(close, ma_length)
# Plot the SMA on the main chart.
draw(
ma,
title="SMA",
frame=0,
color="yellow"
)
# Generate buy and sell signals for visualization.
buy_signal = crossover(close, ma)
sell_signal = crossunder(close, ma)
# Draw buy markers below bullish crossover candles.
drawshape(
buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime"
)
# Draw sell markers above bearish crossover candles.
drawshape(
sell_signal,
shape="triangle_down",
location="AboveBar",
color="red"
)
# Display the currently selected SMA length.
# This updates automatically when the user
# changes the input value.
marker_table(
frame=0,
data=[
["SMA Length", ma_length]
],
position="top_right"
)
# Add a strategy title to the chart.
marker_text(
frame=0,
text="Configurable SMA Strategy",
color="yellow",
x=0.5,
y=0.1,
anchor="custom"
)
# Display completed trades and profit/loss.
marker_trades(
frame=0,
show_pnl=True
)
Configurable RSI Strategy
Demonstrates input().
# ==================================================
# Configurable RSI Strategy
# Demonstrates input()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Create a user-configurable RSI period.
# Users can change RSI sensitivity from settings.
rsi_length = input(
14,
title="RSI Length",
min=2
)
# Calculate RSI using the selected period.
rsi_val = RSI(close, rsi_length)
# Buy when RSI enters the oversold zone.
# Oversold conditions may indicate a reversal.
buy_signal = rsi_val < 30
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Recalculate RSI using the same user input.
rsi_length = input(
14,
title="RSI Length",
min=2
)
rsi_val = RSI(close, rsi_length)
# Exit when RSI enters the overbought zone.
# This may indicate momentum exhaustion.
sell_signal = rsi_val > 70
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# Demonstrates input()
# ==================================================
# User-configurable RSI period.
rsi_length = input(
14,
title="RSI Length",
min=2
)
# Calculate RSI.
rsi_val = RSI(close, rsi_length)
# Plot RSI in a separate indicator panel.
draw(
rsi_val,
title="RSI",
frame=1,
color="blue"
)
# Generate visual signals.
buy_signal = rsi_val < 30
sell_signal = rsi_val > 70
# Mark oversold conditions.
drawshape(
buy_signal,
shape="circle",
location="BelowBar",
color="green"
)
# Mark overbought conditions.
drawshape(
sell_signal,
shape="circle",
location="AboveBar",
color="red"
)
# Display current RSI settings.
marker_table(
frame=0,
data=[
["RSI Length", rsi_length],
["RSI Value", round(rsi_val, 2)]
],
position="top_right"
)
# Strategy title.
marker_text(
frame=0,
text="Configurable RSI Strategy",
color="blue",
x=0.5,
y=0.1,
anchor="custom"
)
# Show completed trades.
marker_trades(
frame=0,
show_pnl=True
)
mtf_data #
(timeframe, expression, script=None)
Requests data from a higher timeframe.
Multi-Timeframe (MTF) Daily Close Strategy
Demonstrates how to use mtf_data() to fetch higher timeframe data inside an intraday strategy.
# ==================================================
# Multi-Timeframe (MTF) Daily Close Strategy
# Demonstrates how to use mtf_data() to fetch
# higher timeframe data inside an intraday strategy.
# ==================================================
# ------------------------------------------
# User Inputs
# ------------------------------------------
# ATR multiplier used for stop-loss calculation.
atr_sl_mult = input(
1.5,
title="ATR Stop Multiplier",
min=0.5,
max=4.0
)
# RSI length.
rsi_len = input(
14,
title="RSI Length",
min=5,
max=50
)
# ------------------------------------------
# Multi-Timeframe Data
# ------------------------------------------
# Function that returns the Daily Close.
# mtf_data() executes this function on the
# requested higher timeframe.
def get_daily_close():
return close
# Fetch the Daily Close of HDFCBANK while
# running this strategy on a lower timeframe
# such as 15 minutes.
daily_close = mtf_data(
"1440",
get_daily_close,
script="HDFCBANK"
)
# ------------------------------------------
# Calculate Indicators
# ------------------------------------------
# ATR for stop-loss calculation.
atr_val = ATR(14)
# VWAP used as an intraday trend filter.
vwap_val = VWAP(hlc3)
# RSI confirms momentum.
rsi_val = RSI(close, rsi_len)
# ------------------------------------------
# Entry Conditions
# ------------------------------------------
# Current price should be above the
# Higher Timeframe Daily Close.
above_daily = close > daily_close
# Price should also trade above VWAP.
above_vwap = close > vwap_val
# RSI confirms bullish momentum.
rsi_ok = rsi_val > 45
# Only trade during market hours.
morning_ok = (time >= 915) & (time <= 1515)
# Allow only one open trade.
flat_filter = position_size == 0
# Final Buy Signal.
buy_signal = (
above_daily &
above_vwap &
rsi_ok &
morning_ok &
flat_filter
)
# ------------------------------------------
# Place Buy Order
# ------------------------------------------
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=HDFCBANK,
action=Buy,
order_type="MARKET"
)
# ------------------------------------------
# Exit Conditions
# ------------------------------------------
# Entry price used for ATR stop-loss.
entry_price = valuewhen(
buy_signal,
close,
0
)
# Dynamic ATR stop-loss.
stop_level = entry_price - (atr_sl_mult * atr_val)
# Exit if stop-loss is hit.
hit_stop = close < stop_level
# Exit if price falls below the Daily Close.
below_daily = close < daily_close
# Force exit at the end of the trading day.
force_exit = DayLastBar
# Final Exit Signal.
exit_signal = (
hit_stop |
below_daily |
force_exit
)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ------------------------------------------
# Canvas
# ------------------------------------------
# Plot the Higher Timeframe Daily Close.
draw(
daily_close,
title="MTF Daily Close",
frame=0,
color="yellow"
)
# Plot VWAP.
draw(
vwap_val,
title="VWAP",
frame=0,
color="cyan"
)
# Plot RSI.
draw(
rsi_val,
title="RSI 14",
frame=1,
color="purple"
)
# Show Buy Signals.
drawshape(
buy_signal,
shape="triangle_up",
location="BelowBar",
color="green",
size="small",
frame=0
)
# Show Exit Signals.
drawshape(
exit_signal,
shape="triangle_down",
location="AboveBar",
color="red",
size="small",
frame=0
)
# Highlight bars where price is above
# the Higher Timeframe Daily Close.
debug_paint_background(
above_daily,
frame=0,
color="green"
)
# Display completed trades.
marker_trades(
frame=0,
show_pnl=True
)
Multi-Timeframe Daily High Breakout Strategy
Demonstrates mtf_data() using the Daily High.
# ==================================================
# Multi-Timeframe Daily High Breakout Strategy
# Demonstrates mtf_data() using the Daily High.
# ==================================================
# ------------------------------------------
# User Inputs
# ------------------------------------------
atr_mult = input(
2.0,
title="ATR Stop Multiplier",
min=1.0,
max=5.0
)
# ------------------------------------------
# Multi-Timeframe Data
# ------------------------------------------
# Function returns the Daily High.
def get_daily_high():
return high
# Fetch Daily High from the higher timeframe.
daily_high = mtf_data(
"1440",
get_daily_high,
script="RELIANCE"
)
# ------------------------------------------
# Indicators
# ------------------------------------------
atr_val = ATR(14)
ema20 = EMA(close, 20)
# ------------------------------------------
# Entry Conditions
# ------------------------------------------
# Price breaks above the Daily High.
breakout = crossover(close, daily_high)
# Trend confirmation.
trend_ok = close > ema20
# Only allow one open position.
flat_filter = position_size == 0
# Final Buy Signal.
buy_signal = breakout & trend_ok & flat_filter
# ------------------------------------------
# Place Entry
# ------------------------------------------
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ------------------------------------------
# Exit Conditions
# ------------------------------------------
entry_price = valuewhen(
buy_signal,
close,
0
)
stop_price = entry_price - (atr_mult * atr_val)
hit_stop = close < stop_price
ema_break = close < ema20
exit_signal = hit_stop | ema_break | DayLastBar
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ------------------------------------------
# Canvas
# ------------------------------------------
draw(
daily_high,
title="MTF Daily High",
frame=0,
color="red"
)
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
drawshape(
buy_signal,
shape="triangle_up",
location="BelowBar",
color="green",
size="small",
frame=0
)
drawshape(
exit_signal,
shape="triangle_down",
location="AboveBar",
color="red",
size="small",
frame=0
)
debug_paint_background(
breakout,
frame=0,
color="green"
)
marker_trades(
frame=0,
show_pnl=True
)
SeriesWrapper #
(data)
Wraps raw arrays for engine compatibility.
Example
# Wrap a raw list into a Series
my_list = [10, 20, 30, 40, 50]
my_series = SeriesWrapper(my_list)
# Now you can use series functions
avg_val = avg(my_series, 5)
SeriesWrapper SMA Strategy
Demonstrates SeriesWrapper().
# ==================================================
# SeriesWrapper SMA Strategy
# Demonstrates SeriesWrapper()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Wrap the close price series.
# Some engine functions may require
# data to be wrapped before processing.
close_series = SeriesWrapper(close)
# Calculate a 20-period SMA using
# the wrapped series.
sma_20 = SMA(close_series, 20)
# Buy when price crosses above the SMA.
# This indicates potential bullish momentum.
buy_signal = crossover(close_series, sma_20)
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Wrap the close series again.
close_series = SeriesWrapper(close)
# Calculate SMA.
sma_20 = SMA(close_series, 20)
# Exit when price crosses below SMA.
# This indicates weakening momentum.
sell_signal = crossunder(close_series, sma_20)
# Close the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# Demonstrates SeriesWrapper()
# ==================================================
# Wrap the close price series.
# SeriesWrapper ensures compatibility
# with engine functions that expect
# wrapped series objects.
close_series = SeriesWrapper(close)
# Calculate a moving average using
# the wrapped series.
sma_20 = SMA(close_series, 20)
# Plot the original close price.
draw(
close,
title="Close Price",
frame=0,
color="white"
)
# Plot the SMA calculated from
# the wrapped series.
draw(
sma_20,
title="Wrapped SMA 20",
frame=0,
color="yellow"
)
# Generate visual signals.
buy_signal = crossover(close_series, sma_20)
sell_signal = crossunder(close_series, sma_20)
# Mark buy signals.
drawshape(
buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime"
)
# Mark sell signals.
drawshape(
sell_signal,
shape="triangle_down",
location="AboveBar",
color="red"
)
# Explain what is being demonstrated.
marker_text(
frame=0,
text="SeriesWrapper Example",
anchor="top_right"
)
# Show current values in a table.
marker_table(
frame=0,
data=[
["Close", round(close, 2)],
["SMA 20", round(sma_20, 2)]
],
position="bottom_right"
)
# Display completed trades.
marker_trades(
frame=0,
show_pnl=True
)
SeriesWrapper Momentum Strategy
Demonstrates SeriesWrapper().
# ==================================================
# SeriesWrapper Momentum Strategy
# Demonstrates SeriesWrapper()
# ==================================================
# ==================================================
# Entry Logic
# ==================================================
# Wrap the close price series.
# Some advanced engine functions may
# require wrapped series objects.
close_series = SeriesWrapper(close)
# Calculate a 10-period EMA using
# the wrapped close series.
ema_10 = EMA(close_series, 10)
# Calculate a 30-period EMA using
# the wrapped close series.
ema_30 = EMA(close_series, 30)
# Buy when the fast EMA crosses
# above the slow EMA.
buy_signal = crossover(ema_10, ema_30)
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Exit Logic
# ==================================================
# Wrap the close series again.
close_series = SeriesWrapper(close)
# Recalculate EMAs.
ema_10 = EMA(close_series, 10)
ema_30 = EMA(close_series, 30)
# Exit when the fast EMA crosses
# below the slow EMA.
sell_signal = crossunder(ema_10, ema_30)
# Close the trade.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Canvas
# Demonstrates SeriesWrapper()
# ==================================================
# Wrap the close price series.
close_series = SeriesWrapper(close)
# Calculate EMAs using wrapped data.
ema_10 = EMA(close_series, 10)
ema_30 = EMA(close_series, 30)
# Plot the original close series.
draw(
close,
title="Close Price",
frame=0,
color="white"
)
# Plot the fast EMA.
draw(
ema_10,
title="EMA 10",
frame=0,
color="green"
)
# Plot the slow EMA.
draw(
ema_30,
title="EMA 30",
frame=0,
color="red"
)
# Generate crossover signals.
buy_signal = crossover(ema_10, ema_30)
sell_signal = crossunder(ema_10, ema_30)
# Mark buy signals.
drawshape(
buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime"
)
# Mark sell signals.
drawshape(
sell_signal,
shape="triangle_down",
location="AboveBar",
color="red"
)
# Display strategy information.
marker_text(
frame=0,
text="SeriesWrapper EMA Cross",
anchor="top_right"
)
# Display indicator values.
marker_table(
frame=0,
data=[
["EMA 10", round(ema_10, 2)],
["EMA 30", round(ema_30, 2)]
],
position="bottom_right"
)
# Show completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
Debugging Tools
log_series_comparison #
(name, *series, maxrows, startdate)
Prints a comparison table of series values.
Bollinger Breakout Strategy
Breakout strategy using Bollinger Bands and volume, with log output.
# ==================================================
# entry_logic.ta
# Bollinger Breakout Strategy
# ==================================================
# Indicators
bb_upper, bb_mid, bb_lower = bb(close, 20, 2)
rsi14 = RSI(close, 14)
volume_avg = SMA(volume, 20)
# Entry
buy_signal = crossover(close, bb_upper) & (volume > volume_avg)
# Log comparison
log_series_comparison(
name="BB Breakout",
close_price=close,
upper_band=bb_upper,
middle_band=bb_mid,
lower_band=bb_lower,
rsi_value=rsi14,
volume=volume,
avg_volume=volume_avg,
maxrows=20
)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
exit_signal = crossunder(close, bb_mid) | (rsi14 < 45)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
bb_upper,
title="Upper Band",
frame=0,
color="red"
)
draw(
bb_mid,
title="Middle Band",
frame=0,
color="yellow"
)
draw(
bb_lower,
title="Lower Band",
frame=0,
color="green"
)
draw(
rsi14,
title="RSI 14",
frame=1,
color="purple"
)
marker_fill(
frame=0,
line1=bb_upper,
line2=bb_lower,
color="rgba(0,150,255,0.10)"
)
marker_trades(
frame=0,
show_pnl=True
)
Log Series Comparison Strategy
Simple EMA crossover with series comparison logging.
# ==================================================
# entry_logic.ta
# Log Series Comparison Strategy
# ==================================================
# Indicators
ema20 = EMA(close, 20)
rsi14 = RSI(close, 14)
atr14 = ATR(14)
# Entry Condition
buy_signal = crossover(close, ema20)
# Log series comparison
log_series_comparison(
name="EMA vs Price",
close_price=close,
ema20=ema20,
rsi14=rsi14,
atr14=atr14,
maxrows=20
)
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
exit_signal = crossunder(close, ema20)
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
draw(
rsi14,
title="RSI 14",
frame=1,
color="purple"
)
draw(
atr14,
title="ATR 14",
frame=2,
color="orange"
)
marker_trades(
frame=0,
show_pnl=True
)
debug_logic_breakdown #
(title, final_signal, ...)
Prints a report explaining why a boolean signal was True/False.
SuperTrend Debug Strategy
Debug individual conditions making up a SuperTrend entry signal.
# ==================================================
# SuperTrend Debug Strategy | entry_logic.ta
# ==================================================
# Indicators
st_val, st_dir = SuperTrend(10, 3.0)
rsi_val = RSI(close, 14)
# Individual Conditions
trend_up = st_dir > 0
rsi_ok = rsi_val > 55
price_above_st = close > st_val
# Final Entry
long_entry = trend_up & rsi_ok & price_above_st
# Debug why entry is or isn't happening
debug_logic_breakdown(
"SuperTrend Entry",
long_entry,
trend_up=trend_up,
rsi_ok=rsi_ok,
price_above_st=price_above_st
)
Entry(
index=1,
logic=long_entry,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
long_exit = (st_dir < 0) | (rsi_val < 45) | DayLastBar
Exit(
index=1,
logic=long_exit,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
st_val,
title="SuperTrend",
frame=0,
color="green"
)
draw(
rsi_val,
title="RSI 14",
frame=1,
color="purple"
)
marker_trades(
frame=0,
show_pnl=True
)
drawshape(
condition=long_entry,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
Bollinger Breakout Debug Strategy
Break down the components of a Bollinger breakout entry.
# ==================================================
# Bollinger Breakout Debug Strategy | entry_logic.ta
# ==================================================
# Indicators
bb_upper, bb_mid, bb_lower = bb(close, 20, 2)
rsi_val = RSI(close, 14)
avg_vol = SMA(volume, 20)
# Individual Conditions
price_breakout = close > bb_upper
volume_confirm = volume > avg_vol
rsi_confirm = rsi_val > 60
# Final Entry
long_entry = price_breakout & volume_confirm & rsi_confirm
# Debug why entry passed or failed
debug_logic_breakdown(
"BB Breakout Entry",
long_entry,
price_breakout=price_breakout,
volume_confirm=volume_confirm,
rsi_confirm=rsi_confirm
)
Entry(
index=1,
logic=long_entry,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
long_exit = (close < bb_mid) | (rsi_val < 45) | DayLastBar
Exit(
index=1,
logic=long_exit,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
bb_upper,
title="Upper Band",
frame=0,
color="red"
)
draw(
bb_mid,
title="Middle Band",
frame=0,
color="white"
)
draw(
bb_lower,
title="Lower Band",
frame=0,
color="green"
)
draw(
rsi_val,
title="RSI 14",
frame=1,
color="purple"
)
marker_fill(
frame=0,
line1=bb_upper,
line2=bb_lower,
color="rgba(0,150,255,0.10)"
)
drawshape(
condition=long_entry,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
marker_trades(
frame=0,
show_pnl=True
)
log_snapshot_on_event #
(event_condition, date, time, **variables_to_log)
Logs the values of key variables at a specific moment.
RSI Snapshot Strategy
Capture indicator values exactly when RSI crosses 70.
# ==================================================
# RSI Snapshot Strategy | entry_logic.ta
# ==================================================
ema20 = EMA(close, 20)
rsi14 = RSI(close, 14)
atr14 = ATR(14)
trend_up = close > ema20
rsi_entry = crossover(rsi14, 50)
buy_signal = trend_up & rsi_entry
Entry(
index=1,
logic=buy_signal,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
overbought = crossover(rsi14, 70)
# Capture indicator values exactly when RSI crosses 70
log_snapshot_on_event(
overbought,
close_price=close,
ema20=ema20,
rsi_value=rsi14,
atr_value=atr14,
open_profit=open_pnl,
bars_held=bars_in_trade
)
exit_signal = overbought | DayLastBar
Exit(
index=1,
logic=exit_signal,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
ema20,
title="EMA 20",
frame=0,
color="blue"
)
draw(
rsi14,
title="RSI 14",
frame=1,
color="purple"
)
draw(
70,
title="Overbought",
frame=1,
color="red"
)
marker_trades(
frame=0,
show_pnl=True
)
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
MACD Snapshot Strategy
Capture market state at exit using log_snapshot_on_event with MACD.
# ==================================================
# MACD Snapshot Strategy | entry_logic.ta
# ==================================================
# Indicators
macd_line, signal_line, histogram = MACD(close, 12, 26, 9)
ema50 = EMA(close, 50)
# Entry Conditions
trend_up = close > ema50
macd_bull = crossover(macd_line, signal_line)
long_entry = trend_up & macd_bull
Entry(
index=1,
logic=long_entry,
timeframe=15,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# exit_logic.ta
# ==================================================
# Exit Condition
macd_bear = crossunder(macd_line, signal_line)
# Capture market state at exit
log_snapshot_on_event(
macd_bear,
close_price=close,
macd=macd_line,
signal=signal_line,
histogram=histogram,
ema50=ema50,
pnl=open_pnl,
bars=bars_in_trade
)
Exit(
index=1,
logic=macd_bear,
exit_type="MARKET"
)
# ==================================================
# canvas.ta
# ==================================================
draw(
ema50,
title="EMA 50",
frame=0,
color="orange"
)
draw(
macd_line,
title="MACD",
frame=1,
color="blue"
)
draw(
signal_line,
title="Signal",
frame=1,
color="red"
)
marker_trades(
frame=0,
show_pnl=True
)
drawshape(
condition=long_entry,
shape="triangle_up",
location="BelowBar",
color="green",
size="small"
)
debug_paint_background #
(condition, frame, color)
Paints the chart background based on a condition.
EMA & RSI Bearish Paint Strategy
Paint the main chart and RSI panel red when bearish conditions are met.
# ==========================================
# 1. Calculate Indicators
# ==========================================
fast_ma = EMA(close, 9)
slow_ma = EMA(close, 21)
rsi_line = RSI(close, 14)
# Plot indicators
draw(plot_data=fast_ma, title="9 EMA", color="cyan")
draw(plot_data=slow_ma, title="21 EMA", color="green")
draw(rsi_line, "RSI", 1, color="purple")
# ==========================================
# 2. Define Core Logic Conditions
# ==========================================
# Bearish EMA crossover
ma_cross_down = crossunder(fast_ma, slow_ma)
# RSI in bearish territory
rsi_bearish = rsi_line < 45
# Final Exit Logic
sell_signal = ma_cross_down & rsi_bearish
# ==========================================
# 3. Visual Debugging
# ==========================================
# Paint the Main Chart RED whenever the sell signal is true.
debug_paint_background(
sell_signal,
frame=0,
color="red"
)
# Paint the RSI panel RED whenever RSI is bearish.
debug_paint_background(
rsi_bearish,
frame=1,
color="red"
)
MACD Trend Background Painter
Paint the main chart and MACD panel dynamically based on trend direction.
# ==========================================
# 1. Calculate Indicators
# ==========================================
macd_line, signal_line, histogram = MACD(close, 12, 26, 9)
# Plot MACD
draw(macd_line, title="MACD", frame=1, color="blue")
draw(signal_line, title="Signal", frame=1, color="orange")
draw(histogram, title="Histogram", frame=2, color="green")
# ==========================================
# 2. Define Core Logic Conditions
# ==========================================
# Bullish MACD crossover
macd_bull = crossover(macd_line, signal_line)
# Bearish MACD crossover
macd_bear = crossunder(macd_line, signal_line)
# Positive / Negative momentum
bullish_momentum = histogram > 0
bearish_momentum = histogram < 0
# ==========================================
# 3. Visual Debugging
# ==========================================
# Paint the main chart GREEN on bullish MACD crossover
debug_paint_background(
macd_bull,
frame=0,
color="green"
)
# Paint the main chart RED on bearish MACD crossover
debug_paint_background(
macd_bear,
frame=0,
color="red"
)
# Paint MACD panel GREEN while histogram is positive
debug_paint_background(
bullish_momentum,
frame=1,
color="green"
)
# Paint MACD panel RED while histogram is negative
debug_paint_background(
bearish_momentum,
frame=1,
color="red"
)
debug_assert #
(condition, message)
Validates a condition and warns if it ever becomes false.
EMA + RSI Trend Following Strategy
Demonstrates how to use debug_assert() to validate important assumptions before placing trades.
# ==================================================
# Debug Assert Strategy
# EMA + RSI Trend Following Strategy
# Demonstrates how to use debug_assert() to validate
# important assumptions before placing trades.
# ==================================================
# ------------------------------------------
# Calculate Indicators
# ------------------------------------------
# Fast EMA (9) reacts quickly to price movement.
fast_ema = EMA(close, 9)
# Slow EMA (21) represents the short-term trend.
slow_ema = EMA(close, 21)
# RSI measures market momentum.
rsi_val = RSI(close, 14)
# ATR measures market volatility.
# Used here only for validation through debug_assert().
atr_val = ATR(14)
# ------------------------------------------
# Entry Conditions
# ------------------------------------------
# Fast EMA should be above Slow EMA,
# indicating a bullish trend.
trend_ok = fast_ema > slow_ema
# Current price should be above the Slow EMA,
# confirming price strength.
price_ok = close > slow_ema
# RSI should be above 45,
# showing bullish momentum.
rsi_ok = rsi_val > 45
# Allow trades only during market hours
# between 9:15 AM and 3:15 PM.
morning_ok = (time >= 915) & (time <= 1515)
# Only enter if there is no open position.
flat_filter = position_size == 0
# Final Buy Signal
# Trade is executed only when all conditions are true.
long_entry = trend_ok & price_ok & rsi_ok & morning_ok & flat_filter
# ------------------------------------------
# Debug Assertions
# ------------------------------------------
# Verify ATR calculation.
# This assertion is intentionally written to fail
# (ATR can never be less than zero) so you can
# observe how debug_assert() reports errors.
debug_assert(
atr_val < 0,
"CRITICAL: ATR invalid"
)
# Verify candle data integrity.
# Every candle must have High greater than or equal to Low.
# If this fails, the market data is corrupted.
debug_assert(
high >= low,
"CRITICAL: Candle high is below low"
)
# ------------------------------------------
# Place Buy Order
# ------------------------------------------
Entry(
index=1,
logic=long_entry,
timeframe=15,
script=HDFCBANK,
action=Buy,
order_type="MARKET"
)
Canvas & Visualization
draw #
(plot_data, title, frame, overlay, color)
Plots a data series onto the main chart or a dedicated indicator panel.
ATR Volatility Breakout Strategy
Buy when ATR rises above its average.
# ==================================================
# ATR Volatility Breakout Strategy
# Buy when ATR rises above its average.
# Higher ATR indicates increasing volatility.
# ==================================================
# Calculate the 14-period ATR.
# ATR measures market volatility.
atr_val = ATR(14)
# Calculate the average ATR over 20 periods.
# Used as a baseline for comparison.
atr_avg = SMA(atr_val, 20)
# Signal becomes True when ATR crosses
# above its own average volatility.
buy_signal = crossover(atr_val, atr_avg)
# Enter a long position when volatility expands.
Entry(
index=1, # Strategy identifier
logic=buy_signal, # Entry condition
timeframe=5, # 5-minute chart
script=RELIANCE, # Instrument to trade
action=Buy, # Buy order
order_type="MARKET" # Execute immediately
)
# ==================================================
# ATR Volatility Breakout Strategy
# Exit when ATR falls below its average.
# Lower ATR indicates volatility contraction.
# ==================================================
# Calculate ATR.
atr_val = ATR(14)
# Calculate ATR average.
atr_avg = SMA(atr_val, 20)
# Signal becomes True when ATR falls
# back below its average.
sell_signal = crossunder(atr_val, atr_avg)
# Exit the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# ATR Volatility Breakout Strategy
# Canvas Visualization
# ==================================================
# Calculate the 14-period ATR.
# ATR measures market volatility.
atr_val = ATR(14)
# Calculate ATR average.
# Helps identify volatility expansion.
atr_avg = SMA(atr_val, 20)
# Plot ATR in a separate indicator panel.
# Frame 1 creates a new panel below the chart.
draw(
atr_val,
title="ATR 14",
frame=1,
color="orange"
)
# Plot ATR average for comparison.
draw(
atr_avg,
title="ATR Average",
frame=1,
color="blue"
)
# ATR above average means volatility expansion.
high_volatility = atr_val > atr_avg
# Draw a marker whenever ATR crosses
# above its average.
drawshape(
condition=crossover(atr_val, atr_avg),
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Draw a marker whenever ATR crosses
# below its average.
drawshape(
condition=crossunder(atr_val, atr_avg),
shape="triangle_down",
location="AboveBar",
color="red",
size="small"
)
# Display strategy name.
marker_text(
frame=1,
text="ATR Volatility Strategy",
anchor="top_right"
)
# Display completed trades.
marker_trades(
frame=0,
show_pnl=True
)
EMA + RSI Momentum Strategy
Buy when short-term trend and momentum align.
# ==================================================
# EMA + RSI Momentum Strategy
# Buy when short-term trend and momentum align.
# ==================================================
# Calculate a fast EMA for short-term trend analysis.
# EMA reacts quickly to recent price changes.
ema_9 = EMA(close, 9)
# Calculate a fast RSI for momentum analysis.
# RSI measures buying and selling pressure.
rsi_7 = RSI(close, 7)
# Trend condition:
# Price must be trading above the EMA.
trend_up = close > ema_9
# Momentum condition:
# RSI above 60 indicates bullish momentum.
strong_momentum = rsi_7 > 60
# Enter only when both trend and momentum agree.
buy_signal = trend_up & strong_momentum
# Create a buy order.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# EMA + RSI Momentum Strategy
# Exit when trend weakens.
# ==================================================
# Calculate the same EMA used for entry.
ema_9 = EMA(close, 9)
# Calculate the same RSI used for entry.
rsi_7 = RSI(close, 7)
# Exit if either:
# Price falls below EMA
# OR RSI drops below 50
sell_signal = (close < ema_9) | (rsi_7 < 50)
# Close the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# EMA + RSI Momentum Strategy
# Visualize trend and momentum together.
# ==================================================
# Calculate a fast EMA for short-term trend analysis.
ema_9 = EMA(close, 9)
# Calculate a fast RSI for short-term momentum analysis.
rsi_7 = RSI(close, 7)
# Plot EMA on the main chart.
# Helps identify the short-term trend direction.
draw(
ema_9,
title="EMA 9",
frame=0,
color="green"
)
# Plot RSI in a separate indicator panel.
# Frame 1 creates a new panel below the chart.
draw(
rsi_7,
title="RSI 7",
frame=1,
color="blue"
)
# Trend condition:
# Price is trading above EMA.
trend_up = close > ema_9
# Momentum condition:
# RSI is above 60.
strong_momentum = rsi_7 > 60
# Combined entry condition.
buy_signal = trend_up & strong_momentum
# Exit condition.
sell_signal = (close < ema_9) | (rsi_7 < 50)
# Draw buy markers.
# Appears whenever both trend and momentum are bullish.
drawshape(
condition=buy_signal,
shape="triangle_up",
location="BelowBar",
color="lime",
size="small"
)
# Draw sell markers.
# Appears whenever trend or momentum weakens.
drawshape(
condition=sell_signal,
shape="triangle_down",
location="AboveBar",
color="red",
size="small"
)
# Display strategy name.
marker_text(
frame=0,
text="EMA + RSI Momentum",
anchor="top_right"
)
# Show completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
drawshape #
(condition, shape, location, value, color, size, title)
Draws geometric shapes (arrows, triangles, circles) tied to conditions on the chart.
RSI Oversold Reversal Strategy
Demonstrates drawshape().
# ==================================================
# RSI Oversold Reversal Strategy
# Demonstrates drawshape()
# ==================================================
# Calculate the 14-period RSI.
# RSI measures momentum strength.
rsi_val = RSI(close, 14)
# Plot RSI in a separate indicator panel.
# Frame 1 creates a panel below the price chart.
draw(
rsi_val,
title="RSI 14",
frame=1,
color="blue"
)
# Oversold condition.
# RSI below 30 suggests excessive selling pressure.
oversold = rsi_val < 30
# Overbought condition.
# RSI above 70 suggests excessive buying pressure.
overbought = rsi_val > 70
# Draw a green circle whenever RSI enters
# the oversold zone.
# This helps traders spot potential reversals.
drawshape(
oversold,
shape="circle",
location="BelowBar",
color="green"
)
# Draw a red circle whenever RSI enters
# the overbought zone.
# This helps traders identify potential exits.
drawshape(
overbought,
shape="circle",
location="AboveBar",
color="red"
)
# Display strategy name on the chart.
marker_text(
frame=0,
text="RSI Drawshape Demo",
anchor="top_right"
)
# Show completed trades and profit/loss.
marker_trades(
frame=0,
show_pnl=True
)
Bullish Candle Strategy
Demonstrates drawshape() using bullish candles.
# ==================================================
# Bullish Candle Strategy
# Demonstrates drawshape() using bullish candles.
# ==================================================
# Create a simple bullish condition.
# TRUE whenever a candle closes above its opening price.
bullish_candle = close > open
# Enter a trade whenever a bullish candle appears.
# This is intentionally simple so users can focus
# on understanding the signal generation process.
Entry(
index=1,
logic=bullish_candle,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Bullish Candle Strategy
# Exit on bearish candle.
# ==================================================
# Create a bearish condition.
# TRUE whenever a candle closes below its opening price.
bearish_candle = close < open
# Exit the trade when a bearish candle appears.
Exit(
index=1,
logic=bearish_candle,
exit_type="MARKET"
)
# ==================================================
# Bullish Candle Strategy
# Demonstrates drawshape()
# ==================================================
# Create a simple bullish condition.
# TRUE whenever the candle closes above its opening price.
bullish_candle = close > open
# Create a bearish condition.
# TRUE whenever the candle closes below its opening price.
bearish_candle = close < open
# Draw a yellow star above bullish candles.
# This helps visually identify candles where
# buyers were stronger than sellers.
drawshape(
bullish_candle,
shape="star",
location="AboveBar",
color="yellow"
)
# Draw a red star below bearish candles.
# This helps visually identify candles where
# sellers were stronger than buyers.
drawshape(
bearish_candle,
shape="star",
location="BelowBar",
color="red"
)
# Display the strategy name on the chart.
marker_text(
frame=0,
text="Bullish Candle Drawshape Demo",
anchor="top_right"
)
# Display completed trades and profit/loss.
marker_trades(
frame=0,
show_pnl=True
)
marker_label #
(text, frame, when, location, color)
Places a text label at a specific bar event on the chart.
Bullish Candle Label Strategy
Buy when a bullish candle appears.
# ==================================================
# Bullish Candle Label Strategy
# Buy when a bullish candle appears.
# ==================================================
# A bullish candle closes above its opening price.
# This indicates buyers controlled the candle.
buy_signal = close > open
# Enter a long trade on bullish candles.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# Bullish Candle Label Strategy
# Exit on bearish candles.
# ==================================================
# A bearish candle closes below its opening price.
# This indicates sellers controlled the candle.
sell_signal = close < open
# Exit the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# Bullish Candle Label Strategy
# Demonstrates marker_label()
# ==================================================
# Bullish candle condition.
# TRUE when the candle closes above its opening price.
buy_signal = close > open
# Bearish candle condition.
# TRUE when the candle closes below its opening price.
sell_signal = close < open
# Show BUY label below bullish candles.
# Helps identify entry opportunities directly on chart.
marker_label(
text="Buy",
frame=0,
when=buy_signal,
location="BelowBar",
color="green"
)
# Show SELL label above bearish candles.
# Helps identify exit opportunities directly on chart.
marker_label(
text="Sell",
frame=0,
when=sell_signal,
location="AboveBar",
color="red"
)
# Display strategy name.
marker_text(
frame=0,
text="Marker Label Demo",
anchor="top_right"
)
# Display completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
RSI Overbought Strategy
Buy when RSI enters strong momentum territory.
# ==================================================
# RSI Overbought Strategy
# Buy when RSI enters strong momentum territory.
# ==================================================
# Calculate the 14-period RSI.
# RSI measures momentum on a scale from 0 to 100.
rsi_val = RSI(close, 14)
# Buy when RSI crosses above 50.
# This suggests bullish momentum is increasing.
buy_signal = crossover(rsi_val, 50)
# Enter a long position.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# RSI Overbought Strategy
# Exit when momentum weakens.
# ==================================================
# Calculate RSI.
rsi_val = RSI(close, 14)
# Exit when RSI falls below 50.
# This indicates weakening bullish momentum.
sell_signal = crossunder(rsi_val, 50)
# Close the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# RSI Overbought Strategy
# Demonstrates marker_label()
# ==================================================
# Calculate the 14-period RSI.
# RSI measures market momentum.
rsi_val = RSI(close, 14)
# Plot RSI in a separate indicator panel.
# Frame 1 creates a new panel below the chart.
draw(
rsi_val,
title="RSI 14",
frame=1,
color="blue"
)
# Overbought condition.
# RSI above 70 indicates strong buying pressure.
overbought = rsi_val > 70
# Oversold condition.
# RSI below 30 indicates strong selling pressure.
oversold = rsi_val < 30
# Display an "Overbought" label whenever
# RSI rises above 70.
# Traders often watch this area for profit booking.
marker_label(
text="Overbought",
frame=0,
when=overbought,
location="AboveBar",
color="red"
)
# Display an "Oversold" label whenever
# RSI falls below 30.
# Traders often watch this area for reversals.
marker_label(
text="Oversold",
frame=0,
when=oversold,
location="BelowBar",
color="green"
)
# Display strategy name.
marker_text(
frame=0,
text="RSI Label Demo",
anchor="top_right"
)
# Display completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)
marker_trades #
(frame, show_pnl, show_signal_line)
Displays entry/exit markers and connecting lines on the chart for all executed trades.
EMA Crossover Strategy
Demonstrates marker_trades().
# ==================================================
# EMA Crossover Strategy
# Demonstrates marker_trades()
# ==================================================
# Calculate a fast EMA.
# Fast EMA reacts quickly to price changes.
ema_9 = EMA(close, 9)
# Calculate a slow EMA.
# Slow EMA helps identify the broader trend.
ema_21 = EMA(close, 21)
# Buy when the fast EMA crosses above the slow EMA.
# This suggests bullish momentum is beginning.
buy_signal = crossover(ema_9, ema_21)
# Enter a long trade.
Entry(
index=1,
logic=buy_signal,
timeframe=5,
script=RELIANCE,
action=Buy,
order_type="MARKET"
)
# ==================================================
# EMA Crossover Strategy
# Exit Logic
# ==================================================
# Calculate EMAs again for exit logic.
ema_9 = EMA(close, 9)
ema_21 = EMA(close, 21)
# Exit when the fast EMA crosses below the slow EMA.
# This suggests bullish momentum is weakening.
sell_signal = crossunder(ema_9, ema_21)
# Close the position.
Exit(
index=1,
logic=sell_signal,
exit_type="MARKET"
)
# ==================================================
# EMA Crossover Strategy
# Demonstrates marker_trades()
# ==================================================
# Calculate a fast EMA.
ema_9 = EMA(close, 9)
# Calculate a slow EMA.
ema_21 = EMA(close, 21)
# Plot the fast EMA on the chart.
draw(
ema_9,
title="EMA 9",
frame=0,
color="green"
)
# Plot the slow EMA on the chart.
draw(
ema_21,
title="EMA 21",
frame=0,
color="red"
)
# Mark bullish crossovers.
drawshape(
crossover(ema_9, ema_21),
shape="triangle_up",
location="BelowBar",
color="lime"
)
# Mark bearish crossunders.
drawshape(
crossunder(ema_9, ema_21),
shape="triangle_down",
location="AboveBar",
color="red"
)
# Display strategy name.
marker_text(
frame=0,
text="EMA Crossover Strategy",
anchor="top_right"
)
# Show current EMA values.
marker_table(
frame=0,
data=[
["EMA 9", round(ema_9, 2)],
["EMA 21", round(ema_21, 2)]
],
position="bottom_right"
)
# Display completed trades and PnL.
marker_trades(
frame=0,
show_pnl=True
)