Backtesting Parabolic SAR Trading Strategy in Tradingview

This script provides a solid foundation for backtesting the Positional Parabolic SAR Strategy in TradingView. We have already discussed the strategy in the last chapter.

				
					//@version=5
strategy("Positional Parabolic SAR Strategy | Unofficed.com", overlay=true)
initial = input(0.02)
step = input(0.02)
cap = input(0.2)
var bool isUptrend = na
var float Extremum = na
var float SARValue = na
var float Accelerator = initial
var float futureSAR = na

if bar_index > 0
    isNewTrendBar = false
    SARValue := futureSAR
    if bar_index == 1
        float pastSAR = na
        float pastExtremum = na
        previousLow = low[1]
        previousHigh = high[1]
        currentClose = close
        pastClose = close[1]
        if currentClose > pastClose
            isUptrend := true
            Extremum := high
            pastSAR := previousLow
            pastExtremum := high
        else
            isUptrend := false
            Extremum := low
            pastSAR := previousHigh
            pastExtremum := low
        isNewTrendBar := true
        SARValue := pastSAR + initial * (pastExtremum - pastSAR)
    if isUptrend
        if SARValue > low
            isNewTrendBar := true
            isUptrend := false
            SARValue := math.max(Extremum, high)
            Extremum := low
            Accelerator := initial
    else
        if SARValue < high
            isNewTrendBar := true
            isUptrend := true
            SARValue := math.min(Extremum, low)
            Extremum := high
            Accelerator := initial
    if not isNewTrendBar
        if isUptrend
            if high > Extremum
                Extremum := high
                Accelerator := math.min(Accelerator + step, cap)
        else
            if low < Extremum
                Extremum := low
                Accelerator := math.min(Accelerator + step, cap)
    if isUptrend
        SARValue := math.min(SARValue, low[1])
        if bar_index > 1
            SARValue := math.min(SARValue, low[2])
    else
        SARValue := math.max(SARValue, high[1])
        if bar_index > 1
            SARValue := math.max(SARValue, high[2])
    futureSAR := SARValue + Accelerator * (Extremum - SARValue)
    if barstate.isconfirmed
        if isUptrend
            strategy.entry("ShortEntry", strategy.short, stop=futureSAR, comment="ShortEntry")
            strategy.cancel("LongEntry")
        else
            strategy.entry("LongEntry", strategy.long, stop=futureSAR, comment="LongEntry")
            strategy.cancel("ShortEntry")
plot(SARValue, style=plot.style_cross, linewidth=3, color=color.white)
plot(futureSAR, style=plot.style_cross, linewidth=3, color=color.red)
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)

				
			
The strategy is made available on TradingView. It’s open source and free, allowing you to utilize it for your personal research and analysis.

[Quant] Positional Parabolic SAR Strategy | Unofficed.com by Amit_Ghosh on TradingView.com

Script Breakdown:

  1. //@version=5: Specifies the version of Pine Script being used, which in this case is version 5.

  2. strategy("Positional Parabolic SAR Strategy", overlay=true): Defines a new strategy with the title “Positional Parabolic SAR Strategy” and sets the overlay to true to display the strategy on the price chart.

  3. initial = input(0.02), step = input(0.02), cap = input(0.2): Initializes input variables for the Parabolic SAR parameters: initial, step, and cap.

  4. Variable Initialization:

    • var bool isUptrend = na: Declares a boolean variable to track if the market is in an uptrend.
    • var float Extremum = na: Tracks the extreme point (highest high or lowest low) in the current trend.
    • var float SARValue = na: Stores the value of the Parabolic SAR.
    • var float Accelerator = initial: Sets the acceleration factor for the Parabolic SAR calculation.
    • var float futureSAR = na: Holds the predicted next period SAR value.
  5. if bar_index > 0: Ensures the code below executes only from the second bar onward to have at least one previous bar for reference.

  6. Main Logic:

    • The section within if bar_index > 0 contains the logic for calculating the Parabolic SAR values based on price action.
    • It checks whether the market is in an uptrend or downtrend, adjusts the acceleration factor, and calculates the SAR value accordingly.
  7. Entry and Exit Logic:

    • Within if barstate.isconfirmed, the script defines the entry and exit conditions using strategy.entry and strategy.cancel functions based on the SAR values and market trend.
  8. Visualization:

    • plot(SARValue, style=plot.style_cross, linewidth=3, color=color.white): Plots the current SAR value on the chart.
    • plot(futureSAR, style=plot.style_cross, linewidth=3, color=color.red): Plots the predicted next period SAR value on the chart.

Backtesting NIFTY Futures

In Tradingview, You can find the NIFTY futures in a continous contact which means it will auto rollver when there is expiry and it will take the prive of the contact whcih is about to expire. So that is exaclty what we need. 

So although the lot size and margin changes over time, we have taken the contract to be 1 which mean it will take the 1 lot automatically. The current margin of 1 lot nifty is around 1,50,000 inr. So, Lets run the strategy with various timeframe to analsyse how it is working. 

The reason of choosing NIFTY straightforward because it is an index. 

The core principal of Parabolic SAR lies on the assumption that the market follows normal distribution. We can refer “index” as “the market” anyways. What can be more appropiate? 

15 Minutes Timeframe

30 Minutes Timeframe

1 Hour Timeframe

1 Day Timeframe

1 Week Timeframe

1 Month Timeframe

The rationale behind selecting the 30-minute strategy for illustration is evident from the above data – the performance dwindles as the timeframe extends. This decline is primarily due to the multitude of events and news that crop up in a longer timeframe, deviating from a normal distribution.

  • While a 15-minute strategy showcases higher profits, it generates twice the number of trades compared to a 30-minute timeframe. Hence, to curb costs, a 30-minute window has been opted for.
  • Also the profitibility of the 30-minute strategy is slight higher.
As we march forward the timeframes, The trades keep reducing significantly, so does the win ratio! The drawdown gets higher!

Although the monthly timeframe emerges as the most favorable, the scant number of trades it produces renders it inadequate as a data point for analysis.

So far, it is a blockbuster and simple strategy that works! 

  1. Now, apart from NIFTY, What other instrument we can backtest with the Parabolic SAR Strategy?
  2.  Also, Can it be automated directly in the account so that We do not have to stay glued into the screen?
  3. Why don’t you explore the strategy yourself with various instruments and various timeframes and share all the interesting results you get. 
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close