OPEN-SOURCE SCRIPT

Trend-Following Strategy for NIFTY or BANK NIFTY

//version=5
strategy("Trend-Following Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=5)

// Input Parameters
macd_fast_length = input(12, title="MACD Fast Length")
macd_slow_length = input(26, title="MACD Slow Length")
macd_signal_length = input(9, title="MACD Signal Length")
sma_length = input(200, title="SMA Length")
atr_length = input(14, title="ATR Length")
atr_multiplier = input(1.5, title="ATR Stop Loss Multiplier")

// Calculate Indicators
[macdLine, signalLine, _] = ta.macd(close, macd_fast_length, macd_slow_length, macd_signal_length)
sma = ta.sma(close, sma_length)
atr = ta.atr(atr_length)

// Define Conditions
longCondition = ta.crossover(macdLine, signalLine) and close > sma
shortCondition = ta.crossunder(macdLine, signalLine) and close < sma

// Stop Loss and Take Profit
longStopLoss = close - atr * atr_multiplier
shortStopLoss = close + atr * atr_multiplier

// Execute Trades
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Long Exit", from_entry="Long", stop=longStopLoss)

if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Short Exit", from_entry="Short", stop=shortStopLoss)

// Plot Indicators
plot(sma, color=color.blue, linewidth=2, title="200 SMA")
hline(0, "Zero Line", color=color.gray)
plot(macdLine, color=color.green, title="MACD Line")
plot(signalLine, color=color.red, title="Signal Line")
Candlestick analysisChart patterns

Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in publication is governed by House rules. You can favorite it to use it on a chart.

Want to use this script on a chart?

Disclaimer