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

AlphaTrend – Amibroker AFL Code to Manage Sideways Markets

3 min read

Very simple and interesting trend following strategy which could manage sideways markets to a greater extent while following the trend. Recently I got inspired by the Pinescript coder Mr KivancOzbilgic and with his indicator Alphatrend in Tradingview and so the strategy conversion for Amibroker users.

What is Alphatrend?

Alpha Trend tries to solve those problems such as:

1-To minimize stop losses and overcome sideways market conditions.
2-To have more accurate BUY/SELL signals during trending market conditions.
3- To have significant support and resistance levels.
4- To bring together indicators from different categories that are compatible with each other and make a meaningful combination regarding momentum, trend, volatility, volume and trailing stop loss.

Purposes of Alpha Trend:
1- Acts like a dead indicator like its ancestor Magic Trendin sideways market conditions and doesn’t give many false signals.
2- With another line with 2 bars offset off the original one Alpha Trend has BUY and SELL signals from their crossovers.

Trading Rules

BUY when AlphaTrend line crosses above its 2 bars offset line
SELL when Alpha Trend line crosses below its 2 bars offset line

Alpha Trend lines
-act as support levels when an uptrend occurs trailing 0.5*ATR (default coefficient) distance from bar’s low values
-conversely, act as resistance levels when a downtrend occurs trailing 0.5*ATR (default coefficient) distance from bar’s high values and acting as trailing stop losses
the more Alpha Trend lines are straighter the more supports and resistances become stronger.

Alphatrend – Amibroker AFL Code

//Alphatrend - Trend Follow Strategy
//Coded by Rajandran R - Founder - Marketcalls / Creator - OpenAlgo
//Website : www.openalgo.in / www.marketcalls.in
//Code Inspired from Tradingview - KivancOzbilgic
//Tradingview URL : https://tradingview.com/script/o50NYLAZ-AlphaTrend/

//Alpha Trend tries to solve those problems such as:

//1-To minimize stop losses and overcome sideways market conditions.
//2-To have more accurate BUY/SELL signals during trending market conditions.
//3- To have significant support and resistance levels.
//4- To bring together indicators from different categories that are compatible with each other and make a meaningful combination regarding momentum, trend, volatility , volume and trailing stop loss.


_SECTION_BEGIN("AlphaTrend");

SetBarsRequired(sbrAll,sbrAll);

coeff = Param("Multiplier",0.5,0.1,1,0.1);
AP = Param("Common Period", 20, 1, 100, 1);

iATR = MA(ATR(1),AP);

src = Close;

showsignalsk = True;
novolumedata = False;

upT = Low - iATR * coeff;
downT = High + iATR * coeff;

hlc3= (H+L+C)/3;

rs = RSIa(Close,14);
mf = MFI(14);

AlphaTrend = 0.0;

//AlphaTrend := (novolumedata ? ta.rsi(src, 14) >= 50 : 
//				ta.mfi(hlc3, 14) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT :
//				 downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT


for(i=1;i<BarCount;i++)
{
if(novolumedata){
	Alphatrend[i] = rs[i]>= 50;

}//end novolumedata
else if(mf[i] >= 50){

if(upT[i] < Alphatrend[i-1])
{
Alphatrend[i] = Alphatrend[i-1] ;
}
else{

Alphatrend[i] = upT[i];

}

}

else
{
if(downT[i] > Alphatrend[i-1])
{
Alphatrend[i] = Alphatrend[i-1] ;
}
else 
{
Alphatrend[i] = downT[i];
}

}//end else 



}//end for loop

color = IIf(AlphaTrend>Ref(AlphaTrend,-2), colorGreen, IIf(AlphaTrend<Ref(AlphaTrend,-2), colorred, 
		IIf(Ref(AlphaTrend,-1) > Ref(AlphaTrend,-3), colorblue, colorYellow)));


Buy = Cross(Alphatrend,Ref(Alphatrend,-2));
Sell = Cross(Ref(AlphaTrend,-2),AlphaTrend);


Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

Short = Sell;
Cover = Buy;


//Non Repainting  - Signals happens only after the close of the current
Buy = Ref(Buy,-1);
Sell = Ref(Sell,-1);
Short = Ref(Short,-1);
Cover = Ref(Cover,-1);


BuyPrice = ValueWhen(Buy,Open);
sellPrice = ValueWhen(sell,Open);
shortPrice = ValueWhen(Short,Open);
coverPrice = ValueWhen(cover,Open);

buycontinue = Flip(Buy,Sell);
color1 = IIf(buycontinue,colorGreen,colorRed);

cloud = ParamToggle("Cloud Enabled","TRUE|False",0);
	
if(cloud)
{
PlotOHLC(AlphaTrend,AlphaTrend,Ref(AlphaTrend,-2),Ref(AlphaTrend,-2), "AlphaTrend",color, styleCloud|styleNoLabel);		
}
else
{
Plot(Alphatrend,"Alphatrend",color1,styleLine | styleThick);
}

/* 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);

PlotShapes(Sell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(Cover * shapestar, colorRed, 0, Low, -12);

_SECTION_END();


_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", color1, styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();



_SECTION_BEGIN("Trading Dashboard");

dashboard = ParamToggle("Show Dashboard","SHOW|HIDE",1);

if(dashboard)
{

fontsize = Param("Font Size",14,8,40,1);

GfxSelectFont("BOOK ANTIQUA", fontsize, 400);
GfxSetTextColor(colorWhite);
GfxSetBkMode(1); //Transparent mode

buycontinue = Flip(Buy,Sell);
sellcontinue = Flip(Sell,Buy);

color = IIf(buycontinue, colorGreen, IIf(sellcontinue, colorRed, colorGrey40));

GfxSelectPen(colorWhite); //pen -> draw outline of the shape
GfxSelectSolidBrush(SelectedValue(color));

width = Status("pxchartwidth");
height = Status("pxchartheight");


GfxRoundRect(20,height-150,320,height-30,10,10);

//Trading Signal Status - e.g Buy Signal or Short Signal
//Profit/Loss for Current Running Trade

sigstatus = WriteIf(buycontinue,"Buy Signal", WriteIf(sellcontinue,"Short Signal", "No Trade(Relax)"));
PNL = IIf(buycontinue,Close-BuyPrice, IIf(sellcontinue, ShortPrice-Close, Null));

//variable sigstatus -> string
//variable PNL -> Array

GfxTextOut("AlphaTrend",30,height-130);
GfxTextOut(sigstatus + " came @ : "+ IIf(buycontinue,BuyPrice, IIf(sellcontinue, ShortPrice, Null)),30,height-110);
GfxTextOut("Profit/Loss :"+SelectedValue(Prec(PNL,2)),30, height-90);


}

_SECTION_END();

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

Line Trading – OpenAlgo Automation Module for Amibroker Users

The line Trading Automation tool is designed for Manual traders who want to perform level-based trade execution faster and also bring some advanced trade...
Rajandran R
55 sec read

Mini Certification Course on Algorithmic Trading

Welcome to the Mini Certification on Algorithmic Trading using Amibroker and OpenAlgo! This comprehensive 4-part series is designed to equip you with the knowledge...
Rajandran R
1 min read

Pivot Reversal Strategy – Tradingview Pinescript to Amibroker AFL…

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....
Rajandran R
3 min read

7 Replies to “AlphaTrend – Amibroker AFL Code to Manage Sideways Markets”

Leave a Reply

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