Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and 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. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Stop and Reverse Cover Orders/Bracket Orders – Automated Chart based Intraday Trading Module for Amibroker

15 min read

Bracket Order and Cover Order are multi-legged orders which come with default protection with stop loss with reasonable intraday leverage. This tutorial focus on building a Plug and Play Amibroker Intraday module where traders can create their own trading strategy in Amibroker and connect their intraday trading strategies with Plug and Play Amibroker Execution Module to bring 100% automation in their intraday traders using Cover and Bracket Orders in Algomojo trading platform

Supported Brokers : Aliceblue, Tradejini, Zebu

Strategy Requirements

  • Enter Buy BO/CO order on Buy Signal
  • Enter Sell BO/CO Order on Short Signal
  • Stop and Reverse from Buy to Short on both Short Signal and Sell Signal
  • Stop and Reverse from Short to Buy on Both Buy Signal and Cover signal
  • Exit BO/CO Order on Sell Signal
  • Exit BO/CO Order on Cover Signal

Sample Donchian Intraday Trading Strategy – Amibroker AFL Code

//Recommended to use the code to trade in less than 15min timeframe intraday
//Goto Tools Menu -> Preferences -> Intraday -> selection Start time of Interval option


_SECTION_BEGIN("Simple Swing Trading System");

SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
//plot the candles
Plot(Close,"Close",colorDefault,styleCandle | styleNoTitle);
//_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Title = "";
N = 1;

// identify new day
dn = DateNum();
newDay = dn != Ref( dn,-1);


len = Param("Length",15,1,50,1);


signalstarttime = ParamTime( "Start Time", "09:30" );
signalendtime = ParamTime( "EndTime", "15:00" );
sqofftime = ParamTime( "Sq Off", "15:15" );


upper = HHV(High,len);
lower = LLV(Low,len);


//refer to previous channel and ignoring the current channel value
upper = Ref(upper,-1);
lower = Ref(lower,-1);


//Plot(upper,"upper",colorRed);
//Plot(lower,"lower",colorGreen);


//Touch based trading system - Trading Logic

Buy = Cross(High,upper) AND TimeNum()>=signalstarttime AND TimeNum()<=signalendtime;
Sell = Cross(lower,Low) OR TimeNum()>=sqofftime;

Buy = Buy AND Sum( Buy, BarsSince( newDay) +1 ) <= N;

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

//check whether signals are continuing or not

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


Short = Cross(lower,Low) AND TimeNum()>=signalstarttime AND TimeNum()<=signalendtime;
Cover =  Cross(High,upper) OR TimeNum()>=sqofftime;

Short = Short AND Sum( Short, BarsSince( newDay) +1 ) <= N;

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

shortcontinue = Flip(Short,Cover);


color = IIf(Buycontinue,colorGreen,IIf(Shortcontinue,colorRed,colorGrey40));

tsl = IIf(Buycontinue,lower,IIf(sellcontinue,upper,null)); //trailing stoploss


Plot(tsl,"Trailing Stoploss",color,styleDashed | styleThick);


//execution logic

SetTradeDelays(0,0,0,0); //No Trade Delay - Execute as it happens

BuyPrice = ValueWhen(Buy,Max(Open,upper));



SellPrice = iif(Cross(lower,Low),ValueWhen(Sell,lower),Close);

ShortPrice = ValueWhen(Short,Min(Open,lower));
CoverPrice = IIf(Cross(High,upper),ValueWhen(Cover,upper),Close);


//position sizing - How much to Bet


SetPositionSize(1*RoundLotSize,spsShares);


/* 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(IIf(sell, shapestar, shapeNone),colorgreen, 0,L, Offset=-45);
PlotShapes(IIf(cover, shapestar, shapeNone),colorRed, 0,H, Offset=-45);


Filter = Buy OR Sell OR Short OR Cover;

AddColumn(Close,"LTP",1.2);
AddColumn(TSL,"Trailing Stop",1.2);
AddColumn(IIf(Buy,'B',IIf(Short,'S',null)),"Entry Signal",formatChar,colorWhite,IIf(Buy,colorGreen,IIf(Short,colorRed,colorGrey40)));
AddColumn(IIf(Sell,'S',IIf(Cover,'C',null)),"Exit Signal",formatChar,colorWhite,IIf(Sell,colorRed,IIf(Cover,colorGreen,colorGrey40)));
AddColumn(IIf(TimeNum()==sqofftime,1,0),"Sqoff Time",1,colorWhite,IIf(TimeNum()==sqofftime,colorOrange,colorBlack));

_SECTION_END();


_SECTION_BEGIN("Dashboard");

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


if(dashboard)
{
//show the dashboard

GfxSelectFont( "BOOK ANTIQUA", 12, 100 );
GfxSetBkMode( 1 ); 
GfxSetTextColor( colorWhite ); 



GfxSelectPen(colorWhite);

GfxSelectSolidBrush(SelectedValue(color));

//Co-ordinates are hard coded

XX = Status( "pxchartwidth"); //total pixel width
YY = Status( "pxchartheight" ) ; //total pixel height

//printf("X Co-Ordinate : "+XX+" ,Y Co-Ordinate : "+YY);


GfxRectangle(20,YY-150,320,YY	);

GfxTextOut("Donchian Dashboard",30,YY-130);

y2 = YY-100;
GfxTextOut(("" + WriteIf(Buy AND NOT cover, "Fresh Buy @ "+ BuyPrice, "")), 30, y2); 
GfxTextOut( ("" + WriteIf(Short AND NOT sell, "Fresh Short @ "+ ShortPrice,"")), 30, y2); 

GfxTextOut(("" + WriteIf(Buy AND Cover, "Stop & Reverse Buy @ "+ BuyPrice, "")), 30, y2); 
GfxTextOut( ("" + WriteIf(Short AND sell, "Stop & Reverse Short @ "+ ShortPrice,"")), 30, y2); 


GfxTextOut(("" + WriteIf(Sell AND NOT Short, "Exit Buy @ "+ sellPrice, "")), 30, y2); 
GfxTextOut( ("" + WriteIf(Cover AND NOT Buy, "Exit Short @ "+ coverPrice,"")), 30, y2); 
GfxTextOut( ("" + WriteIf (Buycontinue AND NOT Buy, "Buy @ "+(BuyPrice),"")), 30, y2); 

GfxTextOut( ("" + WriteIf (Shortcontinue AND NOT Short, "Short @ "+(ShortPrice),"")), 30, y2); 
GfxTextOut( ("" + WriteIf (NOT Buycontinue AND NOT Shortcontinue AND NOT Sell AND NOT cover, "No Trade Zone","")), 30, y2); 


GfxTextOut( ("" + WriteIf (Buycontinue AND NOT Buy, "Profit/Loss : "+NumToStr((C-BuyPrice),1.2)+ "points","")), 30, y2+30); 
GfxTextOut( ("" + WriteIf (Shortcontinue AND NOT Short, "Profit/Loss "+NumToStr((ShortPrice - C),1.2)+ " points","")), 30, y2+30); 
}


_SECTION_END();


_SECTION_BEGIN("Top Dashboard Diplay");



_SECTION_BEGIN("Dashboard");

X0 = 10;
Y0 = 20;

procedure DrawData (Text, x1, y1, x2, y2, colorFrom, colorTo)
{
	GfxSetOverlayMode(0);
	GfxSelectFont("Verdana", 8.5, 700);
	GfxSetBkMode(1);
	GfxGradientRect(x1, y1, x2, y2, colorFrom, colorTo);
	GfxDrawText(Text, x1, y1, x2, y2, 32|1|4|16);
}

//reusing the procedure multiple times

DrawData (Name(), X0, Y0, X0+150, Y0+20, colorGrey40, colorblack);

DrawData ("Open : " + Open, X0+155, Y0, X0+320, Y0+20, colorGrey40, colorblack);
DrawData ("Close : " + Close, X0+325, Y0, X0+450, Y0+20, colorGrey40, colorblack);
DrawData ("High : " + High, X0+455, Y0, X0+580, Y0+20, colorGrey40, colorblack);
DrawData ("Low : " + Low, X0+585, Y0, X0+710, Y0+20, colorGrey40, colorblack);



_SECTION_END();

Intraday Preferences Settings

Goto Amibroker ->Tools Menu -> Preferences and make sure to enable start time of interval option as shown below. It is highly recommended to use for the above coding pattern.

Amibroker Execution Module for BO/CO Orders

Amibroker Execution Module contains two parts

1)Main Chart Based Module
2)Header Module

Main Module (algomojo_chart_based_trading_bo_co_stop_reverse.afl)

//////////////////////////////////////////////
//Multi Broker Amibroker Charting BO/CO Order Module
//Coded by Rajandran R - Co-Founder Algomojo
//Date : 20/03/2021
//////////////////////////////////////////////

//Note : Bracket Order and Cover Order Stop and Reverse Module is designed purely for Intraday Strategies only


#include <BracketCoverOrders.afl>

_SECTION_BEGIN("Algomojo Charting BO/CO Order Module");

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


//Configure Trade Execution Delay


AlgoBuy = lastvalue(Ref(Buy,-tradedelay));
AlgoSell = lastvalue(Ref(Sell,-tradedelay));
AlgoShort = lastvalue(Ref(Short,-tradedelay));
AlgoCover = lastvalue(Ref(Cover,-tradedelay));


//Static Varibales for Order Protection

static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1); 


//Algo Dashboard

GfxSelectFont( "BOOK ANTIQUA", 14, 100 );
GfxSetBkMode( 1 );
if(EnableAlgo == "Enable")
{
AlgoStatus = "Algo Enabled";
GfxSetTextColor( colorGreen ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=1)
{
_TRACE("Algo Status : Enabled");
StaticVarSet(static_name_algo, 1);
}
}
if(EnableAlgo == "Disable")
{
AlgoStatus = "Algo Disabled";
GfxSetTextColor( colorRed ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=0)
{
_TRACE("Algo Status : Disabled");
StaticVarSet(static_name_algo, 0);
}
}
if(EnableAlgo == "LongOnly")
{
AlgoStatus = "Long Only";
GfxSetTextColor( colorYellow ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=2)
{
_TRACE("Algo Status : Long Only");
StaticVarSet(static_name_algo, 2);
}
}
if(EnableAlgo == "ShortOnly")
{
AlgoStatus = "Short Only";
GfxSetTextColor( colorYellow ); 
GfxTextOut( "Algostatus : "+AlgoStatus , 20, 40); 
if(Nz(StaticVarGet(static_name_algo),0)!=3)
{
_TRACE("Algo Status : Short Only");
StaticVarSet(static_name_algo, 3);
}
}


//Execution Module

if(EnableAlgo != "Disable")
    {
        lasttime = StrFormat("%0.f",LastValue(BarIndex()));
        
        SetChartBkColor(colorDarkGrey);
        if(EnableAlgo == "Enable")
        {   
            if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
            {
            // reverse Long Entry 
                
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); 
				BuyOrder(qty,Pcode);
                StaticVarSetText(static_name_+"buyCoverAlgo_barvalue",lasttime);  
                StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Signal : Buy and Cover Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
        
            }
            else if ((AlgoBuy != True OR AlgoCover != True))
            {   
                StaticVarSet(static_name_+"buyCoverAlgo",0);
            }
            
            if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {
            // Long Entry 
                BuyOrder(qty,Pcode);
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoBuy != True)
            {   
                StaticVarSet(static_name_+"buyAlgo",0);
                
            }
            if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            {     
            // Long Exit 
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); //output in string format
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoSell != True )
            {   
                StaticVarSet(static_name_+"sellAlgo",0);
            }
            if (AlgoShort==True AND AlgoSell==True AND  StaticVarGet(static_name_+"ShortSellAlgo")==0 AND StaticVarGetText(static_name_+"ShortSellAlgo_barvalue") != lasttime)
            {
            // reverse Short Entry 
                
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); //output in string format
				SellOrder(qty,Pcode);
                StaticVarSetText(static_name_+"ShortsellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty*2 +"  Signal : Short and Sell Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if ((AlgoShort != True OR AlgoSell != True))
            {   
                StaticVarSet(static_name_+"ShortSellAlgo",0);
            }
                
            if (AlgoShort==True  AND  AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND  StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
            // Short Entry
                SellOrder(qty,Pcode);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Short Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoShort != True )
            {   
                StaticVarSet(static_name_+"ShortAlgo",0);
            }
            if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
            // Short Exit
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); //output in string format
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoCover != True )
            {   
                StaticVarSet(static_name_+"CoverAlgo",0);
            }
        }
        
        
        
        else if(EnableAlgo == "LongOnly")
        {
            
            if (AlgoBuy==True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {  
            //  Long Entry
                BuyOrder(qty,Pcode);
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoBuy != True)
            {   
                StaticVarSet(static_name_+"buyAlgo",0);
            }
            if (AlgoSell==true AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            {  
            // Long Exit
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); //output in string format
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoSell != True )
            {   
                StaticVarSet(static_name_+"sellAlgo",0);
            }
        }
        else if(EnableAlgo == "ShortOnly")
        {
            if (AlgoShort==True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
            // Short Entry
                SellOrder(qty,Pcode);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Short Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoShort != True )
            {   
                StaticVarSet(static_name_+"ShortAlgo",0);
            }
            if (AlgoCover==true AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
            // Short Exit
                resp = GetOrderBook();
				CancelOrder(resp,Tsym,Pcode); //output in string format
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                //_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ qty +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  Response : "+ resp +"  ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
            }
            else if (AlgoCover != True)
            {   
                StaticVarSet(static_name_+"CoverAlgo",0);
            }
        }
        
    }//end main if

    
_SECTION_END();

Header Module (BracketCoverOrders.afl)

save the header module under the folder /Amibroker/Formulas/Include folder

//store the file under the name - ExitBOCOOrders.afl under the Amibroker\Formulas\Include folder

uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","xxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secret = ParamStr("api_secret","xxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
s_prdt_ali = "BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML"; //Product Alias
Tsym = ParamStr("Trading Symbol","RELIANCE-EQ"); //Symbol Name
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX",1); //Exchange
Ret = "DAY"; //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0); // Pricetype
Pcode = ParamList("Pcode","BO|CO",1);
qty = Param("Quantity",1,0,100000,1); // Quantity
AMO = "NO"; //AMO Order
tradedelay = Param("Execution Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode
resp = "";
broker ="tj"; //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version ","1.0");

TokenNo = ParamStr("TokenNo","11184"); //Enter the token number of the symbol here. Check the Algomojo Watchlist symbol info to get the relevant symbol token no.
ltpOratp = "LTP"; //ParamList("ltpOratp","LTP|ATP",0);


 
SqrOffAbsOrticks = "Absolute";  //ParamList("SqrOffAbsOrticks","Absolute|Ticks",0); //If you select absolute then you can enter a decimal quantity. If you selected ticks you need to enter in multiples of ticks
SLAbsOrticks = "Absolute";   //ParamList("SLAbsOrticks","Absolute|Ticks",0);

trailingSL = "N"; //ParamList("trailingSL","Y|N",0); 
tSLticks = 1000; //ParamStr("tSLticks","100"); //Trailing SL value in ticks if user has opted to use trailingSL

stops = Param("Stoploss %", 0.25,0,20,0.01);
target = Param("Target %", 0.5,0,20,0.01);
TickSz = Param("TickSize",0.05); //round off the stops and target to nearest tick size




RequestTimedRefresh(1,False);


buystops1 = (100-stops)/100 * Buyprice;
buytarget1 = (100+target)/100 * Buyprice;


buystops = TickSz * round( buystops1 / TickSz );
buytarget = TickSz * round( buytarget1 / TickSz );

shortstops1 = (100-stops)/100 * Shortprice;
shorttarget1 = (100+target)/100 * Shortprice;


shortstops = TickSz * round( shortstops1 / TickSz );
shorttarget = TickSz * round( shorttarget1 / TickSz );

BuyP = TickSz * round( BuyPrice / TickSz );
ShortP = TickSz * round( ShortPrice / TickSz );


//Buy and Sell Order Functions

function Buyorder(orderqty,Pcode)
{
	if(Pcode=="CO")
	{
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+BuyStops+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
    
    _TRACE("BuyOrder API Request"+api_data);
    resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
    _TRACE("BuyOrder API Response : "+resp);
    _TRACE("Strategy Name : "+stgy_name+";  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ orderqty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	}
	if(Pcode=="BO")
	{
	
	SqrOffvalue = abs(buytarget-BuyP); //ParamStr("SqrOffvalue","1"); 
	SLvalue = abs(BuyP-buystops) ; //ParamStr("SLvalue","30");
	SqrOffvalue = TickSz * round( SqrOffvalue / TickSz );
	SLvalue = TickSz * round( SLvalue / TickSz );
	algomojo=CreateObject("AMAMIBRIDGE.Main");
	api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"Price\":\""+"0"+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
	_TRACE("BuyOrder API Request"+api_data);
	resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
	_TRACE("BuyOrder API Response : "+resp);
    _TRACE("Strategy Name : "+stgy_name+";  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ orderqty +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	
	
	}
	
	
	
	//Say( "Buy Order Placed" ); 
}



function sellorder(orderqty,Pcode)
{	

	if(Pcode=="CO")
	{
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+Shortstops+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
    
    _TRACE("SellOrder API Request"+api_data);
    resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
    _TRACE("SellOrder API Response : "+resp);
    _TRACE("Strategy Name : "+stgy_name+"  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ orderqty +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	}
	if(Pcode=="BO")
	{
	SqrOffvalue = abs(ShortP-shorttarget); //ParamStr("SqrOffvalue","1"); 
	SLvalue = abs(shortstops - ShortP) ; //ParamStr("SLvalue","30");
	SqrOffvalue = TickSz * round( SqrOffvalue / TickSz );
	SLvalue = TickSz * round( SLvalue / TickSz );
	algomojo=CreateObject("AMAMIBRIDGE.Main");
	api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"Price\":\""+"0"+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
	_TRACE("SellOrder API Request"+api_data);
	resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
	_TRACE("SellOrder API Response : "+resp);
    _TRACE("Strategy Name : "+stgy_name+"  AlgoStatus : "+ EnableAlgo);
    _TRACE("Chart Symbol : "+ Name() +"  Trading Symbol : "+  Tsym +"  Quantity : "+ orderqty +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID() + " LTP : "+LastValue(C));
	
	}
}


function GetOrderBook()
{

algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderBook",api_data,broker,ver);
_TRACE("Order Book  : " +resp);
return resp;
}

function ExitOrder(Symbol,OrderType,Nstordno)
{

if(OrderType=="BO")
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"nestordernumber\":\""+Nstordno+"\",\"SyomOrderId\":\""+""+"\",\"status\":\""+"pending"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"ExitBOOrder",api_data,broker,ver);

}

if(OrderType=="CO")
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"NestOrd\":\""+Nstordno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"ExitCOOrder",api_data,broker,ver);

}


return resp;
}

function CancelOrder(resp,Tsym,Pcode)
{

//Initialization
flag = 0;

stringinfo = "Nstordno";

for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{

sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");

if(Pcode == "BO");
{
ordermatch = StrFind(sym,Tsym) AND StrFind(sym,Pcode) AND StrFind(sym,"complete");
}

if(Pcode == "CO");
{
ordermatch = StrFind(sym,Tsym) AND StrFind(sym,Pcode) AND (StrFind(sym,"complete") OR StrFind(sym,"open"));
}


if(ordermatch) //Matches the symbol and //Matches the Order Type
{

flag = 1; //turn on the flag

data = sym;



for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
  
  if(StrFind(posdetails,"\""+stringinfo+"\""))
  {
   posdetails = StrExtract(posdetails,1,':');
   Nstordno = StrTrim(posdetails,"\"");
   ExitOrder(Tsym,Pcode,Nstordno);
  }
  

} //end of for loop
} //end of if loop


}//end of for loop


_TRACE(Tsym+" "+Pcode+" Order Cancelled");

}

Now Drag and Drop the Main execution module on top of the intraday trading system and set the following parameters as shown below

1)Set the API Key and API Secret Key
2)Select the PCode to send BO or CO Orders
3)Set the token no if it is a bracket order (Can get these details from Algomojo Market Watch -> Symbol Information)
4)Set the Stoploss in percentage terms in case of cover order and set the stops and target in case of Bracket order.
5)Set the Broker, Trading Symbol, Exchange
6)Enable to AlgoTrading to start running the intraday trading system

While Coding for BO and CO Module following things needs to be noted

1)Stops and Targets are derived from the BuyPrice and ShortPrice i.e from entry price. Code the BuyPrice and Shortprice properly. Improper calculation could result in poor calculation of Stops and Target levels.

2)Make sure to follow the set of protocols to follow in case if you are building a bracket order strategy

3)Strategy is rounded off to nearest tick size by default tick size is set to 0.05. It could vary depends upon Exchanges and Trading Instruments especially for commodities and currencies.

Bingo! Now you are all set to do a complete automation on Bracket Order and Cover Order strategies.

Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and 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. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[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

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

Leave a Reply

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