Skip to main content

5 MA Pine Strategy

Overview

The 5 MA Pine Strategy is an advanced multi-moving-average trading system designed for traders who want complete flexibility in building their own trend-following strategy. Unlike traditional EMA crossover systems that are limited to two moving averages, this strategy allows traders to configure and combine up to five different moving averages, each with its own settings and calculation method. The strategy is fully compatible with Mirrorpip Automation, allowing users to execute trades automatically across supported exchanges directly from TradingView alerts.

Key Features

Up To 5 Configurable Moving Averages

The strategy supports five independent moving averages:
  • MA 1
  • MA 2
  • MA 3
  • MA 4
  • MA 5
Each moving average can be enabled or disabled individually based on your trading requirements. This allows traders to build:
  • 2 Moving Average Strategies
  • 3 Moving Average Strategies
  • 4 Moving Average Strategies
  • 5 Moving Average Strategies
without modifying any code.

Multiple Moving Average Types

Each moving average can be configured independently. Supported types include:

EMA (Exponential Moving Average)

Gives higher importance to recent price movements and reacts quickly to market changes.

SMA (Simple Moving Average)

Provides smoother trend identification by assigning equal weight to all data points.

WMA (Weighted Moving Average)

Places greater emphasis on recent prices while maintaining smoother trend behavior.

DEMA (Double Exponential Moving Average)

Reduces lag compared to traditional EMAs and provides faster trend signals.

TEMA (Triple Exponential Moving Average)

Offers even faster response to price movements while reducing noise and lag. here is the source code
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mirrorpip

//@version=5
strategy("Mirrorpip 5-MAs Strategy", shorttitle="Mirrorpip 5-MAs Strategy", overlay=true, default_qty_type=strategy.fixed, default_qty_value=1, initial_capital=300000, currency=currency.NONE, commission_value=0, commission_type=strategy.commission.percent, process_orders_on_close=false, calc_on_every_tick=true, calc_on_order_fills=true)
import TradingView/ta/7

////======================================================
paraTradeMode = input.string(title='Trade Mode', defval='Both', options=['Both', 'LongOnly', 'ShortOnly'], group = "Trade Settings")
paraSystemMode = input.session(defval="Intraday", title="System Mode", options=["Intraday", "Positional"], group = "Trade Settings")
s = input.session(title='Intraday Start Session:', defval='0915-1445', group='Trade Settings')
e = input.session(title='Intraday End Session:', defval='1500-1515', group='Trade Settings')

paraMA1Mode = true //input.bool(true, "MA-1", inline = "MA1", group = "MA Settings")
paraMA1Type = input.string("EMA", "MA-1 Type", options=["SMA", "EMA", "WMA", "DEMA", "TEMA"], inline = "MA1", group = "MA Settings")
paraMA1 = input.int(5, "Period", minval = 1, inline = "MA1", group = "MA Settings")

paraMA2Mode = true //input.bool(true, "MA-2", inline = "MA2", group = "MA Settings")
paraMA2Type = input.string("EMA", "MA-2 Type", options=["SMA", "EMA", "WMA", "DEMA", "TEMA"], inline = "MA2", group = "MA Settings")
paraMA2 = input.int(10, "Period", minval = 1, inline = "MA2", group = "MA Settings")

paraMA3Mode = input.bool(true, "MA-3", inline = "MA3", group = "MA Settings")
paraMA3Type = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "DEMA", "TEMA"], inline = "MA3", group = "MA Settings")
paraMA3 = input.int(15, "Period", minval = 1, inline = "MA3", group = "MA Settings")

paraMA4Mode = input.bool(true, "MA-4", inline = "MA4", group = "MA Settings")
paraMA4Type = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "DEMA", "TEMA"], inline = "MA4", group = "MA Settings")
paraMA4 = input.int(20, "Period", minval = 1, inline = "MA4", group = "MA Settings")

paraMA5Mode = input.bool(true, "MA-5", inline = "MA5", group = "MA Settings")
paraMA5Type = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "DEMA", "TEMA"], inline = "MA5", group = "MA Settings")
paraMA5 = input.int(50, "Period", minval = 1, inline = "MA5", group = "MA Settings")

paraTGTMode = input.string(defval="%", title="Target : ", options=["Off", "%", "Pts"], inline = "TGT", group = "Target Settings")
paraTGT1 = input.float(1, "T1 : ", minval = 0, inline = "TGT", group = "Target Settings")
paraTGT = input.float(2, "T2 : ", minval = 0.1, inline = "TGT", group = "Target Settings")

paraSLMode = input.string(defval="%", title="Stoploss : ", options=["Off", "%", "Pts"], inline = "SL", group = "Stoploss Settings")
paraSL = input.float(1, "Value : ", minval = 0.1, inline = "SL", group = "Stoploss Settings")

paraTSLMode = input.string(defval="%", title="Trail SL : ", options=["Off", "%", "Pts"], inline = "TSL", group = "TSL Settings")
paraTSL = input.float(1, "Value : ", minval = 0.1, inline = "TSL", group = "TSL Settings")

paraShowDashboard = input.bool(true, "Show Strategy Dashboard")
////======================================================

////======================================================
grpAlgo = "Algo Setup"
paraExchange = input.string(title='Exchange', defval='delta', group=grpAlgo)
paraCode = input.string(title='Code', defval='XXXXXX', group=grpAlgo)
paraQtyType = input.string(title="Quantity Type", defval='Fixed',options=['Fixed','Exposure'], group=grpAlgo)
paraQty = input.float(title='Quantity ', defval=1, minval=0, group=grpAlgo, tooltip='Qty in Lots for Futures')
paraT1Qty = input.float(title='Target-1 Exit Qty (%)', defval=0, minval=0, maxval = 100, group=grpAlgo, tooltip='Qty in Percentage')
paraMaxProfit = input.int(0, "Max Profit Per Trade", 0, group=grpAlgo, tooltip='Exit on Max. Profit in Rs.')
paraMaxLoss = input.int(0, "Max Loss Per Trade", 0, group=grpAlgo, tooltip='Exit on Max. Loss in Rs.')
////======================================================

////======================================================
var float MA1 = na
var float MA2 = na
var float MA3 = na
var float MA4 = na
var float MA5 = na

if (paraMA1Type == "SMA")
    MA1 := ta.sma(close, paraMA1)
else if (paraMA1Type == "EMA")
    MA1 := ta.ema(close, paraMA1)
else if (paraMA1Type == "WMA")
    MA1 := ta.wma(close, paraMA1)
else if (paraMA1Type == "DEMA")
    MA1 := ta.dema(close, paraMA1)
else if (paraMA1Type == "TEMA")
    MA1 := ta.tema(close, paraMA1)

if (paraMA2Type == "SMA")
    MA2 := ta.sma(close, paraMA2)
else if (paraMA2Type == "EMA")
    MA2 := ta.ema(close, paraMA2)
else if (paraMA2Type == "WMA")
    MA2 := ta.wma(close, paraMA2)
else if (paraMA2Type == "DEMA")
    MA2 := ta.dema(close, paraMA2)
else if (paraMA2Type == "TEMA")
    MA2 := ta.tema(close, paraMA2)

if (paraMA3Type == "SMA")
    MA3 := ta.sma(close, paraMA3)
else if (paraMA3Type == "EMA")
    MA3 := ta.ema(close, paraMA3)
else if (paraMA3Type == "WMA")
    MA3 := ta.wma(close, paraMA3)
else if (paraMA3Type == "DEMA")
    MA3 := ta.dema(close, paraMA3)
else if (paraMA3Type == "TEMA")
    MA3 := ta.tema(close, paraMA3)

if (paraMA4Type == "SMA")
    MA4 := ta.sma(close, paraMA4)
else if (paraMA4Type == "EMA")
    MA4 := ta.ema(close, paraMA4)
else if (paraMA4Type == "WMA")
    MA4 := ta.wma(close, paraMA4)
else if (paraMA4Type == "DEMA")
    MA4 := ta.dema(close, paraMA4)
else if (paraMA4Type == "TEMA")
    MA4 := ta.tema(close, paraMA4)

if (paraMA5Type == "SMA")
    MA5 := ta.sma(close, paraMA5)
else if (paraMA5Type == "EMA")
    MA5 := ta.ema(close, paraMA5)
else if (paraMA5Type == "WMA")
    MA5 := ta.wma(close, paraMA5)
else if (paraMA5Type == "DEMA")
    MA5 := ta.dema(close, paraMA5)
else if (paraMA5Type == "TEMA")
    MA5 := ta.tema(close, paraMA5)
////======================================================

////======================================================
st = paraSystemMode=="Positional" ? true : not na(time(timeframe.period, s))
et = paraSystemMode=="Positional" ? false : not na(time(timeframe.period, e))

MA2Buy = MA1 > MA2
MA2Short = MA1 < MA2

MA3Buy = paraMA3Mode ? MA2 > MA3 : true
MA3Short = paraMA3Mode ? MA2 < MA3 : true
MA3Sell = paraMA3Mode and MA2 < MA3 
MA3Cover = paraMA3Mode and MA2 > MA3 

MA4Buy = paraMA4Mode ? MA3 > MA4 : true
MA4Short = paraMA4Mode ? MA3 < MA4 : true
MA4Sell = paraMA4Mode and MA3 < MA4 
MA4Cover = paraMA4Mode and MA3 > MA4 

MA5Buy = paraMA5Mode ? MA4 > MA5 : true
MA5Short = paraMA5Mode ? MA4 < MA5 : true
MA5Sell = paraMA5Mode and MA4 < MA5 
MA5Cover = paraMA5Mode and MA4 > MA5 

eSignal = 0
eBuy = MA2Buy and MA3Buy and MA4Buy and MA5Buy 
eShort = MA2Short and MA3Short and MA4Short and MA5Short 
eSell = eShort or et or (not MA2Buy or MA3Sell or MA4Sell or MA5Sell)
eCover = eBuy or et or (not MA2Short or MA3Cover or MA4Cover or MA5Cover) 
eSignal := eBuy ? 1 : eShort ? -1 : eSell and eSignal[1] > 0 ? 0 : eCover and eSignal[1] < 0 ? 0 : eSignal[1]

MainSignal = 0
BuySignal = paraTradeMode!="ShortOnly" and st and eSignal > 0 and eSignal[1] <= 0 and barstate.isconfirmed and (nz(MainSignal[1]) <= 0)
ShortSignal = paraTradeMode!="LongOnly" and st and eSignal < 0 and eSignal[1] >= 0 and barstate.isconfirmed and (nz(MainSignal[1]) >= 0)
SellSignal = (((ShortSignal or eSell) and barstate.isconfirmed) or et) and (nz(MainSignal[1]) == 1)
CoverSignal = (((BuySignal or eCover) and barstate.isconfirmed) or et) and (nz(MainSignal[1]) == -1)
MainSignal := BuySignal ? 1 : ShortSignal ? -1 : SellSignal and MainSignal[1] > 0 ? 0 : CoverSignal and MainSignal[1] < 0 ? 0 : MainSignal[1]
////======================================================

////======================================================
symbol = syminfo.ticker

eBuyPrice = ta.valuewhen(eBuy, close, 0)
eShortPrice = ta.valuewhen(eShort, close, 0)

LESym = str.tostring(syminfo.ticker) 
LXSym = str.tostring(syminfo.ticker) 
SESym = str.tostring(syminfo.ticker) 
SXSym = str.tostring(syminfo.ticker) 

var float BuyTradeQty = na
var float ShortTradeQty = na
var float BuyRisk = na
var float ShortRisk = na

BuyTradeQty := paraQty
ShortTradeQty := paraQty

if (paraQtyType=="Exposure")
    BuyTradeQty := paraQty / eBuyPrice
    BuyTradeQty := math.round(BuyTradeQty / syminfo.pointvalue) 
    ShortTradeQty := paraQty / eShortPrice
    ShortTradeQty := math.round(ShortTradeQty / syminfo.pointvalue) 

    if (BuyTradeQty < 0)
        BuyTradeQty := 1
    if (ShortTradeQty < 0)
        ShortTradeQty := 1

buyData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + LESym + '", "order_type": "BUY", "instrument_type": "NA", "quantity": "' + str.tostring(BuyTradeQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
sellData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + LXSym + '", "order_type": "SELL", "instrument_type": "NA", "quantity": "' + str.tostring(BuyTradeQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
shortData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + SESym + '", "order_type": "SHORT", "instrument_type": "NA", "quantity": "' + str.tostring(ShortTradeQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
coverData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + SXSym + '", "order_type": "COVER", "instrument_type": "NA", "quantity": "' + str.tostring(ShortTradeQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
////======================================================

////======================================================
if BuySignal and strategy.position_size < 0 
    strategy.entry('BUY', strategy.long, comment='Buy', qty=BuyTradeQty, alert_message="["+coverData+","+buyData+"]")
else if BuySignal and strategy.position_size == 0 
    strategy.entry('BUY', strategy.long, comment='Buy', qty=BuyTradeQty, alert_message="["+buyData+"]")

if ShortSignal and strategy.position_size > 0 
    strategy.entry('SHORT', strategy.short, comment='Short', qty=ShortTradeQty, alert_message="["+sellData+","+shortData+"]")
else if ShortSignal and strategy.position_size == 0 
    strategy.entry('SHORT', strategy.short, comment='Short', qty=ShortTradeQty, alert_message="["+shortData+"]")

varip float Pos_Size = na
var float BuyPrice = na
var float ShortPrice = na
var float BuyTGT = na
var float ShortTGT = na
var float BuyTGT1 = na
var float ShortTGT1 = na
var float BuySL = na
var float ShortSL = na
var float BuyTSL = na
var float ShortTSL = na

ut = (paraTGTMode != "Off")
us = (paraSLMode != "Off")

if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
    BuyPrice := strategy.position_avg_price
    if (paraSLMode=="%")
        BuySL := BuyPrice * (1-(paraSL/100))
    else if (paraSLMode=="Pts")
        BuySL := BuyPrice - (paraSL)

    if (paraTGTMode=="%")
        BuyTGT1 := BuyPrice * (1+(paraTGT1/100))
        BuyTGT := BuyPrice * (1+(paraTGT/100))
    else if (paraTGTMode=="Pts")
        BuyTGT1 := BuyPrice + (paraTGT1)
        BuyTGT := BuyPrice + (paraTGT)

if (strategy.position_size < 0 and strategy.position_size[1] >= 0)
    ShortPrice := strategy.position_avg_price
    if (paraSLMode=="%")
        ShortSL := ShortPrice * (1+(paraSL/100))
    else if (paraSLMode=="Pts")
        ShortSL := ShortPrice + (paraSL)

    if (paraTGTMode=="%")
        ShortTGT1 := ShortPrice * (1-(paraTGT1/100))
        ShortTGT := ShortPrice * (1-(paraTGT/100))
    else if (paraTGTMode=="Pts")
        ShortTGT1 := ShortPrice - (paraTGT1)
        ShortTGT := ShortPrice - (paraTGT)

if (paraTSLMode != "Off")
    if (strategy.position_size > 0 and strategy.position_size[1] > 0)
        if (paraTSLMode=="%")
            BuyTSL := high[1] * (1-(paraTSL/100))
        else
            BuyTSL := high[1] - paraTSL
        if (BuySL < BuyTSL)
            BuySL := BuyTSL
    if (strategy.position_size < 0 and strategy.position_size[1] < 0)
        if (paraTSLMode=="%")
            ShortTSL := low[1] * (1+(paraTSL/100))
        else
            ShortTSL := low[1] + paraTSL
        if (ShortSL > ShortTSL)
            ShortSL := ShortTSL

if (paraMaxProfit > 0)
    if (strategy.position_size > 0 and strategy.opentrades.profit(strategy.opentrades - 1) >= paraMaxProfit)
        strategy.close("BUY", immediately = true, alert_message="["+sellData+"]")
    if (strategy.position_size < 0 and strategy.opentrades.profit(strategy.opentrades - 1) >= paraMaxProfit)
        strategy.close("SHORT", immediately = true, alert_message="["+coverData+"]")

if (paraMaxLoss > 0)
    if (strategy.position_size > 0 and strategy.opentrades.profit(strategy.opentrades - 1) <= -(paraMaxLoss))
        strategy.close("BUY", immediately = true, alert_message="["+sellData+"]")
    if (strategy.position_size < 0 and strategy.opentrades.profit(strategy.opentrades - 1) <= -(paraMaxLoss))
        strategy.close("SHORT", immediately = true, alert_message="["+coverData+"]")

Pos_Size := math.abs(strategy.position_size)
T1ExQty = math.round(Pos_Size*(paraT1Qty/100))
TPsellData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + LXSym + '", "order_type": "SELL", "instrument_type": "NA", "quantity": "' + str.tostring(T1ExQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
TPcoverData = '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + SXSym + '", "order_type": "COVER", "instrument_type": "NA", "quantity": "' + str.tostring(T1ExQty) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'

sellData := '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + LXSym + '", "order_type": "SELL", "instrument_type": "NA", "quantity": "' + str.tostring(Pos_Size) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'
coverData := '{ "exchange": "' + paraExchange + '", "price": "' + str.tostring(close) + '", "chart_symbol": "' + SXSym + '", "order_type": "COVER", "instrument_type": "NA", "quantity": "' + str.tostring(Pos_Size) + '", "tp": "0", "sl": "0", "code": "'+paraCode+'"}'

if ut == true and us == false
    if (strategy.position_size > 0)
        if (paraT1Qty > 0 and paraTGT1 > 0)
            strategy.exit(id="LongT1Exit", from_entry="BUY", qty = T1ExQty, limit=BuyTGT1, comment="TPSell", alert_message="["+TPsellData+"]", oca_name = "LX1")
        strategy.exit(id='LongExit', comment="Sell", from_entry='BUY', limit=BuyTGT, alert_message="["+sellData+"]")
    if (strategy.position_size < 0)
        if (paraT1Qty > 0 and paraTGT1 > 0)
            strategy.exit(id="ShortT1Exit", from_entry="SHORT", qty = T1ExQty, limit=ShortTGT1, comment="TPCover", alert_message="["+TPcoverData+"]", oca_name = "SX1")
        strategy.exit(id='ShortExit', comment="Cover", from_entry='SHORT', limit=ShortTGT, alert_message="["+coverData+"]")
if us == true and ut == false 
    if (strategy.position_size > 0)
        strategy.exit(id='LongExit', comment="Sell", from_entry='BUY', stop=BuySL, alert_message="["+sellData+"]")
    if (strategy.position_size < 0)
        strategy.exit(id='ShortExit', comment="Cover", from_entry='SHORT', stop=ShortSL, alert_message="["+coverData+"]")
if ut == true and us == true
    if (strategy.position_size > 0)
        if (paraT1Qty > 0 and paraTGT1 > 0)
            strategy.exit(id="LongT1Exit", from_entry="BUY", qty = T1ExQty, limit=BuyTGT1, stop=BuySL, comment="TPSell", alert_message="["+TPsellData+"]", oca_name = "LX1")
        strategy.exit(id='LongExit', comment="Sell", from_entry='BUY', limit=BuyTGT, stop=BuySL, alert_message="["+sellData+"]")
    if (strategy.position_size < 0)
        if (paraT1Qty > 0 and paraTGT1 > 0)
            strategy.exit(id="ShortT1Exit", from_entry="SHORT", qty = T1ExQty, limit=ShortTGT1, stop=ShortSL, comment="TPCover", alert_message="["+TPcoverData+"]", oca_name = "SX1")
        strategy.exit(id='ShortExit', comment="Cover", from_entry='SHORT', limit=ShortTGT, stop=ShortSL, alert_message="["+coverData+"]")

if (et or (SellSignal and (not ShortSignal))) and strategy.position_size > 0 
    strategy.cancel('LongExit')
    strategy.cancel('LongT1Exit')
    strategy.close(id='BUY', comment="Sell", alert_message="["+sellData+"]")

if (et or (CoverSignal and (not BuySignal))) and strategy.position_size < 0 
    strategy.cancel('ShortExit')
    strategy.cancel('ShortT1Exit')
    strategy.close(id='SHORT', comment="Cover", alert_message="["+coverData+"]")

if (strategy.position_size <= 0)
    strategy.cancel('LongExit')
    strategy.cancel('LongT1Exit')
if (strategy.position_size >= 0)
    strategy.cancel('ShortExit')
    strategy.cancel('ShortT1Exit')
////======================================================

////======================================================
plot(MA1, "MA-1", color.white)
plot(MA2, "MA-2", color.yellow)
plot(paraMA3Mode ? MA3 : na, "MA-3", color.green)
plot(paraMA4Mode ? MA4 : na, "MA-4", color.red)
plot(paraMA5Mode ? MA5 : na, "MA-5", color.blue)

plot((strategy.position_size > 0)?BuyPrice:na, color=color.fuchsia, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size > 0)?BuyTGT1:na, color=color.blue, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size > 0)?BuyTGT:na, color=color.blue, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size > 0)?BuySL:na, color=color.orange, linewidth=1, style=plot.style_linebr)

plot((strategy.position_size < 0)?ShortPrice:na, color=color.fuchsia, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size < 0)?ShortTGT1:na, color=color.blue, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size < 0)?ShortTGT:na, color=color.blue, linewidth=1, style=plot.style_linebr)
plot((strategy.position_size < 0)?ShortSL:na, color=color.orange, linewidth=1, style=plot.style_linebr)
////======================================================

////======================================================
totalCols = 2
totalRows = 5 
stgTGTFlag = paraTGTMode != "Off"
stgSLFlag = paraSLMode != "Off"

if stgTGTFlag
    totalRows += 1
if stgSLFlag
    totalRows += 1

var dashtable = table.new(position.bottom_left, totalCols, totalRows,
  frame_color=color.new(#000000,0),
  frame_width=1,
  border_color=color.new(#000000,0),
  border_width=1)

cell_up = #237a27 //input.color(#237a27,'Buy Cell Color'  ,group='Style Settings')
cell_dn = color.red //input.color(color.red,'Sell Cell Color'  ,group='Style Settings')
cell_Neut = color.gray //input.color(color.gray,'Neut Cell Color'  ,group='Style Settings')
txt_col = color.white

table_text_size = size.small

openProfit = strategy.openprofit
lastProfit = strategy.closedtrades.profit(strategy.closedtrades-1)
openProfitColor = openProfit >= 0 ? cell_up : cell_dn
lastProfitColor = lastProfit >= 0 ? cell_up : cell_dn

rowCtr = 0
colCtr = 0

if (barstate.islast and paraShowDashboard)
    table.cell(dashtable, 0, rowCtr, "Mirrorpip Dashboard", text_color=txt_col, text_size=table_text_size, bgcolor=color.new(color.blue,80), tooltip="")  
    table.cell(dashtable, 1, rowCtr, '', text_color=txt_col, text_size=table_text_size, bgcolor=color.new(color.blue,80), tooltip="")
    table.merge_cells(dashtable, 0, 0, 1, 0)

    if strategy.position_size > 0
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Buy",text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(strategy.position_avg_price, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Qty.",text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(strategy.position_size, "#"),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        if (stgTGTFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "TGT",text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
            if (not na(BuyTGT1))
                table.cell(dashtable, 1, rowCtr, str.tostring(BuyTGT1, format.mintick) + "/"+ str.tostring(BuyTGT, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
            else    
                table.cell(dashtable, 1, rowCtr, str.tostring(BuyTGT, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        if (stgSLFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "SL",text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
            table.cell(dashtable, 1, rowCtr, str.tostring(BuySL, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "P&L",text_color=txt_col,text_size=table_text_size,bgcolor=openProfitColor,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(openProfit, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=openProfitColor,tooltip="")

    if strategy.position_size < 0
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Short",text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(strategy.position_avg_price, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Qty.",text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(strategy.position_size, "#"),text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        if (stgTGTFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "TGT",text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
            if (not na(ShortTGT1))
                table.cell(dashtable, 1, rowCtr, str.tostring(ShortTGT1, format.mintick) + "/"+ str.tostring(ShortTGT, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
            else    
                table.cell(dashtable, 1, rowCtr, str.tostring(ShortTGT, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_up,tooltip="")
        if (stgSLFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "SL",text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
            table.cell(dashtable, 1, rowCtr, str.tostring(ShortSL, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=cell_dn,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "P&L",text_color=txt_col,text_size=table_text_size,bgcolor=openProfitColor,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(openProfit, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=openProfitColor,tooltip="")

    if strategy.position_size == 0
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "No Trade", text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        table.cell(dashtable, 1, rowCtr, "Relax", text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        table.cell(dashtable, 1, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        if (stgTGTFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
            table.cell(dashtable, 1, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        if (stgSLFlag)
            rowCtr += 1
            table.cell(dashtable, 0, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
            table.cell(dashtable, 1, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")
        table.cell(dashtable, 1, rowCtr, "",text_color=txt_col,text_size=table_text_size,bgcolor=cell_Neut,tooltip="")

    if strategy.position_size <= 0 and strategy.position_size[1] > 0
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Exit Buy",text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(lastProfit, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
    else if strategy.position_size >= 0 and strategy.position_size[1] < 0
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Exit Short",text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(lastProfit, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
    else    
        rowCtr += 1
        table.cell(dashtable, 0, rowCtr, "Last P&L",text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
        table.cell(dashtable, 1, rowCtr, str.tostring(lastProfit, format.mintick),text_color=txt_col,text_size=table_text_size,bgcolor=lastProfitColor,tooltip="")
////======================================================


Fully Customizable MA Periods

Each moving average can have its own period setting. Examples:
  • MA 1 = 9 EMA
  • MA 2 = 20 EMA
  • MA 3 = 50 SMA
  • MA 4 = 100 WMA
  • MA 5 = 200 TEMA
Every trader can create their own unique trend model.

Flexible Strategy Configurations

2 MA Crossover Setup

Example:
  • 20 EMA
  • 50 EMA
Entry occurs when the fast MA crosses above the slow MA.

3 MA Trend Confirmation

Example:
  • 20 EMA
  • 50 EMA
  • 200 EMA
Used to confirm trend direction before entering trades.

4 MA Trend Structure

Example:
  • 9 EMA
  • 21 EMA
  • 50 EMA
  • 200 EMA
Provides deeper trend filtering and reduces false signals.

5 MA Advanced Trend System

Example:
  • 9 EMA
  • 20 EMA
  • 50 EMA
  • 100 EMA
  • 200 EMA
Suitable for professional traders looking for multi-layer trend confirmation.

Entry Logic

The strategy automatically generates Buy and Sell signals based on the alignment and crossover of enabled moving averages.

Long Entry

A Buy signal may be generated when:
  • Faster moving averages cross above slower moving averages.
  • Selected MA alignment becomes bullish.
  • Trend confirmation rules are satisfied.
Mirrorpip automatically places the Buy order on the connected exchange.

Short Entry

A Sell or Short signal may be generated when:
  • Faster moving averages cross below slower moving averages.
  • Selected MA alignment becomes bearish.
  • Trend confirmation rules are satisfied.
Mirrorpip automatically executes the Short order on supported exchanges.

Enable or Disable Any Moving Average

One of the most powerful features of the strategy is complete flexibility. You can:

Enable Only 2 MAs

Example:
  • MA 1 = Enabled
  • MA 2 = Enabled
  • MA 3 = Disabled
  • MA 4 = Disabled
  • MA 5 = Disabled
Acts like a traditional moving average crossover strategy.

Enable Only 3 MAs

Example:
  • MA 1 = Enabled
  • MA 2 = Enabled
  • MA 3 = Enabled
  • MA 4 = Disabled
  • MA 5 = Disabled
Adds an additional trend filter.

Enable All 5 MAs

Provides maximum trend confirmation and market structure analysis.

Dual Profit Targets

The strategy supports two independent profit targets.

Target 1 (T1)

Configurable in:
  • Percentage (%)
  • Points
Examples:
  • 1%
  • 2%
  • 100 Points

Target 2 (T2)

Configurable independently in:
  • Percentage (%)
  • Points
Examples:
  • 3%
  • 5%
  • 300 Points
This enables partial profit booking while keeping a portion of the trade running.

Stop Loss Management

The strategy includes flexible Stop Loss functionality.

Percentage-Based Stop Loss

Examples:
  • 1%
  • 2%
  • 3%

Point-Based Stop Loss

Examples:
  • 50 Points
  • 100 Points
  • 200 Points
Mirrorpip automatically exits the position once the stop loss level is reached.

Trailing Stop Loss (TSL)

The strategy includes an advanced Trailing Stop Loss system.

TSL Options

Users can configure:
  • Percentage-Based TSL
  • Point-Based TSL
Benefits:
  • Locks in profits automatically.
  • Allows traders to capture larger trends.
  • Reduces risk during reversals.

Intraday and Positional Trading

Intraday Mode

Ideal for:
  • NSE Stocks
  • Bank Nifty
  • Nifty
  • Futures & Options
Recommended Timeframes:
  • 5 Minute
  • 15 Minute
  • 30 Minute

Positional Mode

Ideal for:
  • Cryptocurrency Markets
  • Forex Markets
  • International Markets
Recommended Timeframes:
  • 1 Hour
  • 4 Hour
  • Daily

Fully Automated with Mirrorpip

The strategy comes with pre-built Mirrorpip automation support.

Setup Process

  1. Add the strategy to your TradingView chart.
  2. Select the moving average types.
  3. Configure MA periods.
  4. Enable or disable desired moving averages.
  5. Configure Targets, Stop Loss, and Trailing Stop Loss.
  6. Create a TradingView Alert.
  7. Connect the alert to Mirrorpip.
  8. Mirrorpip automatically executes trades on your exchange account.
No programming knowledge is required.

Supported Exchanges

Mirrorpip supports automated execution on leading exchanges including:
  • Bybit
  • Binance
  • Delta Exchange
  • CoinSwitch
  • OKX
  • Bitget
  • Gate.io
  • KuCoin
  • Shark Exchange
and many more.

Why Traders Prefer the 5 MA Strategy

  • Supports multiple moving average types.
  • Completely customizable.
  • Suitable for beginners and advanced traders.
  • Works across stocks, futures, forex, and crypto.
  • Reduces false signals through trend confirmation.
  • Allows traders to build their own MA systems without coding.
  • Fully automated through Mirrorpip.

Risk Disclaimer

Trading involves substantial risk and no strategy guarantees profits. Always:
  • Use proper position sizing.
  • Configure stop losses.
  • Test settings before deploying live capital.
  • Monitor TradingView alerts and exchange connectivity.

Conclusion

The 5 MA Pine Strategy is one of the most flexible moving average trading systems available for TradingView automation. With support for up to five configurable moving averages, multiple MA types including EMA, SMA, WMA, DEMA, and TEMA, dual profit targets, advanced risk management tools, and seamless Mirrorpip integration, traders can create and automate virtually any moving average-based trading strategy with ease.