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/Futures | Orders to be Placed |
Buy Signal | Long Futures and Long OTM Put Options |
Sell Signal | Short Futures and Exit OTM Put Options |
Short Signal | Short Futures and Long OTM Call Options |
Cover Signal | Long Futures and Exit OTM Call Options |
Buy and Cover Signal | 2 times of Long Futures, Long OTM Put Options and Exit OTM Call Options |
Short and Cover Signal | 2 times of Short Futures, Long OTM Call Options, and Exit OTM Put Options |
Supported Brokers
Alice blue, Tradejini, Zebu
Supported Amibroker Version: 5.8 or above
Amibroker AFL Code uses persistent static variables to store the options data in temporary memory to exit the positions later point in time and it requires Amibroker 5.8 or above and the static variable will be stored in PersistVars.bin file when AmiBroker folder while it is closing and reloaded automatically on next startup, preserving the values of static variables between application runs).
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 Option Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 30/12/2020
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Options Module");
RequestTimedRefresh(1,False);
EnableTextOutput(False);
SetOption("StaticVarAutoSave",30);
clientid = ParamStr("Client ID","TS2499");
apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
apisecret = ParamStr("api_secret","f2800307bdff70f8f856f6728ea7a58b"); //Enter your API secret key here
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT",0);
Pcode = ParamList("Pcode","NRML|MIS",1);
Price = 0;
TrigPrice = 0;
strg_name = ParamStr("Strategy Name","Options Strategy");
spot_sym = Paramlist("spot_sym","NIFTY|BANKNIFTY",0); //Broker Symbol Format
expiry_dt = Paramstr("expiry_dt","26AUG21");
transtype = Paramlist("Options Transaction Type","B|S",0);
strike_int = 50;
if(spot_sym == "NIFTY")
{
strike_int = 50;
lotsize = 50;
}
if(spot_sym == "BANKNIFTY")
{
strike_int = 100;
lotsize = 25;
}
Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);
qty = Param("Quantity(Lots)",1,1,100,1)*lotsize;
//Leg 2 is enabled by default
leg2symbol = ParamStr("Futures Symbol","NIFTY26AUG21FUT");
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", "26AUG21"); //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",0); //need to handle positive offset for long call option and negative offset for long put option
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
s_prdt_ali = "BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML"; //Product Alias
exch = "NFO"; //required for order cancellation purpose
Exchangeseg = "nse_fo"; //require for squareoff the order purpose.
Ret = "DAY"; //Retention
AMO = "NO"; //AMO Order
clear = ParamTrigger("Clear Static Var","Clear");
static_var_options = "staticvar_options"+Name() + Interval(2) + GetChartID() + strg_name;
if(clear)
{
StaticVarRemove("staticvar_options*");
_TRACE("Static Variables Cleared");
}
//Internal Memory
opt_type = "CE";
printf("\n-------Hedged CE Orders Internal Memory----------");
printf("\nOrder Type :"+StaticVarGetText(static_var_options+"Option_Trans"+opt_type));
printf("\n OrderNo : "+StaticVarGetText(static_var_options+"Option_OrderNo"+opt_type)); //Get the OrderNo
printf("\n Symbol : "+StaticVarGetText(static_var_options+"Option_Symbol"+opt_type));
printf("\n Status : "+StaticVarGetText(static_var_options+"Option_Orderstatus"+opt_type));
printf("\n Quantity : "+StaticVarGet(static_var_options+"Option_Netqty"+opt_type));
opt_type = "PE";
printf("\n\n\n\n-------Hedged PE Orders Internal Memory----------");
printf("\nOrder Type :"+StaticVarGetText(static_var_options+"Option_Trans"+opt_type));
printf("\n OrderNo : "+StaticVarGetText(static_var_options+"Option_OrderNo"+opt_type)); //Get the OrderNo
printf("\n Symbol : "+StaticVarGetText(static_var_options+"Option_Symbol"+opt_type));
printf("\n Status : "+StaticVarGetText(static_var_options+"Option_Orderstatus"+opt_type));
printf("\n Quantity : "+StaticVarGet(static_var_options+"Option_Netqty"+opt_type));
function futuresorder(Tsym,orderqty,transactiontype)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"strg_name\":\""+strg_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(apikey, apisecret,"PlaceOrder",api_data,broker,ver);
_TRACEF("\nFutures Order Response :"+resp);
return resp;
}
function GetOrderBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("OrderBook API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"OrderBook",api_data,broker,ver);
_TRACE("OrderBook API Response : "+resp);
return resp;
}
function GetTradeBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("OrderBook API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"TradeBook",api_data,broker,ver);
_TRACE("OrderBook API Response : "+resp);
return resp;
}
function GetPositionsBook()
{
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{ \"uid\": \""+ClientID+"\", \"actid\": \""+ClientID+"\", \"type\": \"NET\", \"s_prdt_ali\": \"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\" }";
_TRACE("PositionBook API Request"+api_data);
//Sending The Broker Request for NetOpenPositions
resp=algomojo.AMDispatcher(apikey, apisecret,"PositionBook",api_data,broker,ver);
_TRACE("PositionBook API Response : "+resp);
return resp;
}
function ParsePositionBook(resp,Tsym,Pcode,stringinfo)
{
//Initialization
flag = 0;
possym = "";
Netqty ="";
posdetails = "";
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
{
data = sym;
_TRACE("data : "+data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(StrFind(posdetails,"\""+stringinfo+"\""))
{
flag = 1; //turn on the flag
posdetails = StrExtract(posdetails,1,':');
posdetails = StrTrim(posdetails,"\"");
NetQty = posdetails;
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
NetQty = "0";
}
//_TRACE("\nNetQty : "+NetQty);
return NetQty;
}
function NetOpenPositions()
{
resp = GetPositionsBook();
Netqty = ParsePositionBook(resp,Tsym,Pcode,"Netqty"); //output in string format
Netqty = StrToNum(Netqty);
_TRACE("Order No : "+Netqty);
return Netqty;
}
function NetOpenPos(Symbol)
{
resp = GetPositionsBook();
Netqty = ParsePositionBook(resp,Symbol,Pcode,"Netqty"); //output in string format
Netqty = StrToNum(Netqty);
_TRACE("Net Qty : "+Netqty);
return Netqty;
}
function Getorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
_TRACE("Order No : "+NOrdNo);
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+clientid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("Broker Order History Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"OrderHistory",api_data,broker,ver);
_TRACE("Broker Order History Response"+resp);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
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,"\"");
}
}
}
}
_TRACE("Traded Symbol: "+Trsym);
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"open") OR StrFind(sym,"trigger pending") OR StrFind(sym,"rejected") OR StrFind(sym,"cancelled")) //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,"\"");
}
}
}
}
_TRACE("Order Status : "+orderstatus);
return orderstatus;
}
function getaverageprice(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
averageprice="";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
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,"averageprice"))
{
averageprice = StrExtract(ohistory,1,':');
averageprice = StrTrim(averageprice,"\"");
}
}
}
}
if(averageprice=="0.0") //use it only for testing pupose
{
averageprice = "100";
}
_TRACE("Average Price : "+averageprice);
return averageprice;
}
function PlaceOptionOrder(spot_sym,expiry_dt,strike_int,quantity,Ttranstype,opt_type,offset,legno)
{
if(opt_type=="PE")
{
offset = -offset;
}
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data
api_data ="{\"strg_name\":\""+strg_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt_type+"\",\"Ttranstype\":\""+""+Ttranstype+""+"\",\"prctyp\":\""+"MKT"+"\",\"qty\":\""+quantity+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+offset+"\"}";
_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceFOOptionsOrder",api_data,broker,ver);
//Store the OrderNo, Trading Symbol, OrderStatus, NetQty
Trans = Ttranstype;
StaticVarSetText(static_var_options+"Option_Trans"+opt_type,Trans,True); //Get the Transaction Type
OrderNo = Getorderno(resp);
StaticVarSetText(static_var_options+"Option_OrderNo"+opt_type,OrderNo,True); //Get the OrderNo
Symbol = getsymbol(OrderNo);
StaticVarSetText(static_var_options+"Option_Symbol"+opt_type,Symbol,True);
Orderstatus = getorderstatus(OrderNo);
StaticVarSetText(static_var_options+"Option_Orderstatus"+opt_type,Orderstatus,True);
Netqty = NetOpenPos(Symbol);
StaticVarSet(static_var_options+"Option_Netqty"+opt_type,Netqty,True);
_TRACE("API Response : "+resp);
return resp;
}
function SquareOffPosition(opt_type,legno)
{
resp =null;
Symbol = StaticVarGetText(static_var_options+"Option_Symbol"+opt_type);
Netqty = StaticVarGet(static_var_options+"Option_Netqty"+opt_type);
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data
api_data ="{\"uid\":\""+clientid+"\",\"actid\":\""+clientid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Exchangeseg\":\""+Exchangeseg+"\",\"Pcode\":\""+""+Pcode+""+"\",\"Netqty\":\""+Netqty+"\",\"Token\":\""+""+"\",\"Symbol\":\""+Symbol+"\",\"orderSource\":\""+"NEST_REST"+"\"}";
_TRACE("Squareoff API Request"+api_data);
if(Netqty==0)
{
resp=algomojo.AMDispatcher(apikey, apisecret,"SquareOffPosition",api_data,broker,ver);
}
if(resp!=Null)
{
_TRACE("Squareoff API Response : "+resp);
}
else
{
_TRACE("Squareoff Order Not Triggered");
}
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 Rajandran - Algomojo Co-Founder
//Date : 30/12/2020
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Options Module");
RequestTimedRefresh(1,False);
EnableTextOutput(False);
SetOption("StaticVarAutoSave",30);
clientid = ParamStr("Client ID","TS2499");
apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
apisecret = ParamStr("api_secret","f2800307bdff70f8f856f6728ea7a58b"); //Enter your API secret key here
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT",0);
Pcode = ParamList("Pcode","NRML|MIS",1);
Price = 0;
TrigPrice = 0;
strg_name = ParamStr("Strategy Name","Options Strategy");
spot_sym = Paramlist("spot_sym","NIFTY|BANKNIFTY",0); //Broker Symbol Format
expiry_dt = Paramstr("expiry_dt","26AUG21");
transtype = Paramlist("Options Transaction Type","B|S",0);
strike_int = 50;
if(spot_sym == "NIFTY")
{
strike_int = 50;
lotsize = 50;
}
if(spot_sym == "BANKNIFTY")
{
strike_int = 100;
lotsize = 25;
}
Entrydelay = Param("Entry Delay",0,0,1); // 0 - Execution with No Delay after a signal, 1- Execution at the end of the candle
Exitdelay = Param("Exit Delay",0,0,1);
qty = Param("Quantity(Lots)",1,1,100,1)*lotsize;
//Leg 2 is enabled by default
leg2symbol = ParamStr("Futures Symbol","NIFTY26AUG21FUT");
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", "26AUG21"); //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",0); //need to handle positive offset for long call option and negative offset for long put option
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
s_prdt_ali = "BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML"; //Product Alias
exch = "NFO"; //required for order cancellation purpose
Exchangeseg = "nse_fo"; //require for squareoff the order purpose.
Ret = "DAY"; //Retention
AMO = "NO"; //AMO Order
clear = ParamTrigger("Clear Static Var","Clear");
static_var_options = "staticvar_options"+Name() + Interval(2) + GetChartID() + strg_name;
if(clear)
{
StaticVarRemove("staticvar_options*");
_TRACE("Static Variables Cleared");
}
//Internal Memory
opt_type = "CE";
printf("\n-------Hedged CE Orders Internal Memory----------");
printf("\nOrder Type :"+StaticVarGetText(static_var_options+"Option_Trans"+opt_type));
printf("\n OrderNo : "+StaticVarGetText(static_var_options+"Option_OrderNo"+opt_type)); //Get the OrderNo
printf("\n Symbol : "+StaticVarGetText(static_var_options+"Option_Symbol"+opt_type));
printf("\n Status : "+StaticVarGetText(static_var_options+"Option_Orderstatus"+opt_type));
printf("\n Quantity : "+StaticVarGet(static_var_options+"Option_Netqty"+opt_type));
opt_type = "PE";
printf("\n\n\n\n-------Hedged PE Orders Internal Memory----------");
printf("\nOrder Type :"+StaticVarGetText(static_var_options+"Option_Trans"+opt_type));
printf("\n OrderNo : "+StaticVarGetText(static_var_options+"Option_OrderNo"+opt_type)); //Get the OrderNo
printf("\n Symbol : "+StaticVarGetText(static_var_options+"Option_Symbol"+opt_type));
printf("\n Status : "+StaticVarGetText(static_var_options+"Option_Orderstatus"+opt_type));
printf("\n Quantity : "+StaticVarGet(static_var_options+"Option_Netqty"+opt_type));
function futuresorder(Tsym,orderqty,transactiontype)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"strg_name\":\""+strg_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(apikey, apisecret,"PlaceOrder",api_data,broker,ver);
_TRACEF("\nFutures Order Response :"+resp);
return resp;
}
function GetOrderBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("OrderBook API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"OrderBook",api_data,broker,ver);
_TRACE("OrderBook API Response : "+resp);
return resp;
}
function GetTradeBook()
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("OrderBook API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"TradeBook",api_data,broker,ver);
_TRACE("OrderBook API Response : "+resp);
return resp;
}
function GetPositionsBook()
{
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{ \"uid\": \""+ClientID+"\", \"actid\": \""+ClientID+"\", \"type\": \"NET\", \"s_prdt_ali\": \"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\" }";
_TRACE("PositionBook API Request"+api_data);
//Sending The Broker Request for NetOpenPositions
resp=algomojo.AMDispatcher(apikey, apisecret,"PositionBook",api_data,broker,ver);
_TRACE("PositionBook API Response : "+resp);
return resp;
}
function ParsePositionBook(resp,Tsym,Pcode,stringinfo)
{
//Initialization
flag = 0;
possym = "";
Netqty ="";
posdetails = "";
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
{
data = sym;
_TRACE("data : "+data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(StrFind(posdetails,"\""+stringinfo+"\""))
{
flag = 1; //turn on the flag
posdetails = StrExtract(posdetails,1,':');
posdetails = StrTrim(posdetails,"\"");
NetQty = posdetails;
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
NetQty = "0";
}
//_TRACE("\nNetQty : "+NetQty);
return NetQty;
}
function NetOpenPositions()
{
resp = GetPositionsBook();
Netqty = ParsePositionBook(resp,Tsym,Pcode,"Netqty"); //output in string format
Netqty = StrToNum(Netqty);
_TRACE("Order No : "+Netqty);
return Netqty;
}
function NetOpenPos(Symbol)
{
resp = GetPositionsBook();
Netqty = ParsePositionBook(resp,Symbol,Pcode,"Netqty"); //output in string format
Netqty = StrToNum(Netqty);
_TRACE("Net Qty : "+Netqty);
return Netqty;
}
function Getorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
_TRACE("Order No : "+NOrdNo);
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+clientid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
_TRACE("Broker Order History Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"OrderHistory",api_data,broker,ver);
_TRACE("Broker Order History Response"+resp);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
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,"\"");
}
}
}
}
_TRACE("Traded Symbol: "+Trsym);
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"open") OR StrFind(sym,"trigger pending") OR StrFind(sym,"rejected") OR StrFind(sym,"cancelled")) //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,"\"");
}
}
}
}
_TRACE("Order Status : "+orderstatus);
return orderstatus;
}
function getaverageprice(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
averageprice="";
if((sym = StrExtract( ordresp, 1,'{' ))!="")
{
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,"averageprice"))
{
averageprice = StrExtract(ohistory,1,':');
averageprice = StrTrim(averageprice,"\"");
}
}
}
}
if(averageprice=="0.0") //use it only for testing pupose
{
averageprice = "100";
}
_TRACE("Average Price : "+averageprice);
return averageprice;
}
function PlaceOptionOrder(spot_sym,expiry_dt,strike_int,quantity,Ttranstype,opt_type,offset,legno)
{
if(opt_type=="PE")
{
offset = -offset;
}
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data
api_data ="{\"strg_name\":\""+strg_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt_type+"\",\"Ttranstype\":\""+""+Ttranstype+""+"\",\"prctyp\":\""+"MKT"+"\",\"qty\":\""+quantity+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+offset+"\"}";
_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceFOOptionsOrder",api_data,broker,ver);
//Store the OrderNo, Trading Symbol, OrderStatus, NetQty
Trans = Ttranstype;
StaticVarSetText(static_var_options+"Option_Trans"+opt_type,Trans,True); //Get the Transaction Type
OrderNo = Getorderno(resp);
StaticVarSetText(static_var_options+"Option_OrderNo"+opt_type,OrderNo,True); //Get the OrderNo
Symbol = getsymbol(OrderNo);
StaticVarSetText(static_var_options+"Option_Symbol"+opt_type,Symbol,True);
Orderstatus = getorderstatus(OrderNo);
StaticVarSetText(static_var_options+"Option_Orderstatus"+opt_type,Orderstatus,True);
Netqty = NetOpenPos(Symbol);
StaticVarSet(static_var_options+"Option_Netqty"+opt_type,Netqty,True);
_TRACE("API Response : "+resp);
return resp;
}
function SquareOffPosition(opt_type,legno)
{
resp ="";
Symbol = StaticVarGetText(static_var_options+"Option_Symbol"+opt_type);
Netqty = StaticVarGet(static_var_options+"Option_Netqty"+opt_type);
//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data
api_data ="{\"uid\":\""+clientid+"\",\"actid\":\""+clientid+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Exchangeseg\":\""+Exchangeseg+"\",\"Pcode\":\""+""+Pcode+""+"\",\"Netqty\":\""+Netqty+"\",\"Token\":\""+""+"\",\"Symbol\":\""+Symbol+"\",\"orderSource\":\""+"NEST_REST"+"\"}";
_TRACE("Squareoff API Request"+api_data);
if(Netqty!=0)
{
resp=algomojo.AMDispatcher(apikey, apisecret,"SquareOffPosition",api_data,broker,ver);
}
if(resp!="")
{
_TRACE("Squareoff API Response : "+resp);
}
else
{
_TRACE("Squareoff Order Not Triggered");
}
return resp;
}
_SECTION_END();
4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity
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
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)Interpretation Section and Amibroker Internal Memory
One can see the recently placed CE and PE orders from the Interpretation Section as shown below

9)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.