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.

Amibroker Execution Module – Hedged Index Futures for Directional Trading in Algomojo Platform

14 min read

In the last tutorial, we learn the importance of Hedging Futures Position with OTM Options for Reduced Margin. This tutorial focus on how to automate your positional buy and sell signal ideas with Hedged Index Futures to reduce your trading margin significantly

Trading Signal in Spot/FuturesOrders to be Placed
Buy SignalLong Futures and Long OTM Put Options
Sell SignalShort Futures and Exit OTM Put Options
Short SignalShort Futures and Long OTM Call Options
Cover SignalLong Futures and Exit OTM Call Options
Buy and Cover Signal2 times of Long Futures, Long OTM Put Options and Exit OTM Call Options
Short and Cover Signal2 times of Short Futures, Long OTM Call Options, and Exit OTM Put Options

Bringing Smartness in Execution

While Placing Orders to the System it checks the Position Book and Executes Trades smartly. Always hedge is executed first to get an effective margin and if no positions are there in the open positions then the system will not take reverse trade.

In case if you are new to option execution module then kindly kickstart with the basic tutorial on Sending Option Orders from Amibroker using Algomojo Platform

Supported Brokers : Aliceblue, Tradejini, Zebu
Supported Trading Instruments : Index Futures (Nifty, Bank Nifty, Finnifty) with Long Options as a Hedge

To Build this module we need 3 components

1)Trading System with Buy/Sell/Short/Cover Signals
2)Header Option Execution Module that needs to be placed inside the Amibroker\Formulas\Include folder
3)Main Option Execution Module that needs to be drag and dropped over the Trading System

1)Building your Trading System

Apply the Trading System with your Buy/Sell/Short/Cover variables on the charts.

Here is the sample EMA Crossover Trading System with Buy,Sell,Short,Cover variables.

//Candle Plot and Axis
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", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 

//Controls
len1 = Param("Length1",20,1,100,1);
len2 = Param("Length2",50,1,100,1);

//Plot Functions
Plot(EMA(Close,len1),"EMA1",colorGreen, styleLine | styleThick);
Plot(EMA(Close,len2),"EMA2",coloryellow, styleLine | styleThick);


//Trading Rules
Buy = Cross(EMA(Close,len1), EMA(Close,len2)); //Positive EMA Crossover
Sell = Cross(EMA(Close,len2), EMA(Close,len1)); //Negative EMA Crossover

//Stop and Reverse

Short = Sell;
Cover = Buy;

/* 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(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);


Note: Buy/Sell/Short/Cover parameters are mandatory without that execution will not happen properly

If in case your trading system supports only Buy and Sell and you don’t want to use short and cover variables, in that case, use the below-mentioned logic where initialize short and cover variables to zero.

Buy = your buy trading logic ;
Sell = your sell trading logic ;

short =0;
cover =0;

2)Header Include Option Execution Module

Copy the Header Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojohedgedfutures.afl

/////////////////////////////////////////////////////////
//Multi Broker Amibroker Hedged Futures Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 10/12/2020
////////////////////////////////////////////////////////



//Use this code only for Single Legged Long Only Options and Exiting Long Only Options


_SECTION_BEGIN("Algomojo Hedged Futures- Include Module");


uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
exch = "NFO"; //Exchange
Ret = "DAY"; //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
AMO = "NO"; //AMO Order

stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","ab"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 1; //3 seconds for providing delay after placing order

RequestTimedRefresh(1,False);


function futuresorder(Tsym,orderqty,transactiontype)
{
	
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+transactiontype+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
    _TRACE("");
    _TRACE("API Request"+api_data);
    resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
    Say( "Buy Order Placed" ); 
    return resp;
}


function NetOpenPositions(Tsym)
{
flag = 0;

algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"NET"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
_TRACE("Position Book Response : " +resp);
posNetqty =0;

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


if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{

flag = 1; //turn on the flag

for( jitem = 0; ( posdetails = StrExtract( sym, jitem,',' )) != ""; jitem++ )
{

 if(Strfind(posdetails,"Tsym"))
  {
   posdetails = StrExtract(posdetails,1,':');
   possym = StrTrim(posdetails,"\"");
    _TRACE("\nSymbol : "+possym);
  }

  if(Strfind(posdetails,"Netqty"))
  {
   posdetails = StrExtract(posdetails,1,':');
   posNetqty = StrToNum(StrTrim(posdetails,"\""));
   _TRACE("\nNetQty : "+posNetqty);
  }
  if(Strfind(posdetails,"unrealisedprofitloss"))
  {
	posdetails = StrExtract(posdetails,1,':');
	posupnl = StrTrim(posdetails,"\"");
    _TRACE("\nUnRealized PNL : "+posupnl);
  }
  if(Strfind(posdetails,"realisedprofitloss"))
  {
    posdetails = StrExtract(posdetails,1,':');
	posrpnl = StrToNum(StrTrim(posdetails,"\""));
    _TRACE("\n Realized PNL : "+posrpnl);
  }
 
  if(Strfind(posdetails,"MtoM"))
  {
    posdetails = StrExtract(posdetails,1,':');
	posmtm = StrToNum(StrTrim(posdetails,"\""));
    _TRACE("\nMTM PNL : "+posmtm);
  }

} //end of for loop
}

}//end of for loop


if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
//posNetqty =0;
_TRACE("\nNetQty : "+posNetqty);
}

return posNetqty;


}//end of Net Open Positions




function getnestorderno(response)
{

NOrdNo = "";


if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}

return NOrdNo;
}

function getorderhistory(orderno)
{

algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);

return resp;


}


function getsymbol(orderno)
{

ordresp = getorderhistory(orderno);

data = "";
Trsym="";

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

sym = StrTrim(sym," "); //Trim Whitespaces




if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{

flag = 1; //turn on the flag

data = sym;

for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{

if(Strfind(ohistory,"Trsym"))
  {
   Trsym = StrExtract(ohistory,1,':');
   Trsym = StrTrim(Trsym,"\"");
   
  }

}

}

}

return Trsym;

}

function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);

data = "";

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

sym = StrTrim(sym," "); //Trim Whitespaces


if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{

flag = 1; //turn on the flag

data = sym;

for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{

if(Strfind(ohistory,"Status"))
  {
   orderstatus = StrExtract(ohistory,1,':');
   orderstatus = StrTrim(orderstatus,"\"");
   
  }

}

}

}

return orderstatus;
}//end function


function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);

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

sym = StrTrim(sym," "); //Trim Whitespaces

data = sym;

for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{

if(Strfind(ofetch,"symbol_token"))
  {
   stoken = StrExtract(ofetch,1,':');
   stoken = StrTrim(stoken,"\"");
   
  }

}

}
return stoken;
}

function writetofile(filepath,ordno,symbol,ostatus)
{
    result =0;
	if(ostatus=="complete" OR ostatus=="rejected")
	{
    fh = fopen( filepath, "w"); //Filepath of csv file with symbols
	if(fh)
    {
		
		fputs(ordno + ",", fh);
		fputs(symbol + ",", fh);
		fputs(ostatus+",", fh);
		fclose(fh);
		result =1;
    } 
    }
    
    return result; 
}



function placeoptionorder(spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off,leg)
{

algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
_TRACE("\n"+api_data);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);

tradetime=GetPerformanceCounter()/1000; 

while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{            

//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);

//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+leg+"AlgomojoPE.csv";
}

writestatus = writetofile(path,nestorderno,Tsym,orderstatus);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;

}


function getquantity(Tsym)
{

algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"NET"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);

//Initialization
flag = 0;
possym = "";
posNetqty =0;


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

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

if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{

flag = 1; //turn on the flag

data = sym;

_TRACE(" Position Book  : " +data);

for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{

  if(Strfind(posdetails,"Netqty"))
  {
   posdetails = StrExtract(posdetails,1,':');
   posNetqty = StrToNum(StrTrim(posdetails,"\""));
   _TRACE("\nNetQty : "+posNetqty);
  }
  

} //end of for loop
}

}//end of for loop

if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}

return posNetqty;

}


function squareoffoptions(opt,Ttranstype,leg)
{

ttype="";

if(Ttranstype=="B")
{

ttype = "S";

}

if(Ttranstype=="S")
{

ttype = "B";

}


ordno = "";
Symbol = "";
ostatus ="";

	if(opt=="CE")
	{
	fpath = fpath+leg+"AlgomojoCE.csv";
	}
	if(opt=="PE")
	{
	fpath = fpath+leg+"AlgomojoPE.csv";
	}
	
	fh = fopen(fpath, "r"); 
	if(fh)
	{
		
		read = fgets(fh);
		ordno = StrTrim(StrExtract(read,0)," ");
		Symbol = StrTrim(StrExtract(read,1)," ");
		ostatus = StrTrim(StrExtract(read,2)," ");
					
		fclose(fh);
	}
	
	exitqty = getquantity(Symbol);
	_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
	
	if(ostatus=="complete" AND exitqty!=0)
	{
	algomojo=CreateObject("AMAMIBRIDGE.Main");
	api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+ttype+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
	resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
	//Get Nest Order Number
	nestorderno = getnestorderno(resp);
	_TRACE("\nNest Order No : "+nestorderno);

	tradetime=GetPerformanceCounter()/1000; 

	while ((GetPerformanceCounter()/1000 - tradetime) < timer)
	{            

	//Get Trading Symbol
	Tsym = getsymbol(nestorderno);
	}
	_TRACE("\nTrading Symbol : "+Tsym);

	//Get Order Status
	orderstatus = getorderstatus(nestorderno);
	_TRACE("\nOrder Status : "+orderstatus);
	
	}
	else
	{
	
	resp = "Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State";
	
	}
	
	return resp;
}


_SECTION_END();

3)Main Option Execution Module

Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Algomojo Hedged Futures Module to Save Margin.afl

Now drag and Drop the Module on top of your Charting with Buy/Sell Trading System

//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Kalaiselvan - Algomojo Developer
//Date : 30/12/2020
//////////////////////////////////////////////

#include < algomojohedgedfutures.afl >

//Note : First Trade in Pure Long/Short Strategy is always manual.

_SECTION_BEGIN("Hedged Index Futures - Main Module");

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

//Initialization




spot_sym = ParamStr("spot_sym","NIFTY"); //Enter the symbol name here
strike_int = ParamStr("strike_int","50");
lotsize = Param("Symbol Lot Size",75,1,50000);

//Leg 2 is enabled by default
leg2symbol = ParamStr("Futures Symbol","NIFTY28JAN21FUT");
leg2qty = Param("Futures Lot Size",1)*lotsize;

//Option Buying Leg for Reduced Margin
//Leg 1 is optional for Hedging Purpose
leg1 = ParamToggle("Hedge","Disable|Enable"); //Enable the Hedge
leg1expiry_dt = ParamStr("Leg 1 expiry_dt", "21JAN21"); //Always prefer using weekly expiry so reduce your margin exposure
leg1qty = Param("Leg 1 Lot Size",1)*lotsize;
leg1Ttranstype = ParamStr("Leg 1 Transaction Type","B");
//leg1opt_type = ParamList("Leg 1 Option Type","CE|PE",0);
leg1offset = Param("Leg 1 Offset",10); //need to handle positive offset for long call option and negative offset for long put option







tradedelay = Param("Trade Delay",0);
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode



//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 )
            {
            // Buying Put Option as Hedge + Long Futures + Exiting Call Option
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +"  Signal : Buy and Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
				if(leg1)
				{
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
				_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
				}
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				_TRACE("\nNo Open Positions");
				}
				else if(NetOpenPositions(leg2symbol) == -leg2qty)
				{
				NewQty = 2*leg2qty;
				}
				else
				{
				NewQty = 2*leg2qty;
				_TRACE("\nReversal signal will be taken with 2 times of Trading Quantity");
				_TRACE("\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.");
				}
				
				
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
				_TRACEF("\nLong Futures Response :"+enterlongresponse);
				
				//Exit Call Option 
				if(leg1)
				{
				sqoff1status = squareoffoptions("CE","S",1);
				_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
				}
				
                StaticVarSetText(static_name_+"buyCoverAlgo_barvalue",lasttime);  
                StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
        
            }
            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)
            {
            // Buy Long Put Option as Hedge + Long Futures
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                
                if(leg1)
                {
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
				_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
				}
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
				_TRACEF("\nLong Futures Response :"+enterlongresponse);
				
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {     
            // Short Futures + Exit Put Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                
                if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = 0;
				_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
				}
				else if(NetOpenPositions(leg2symbol) == leg2qty)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
				_TRACEF("\nShort Futures Response :"+enterlongresponse);
				if(leg1)
				{
				sqoff1status = squareoffoptions("PE","S",1);
				_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
                }
                
                
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {
            // Long Call Options + Short Futures and Exit Long Put Options
            
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Short and Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
                if(leg1)
				{
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
				_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
				}
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				_TRACE("\nNo Open Positions");
				}
				else if(NetOpenPositions(leg2symbol) == leg2qty)
				{
				NewQty = 2*leg2qty;
				}
				else
				{
				NewQty = 2*leg2qty;
				_TRACE("\nReversal signal will be taken with 2 times of Trading Quantity");
				_TRACE("\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.");
				}
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
				_TRACEF("\nShort Futures Response :"+enterlongresponse);
				
				//Exit Put Option 
				if(leg1)
				{
				sqoff1status = squareoffoptions("PE","S",1);
				_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
				}
				
                StaticVarSetText(static_name_+"ShortsellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {
            // Buy Long Call as Hedge + Short Futures
            
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Short Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
               if(leg1)
				{
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
				_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
				}
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
				_TRACEF("\nShort Futures Response :"+enterlongresponse);
				
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {
            // Buy the Futures + Exit Call Option
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = 0;
				_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
				}
				else if(NetOpenPositions(leg2symbol) == -leg2qty)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				
                enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
				_TRACEF("\nLong Futures Response :"+enterlongresponse);
				if(leg1)
				{
				sqoff1status = squareoffoptions("CE","S",1);
				_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
                }
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {  
            //  Buy Put Option as Hedge and Long Futures
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                if(leg1)
				{
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
				_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
				}
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
				_TRACEF("\nLong Futures Response :"+enterlongresponse);
                StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {  
            // Short Futures and Exit Put Option
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                
                if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = 0;
				_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
				}
				else if(NetOpenPositions(leg2symbol) == leg2qty)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
                
                enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
				_TRACEF("\nShort Futures Response :"+enterlongresponse);
				if(leg1)
				{
				sqoff1status = squareoffoptions("PE","S",1);
				_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
                }
                
                
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            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)
            {
            // Long Call Option and Short Futures
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : ShortSignal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                
                
                if(leg1)
				{
                orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
				_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
				}
				
				
				if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
				enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
				_TRACEF("\nShort Futures Response :"+enterlongresponse);
                
                
                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)
            {
            // Long Futures and Exit Call Option
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                
                if(NetOpenPositions(leg2symbol) == 0)
				{
				NewQty = 0;
				_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
				}
				else if(NetOpenPositions(leg2symbol) == -leg2qty)
				{
				NewQty = leg2qty;
				}
				else
				{
				NewQty = leg2qty;
				_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
				_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
				}
				
                enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
				_TRACEF("\nLong Futures Response :"+enterlongresponse);
				if(leg1)
				{
				sqoff1status = squareoffoptions("CE","S",1);
				_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
                }
                
                StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
                
            }
            else if (AlgoCover != True)
            {   
                StaticVarSet(static_name_+"CoverAlgo",0);
            }
        }
        
    }//end main if

    
_SECTION_END();




4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity

5)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.

Ensure while entering the Option Expiry Format. Login to Algomojo Terminal and check out the weekly and monthly option format and enter the expiry date accordingly.

For Aliceblue account holders Monthly Option Symbol Format: NIFTY21JAN14500CE

Hence the Expiry Date needs to be entered as 21JAN

For Aliceblue Account holders weekly Option Symbol Format: NIFTY2111414500CE

Hence the Expiry Date needs to be entered as 21114

For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY28JAN2114500CE

Hence the Expiry Date needs to be entered as 28JAN21

For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY14JAN2114500CE

Hence the Expiry Date needs to be entered as 14JAN21

1AlgomojoCE.csv and 1AlgomojoPE.csv will be saved whenever the hedged option traders are executed and files will be saved only if the execution status is in complete or in rejected mode.

6)Enable the Hedge Option, Enter the Futures Symbol, Enter the Option Hedging Expiry, Lot Size, Transaction Type and Offset (To Select OTM/ATM. Keep the value as zero for ATM Option selection)

7)Ensure Log Window is open to capture the Trace Logs

8)Bingo Now you can Send Hedged Orders from Amibroker by connecting any of your Buy/Sell Trading System. To Send ATM/ITM/OTM Option Orders, adjust the offset parameters from the Properties section.

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.

Multi Broker – Multi Client Algomojo Trading – Amibroker…

Here are simple Amibroker AFL - Button-based Trading modules which help traders to route their orders to different brokers simultaneously. Here is the prototype...
Rajandran R
4 min read

Single Broker Multi-Client Amibroker Trading Module

Got frequent requirements from many traders to automate Amibroker based trading system where one single generation from charts could punch orders in multiple accounts...
Rajandran R
5 min read

How to Calculate the Order Execution Response time using…

To send automated orders using Amibroker usually one uses the API-based trading solutions. API works on the concept of request and response. Every Place...
Rajandran R
2 min read

Leave a Reply

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