Mastering Pine Script v5: Building a Multi-Timeframe Trend Following Indicator


TradingView’s Pine Script v5 allows traders and algorithmic engineers to rapidly prototype and deploy indicators directly onto real-time charts.

A common pitfall with basic trend indicators is getting chopped up during consolidation regimes. In this tutorial, we construct a Multi-Timeframe (MTF) Trend Engine that confirms 15-minute signals against a 1-hour exponential moving average (EMA) trend filter.

1. Indicator Concept

  • Primary Chart (15m): 9 EMA and 21 EMA cross.
  • Higher Timeframe Filter (1h): Price must reside above the 200 EMA to allow long signals.
  • Alert Webhook: Emits formatted JSON payloads ready for your execution bot or broker webhook.

2. Pine Script v5 Code

//@version=5
indicator("XAlgoPro - MTF Trend Engine", overlay=true)

// Inputs
fastLen = input.int(9, "Fast EMA Length")
slowLen = input.int(21, "Slow EMA Length")
htfResolution = input.timeframe("60", "Higher Timeframe Filter")
htfLen = input.int(200, "HTF EMA Length")

// Calculations
fastEMA = ta.ema(close, fastLen)
slowEMA = ta.ema(close, slowLen)

// Request Higher Timeframe Data without Lookahead Bias
htfEMA = request.security(syminfo.tickerid, htfResolution, ta.ema(close, htfLen), barmerge.gaps_off, barmerge.lookahead_off)

// Signals
longSignal = ta.crossover(fastEMA, slowEMA) and close > htfEMA
shortSignal = ta.crossunder(fastEMA, slowEMA) and close < htfEMA

// Plots
plot(fastEMA, color=color.blue, title="Fast EMA")
plot(slowEMA, color=color.orange, title="Slow EMA")
plot(htfEMA, color=color.white, linewidth=2, title="HTF 200 EMA")

plotshape(longSignal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(shortSignal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

// Automated Alert condition
if longSignal
    alert('{"action": "BUY", "ticker": "' + syminfo.ticker + '", "price": ' + str.tostring(close) + '}', alert.freq_once_per_bar_close)

3. Deployment & Automation

  1. Open TradingView, switch to the Pine Editor tab, paste the code, and click Add to Chart.
  2. Click Create Alert on the indicator condition.
  3. In the alert webhook URL field, link your EC2 execution server endpoint to execute paper or live trades via broker APIs (Alpaca, Interactive Brokers).
SEBI MANDATORY REGULATORY DISCLAIMER

Important Notice & Educational Purpose: XAlgoPro (xalgopro.com) and its authors/contributors are NOT SEBI registered Research Analysts (RA) or Investment Advisers (IA) under the SEBI (Research Analysts) Regulations, 2014, or SEBI (Investment Advisers) Regulations, 2013.

All content, algorithmic logic, indicators, Pine Script codes, Python scripts, statistical models, mathematical formulas, and backtest results presented on this platform are published strictly for educational, academic, and technological research purposes only. Nothing on this website constitutes investment advice, financial guidance, an offer, recommendation, or solicitation to buy or sell any security, derivative, contract, or financial instrument on the National Stock Exchange (NSE), Bombay Stock Exchange (BSE), or any other global exchange.

SEBI Statutory Risk Disclosure on Derivatives (F&O):As per SEBI study on Intraday & Derivatives trading, 9 out of 10 individual traders in the Equity Futures and Options (F&O) segment incurred net losses, with an average loss of over ₹50,000 per trader. Over and above net trading losses, loss-makers expended an additional 15% to 50% in transaction fees, brokerage, and statutory taxes (STT, GST, Stamp Duty). Trading options and futures involves substantial financial risk, leverage, and potential loss of entire invested capital.

Past algorithmic backtest performance or hypothetical simulations do not guarantee or represent future live trading results. Readers and users must perform their own independent due diligence, test thoroughly in simulated/paper trading environments, and consult an authorized SEBI Registered Financial Advisor before risking actual capital in Indian equity or derivatives markets. You are solely responsible for all trading decisions, capital allocations, and monetary risks undertaken.