Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

Sending Smart Futures/Spot – Signals to Two-Legged Options Execution Module – Amibroker AFL Code

12 min read

Thought of making an open source AFL code demanded by most of the option traders to control the cost, to control the risk, and to configure the two-legged option trading strategy of their choice with smart order execution functionality and provision to slice larger orders. So here is a two-legged options execution Amibroker module for the Algomojo trading platform where users can simply drag and drop the module on top of their own trading logic to convert any spot/futures signals into 9 types of two-legged options execution module.

What is a Two-Legged Options Strategy?

A two-legged options trading strategy involves buying or selling two options at the same time, typically with different strike prices or expiration dates. The strategy is designed to take advantage of the price difference between the two options and can be used for a variety of purposes, such as hedging, speculation, or income generation.

Features of the Two-Legged Options Execution Module

1)Simple Drag and Drop Module on top of any Amibroker trading strategy with the proper buy, sell, short, and cover defined variables.
2)Configure various styles of two-legged options execution strategies. Supports 9 types of two-legged options trading strategies.
3)Configure separate options trading strategies for long-entry and short-entry signals in spot/futures charts
4)Place Smart Option Orders to intelligent send orders by manipulating the current existing positions.
5)Place Larger Option Orders by Splitting Larger Orders into multiple small orders.
6)Option Strike calculation at Amibroker end (Trades can configure the Underlying symbol as Spot./Futures) based on their trading requirement) accordingly, options strikes will be calculated.

Here are the Supported two-legged options trading strategies:

Credit Spread: Selling an option at one strike price and buying an option at a lower strike price.

Debit Spread: Buying an option at one strike price and selling an option at a higher strike price.

Straddle: buying a call and a put option with the same strike price and expiration date.

Strangle: buying a call option with a higher strike price and a put option with a lower strike price

Synthetic Futures: Buying/Selling a call option and selling/Buying a put option of the same strike price and expiration date

Diagonal Spread: Buying a call or put option with a longer expiration date and selling a call or put option with a shorter expiration date and a different strike price.

Calendar Spread: Buying a call or put option with a longer expiration date and selling a call or put option with a shorter expiration date.

Ratio Spread: Buying a call or put option at one strike price and selling multiple options at a different strike price

Ratio Back Spread: Buying multiple options at one strike price and selling an option at a different strike price

Amibroker AFL Code


/*
Algomojo - Smart Spot/Futures to Two Leg Options Trading Module with Split Order Controls

Supported Two Leg Strategies
Strategies that be built using this module
1)Credit Spread
2)Debit Spread
3)Straddle
4)Strangle
5)Synthetic Futures
6)Diagonal spread
7)Calendar Spread
8)Ratio Spread
9)Ratio Back Spread


Created By : Rajandran R(Founder - Marketcalls / Co-Founder Algomojo )
Created on : 24 Jan 2022.
Website : www.marketcalls.in / www.algomojo.com
*/


_SECTION_BEGIN("Algomojo - Broker Controls");


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

//Creating Input Controls for Setting Order Related Information

broker =Paramlist("Broker","an|ab|fs|fy|gc|pt|sm|tc|up|zb|ze",0);
ver = ParamStr("API Version ","v1");
apikey = ParamStr("apikey","46ad9245cca3dfe957deb235a39d02a3"); //Enter your API key here
apisecret = ParamStr("secretkey","066e9a54de007b672f7a6291e017b68e"); //Enter your API secret key here

_SECTION_END();


_SECTION_BEGIN("Algomojo - Order Controls");

strategy = ParamStr("Strategy Name", "Test Strategy");

spot = Paramlist("Spot Symbol","NIFTY|BANKNIFTY");
expiry_leg1 = ParamStr("Expiry Date1","25JAN23");
expiry_leg2 = ParamStr("Expiry Date2","25JAN23");

exchange = ParamList("Exchange","NFO|MCX",0); 
Symbol = ParamStr("Underlying Symbol","NIFTY-I.NFO");
iInterval= Param("Strike Interval",50,1,10000,1);
LotSize = Param("Lot Size",50,1,10000,1);

quantity_leg1 = Param("quanity1(Lot Size)",1,0,10000)*LotSize;
quantity_leg2 = Param("quanity2(Lot Size)",1,0,10000)*LotSize;

opttype_buyleg1 = ParamList("Option Type1(Buy)","CE|PE",0);
opttype_buyleg2 = ParamList("Option Type2(Buy)","CE|PE",0);

tradetype_buyleg1 = ParamList("Option Trade Type1(Buy)","BUY|SELL",0);
tradetype_buyleg2 = ParamList("Option Trade Type2(Buy)","BUY|SELL",0);


offset_buyleg1 = Param("Offset1(Buy)",0,-40,40,1);
offset_buyleg2 = Param("Offset2(Buy)",0,-40,40,1);

opttype_shortleg1 = ParamList("Option Type1(Short)","CE|PE",0);
opttype_shortleg2 = ParamList("Option Type2(Short)","CE|PE",0);



tradetype_shortleg1 = ParamList("Option Trade Type1(Short)","BUY|SELL",0);
tradetype_shortleg2 = ParamList("Option Trade Type2(Short)","BUY|SELL",0);


offset_shortleg1 = Param("Offset1(Short)",0,-40,40,1);
offset_shortleg2 = Param("Offset2(Short)",0,-40,40,1);

pricetype = ParamList("Order Type","MARKET",0);
product = ParamList("Product","MIS|NRML",1);



price = 0; 
disclosed_quantity = 0;
trigger_price = 0;
amo = "NO";
splitorder = ParamList("To Split Orders","NO|YES",0);
split_quantity = Param("Split Quantity",500,1,100000,1);

VoiceAlert = ParamList("Voice Alert","Disable|Enable",1);

Entrydelay = Param("Entry Delay",1,1);
Exitdelay = Param("Exit Delay",1,1);
EnableAlgo = ParamList("AlgoStatus","Disable|Enable|LongOnly|ShortOnly",0);
resp = "";


//Static Variables for Order protection

static_name_ = Name()+GetChartID()+interval(2)+strategy;
static_name_algo = Name()+GetChartID()+interval(2)+strategy+"algostatus";


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



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


EnableTextOutput(False);



//optionCEtype = WriteIf(offsetCE == 0, "ATM CE", WriteIf(offsetCE<0,"ITM"+abs(offsetCE)+" CE","OTM"+abs(offsetCE)+" CE"));
//optionPEtype = WriteIf(offsetPE == 0, "ATM PE", WriteIf(offsetPE<0,"ITM"+abs(offsetPE)+" PE","OTM"+abs(offsetPE)+" PE"));


SetForeign(Symbol);
spotC = Ref(Close,-1); //Underlying Price should not fluctuate
RestorePriceArrays();

//Maintain Array to Store ATM Strikes for each and every bar
strike = IIf(spotC % iInterval > iInterval/2, spotC - (spotC%iInterval) + iInterval,
			spotC - (spotC%iInterval));
			
//Buy Signal Entry Strikes	

if(opttype_buyleg1=="CE")
{	
strike_buyleg1 = strike + (offset_buyleg1 * iInterval);
}
if(opttype_buyleg1=="PE")
{	
strike_buyleg1 = strike - (offset_buyleg1 * iInterval);
}
if(opttype_buyleg2=="CE")
{	
strike_buyleg2 = strike + (offset_buyleg2 * iInterval);
}
if(opttype_buyleg2=="PE")
{	
strike_buyleg2 = strike - (offset_buyleg2 * iInterval);
}

//Short Signal Entry Strikes	

if(opttype_shortleg1=="CE")
{	
strike_shortleg1 = strike + (offset_shortleg1 * iInterval);
}
if(opttype_shortleg1=="PE")
{	
strike_shortleg1 = strike - (offset_shortleg1 * iInterval);
}
if(opttype_shortleg2=="CE")
{	
strike_shortleg2 = strike + (offset_shortleg2 * iInterval);
}
if(opttype_shortleg2=="PE")
{	
strike_shortleg2 = strike - (offset_shortleg2 * iInterval);
}


buycontinue = Flip(Buy,Sell);
shortcontinue  = Flip(Short,Cover);

exitsymbol_buyleg1 = "";
exitsymbol_buyleg2 = "";
exitsymbol_shortleg1 = "";
exitsymbol_shortleg2 = "";

ExitStrike_buyleg1 = ValueWhen(Ref(Buy,-Entrydelay),strike_buyleg1);
ExitStrike_buyleg2 = ValueWhen(Ref(Buy,-Entrydelay),strike_buyleg2);

ExitStrike_shortleg1 = ValueWhen(Ref(Short,-Entrydelay),strike_shortleg1);
ExitStrike_shortleg2 = ValueWhen(Ref(Short,-Entrydelay),strike_shortleg2);

if(broker=="tc" OR broker=="fs")
{

if(opttype_buyleg1=="CE") opttype_buy_leg1 = "C";
if(opttype_buyleg1=="PE") opttype_buy_leg1 = "P";

if(opttype_buyleg2=="CE") opttype_buy_leg2 = "C";
if(opttype_buyleg2=="PE") opttype_buy_leg2 = "P";

if(opttype_shortleg1=="CE") opttype_short_leg1 = "C";
if(opttype_shortleg1=="PE") opttype_short_leg1 = "P";

if(opttype_shortleg2=="CE") opttype_short_leg2 = "C";
if(opttype_shortleg2=="PE") opttype_short_leg2 = "P";


exitsymbol_buyleg1 = WriteIf(buycontinue OR sell,spot+expiry_leg1+opttype_buy_leg1+ExitStrike_buyleg1,"");
exitsymbol_buyleg2 = WriteIf(buycontinue OR sell,spot+expiry_leg2+opttype_buy_leg2+ExitStrike_buyleg2,"");
exitsymbol_shortleg1 = WriteIf(shortcontinue OR cover,spot+expiry_leg1+opttype_short_leg1+ExitStrike_shortleg1,"");
exitsymbol_shortleg2 = WriteIf(shortcontinue OR cover,spot+expiry_leg2+opttype_short_leg2+ExitStrike_shortleg2,"");

}

else
{
exitsymbol_buyleg1 = WriteIf(buycontinue OR sell,spot+expiry_leg1+ExitStrike_buyleg1+opttype_buyleg1,"");
exitsymbol_buyleg2 = WriteIf(buycontinue OR sell,spot+expiry_leg2+ExitStrike_buyleg2+opttype_buyleg2,"");
exitsymbol_shortleg1 = WriteIf(shortcontinue OR cover,spot+expiry_leg1+ExitStrike_shortleg1+opttype_shortleg1,"");
exitsymbol_shortleg2 = WriteIf(shortcontinue OR cover,spot+expiry_leg2+ExitStrike_shortleg2+opttype_shortleg2,"");
}





printf("\n\n\nLeg1 Symbol(Buy) : "+exitsymbol_buyleg1);
printf("\nLeg2 Symbol(Buy) : "+exitsymbol_buyleg2);

printf("\n\n\nLeg1 Symbol(Short) : "+exitsymbol_shortleg1);
printf("\nLeg2 Symbol(Short) : "+exitsymbol_shortleg2);



_SECTION_END();




//Buy and Sell Order Functions
//signaltype = "buy" OR "short
//leg = "leg1","leg2"
function Placeorder(action,OptionType,orderqty,expiry,signaltype,leg)
{
//strike_buyleg1	
    algomojo=CreateObject("AMAMIBRIDGE.Main");
    
    if(broker=="tc" OR broker=="fs" )
	{
		if(OptionType=="CE") OptType = "C";
		if(OptionType=="PE") OptType = "P";
		tradingsymbol = spot+expiry+OptType+VarGetText("strike_"+signaltype+leg);
    }
    else
	{
		tradingsymbol = spot+expiry+VarGetText("strike_"+signaltype+leg)+OptionType;
    }
    api_data = "{ \"broker\": \""+broker+"\",
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+tradingsymbol+"\",
            \"action\":\""+action+"\",
            \"product\":\""+product+"\",
            \"pricetype\":\""+pricetype+"\",
            \"quantity\":\""+orderqty+"\",
            \"price\":\""+price+"\",      
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"amo\":\""+amo+"\",
            \"splitorder\":\""+splitorder+"\",
            \"split_quantity\":\""+split_quantity+"\"
          
        }"; 
    _TRACE("Signal Type"+signaltype+" Option Leg : "+leg);
    _TRACE("API Request"+api_data);
    resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceOrder",api_data,"am",ver);
    _TRACE("API Response : "+resp);
    
    if(VoiceAlert == "Enable")
	Say( "Order Placed" ); 
}

//Squareoff Function to Exit Open Positions

//signaltype = "buy" OR "short
//leg = "leg1","leg2"

function ExitOrder(action,OptionType,expiry,signaltype,leg)
{


 algomojo=CreateObject("AMAMIBRIDGE.Main");
//exitsymbol_buyleg1
if(broker=="tc" or broker=="fs")
{
	if(OptionType=="CE") OptType = "C";
	if(OptionType=="PE") OptType = "P";
					//spot+expiry+OptType+VarGetText("strike_"+signaltype+leg);
	tradingsymbol = VarGetText("exitsymbol_"+signaltype+leg);
}

else
{
	tradingsymbol = VarGetText("exitsymbol_"+signaltype+leg);
}

api_data = "{ \"broker\": \""+broker+"\",
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+tradingsymbol+"\",
            \"action\":\""+action+"\",
            \"product\":\""+product+"\",
            \"pricetype\":\""+pricetype+"\",
            \"quantity\":\""+"0"+"\",
            \"price\":\""+price+"\",
            \"position_size\":\""+"0"+"\",            
            \"disclosed_quantity\":\""+disclosed_quantity+"\",
            \"trigger_price\":\""+trigger_price+"\",
            \"amo\":\""+amo+"\",
            \"splitorder\":\""+splitorder+"\",
            \"split_quantity\":\""+split_quantity+"\"
          
        }"; 

_TRACE("Signal Type"+signaltype+" Option Leg : "+leg);
_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceSmartOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

if(VoiceAlert == "Enable")
	Say( "Order Placed" );

return resp;

}



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 )
            {
            
	//ExitOrder(action,OptionType,orderqty,position_size,expiry,signaltype,leg)
	//leg = "leg1","leg2"
				
				//Cover Signal
				if(tradetype_shortleg1=="SELL")
				{
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1"); 
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2");
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1");  
				}
				//Buy Signal
				if(tradetype_buyleg1=="BUY")
				{
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				}
				else
				{
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				}
					
				
				
				
                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);
                StaticVarSetText(static_name_+"buyCoverAlgo_barvalue","");
            }
            
            if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {
				
				//Buy Signal
				if(tradetype_buyleg1=="BUY")
				{
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				}
				else
				{
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				}
				
				
                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);
                StaticVarSetText(static_name_+"buyAlgo_barvalue","");
                
            }
            if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            {     
				//Sell Signal
				if(tradetype_buyleg1=="SELL")
				{
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1"); 
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2");
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1");  
				}
                
                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);
                StaticVarSetText(static_name_+"sellAlgo_barvalue","");
            }
            if (AlgoShort==True AND AlgoSell==True AND  StaticVarGet(static_name_+"ShortSellAlgo")==0 AND StaticVarGetText(static_name_+"ShortSellAlgo_barvalue") != lasttime)
            {
				//Sell Signal
				if(tradetype_buyleg1=="SELL")
				{
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1"); 
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2");
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1");  
				}
				//Short
				if(tradetype_shortleg1=="BUY")
				{
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				}
				else
				{
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				}
				
				
                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);
                StaticVarSetText(static_name_+"ShortsellAlgo_barvalue","");
            }
                
            if (AlgoShort==True  AND  AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND  StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
				//Short
				if(tradetype_shortleg1=="BUY")
				{
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				}
				else
				{
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				}
				
                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);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue","");
            }
            if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
				
				//Cover Signal
				if(tradetype_shortleg1=="SELL")
				{
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1"); 
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2");
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1");  
				}
               
                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);
                StaticVarSetText(static_name_+"CoverAlgo_barvalue","");
            }
        }
        
      else if(EnableAlgo == "LongOnly")
        {
        
			 if (AlgoBuy==True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
            {
            
				//Buy Signal
				if(tradetype_buyleg1=="BUY")
				{
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				}
				else
				{
				PlaceOrder(tradetype_buyleg2,opttype_buyleg2,quantity_leg2,expiry_leg2,"buy","leg2");
				PlaceOrder(tradetype_buyleg1,opttype_buyleg1,quantity_leg1,expiry_leg1,"buy","leg1");
				}
				
                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);
                StaticVarSetText(static_name_+"buyAlgo_barvalue","");
            
            }
            
             if (AlgoSell==True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
            { 
            
				//Sell Signal
				if(tradetype_buyleg1=="SELL")
				{
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1"); 
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_buyleg2,opttype_buyleg2,expiry_leg2,"buy","leg2");
				ExitOrder(tradetype_buyleg1,opttype_buyleg1,expiry_leg1,"buy","leg1");  
				}
				
                StaticVarSet(static_name_+"sellAlgo",1);
                StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
            }
            else if (AlgoSell != True )
            {  
                StaticVarSet(static_name_+"sellAlgo",0);
                StaticVarSetText(static_name_+"sellAlgo_barvalue","");
            
            }
            
        } 
        else if(EnableAlgo == "ShortOnly")
        {
            if (AlgoShort==True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
            {
				//Short
				if(tradetype_shortleg1=="BUY")
				{
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				}
				else
				{
				PlaceOrder(tradetype_shortleg2,opttype_shortleg2,quantity_leg2,expiry_leg2,"short","leg2");
				PlaceOrder(tradetype_shortleg1,opttype_shortleg1,quantity_leg1,expiry_leg1,"short","leg1");
				}
				
                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);
                StaticVarSetText(static_name_+"ShortAlgo_barvalue","");
            }
            if (AlgoCover==true AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
            {
            
				//Cover Signal
				if(tradetype_shortleg1=="SELL")
				{
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1"); 
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2"); 
				}
				else
				{
				ExitOrder(tradetype_shortleg2,opttype_shortleg2,expiry_leg2,"short","leg2");
				ExitOrder(tradetype_shortleg1,opttype_shortleg1,expiry_leg1,"short","leg1");  
				}
               
                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);
                StaticVarSetText(static_name_+"CoverAlgo_barvalue","");
            }
        } 
        
    }
    
  
_SECTION_END();
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

How to Send Bulk Orders from Excel Sheet to…

This video tutorial explores how to send bulk orders from the Excel sheet module to multiple brokers. Bulk Order Entry allows placing multiple orders(MKT,LMT,SL,SL-LMT,CO,BO)...
Rajandran R
2 min read

Realtime Option Greeks Indicator and Exploration Module for Amibroker

Option Greeks are a set of mathematical models used to analyze the behavior of options. Real-time Option Greeks refer to the calculation of these...
Rajandran R
5 min read

Sending Futures/Spot – Signals to Two-Legged Options Execution Module…

Thought of making an open-source Tradingview Pinescript code demanded by most of the option traders to control the cost, control the risk, and configure...
Rajandran R
16 min read

Leave a Reply

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