Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Pivot Reversal Strategy – Tradingview Pinescript to Amibroker AFL Conversion

3 min read

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:

  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.

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)

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.
Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Interactive Brokers – Smart Order Chart Trading Module using…

The IB Controller is an interface designed to facilitate automatic trading with AmiBroker and Interactive Brokers (IB) TWS (Trader Workstation). It serves as a...
Rajandran R
8 min read

Introducing OpenAlgo V1.0: The Ultimate Open-Source Algorithmic Trading Framework…

OpenAlgo V1.0 is an open-source algorithmic trading platform to automate your trading strategies using Amibroker, Tradingview, Metatrader, Python etc. Designed with the modern trader...
Rajandran R
2 min read

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

Leave a Reply

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