Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

Simplified Intraday Module with Target, Stoploss, PNL Dashboard and AllinOneAlert Controls – Amibroker AFL Code

8 min read

Here is a simple module that converts any End of Candle strategy into an Intraday module. With Targets, Stoploss, Alerts, and PNL Dashboard controls. This code brings down the complexity of coding, which the majority of the intraday traders face while building a simple trading system with various controls.

Features of the Module

  • Intraday Module with Stoploss and Target Management
  • All in One Alerts (Arrow Alert, Label Alert, Voice Alert, Sound Alert, Email Alert, Telegram Alert)
  • Profit/Loss Dashboard
  • Drag and Drop on Any of your simple End of the candle strategy rest intraday module will take care.
  • Time-Based Intraday Controls with Number of Entry/Exit – Limit

Steps to use the module

1)Download the AFL Code and Store it as Intraday.afl under any of the Amibroker Formulas Folder.

2)Ensure your strategy has Buy,sell,short,cover parameters. Apply your trading system on a blank chart and drag and drop the Intraday.afl on top of your trading system

3)if your strategy doesnt has short and cover variables use short =0; and cover = 0; in your code before dragging and dropping

4)Use the code only on Top of End of Candle Strategy and not on tough based trading system

5)Avoid giving any trade delay in your strategy as it is already handles inside the module

Amibroker AFL Code – Intraday Module


//Intraday Module - Readmade Module (Drag and Drop on top of your trading strategy)
//Built in Target and Stoploss Based Exit (Touch based Exit)
//Regular Exit(Close of Candle) and Time Based Exit(Close of Candle)

//Warning : Use the Module only on top of End of candle strategy 
//Avoid giving any delay in your strategy as it is already handles inside the module

//Coded by Rajandran R - Founder - Marketcalls / Co-Founder - Algomojo
//Coded on 12th Jan 2022
//Website - www.marketcalls.in / www.algomojo.com
//Version - 1.0


_SECTION_BEGIN("Marketcalls - All in One Alerts Module");

//For 6.17 or higher version users Telegram Modern Alert mehtod will be used
//For lower version users VBscript based Telegram Alert (Legacy Method is used)
AmiVersion = 6.17;  

// Send Alerts even if Amibroker is minimized or Chart is not active
RequestTimedRefresh(1, False); 

//Initialization

ArrowAlerts = ParamToggle("Arrow Alerts","Enable|Disable",1);
LabelAlerts = ParamToggle("Label Alerts","Enable|Disable",0);
SoundAlerts = ParamToggle("Sound Alerts","Enable|Disable",0);
EmailAlerts = ParamToggle("Mail Alerts","Enable|Disable",0);
VoiceAlerts = ParamToggle("Voice Alerts","Enable|Disable",0);
PopUpAlerts = ParamToggle("PopUp Alerts","Enable|Disable",0);
TelegramAlerts = ParamToggle("Telegram Alerts","Enable|Disable",0);
TelegramAPI_ID = ParamStr("Telegram Bot API Key","1734928163:AAEiZ_64DJmk7jtosP1hkRywz1savZWUHAY");  //Get the Bot API key via BotFather in Telgram
TelgramCHAT_ID = ParamStr("Telegram Channel ID","@quantalerts2021");  //Channel ID example : @marketcalls_in
tradedelay = Param("Execution Delay",0,0,1); // 0 - Alerts with No Delay (Touch Based Strategies), 1- Alerts with 1 Bar Delay (EOD of Candle - Next Bar Open based Alerts)
AlertName = ParamStr("Alert Name","Strategy Alerts");
fontsize = Param("Font Size",10,10,40,1);


//User Defined Function -> Created using VBscript
EnableScript("VBScript"); 

<% 

Public Sub Telegram(Message_Text)


sAPI_ID = AFL.Var("TelegramAPI_ID")
sChat_ID = AFL.Var("TelgramCHAT_ID")
sMSG = Message_Text

'URL to open....
sUrl = "https://api.telegram.org/bot" & sAPI_ID & "/sendMessage"
'POST Request to send.
sRequest = "text=" & sMSG & "&chat_id=" & sChat_ID


set oHTTP = CreateObject("Microsoft.XMLHTTP")
oHTTP.open "POST", sUrl,false
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.setRequestHeader "Content-Length", Len(sRequest)
oHTTP.send sRequest
HTTPPost = oHTTP.responseText


'Store response 
'msgbox(objXmlHttpMain.responseText)
'response.Write (objXmlHttpMain.responseText) 

End Sub 

%> 

tg = GetScriptObject(); 



function SignalArrowPlots(iBuy,iSell,iShort,iCover)
{
/* Plot Buy and Sell Signal Arrows */

PlotShapes(IIf(iBuy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(iBuy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(iBuy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(iShort, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(iShort, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(iShort, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(iSell * shapestar, colorBrightGreen, 0, High, 12);
PlotShapes(iCover * shapestar, colorRed, 0, Low, -12);

}

function SignalTextLabels(iBuy,iSell,ishort,iCover)
{


for( i = 0; i < BarCount; i++ ) 
 {  
if( iBuy[i] ) PlotTextSetFont("Long Entry","Arial", fontsize,i,L[i],colorWhite,colorGreen,-30);
if( iSell[i] ) PlotTextSetFont("Long Exit","Arial", fontsize,i,H[i],colorWhite,colorGreen,30);
if( ishort[i] ) PlotTextSetFont("Short Entry","Arial", fontsize,i,H[i],colorWhite,colorRed,50);
if( iCover[i] ) PlotTextSetFont("Short Exit","Arial", fontsize,i,L[i],colorWhite,colorRed,-50);


}

}



//Buy and Sell Order Functions

function BuyAlerts(AlertBuy,AlertCover,Message)
{

if(SoundAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		AlertIf(AlertBuy,"SOUND C:\\Windows\\Media\\Ding.wav",Message,1,flag=1+2);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		AlertIf(AlertCover,"SOUND C:\\Windows\\Media\\Ding.wav",Message,4,flag=1+2);
	}
	
	if(AlertBuy AND AlertCover)
	{
		AlertIf(AlertBuy AND AlertCover,"SOUND C:\\Windows\\Media\\Ding.wav",Message,5,flag=1+2);
		
	}

}

if(EmailAlerts)
{

	if(AlertBuy AND !AlertCover)
	{
		AlertIf(AlertBuy,"EMAIL",Message,1,flag=1+2);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		AlertIf(AlertCover,"EMAIL",Message,4,flag=1+2);
	}
	
	if(AlertBuy AND AlertCover)
	{
		AlertIf(AlertBuy AND AlertCover,"EMAIL",Message,5,flag=1+2);
	}



}

if(VoiceAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		Say("Buy Signal");
	}
	
	if(!AlertBuy AND AlertCover)
	{
		Say("Cover Signal");
	}
	
	if(AlertBuy AND AlertCover)
	{
		Say("Buy and Cover Signal");
	}


}

if(PopUpAlerts)
{
	if(AlertBuy AND !AlertCover)
	{
		PopupWindow("Buy Signal",Message);
	}
	
	if(!AlertBuy AND AlertCover)
	{
		PopupWindow("Cover Signal",Message);
	}
	
	if(AlertBuy AND AlertCover)
	{
		PopupWindow("Buy and Cover Signal",Message);
	}


}

if(TelegramAlerts)
{	
	if(Version() >= AmiVersion)
	{
	//call the modern Internet Function
	ih = InternetOpenURL("https://api.telegram.org/bot"+TelegramAPI_ID+"/sendMessage?chat_id="+TelgramCHAT_ID+"&text="+Message ); 
	InternetClose(ih);
	}
	else
	{
	//call the legacy method
	tg.Telegram(Message);
	}

}



}



function SellAlerts(AlertShort,AlertSell,Message)
{
if(SoundAlerts)
{
	if(AlertShort AND !AlertSell)
	{
	AlertIf(AlertShort,"SOUND C:\\Windows\\Media\\Ding.wav",Message,3,flag=1+2);
	}
	
	if(!AlertShort AND AlertSell)
	{
	AlertIf(AlertSell,"SOUND C:\\Windows\\Media\\Ding.wav",Message,2,flag=1+2);
	}
	
	if(AlertShort AND AlertSell)
	{
	AlertIf(AlertShort AND AlertSell,"SOUND C:\\Windows\\Media\\Ding.wav",Message,6,flag=1+2);
	}

}
if(EmailAlerts)
{

	if(AlertShort AND !AlertSell)
	{
		AlertIf(AlertShort,"EMAIL",Message,3,flag=1+2);
	}
	
	if(!AlertShort AND AlertSell)
	{
		AlertIf(AlertSell,"EMAIL",Message,2,flag=1+2);
	}
	
	if(AlertShort AND AlertSell)
	{
		AlertIf(AlertShort AND AlertSell,"EMAIL",Message,6,flag=1+2);
	}

}

if(VoiceAlerts)
{
	if(AlertShort AND !AlertSell)
	{
		Say("Short Signal");
	}
	
	if(!AlertShort AND AlertSell)
	{
		Say("Sell Signal");
	}
	
	if(AlertShort AND AlertSell)
	{
		Say("Short and Sell Signal");
	}

}

if(PopUpAlerts)
{
	if(AlertShort AND !AlertSell)
	{
		PopupWindow("Short Signal",Message);
	}
	
	if(!AlertShort AND AlertSell)
	{
		PopupWindow("Sell Signal",Message);
	}
	
	if(AlertShort AND AlertSell)
	{
		PopupWindow("Short and Sell Signal",Message);
	}

}

if(TelegramAlerts)
{
	if(Version()>=AmiVersion)
	{
	ih = InternetOpenURL("https://api.telegram.org/bot"+TelegramAPI_ID+"/sendMessage?chat_id="+TelgramCHAT_ID+"&text="+Message ); 
	InternetClose(ih);
	}
	else
	{
	//call the legacy method
	tg.Telegram(Message);
	}
}

} //end of function

function AllinOneAlerts(iBuy,iSell,iShort,iCover)
{


//Configure Trade Execution Delay


AlertBuy = lastvalue(Ref(iBuy,-tradedelay));
AlertSell = lastvalue(Ref(iSell,-tradedelay));
AlertShort = lastvalue(Ref(iShort,-tradedelay));
AlertCover = lastvalue(Ref(iCover,-tradedelay));

//Static Varibales for Alert Protection

static_name_ = Name()+GetChartID()+interval(2)+AlertName;

BuyMessage = 	"Buy Signal in "+Name()+" Buy Price :"+BuyPrice;
CoverMessage =  "Cover Signal in "+Name()+" Cover Price :"+CoverPrice;
BuyCoverMessage = 	"Buy and Cover Signal in "+Name()+" Stop and Reverse Buy @ :"+BuyPrice;

ShortMessage =  "Short Signal in "+Name()+" Short Price :"+ShortPrice;
SellMessage = 	"Sell Signal in "+Name()+" Sell Price :"+SellPrice;
ShortSellMessage = 	"Short and Sell Signal in "+Name()+" Stop and Reverse Short @ :"+ShortPrice;

if(ArrowAlerts)
{
SignalArrowPlots(iBuy,iSell,iShort,iCover);
}
if(LabelAlerts)
{
SignalTextLabels(iBuy,iSell,ishort,iCover);
}



//Enable Dual Alert Protection using Static Variables
         
	if (AlertBuy==True AND AlertCover == True AND StaticVarGet(static_name_+"buyCoverAlerts")==0)
    {
		// Stop and Reverse Long Entry 
		BuyAlerts(AlertBuy,AlertCover,BuyCoverMessage);
		StaticVarSet(static_name_+"buyCoverAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if ((AlertBuy != True OR AlertCover != True))
    {   
    StaticVarSet(static_name_+"buyCoverAlerts",0);
    }
            
    if (AlertBuy==True AND AlertCover != True AND StaticVarGet(static_name_+"buyAlerts")==0)
    {
		// Long Entry 
		BuyAlerts(AlertBuy,AlertCover,BuyMessage);
		StaticVarSet(static_name_+"buyAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertBuy != True)
    {   
		StaticVarSet(static_name_+"buyAlerts",0);
                
    }
    
    if (AlertSell==true AND AlertShort != True AND StaticVarGet(static_name_+"sellAlerts")==0)
    {     
		// Long Exit 
		SellAlerts(AlertShort,AlertSell,SellMessage);
		StaticVarSet(static_name_+"sellAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertSell != True )
    {   
		StaticVarSet(static_name_+"sellAlerts",0);
    }
            
    if (AlertShort==True AND AlertSell==True AND  StaticVarGet(static_name_+"ShortSellAlerts")==0)
    {
		// Stop and Reverse Short Entry
		SellAlerts(AlertShort,AlertSell,ShortSellMessage);
		StaticVarSet(static_name_+"ShortSellAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if ((AlertShort != True OR AlertSell != True))
    {   
        StaticVarSet(static_name_+"ShortSellAlerts",0);
    }
                
    if (AlertShort==True  AND  AlertSell != True AND StaticVarGet(static_name_+"ShortAlerts")==0)
    {
		// Short Entry
		SellAlerts(AlertShort,AlertSell,ShortMessage);
		StaticVarSet(static_name_+"ShortAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertShort != True )
    {   
        StaticVarSet(static_name_+"ShortAlerts",0);
    }
    if (AlertCover==true AND AlertBuy != True AND StaticVarGet(static_name_+"CoverAlerts")==0)
    {
		// Short Exit
		BuyAlerts(AlertBuy,AlertCover,CoverMessage);
		StaticVarSet(static_name_+"CoverAlerts",1); //Alerts Order was triggered, no more order on this bar
    }
    else if (AlertCover != True )
    {   
        StaticVarSet(static_name_+"CoverAlerts",0);
    }
       

}        
        
        
      


    
_SECTION_END();




_SECTION_BEGIN("Marketcalls Intraday - Module ");



//Remove Excessive Signals
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

//Intraday Trading Controls

LimitTrades = Param("Limit No of Trades",2,1,100,1);
TickSz = Param("Tick Size",0.05);
StartTradeTime = ParamTime("Start Time","09:30");
EndTradeTime = ParamTime("End Time","15:00");
ExitTradeTime = ParamTime("Squareoff Time","15:15");

RiskControl = ParamToggle("Enable Stop and Target","Enable|Disable",1);
mode = ParamList("Stop and Target Mode","Points|Percentage|Volatility");
stops = Param("Stoploss",50,0.05,1000,0.05);
target = Param("Targets",100,0.05,1000,0.05);

//Multipliers, iLength & iATR used for computing Volatility stops and Targets
multiplier = Param("Volatility Multiplier",1.5,0.25,20,0.25);
ilength = Param("ATR Length",10,1,100,1);
iATR = ATR(ilength);

//Signal Executes on Close of the Candle
SignalDelay = Param("Signal Delay",1,0,10,1);

newday = Day() != Ref(Day(),-1);

//Targets and Stops are Not Enabled
if(!Riskcontrol)
{



Buy = Buy AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
Sell = Sell OR TimeNum() >= ExitTradeTime;

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

Short = Short AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
Cover = Cover OR TimeNum() >= ExitTradeTime;

Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);

SetTradeDelays(0,0,0,0); //No Trade Delays provided

Buy = Ref(Buy,-SignalDelay);
sell = Ref(sell,-SignalDelay);
short = Ref(Short,-SignalDelay);
cover = Ref(cover,-SignalDelay);

BuyPrice = ValueWhen(Buy,Open);
SellPrice = ValueWhen(Sell,Open);
ShortPrice = ValueWhen(Short,Open);
CoverPrice = ValueWhen(Cover,Open);


buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(short,cover);


}

//Targets and Stops are Enabled
if(Riskcontrol)
{

SetTradeDelays(0,0,0,0); //No Trade Delays provided

Buy = Buy AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
iSell = Sell OR TimeNum() >= ExitTradeTime;

Buy = Ref(Buy,-SignalDelay);
iSell = Ref(iSell,-SignalDelay);

BuyPrice = ValueWhen(Buy,Open);

if(mode=="Points")
{
BuyStop = BuyPrice - stops;
BuyTarget = BuyPrice + target;

}


if(mode=="Percentage")
{
BuyStop1 = (100-stops)/100*BuyPrice; 
BuyTarget1 = (100+target)/100*BuyPrice;

//Round it of to nearest Tick Size
BuyStop = TickSz * round(Buystop1/TickSz);
BuyTarget = TickSz * round(BuyTarget1/TickSz);

}

if(mode=="Volatility")
{

BuyStop = ValueWhen(Buy,BuyPrice - iATR * Multiplier);
BuyTarget = ValueWhen(Buy,BuyPrice + iATR * Multiplier);

}

Sell = isell OR Cross(H,BuyTarget) OR Cross(Buystop,L);


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

//Regular Exit - Open of Next Bar
//Time Based Exit - Open of Next Bar
//Target Hit - BuyTarget
//Stop Hit - Buystop


SellPrice = ValueWhen(Sell, IIf(Cross(H,BuyTarget),BuyTarget,
								IIf(Cross(Buystop,L),Buystop,Open)));
								

short = short AND TimeNum() >= StartTradeTime AND TimeNum() <= EndTradeTime;
iCover = cover OR TimeNum() >= ExitTradeTime;

short = Ref(short,-SignalDelay);
iCover = Ref(iCover,-SignalDelay);

shortPrice = ValueWhen(short,Open);


if(mode=="Points")
{
ShortStop = ShortPrice + stops;
ShortTarget = ShortPrice - target;

}


if(mode=="Percentage")
{
ShortStop1 = (100+stops)/100*ShortPrice; 
ShortTarget1 = (100-target)/100*ShortPrice;

//Round it of to nearest Tick Size
ShortStop = TickSz * round(ShortStop1/TickSz);
ShortTarget = TickSz * round(ShortTarget1/TickSz);

}

if(mode=="Volatility")
{

ShortStop = ValueWhen(short,ShortPrice + iATR * Multiplier);
ShortTarget = ValueWhen(short,ShortPrice - iATR * Multiplier);

}

cover = icover OR Cross(H,Shortstop) OR Cross(ShortTarget,L);


Short = ExRem(Short,Cover);
Cover = ExRem(Cover,Short);



CoverPrice = ValueWhen(Cover, IIf( Cross(ShortTarget,L),ShortTarget,
								IIf(Cross(H,Shortstop),Shortstop,Open)));



Buy = Buy AND Sum(Buy OR Short, BarsSince(newday) + 1) <= LimitTrades;
Short = Short AND Sum(Buy OR Short, BarsSince(newday) + 1) <= LimitTrades;

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


buycontinue = Flip(Buy,Sell);
shortcontinue = Flip(short,cover);

}

AllinOneAlerts(Buy,Sell,Short,Cover);



//Plot Stops and Targets - only if the trade is continue

Plot(IIf(buycontinue OR Sell, BuyStop,Null),"BuyStops",colorRed,styleDashed | styleThick);
Plot(IIf(buycontinue OR Sell, Buytarget,Null),"BuyTarget",colorGreen,styleDashed | styleThick);

Plot(IIf(shortcontinue OR cover, ShortStop,Null),"ShortStops",colorRed,styleDashed | styleThick);
Plot(IIf(shortcontinue OR cover, Shorttarget,Null),"ShortTarget",colorGreen,styleDashed | styleThick);





//Dashboard Controls.


_SECTION_BEGIN("Trading Dashboard");

strg_name = ParamStr("Strategy Name","Simple Trading System");
fontsize = Param("Font Size",14,12,36,1);

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

//build dyanmic dashboard colors based on the ongoing trades
color = IIf(buycontinue,colorGreen,IIf(shortcontinue,colorRed,colorGrey40));

GfxSelectPen(colorWhite);
GfxSelectSolidBrush(SelectedValue(color));

width = Status("pxchartwidth"); //output will be in terms of number of pixels
height = Status("pxchartheight");

//GfxRoundRect(20,height-150,320,height-30,15,15);

GfxGradientRect(20,height-150,320,height-30,SelectedValue(color),colorBlack);

sigstatus = WriteIf(buycontinue,"Buy Signal",WriteIf(shortcontinue,"Short Signal","No Trade - Relax"));
PNL =  IIf(buycontinue,Close-buyprice,IIf(shortcontinue,ShortPrice-close,Null));
GfxTextOut(strg_name,30,height-130);
GfxTextOut(sigstatus+" : "+IIf(buycontinue,BuyPrice,IIf(shortcontinue,ShortPrice,Null)),30,height-110);
GfxTextOut("Profit/Loss : "+SelectedValue(Prec(PNL,2)),30,height-90);




_SECTION_END();
Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

Introduction to QuantZilla 2.0

QuantZilla is a 75+ hours of immersive coding mentor-ship program on designing trading systems, converting trading ideas into indicators and trading strategies, automating the...
Rajandran R
4 min read

[Free Course] Mini Certification on Amibroker AFL Programming

Interested in getting to know the basics of Amibroker AFL Programming then here is a free live training course to access hands-on training on...
Rajandran R
53 sec read

Smart Button Trading Module – Trade Automation – Amibroker…

This Algomojo Button trading module provides 4 modes of the button to place orders with a single click directly from Amibroker using simple smart...
Rajandran R
4 min read

Leave a Reply

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