
Here is a simple button trading module which can be used to send option trading order with buttons. Users can configure the button to send ATM, ITM, OTM Options and with one touch one will be able to send orders a split second. Entry Order and Exit order buttons are provided to users.
Supported Brokers : Aliceblue, Mastertrust, Tradejini, Zebu
AlgoPlatform : Algomojo
Supported Amibroker Version : 6.22 or above
Buttons | Type |
Long CE Entry | Entry Order |
Long CE Exit | Exit Order |
Long PE Entry | Entry Order |
Long PE Exit | Exit Order |
Short CE Entry | Entry Order |
Short CE Exit | Exit Order |
Short PE Entry | Entry Order |
Short PE Exit | Exit Order |
Button Offset Parameter Controls in Amibroker
Option Type | Offset |
ATM | 0 |
OTM | Positive Value |
ITM | Negative Value |
Execution Logic for Placing Options Order

Execution Logic for Exiting Options Order

Setting up the Options Button Trading AFL File
1)Save the AFL file under the name Algomojo Options Button Trading.afl under Amibroker/formulas/Algomojo folder. Create Algomojo Folder if it doesn’t exist.
/*
Created By : Rajandran R(Founder - Marketcalls / Co-Founder Algomojo )
Created on : 11 May 2021
Website : www.marketcalls.in / www.algomojo.com
*/
#include < algomojooptions.afl > //remove the spaces to make the afl work
_SECTION_BEGIN("Amibroker Version Check");
Version(6.22);
RequestTimedRefresh(1, False); // Send orders even if Amibroker is minimized or Chart is not active
_SECTION_END();
_SECTION_BEGIN("Button Controls");
//Default strike is ATM, Positve Offset = OTM, Negative Offset = ITM -> AFL Side
spot = ParamStr("Spot Symbol","NIFTY");
expiry = ParamStr("Expiry Date","27MAY21");
iInterval= Param("Strike Interval",50,1,5000,1);
//Long CE Entry and Exit Button Controls
btn12_qty = Param("Long CE Qty",75,0,10000,1);
offset_btn12 = Param("Long CE Offset",0,-20,20,1);
optiontype12 = WriteIf(offset_btn12 == 0, "ATM", WriteIf(offset_btn12<0,"ITM","OTM"));
btn1_name = optiontype12+"-"+abs(offset_btn12)+" Long CE Entry "+btn12_qty+" shares";
btn2_name = optiontype12+"-"+abs(offset_btn12)+" Long CE Exit "+btn12_qty+" shares";
btn34_qty = Param("Long PE Qty",75,0,10000,1);
offset_btn34 = Param("Long PE Offset",0,-20,20,1);
optiontype34 = WriteIf(offset_btn34 == 0, "ATM", WriteIf(offset_btn34<0,"ITM","OTM"));
btn3_name = optiontype34+"-"+abs(offset_btn34)+" Long PE Entry "+btn34_qty+" shares";
btn4_name = optiontype34+"-"+abs(offset_btn34)+" Long PE Exit "+btn34_qty+" shares";
btn56_qty = Param("Short CE Qty",75,0,10000,1);
offset_btn56 = Param("Short CE Offset",0,-20,20,1);
optiontype56 = WriteIf(offset_btn56 == 0, "ATM", WriteIf(offset_btn56<0,"ITM","OTM"));
btn5_name = optiontype56+"-"+abs(offset_btn56)+" Short CE Entry "+btn56_qty+" shares";
btn6_name = optiontype56+"-"+abs(offset_btn56)+" Long CE Exit "+btn56_qty+" shares";
btn78_qty = Param("Short PE Qty",75,0,10000,1);
offset_btn78 = Param("Short PE Offset",0,-20,20,1);
optiontype78 = WriteIf(offset_btn78 == 0, "ATM", WriteIf(offset_btn78<0,"ITM","OTM"));
btn7_name = optiontype78+"-"+abs(offset_btn78)+" Shortong PE Entry "+btn78_qty+" shares";
btn8_name = optiontype78+"-"+abs(offset_btn78)+" Short PE Exit "+btn78_qty+" shares";
_SECTION_END();
_SECTION_BEGIN("Algo Dashboard");
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
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);
}
}
_SECTION_END();
_SECTION_BEGIN("Algomojo Button GUI Creation and Event Handling");
resp = "";
function CreateGUI( ButtonName, x, y, width, Height ) {
/// @link http://forum.amibroker.com/t/guibuttons-for-everyone/1716/4
/// by beaver & fxshrat
/// version 1.1
global IDset;
local id, event, clickeven;
if( typeof( IDset ) == "undefined" ) IDset = 0;
//_TRACEF( "IDset before: %g", IDset );
GuiButton( ButtonName, ++IDset, x, y, width, height, 7 );
//_TRACEF( "IDset after: %g", IDset );
result = 1;
return result;
}
function HandleEvents()
{
result = 0;
id = GuiGetEvent( 0, 0 );// receiving button id
event = GuiGetEvent( 0, 1 );// receiving notifyflag
clickevent = event == 1;
LongCEEntry = id == 1 && clickevent;
LongCEExit = id == 2 && clickevent;
LongPEEntry = id == 3 && clickevent;
LongPEExit = id == 4 && clickevent;
ShortCEEntry = id == 5 && clickevent;
ShortCEExit = id == 6 && clickevent;
ShortPEEntry = id == 7 && clickevent;
ShortPEExit = id == 8 && clickevent;
result = 0;
if(EnableAlgo == "Enable")
{
if( LongCEEntry AND StaticVarGet(Name()+GetChartID()+"LongCEEntry")==0 )
{
_TRACE("Call Long Entry");
orderresponse = placeoptionorder(1,spot,expiry,iInterval,btn12_qty,"B","CE",offset_btn12);
result = 1;
StaticVarSet(Name()+GetChartID()+"LongCEEntry",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"LongCEEntry",0);
}
if( LongCEExit AND StaticVarGet(Name()+GetChartID()+"LongCEExit")==0 )
{
_TRACE("Call Long Exit");
sqoffstatus = squareoffoptions(1,"CE");
result = 1;
StaticVarSet(Name()+GetChartID()+"LongCEExit",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"LongCEExit",0);
}
if( LongPEEntry AND StaticVarGet(Name()+GetChartID()+"LongPEEntry")==0 )
{
_TRACE("Put Long Entry");
orderresponse = placeoptionorder(2,spot,expiry,iInterval,btn34_qty,"B","PE",offset_btn34);
result = 1;
StaticVarSet(Name()+GetChartID()+"LongPEEntry",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"LongPEEntry",0);
}
if( LongPEExit AND StaticVarGet(Name()+GetChartID()+"LongPEExit")==0 )
{
_TRACE("Put Long Exit");
sqoffstatus = squareoffoptions(2,"PE");
result = 1;
StaticVarSet(Name()+GetChartID()+"LongPEExit",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"LongPEExit",0);
}
if( ShortCEEntry AND StaticVarGet(Name()+GetChartID()+"ShortCEEntry")==0 )
{
_TRACE("Call Short Entry");
orderresponse = placeoptionorder(3,spot,expiry,iInterval,btn56_qty,"S","CE",offset_btn56);
result = 1;
StaticVarSet(Name()+GetChartID()+"ShortCEEntry",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"ShortCEEntry",0);
}
if( ShortCEExit AND StaticVarGet(Name()+GetChartID()+"ShortCEExit")==0 )
{
_TRACE("Call Short Exit");
sqoffstatus = squareoffoptions(3,"CE");
result = 1;
StaticVarSet(Name()+GetChartID()+"ShortCEExit",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"ShortCEExit",0);
}
if( ShortPEEntry AND StaticVarGet(Name()+GetChartID()+"ShortPEEntry")==0 )
{
_TRACE("Put Short Entry");
orderresponse = placeoptionorder(4,spot,expiry,iInterval,btn78_qty,"S","PE",offset_btn78);
result = 1;
StaticVarSet(Name()+GetChartID()+"ShortPEEntry",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"ShortPEEntry",0);
}
if( ShortPEExit AND StaticVarGet(Name()+GetChartID()+"ShortPEExit")==0 )
{
_TRACE("Put Short Exit");
sqoffstatus = squareoffoptions(4,"PE");
result = 1;
StaticVarSet(Name()+GetChartID()+"ShortPEExit",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"ShortPEExit",0);
}
}
return result; //result = 1 - order is successfully placed, 0 - Algotrading is in disabled state or orders are not went through
}
LongCEEntry = CreateGUI( btn1_name, 0, 100, 200, 30 );
LongCEExit = CreateGUI( btn2_name, 200, 100, 200, 30 );
LongPEEntry = CreateGUI( btn3_name, 0, 150, 200, 30 );
LongPEExit = CreateGUI( btn4_name, 200, 150, 200, 30 );
ShortCEEntry = CreateGUI( btn5_name, 0, 200, 200, 30 );
ShortCEExit = CreateGUI( btn6_name, 200, 200, 200, 30 );
ShortPEEntry = CreateGUI( btn7_name, 0, 250, 200, 30 );
ShortPEExit = CreateGUI( btn8_name, 200, 250, 200, 30 );
handleevents();
GuiSetColors( 1, 2, 2, colorGreen, colorBlack, colorGreen, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow );
GuiSetColors( 3, 4, 2, colorred, colorBlack, colorRed, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow );
GuiSetColors( 5, 6, 2, colorBlue, colorBlack, colorBlue, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow );
GuiSetColors( 7, 8, 2, colorLavender, colorBlack, colorLavender, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow );
_SECTION_END();
_SECTION_BEGIN("Price");
SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
_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 the candles
Plot(Close,"Close",colorDefault,GetPriceStyle() | styleNoTitle);
_SECTION_END();
2)Copy the AFL under the name algomojooptions.afl under the path Amibroker\formulas\include folder
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 11/05/2021
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Options");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","2c674f6696f5527e40af1b052c262178"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","tj"); //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 = 2; //3 seconds for providing delay after placing order
EnableAlgo = ParamList("Algo Mode","Enable|Disable",1); // Algo Mode
OrderAlerts = ParamToggle("Order Alerts","Enabled|Disabled",0);
RequestTimedRefresh(1,False);
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,Ttranstype)
{
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);
fputs(Ttranstype+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
//placeoptionorder(1,spot,expiry,iInterval,btn12_qty,"B","CE",offset_btn12);
function placeoptionorder(group,spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off)
{
if(opt=="CE")
{
off = off; //sign remains the same
}
if(opt=="PE")
{
off = -off; //reverse the sign
}
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+"\"}";
_TRACE("API Data :"+api_data);
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
if(OrderAlerts)
{
Say("Entry Order Placed");
}
//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+group+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+group+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus,Ttranstype);
_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(group,opt)
{
ordno = "";
Symbol = "";
ostatus ="";
Ttype = "";
if(opt=="CE")
{
fpath = fpath+group+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+group+"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)," ");
Ttype = StrTrim(StrExtract(read,3)," ");
fclose(fh);
}
if(Ttype == "B")
{
TransType = "S";
}
if(Ttype == "S")
{
TransType = "B";
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
//if(ostatus=="complete" AND exitqty!=0)
if(ostatus=="rejected") //Enable only for testing purpose
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+TransType+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
_TRACE("API Data :"+api_data);
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
if(OrderAlerts)
{
Say("Exit Order Placed");
}
//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. Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
Now Drag and Drop the Algomojo Options Button Trading to the new blank charts. Configure the API Key, API Secret Key, Broker Name, Spot, Expiry Date, Strike Interval and the Button Controls, Offset and Quantity.
Bingo! Now with the press of the button you will be able to place orders automatically.
The post Option Button Trading to Trade ATM, ITM, OTM Options – Amibroker AFL Code appeared first on Marketcalls.