Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Pivot Reversal Strategy – Tradingview Pinescript to Amibroker AFL Conversion

6 min read

The pivot reversal strategy AFL below is my AmiBroker conversion of TradingView’s built-in Pivot Reversal Strategy. It marks swing highs and swing lows using 4 bars on the left and 2 bars on the right, goes long when price breaks above the last pivot high and goes short when price breaks below the last pivot low. You get the original Pine Script v5 code, the full AFL, two small fixes and a backtest add-on that mimics TradingView’s stop-order fills.

Pivot Reversal Strategy is a popular in-built strategy in Tradingview Platform. Here I had attempted to convert the pinescript v5 to Amibroker AFL Code. A pivot reversal strategy is a trading approach focused on identifying key turning points, or “pivots,” in the market where a trend may reverse direction.

Here’s a concise breakdown:

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls
  1. Identifying Pivots: Traders look for specific patterns in price movements to identify pivot points. A pivot high occurs when a high point is surrounded by lower highs, suggesting a potential downtrend reversal. Conversely, a pivot low occurs when a low point is surrounded by higher lows, indicating a potential uptrend reversal.
  2. Entry and Exit Signals: The strategy generates buy signals when the price crosses above a pivot high and sell signals when the price crosses below a pivot low. These signals indicate potential opportunities to enter or exit positions in the market.
  3. Parameter Adjustment: Traders can adjust parameters such as the number of bars considered when identifying pivot points to tailor the strategy to different market conditions or trading preferences.

How the pivot reversal strategy works

A pivot high with 4 left bars and 2 right bars is a bar whose high is above the 4 bars before it and the 2 bars after it. Because you need those 2 right bars to close, a pivot is only confirmed 2 bars after it forms. The strategy then:

  1. Stores the latest confirmed pivot high (hprice) and pivot low (lprice).
  2. Places a buy stop one tick above hprice and a sell stop one tick below lprice.
  3. Stays always in the market: a long entry closes any short and a short entry closes any long.

In other words, this is a breakout-of-swing system with built-in reversal, not a strategy that buys at the pivot low itself.

Pivot reversal strategy AFL in AmiBroker with PivRevLE and PivRevSE signals and pivot levels

Pivot Reversal Strategy – Tradingview Pinescript Code

//@version=5
strategy("Pivot Reversal Strategy", overlay=true)
leftBars = input(4)
rightBars = input(2)
swh = ta.pivothigh(leftBars, rightBars)
swl = ta.pivotlow(leftBars, rightBars)
swh_cond = not na(swh)
hprice = 0.0
hprice := swh_cond ? swh : hprice[1]
le = false
le := swh_cond ? true : (le[1] and high > hprice ? false : le[1])
if (le)
	strategy.entry("PivRevLE", strategy.long, comment="PivRevLE", stop=hprice + syminfo.mintick)
swl_cond = not na(swl)
lprice = 0.0
lprice := swl_cond ? swl : lprice[1]
se = false
se := swl_cond ? true : (se[1] and low < lprice ? false : se[1])
if (se)
	strategy.entry("PivRevSE", strategy.short, comment="PivRevSE", stop=lprice - syminfo.mintick)
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)

TradingView has since moved to Pine Script v6. The v5 code above still compiles and runs unchanged on TradingView, so you can use it as is or upgrade it with the Pine Editor’s conversion tool.

TradingView built-in Pivot Reversal Strategy applied on a chart with long and short stop entries

Pine Script to AFL: key conversion points

Pine Script v5AmiBroker AFL equivalentNote
input(4)Param("Left Bars", 4, 1, 10, 1)Adjustable from the Parameters window
ta.pivothigh(leftBars, rightBars)Custom PivotHigh() loop functionValue appears on the confirmation bar, so no look-ahead
hprice := swh_cond ? swh : hprice[1]ValueWhen(Nz(swh)!=0, swh)Carries the last pivot level forward
strategy.entry(..., stop=hprice + syminfo.mintick)Buy = Cross(High, hprice)AFL fills at the close by default; see the backtest add-on below
Reversal via opposite strategy.entryExRem(Buy, Short) and ExRem(Short, Buy)Removes repeated signals in the same direction

Pivot Reversal Strategy – Amibroker AFL Code

//Coded by Rajandran R - Founder - Marketcalls / Creator - OpenAlgo
//Coded on 10th May 2024
//Website - www.marketcalls.in / www.openalgo.in
//Version - 1.0
//Code inspired from Tradingview Pivot Reversal Strategy (in-built strategy)


_SECTION_BEGIN("Pivot Reversal Strategy");

// Define the left and right bars for pivot calculations
leftBars = Param("Left Bars", 4, 1, 10, 1);
rightBars = Param("Right Bars", 2, 1, 10, 1);
showpivot = ParamToggle("Show Pivot","YES|NO",0);
showpivotlevels = ParamToggle("Show Pivot Levels","YES|NO",0);

// Custom functions to find pivot highs and lows
// Function to find pivot highs
function PivotHigh(leftBars, rightBars)
{
    array = Null;
    for (i = leftBars+rightBars; i < BarCount; i++)
    {
        isPivot = True;
        // Check if Pivot bar is higher than the left bars
        for (j = 1; j <= leftBars; j++)
        {
            if (High[i - j-rightBars] >= High[i-rightBars])
            {
                isPivot = False;
                break;
            }
        }
        // Check if Pivot bar is higher than the right bars
        for (j = 1; j <= rightBars; j++)
        {
            if (High[i + j-rightBars] >= High[i-rightBars])
            {
                isPivot = False;
                break;
            }
        }
        if (isPivot) array[i] = High[i-rightBars];
    }
    return array;
}

// Function to find pivot lows
function PivotLow(leftBars, rightBars)
{
    array = Null;
    for (i = leftBars+rightBars; i < BarCount - rightBars; i++)
    {
        isPivot = True;
        // Check if Pivot bar is lower than the left bars
        for (j = 1; j <= leftBars; j++)
        {
            if (Low[i - j-rightBars] <= Low[i-rightBars])
            {
                isPivot = False;
                break;
            }
        }
        // Check if Pivot bar is lower than the right bars
        for (j = 1; j <= rightBars; j++)
        {
            if (Low[i + j-rightBars] <= Low[i-rightBars])
            {
                isPivot = False;
                break;
            }
        }
        if (isPivot) array[i] = Low[i-rightBars];
    }
    return array;
}

// Calculate pivot highs and lows
swh = PivotHigh(leftBars, rightBars);
swl = PivotLow(leftBars, rightBars);


hprice = ValueWhen(Nz(swh)!=0,swh);
lprice = ValueWhen(Nz(swl)!=0,swl);


Buy = Cross(High,hprice);
Short = Cross(lprice,Low);

Buy = ExRem(Buy,Short);
Short = ExRem(Short,Buy);


//This Block look into the future to plot the pivot high and low bars.
//It is not part of the trading strategy. so this look into future will not impact trading strategy

if(showpivot)
{
PlotShapes(IIf(Ref(swh,2),shapeCircle,shapeNone),colorRed,0,Ref(swh,2),12);
PlotShapes(IIf(Ref(swl,2),shapeCircle,shapeNone),colorGreen,0,Ref(swh,2),-12);
}

if(showpivotlevels)
{
Plot(hprice,"hprice",colorRed,styleDashed);
Plot(lprice,"lprice",colorGreen,styleDashed);
}
_SECTION_END();

_SECTION_BEGIN("Candlestick Charts with Date & Time Axis");

//Enable the Date & Time Axis
SetChartOptions(0, chartShowArrows | chartShowDates);

//Plotting Candlestick charts
Plot(Close,"Candle",colorDefault,styleCandle);


_SECTION_END();

_SECTION_BEGIN("Trading Signals");

/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);


fontsize = Param("Font Size",10,10,40,1);
for( i = 0; i < BarCount; i++ ) 
 {  
if( Buy[i] ) PlotTextSetFont("PivRevLE","Arial", fontsize,i,L[i],colorWhite,colorGreen,-70);
if( short[i] ) PlotTextSetFont("PivRevSE","Arial", fontsize,i,H[i],colorWhite,colorRed,70);


}



_SECTION_END();

Here is the breakdown of the code.

Here’s a breakdown of how it works:

  1. Setting Parameters: Traders can adjust parameters like the number of bars to the left and right to calculate pivot points.
  2. Calculating Pivot Highs and Lows: The code calculates pivot highs and lows based on the specified number of bars to the left and right. A pivot high occurs when a high point is surrounded by lower highs, and a pivot low occurs when a low point is surrounded by higher lows.
  3. Identifying Buy and Sell Signals: Once pivot highs and lows are identified, the code looks for buy signals when the price crosses above a pivot high and sell signals when the price crosses below a pivot low.
  4. Plotting Pivot Points: Optionally, the code can plot pivot highs and lows on the chart for visual reference.
  5. Displaying Candlestick Charts: The code also displays candlestick charts with date and time axes.
  6. Displaying Trading Signals: Buy and sell signals are marked on the chart with arrows, and text labels indicate the points at which the signals occur.

Updated version (2026): two fixes and a backtest add-on

While reviewing the code again I found two small issues. Neither affects the Buy and Short signals much, but they are worth correcting:

  • The PivotLow() loop stops at BarCount - rightBars while PivotHigh() runs to BarCount. This can miss a pivot low confirmed on the latest bars and delay a short signal in live charts.
  • In the Show Pivot block, the green circle for pivot lows is plotted at Ref(swh,2) (the pivot high) instead of Ref(swl,2), and the shift is fixed at 2 bars even if you change Right Bars.
// Corrections for the original code (replace the matching lines)

// 1) PivotLow: scan to the last bar, same as PivotHigh,
//    so pivot lows near the right edge are not missed
for (i = leftBars+rightBars; i < BarCount; i++)

// 2) Show Pivot: plot pivot lows at the swing low price
//    and use rightBars instead of a fixed 2
PlotShapes(IIf(Ref(swh,rightBars),shapeCircle,shapeNone),colorRed,0,Ref(swh,rightBars),12);
PlotShapes(IIf(Ref(swl,rightBars),shapeCircle,shapeNone),colorGreen,0,Ref(swl,rightBars),-12);

The original AFL has no Sell or Cover rules and fills at the bar close, so backtest numbers will not match TradingView, which fills at the stop level and reverses position. Add this block at the end of the code before running a backtest:

// Backtest add-on: stop entries and always-in reversal like the TradingView strategy
// Add this block below the original code

SetTradeDelays(0, 0, 0, 0);

if (TickSize == 0) ts = 0.05; else ts = TickSize;

BuyPrice   = Max(Open, hprice + ts);   // long stop at pivot high + 1 tick (or the open on a gap)
ShortPrice = Min(Open, lprice - ts);   // short stop at pivot low - 1 tick (or the open on a gap)

Sell  = Short;  SellPrice  = ShortPrice;  // a short entry closes the long
Cover = Buy;    CoverPrice = BuyPrice;    // a long entry closes the short

With these settings AmiBroker enters at the pivot level plus or minus one tick, or at the open when price gaps beyond it, and treats every new signal as a reversal. Set your brokerage and slippage in the Analysis settings before you compare results.

Tips for using the pivot reversal strategy AFL

  • Tune left and right bars together. More right bars confirm pivots later but filter noise. Try 4/2 for intraday and 5/3 or 10/5 for daily charts, and check how many trades each produces.
  • Add a trend filter. Taking only longs above a 200-period moving average (and shorts below) usually cuts the whipsaws in sideways markets.
  • Expect many reversals in ranges. Always-in systems lose repeatedly when price chops between nearby pivots. Review the trade list, not just the net profit.
  • Automate carefully. If you route signals to a broker, OpenAlgo can take TradingView or AmiBroker alerts and place the orders for you.

Frequently Asked Questions

What is the pivot reversal strategy in TradingView?

It is one of TradingView’s built-in strategies. It finds swing highs and lows with ta.pivothigh and ta.pivotlow, then places stop orders to go long above the last pivot high and short below the last pivot low.

Does the pivot reversal strategy AFL repaint?

The trading signals do not, because each pivot value is stored only on the bar where it is confirmed. The optional Show Pivot circles are shifted back to the actual swing bar for display, which is why that block looks into the future.

Can I use this AFL for Nifty intraday trading?

Yes. Apply it on a 5 or 15 minute Nifty or Bank Nifty futures chart, backtest with realistic costs and slippage, and add a time filter to avoid entries in the last few minutes of the session.

More Pine Script to AFL conversions: Reversal Finder and CM Williams VIX Fix. To understand the numbers your backtest produces, see AmiBroker backtesting metrics explained.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More