Code Library / Grid Trading

Pine Script Grid Trading Backtest

Backtest a grid trading strategy on TradingView.

Language: Pine Script · Category: Grid Trading · Tags: grid, backtest, Pine Script, strategy, simulation

Source code

//@version=5
strategy("Grid Backtest",overlay=true)
gridPct=input.float(1.0,"Grid %%"); levels=input.int(3,"Levels")
base=ta.sma(close,200); step=base*gridPct/100
for i=1 to levels
    if close<=base-step*i and close[1]>base-step*i
        strategy.entry("Buy"+str.tostring(i),strategy.long)
    if close>=base+step*i and close[1]<base+step*i
        strategy.entry("Sell"+str.tostring(i),strategy.short)
plot(base,"Base",color.yellow)

How to use this snippet

This is a building block, not a finished trading system. Paste it into your own Pine Script project, compile it, and test it on a demo account with your broker's real spreads before relying on it. You can convert it to MQL4 or MQL5 with the Pine Script converter.

Related snippets