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

This tutorial helps you to understand how to connect your simple Buy and Sell Trading signals to send ATM/ITM/OTM option orders (Option Buying/Option Selling) 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 if one running in ATM/ITM Option Buying instead of Futures. Big Gap up and Gap down risk could be reduced drastically while carry forwarding your positions.

Supported Brokers

Alice blue, Tradejini, Zebu

Supported Amibroker Version: 5.8 or above

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

Where to check the status of Internal Memory

One can see the recently placed CE and PE orders from the Interpretation Section as shown below

One can clear the Internal memory by pressing the clear button (clear static var) under the parameters section

Strategy Parameter Settings for Option Long and Exit Strategy

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

Strategy Parameter Settings for Option Short and Exit Strategy

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

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.

//Strategy Created by Rajandran R 
//Founder - Marketcalls (www.marketcalls.in) and Co-Founder (www.algomojo.com)
//Coded Date : 24th Jan 2020

_SECTION_BEGIN("Simple EMA Crossover Intraday Strategy");

SetChartBkColor(colorBlack);

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 Candles AND X-Axis 
SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
Plot(Close,"Close",colorDefault,GetPriceStyle() | styleNoTitle);


//Set Position Size
SetPositionSize(75,spsShares);

//Controls
LimitTrades = Param("Limit Trades",1,10,1);
FirstTradeTime = ParamTime("Start Time","09:15");				// Earliest time to take a trade
LastTradeTime = ParamTime("Last Time","15:00");					// Latest time to take new trades
ExitAllPositionsTime = ParamTime("Squareoff Time","15:20");		// Exit all trades
color1 = ParamColor("Color1",colorGreen);
color2 = ParamColor("Color2",colorRed);

P = ParamField("Price field",-1);
per1 = Param("EMA1",9,1,20,1);
per2 = Param("EMA2",36,1,50,1);

newday = Day() != Ref(Day(),-1);

//Trading Logic

Buy = Cross(EMA(P,per1),EMA(P,per2)) AND (TimeNum() >= FirstTradeTime AND TimeNum() <= LastTradeTime );
Sell= Cross(EMA(P,per2),EMA(P,per1)) OR  TimeNum() == ExitAllPositionsTime;

Short=Cross(EMA(P,per2),EMA(P,per1)) AND (TimeNum() >= FirstTradeTime AND TimeNum() <= LastTradeTime );
Cover=Cross(EMA(P,per1),EMA(P,per2)) OR TimeNum() == ExitAllPositionsTime;



Buy = Buy AND Sum( Buy OR Short, BarsSince( newday) +1 ) <= LimitTrades;
Short = Short AND Sum( Buy OR Short, BarsSince( newday) +1 ) <= LimitTrades;

//Rempve Excessive Signals

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

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

//Intialize trade delay to zero to avoid any over-riding from external parameters - 
SetTradeDelays(0,0,0,0);


//Generate Signals on Closing Basis - Non Repainting and Signals delayed by 1 bar
Buy = Ref(Buy,-1);
Sell = Ref(Sell,-1);
Short = Ref(Short,-1);
Cover = Ref(Cover,-1);

//Buy at Next Bar Open, Trade Delay is already given at 
BuyPrice=ValueWhen(Buy,Open);
SellPrice=ValueWhen(Sell,Open);
ShortPrice=ValueWhen(Short,Open);
CoverPrice=ValueWhen(Cover,Open);

Plot( EMA( P, per1 ), "EMA1", ParamColor( "Color1", colorCycle ), ParamStyle("Style") | styleThick ); 
Plot( EMA( P, per2 ), "EMA2", ParamColor( "Color2", colorCycle ), ParamStyle("Style") | styleThick ); 


PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);                      
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45); 
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);                      
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);


PlotShapes(IIf(Sell, shapeStar, shapeNone),colorGreen,0 ,H,5);
PlotShapes(IIf(cover, shapeStar, shapeNone),colorRed,0,L,5);

_SECTION_END();


_SECTION_BEGIN("Signal Dashboard");

showMsgBoard = ParamToggle("Message Board", "Hide|Show", 1);

if ( showMsgBoard == 1 )
{
Long=Flip(Buy,Sell); 
Shrt=Flip(Short,Cover); 
Relax = NOT Long AND NOT Buy AND NOT shrt AND NOT Short AND NOT Sell AND NOT Cover;
BarsSincebuy = BarsSince( Buy ); 
BarsSinceshort = BarsSince( Short ); 
LastSignal = IIf( BarsSincebuy < BarsSinceshort, 1, -1 ); 

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

//if ( SelectedValue( LastSignal ) == 1 )
if ( SelectedValue( Long ) == 1 ) 
{ 
	GfxSelectSolidBrush( colorDarkGreen ); 
} 
else if ( SelectedValue( Shrt ) == 1 )
{ 
	GfxSelectSolidBrush( colorDarkRed ); 
} 
else
{ 
	GfxSelectSolidBrush( colorDarkGrey ); 
} 

pxHeight = Status( "pxchartheight" ) ; 
xx = Status( "pxchartwidth"); 
Left = 1100; 
width = 310; 
x = 5; 
x2 = 265; 
y = pxHeight; 
y2 = y;

GfxSelectPen( colorWhite, 1); // border color 
GfxRoundRect( x, y - 98, x2, y , 7, 7 ) ; 
GfxTextOut( ( "EMA Intraday Trading System"),13,y-93);

y2 = y2-70;
GfxTextOut( ("" + WriteIf(Buy, "Buy @ "+ BuyPrice, "")), 13, y2); 
GfxTextOut( ("" + WriteIf(Short, "Short @ "+ ShortPrice,"")), 13, y2); 
GfxTextOut( ("" + WriteIf (Long AND NOT Buy, "Long @ "+(BuyPrice),"")), 13, y2); 
GfxTextOut( ("" + WriteIf (shrt AND NOT Short, "Short @ "+(ShortPrice),"")), 13, y2); 
//GfxTextOut( ("" + WriteIf(notrade,"No Trade Day", WriteIf(Relax, "No Trade Zone - Wait!",""))), 13, y2); 
//GfxTextOut( ("" + WriteIf (Relax, "No Trade Zone - Wait!","")), 13, y2); 


y2 = y2+20;
GfxTextOut( ("" + WriteIf (Long AND NOT Buy, "Current P/L: "+NumToStr((C-BuyPrice),1.2)+" Points","")), 13, y2); 
GfxTextOut( ("" + WriteIf (shrt AND NOT Short, "Current P/L: "+NumToStr((ShortPrice-C),1.2)+" Points","")), 13, y2); 

y2 = y2-20;
GfxTextOut( ("" + WriteIf (Sell AND NOT Short, "Exit Long @ "+ SellPrice ,"")), 13, y2);
GfxTextOut( ("" + WriteIf (Cover AND NOT Buy, "Exit Short @ "+ CoverPrice,"")), 13, y2);

y2 = y2+20;
GfxTextOut( ("" + WriteIf (Sell AND NOT Short, "P/L : "+NumToStr((SellPrice-BuyPrice),1.2)+" Points","")), 13, y2); 
GfxTextOut( ("" + WriteIf (Cover AND NOT Buy, "P/L : "+NumToStr((ShortPrice-CoverPrice),1.2)+" Points","")), 13, y2); 
}
_SECTION_END();
 
_SECTION_BEGIN("Top Dashboard");

X0 = 10;
Y0 = 20;

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


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


_SECTION_END();

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 Rajandran R - Algomojo Co-Founder
//Date : 11/08/2021
//Version : 1.0.0.1
//////////////////////////////////////////////

#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

leg_no = 1;

if(transtype=="B")
{
opt_typ1 = "CE";
opt_typ2 = "PE";
}

if(transtype=="S")
{
opt_typ2 = "CE";
opt_typ1 = "PE";
}

//Configure Trade Execution Delay


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

//Static Varibales for Order Protection

static_name_ = Name()+GetChartID()+interval(2)+strg_name;
static_name_algo = Name()+GetChartID()+interval(2)+strg_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
				           
								
                placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ1,offset,leg_no);
				SquareOffPosition(opt_typ2,leg_no);				

				_TRACE("Strategy : "+ strg_name +"Chart Symbol : "+ Name() +"  Signal : Buy and Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                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 : "+ strg_name +"Chart Symbol : "+ Name() +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ1,offset,leg_no);
				
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                SquareOffPosition(opt_typ1,leg_no);	
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Short and Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
                placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ2,offset,leg_no);
				SquareOffPosition(opt_typ1,leg_no);	
				
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Short Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
            
               placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ2,offset,leg_no);
				
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                 SquareOffPosition(opt_typ2,leg_no);
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Buy Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
				
                placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ1,offset,leg_no);
				
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Sell Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                SquareOffPosition(opt_typ1,leg_no);	
                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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : ShortSignal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                placeoptionorder(spot_sym,expiry_dt,strike_int,transtype,opt_typ2,offset,leg_no);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime); 
                StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
                _TRACE("Strategy : "+ strg_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 : "+ strg_name +"Chart Symbol : "+ Name()  +"  Signal : Cover Signal  TimeFrame : "+ Interval(2)+"  ChardId : "+ GetChartID());
                SquareOffPosition(opt_typ2,leg_no);	
                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 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;
lotize = 50;
}

if(spot_sym == "BANKNIFTY")
{
strike_int  = 100;
lotize = 25;
}

offset = Param("Option Offset",0,-20,20,1); //Default ATM Options will be selected
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)*lotize;


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-------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-------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 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,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\":\""+qty+"\",\"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

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

7)Enter the Spot Symbol, Expiry Date, Strike Interval, Offset, and Trade Delay

Note : 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

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

2 comments

  1. I am getting error message as Error 42, Include file doesn’t exists . Ass per the instructions given I have copied the Header Include Option Execution Module to include folder, but still I get error. Please guide me to clear the issue

Leave a Reply

Your email address will not be published. Required fields are marked *