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.

Send Option Orders from Futures or Spot Signals in Amibroker using Algomojo Platform

9 min read

This tutorial helps you to understand how to connect your simple Buy and Sell Trading signals to send ATM option orders in the Algomojo Platform. This kind of system helps traders to mitigate the risk especially when a sudden fall/rise is expected and that brings the system free from extreme black swan risk. Big Gap up and Gap down risk while carry forwarding your positions.

Trading Signal in Spot/FuturesOrders to be Placed
Buy SignalLong Call
Sell SignalExit Long Call
Short SignalLong Put
Cover SignalExit Long Put
Buy and Cover SignalLong Call
Exit Long Put
Short and Cover SignalLong Put
Exit Long Call

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

To Build this module we need 3 components

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

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)Main Option Execution Module

Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Algomojo Spot Or Future Signals to Option Orders.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 < algomojooptions.afl >

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


// 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
expiry_dt = ParamStr("expiry_dt", "28JAN21");
strike_int = ParamStr("strike_int","50");
//Ttranstype = ParamList("Transaction Type","B|S");
opt_type = ParamList("opt_type","CE|PE",0);
offset = ParamStr("Offset","0"); //No. of strikes away from ATM Strike

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 )
            {
            // Buy Call and Exit Long Put Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +"  Signal : Buy and Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
            
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
				_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
				
				sqoffstatus = squareoffoptions("PE");
				_TRACEF("\nExit Put Response :"+sqoffstatus);
				
				
                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 Call Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
				_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
				
                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)
            {     
            // Exit Long Call Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                sqoffstatus = squareoffoptions("CE");
				_TRACEF("\nExit Call Response :"+sqoffstatus);
                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 Put Options and Exit Long Call Options
            
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Short and Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
				_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
				
				sqoffstatus = squareoffoptions("CE");
				_TRACEF("\nExit Call Response :"+sqoffstatus);
				
                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 Put Options
            
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Short Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
				_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
				
                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)
            {
            // Exit Long Put
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                sqoffstatus = squareoffoptions("PE");
				_TRACEF("\nExit Put Response :"+sqoffstatus);
                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 Call Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
				_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
                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)
            {  
            // Exit Long Call Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                sqoffstatus = squareoffoptions("CE");
				_TRACEF("\nExit Call Response :"+sqoffstatus);
                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 Put Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : ShortSignal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
				_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
                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)
            {
            // Exit Long Put Options
				_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                sqoffstatus = squareoffoptions("PE");
				_TRACEF("\nExit Put Response :"+sqoffstatus);
                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();




3)Header Include Option Execution Module

Copy the Header Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojooptions.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");


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";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
qty = Param("Quatity",75,0,100000,1); 
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 = 3; //3 seconds for providing delay after placing order

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)
{
    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,Ttranstype,opt,off)
{

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);

//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+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+"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\":\""+"DAY"+"\",\"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)
{

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

	if(opt=="CE")
	{
	fpath = fpath+"AlgomojoCE.csv";
	}
	if(opt=="PE")
	{
	fpath = fpath+"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\":\""+"S"+"\",\"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. Prev Signal Status Not in Completed State";
	
	}
	
	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

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.

AlgomojoCE.csv and AlgomojoPE.csv will be saved separately only if the execution status is in complete mode. If the order is rejected then the file will not be saved with an executed symbol.

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

7)Bingo Now you can Send ATM Option Orders from Amibroker by connecting any of your Buy/Sell Trading System. To Send ITM/OTM Option Orders to 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.

Send Option Orders from Futures or Spot Signals in…

This tutorial helps you to understand how to connect your simple Buy and Sell Trading signals to send ATM option orders in the...
Rajandran R
9 min read

How to Send Automated Orders from Tradingview to Algomojo…

This tutorial explores how to send automated orders from Tradingview using webhook method to Algomojo Trading Platform. Webhook is a unique way of communicating...
Rajandran R
2 min read

TradersKart – One Stop Shop for Traders

TradersKart offers One-Stop E-commerce Solution for all the traders, where traders will get access to their trading needs. Traderskart provides the necessary tools required...
Rajandran R
53 sec read

6 Replies to “Send Option Orders from Futures or Spot Signals in…”

      1. I extracted only timer:

        RequestTimedRefresh(1, False);

        timer = 3; //3 seconds for providing delay after placing order
        tradetime=GetPerformanceCounter()/1000;

        while ((GetPerformanceCounter()/1000 – tradetime) < timer)
        {
        _TRACE("\nTest");
        //Error 13. Endless loop detected in WHILE loop
        }

  1. i am getting this error. it is not able to locate the formula/include folder. how to make it recognize. the moment i am dragging and dropping on my buy and sell affl it is giving the error. I have pasted the header execution in include folder

Leave a Reply

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