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)

Algomojo Autocancellation of Limit Orders After N seconds

2 min read

In this tutorial, I’m going to demonstrate how to use Amibroker AFL code to perform auto cancellation of limit order after N seconds in Algomojo Platform. Let say I want to send 100 shares of INFY and if the fill is not happening immediately within the next 10 seconds from the executed order I want to cancel the placed orders automatically.

Here is the sample Amibroker Code which does the logic and provides the control to specify the amount of seconds to cancel the limit order trade.

The below mentioned code is just a prototype and for educational purpose only not for real-world executions.

//Algomojo Limit Order and Autocancellation after N Seconds
//Coded by Rajandran R
//Founder - Marketcalls & Algomojo - CoFounder
//Websites : www.algomojo.com & www.marketcalls.in

_SECTION_BEGIN("Algomojo Limit Order and Autocancellation after N Seconds");



function GetSecondNum()
{
    Time        = Now( 4 );
    Seconds     = int( Time % 100 );
    Minutes     = int( Time / 100 % 100 );
    Hours   = int( Time / 10000 % 100 );
    SecondNum = int( Hours * 60 * 60 + Minutes * 60 + Seconds );
    return SecondNum;
}

//_TRACE("seconds :"+GetSecondNum());

PlaceOrder = ParamTrigger("PlaceOrder","PRESS");
CancelOrder = ParamTrigger("CancelOrder","PRESS");
PositionBook = false; //ParamTrigger("PositionBook","PRESS");



user_apikey = ParamStr("user_apikey","c1997d92a3bb556a67dca7d1446b7087"); //Enter your API key here
api_secret = ParamStr("api_secret","5306433329e81ba41203653417063c71"); //Enter your API secret key here
clnt_id = ParamStr("Client ID","TS2499");
s_prdt_ali = ParamList("s_prdt_ali","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",3); //Type of order
Tsym = ParamStr("Tsym","YESBANK-EQ"); //Enter the symbol name here
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); 
Ret = ParamList("Ret","DAY|IOC",0);
Ttranstype = ParamList("Ttranstype","B|S",0);
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
sectocancel = Param("Sec to Cancel LMT order", 10, 3, 60,1);
Pcode = ParamList("Pcode","NRML|BO|CNC|CO|MIS",4);
Price = Param("Limit Price",0,1,100000,1);
TrigPrice = ParamList("TrigPrice","0");
qty = Param("Quatity",75,0,100000,1); 
discqty = ParamList("discqty","0");
AMO = ParamList("AMO","NO|YES",0); //After market order
TokenNo = ParamStr("TokenNo","11184"); //Enter the token number of the symbol here
ltpOratp = ParamList("ltpOratp","LTP|ATP",0);
SqrOffAbsOrticks = ParamList("SqrOffAbsOrticks","Absolute|Ticks",0); //If you select absolute then you can enter a decimal quantity. If you selected ticks you need to enter in multiples of ticks
SqrOffvalue = ParamStr("SqrOffvalue","1"); 
SLAbsOrticks = ParamList("SLAbsOrticks","Absolute|Ticks",0);
SLvalue = ParamStr("SLvalue","1");
trailingSL = ParamList("trailingSL","Y|N",0); 
tSLticks = ParamStr("tSLticks","1"); //Trailing SL value in ticks if user has opted to use trailingSL
stgy_name = ParamStr("Strategy Name", "Test Strategy Chart");








if (PlaceOrder) {

algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+Ttranstype+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+discqty+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data);

StaticVarSetText("NestOrderId", StrTrim( resp, "{\"NOrdNo\":" ));
StaticVarSetText("NestOrderId", StrTrim( StaticVarGetText("NestOrderId"), "\",\"stat\":\"Ok\"}" ));



StaticVarSet("OrderTime",GetSecondNum(),persist = True);
_TRACE("Order Response : " +resp);
_TRACE("Order Time : " +Now());
_TRACE("Nest Order Id : " +StaticVarGet("NestOrderId"));
_TRACE("Seconds Left to Cancel the Order : " +sectocancel+" secs");
StaticVarSet("IfOrderPlaced",1);
}

//Manual Cancellation
if(CancelOrder)
{

algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"uid\":\""+clnt_id+"\",\"NestOrd\":\""+StaticVarGetText("NestOrderId")+"\",\"sTradeSymbol\":\""+Tsym+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"sExch\":\""+exch+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"CancelOrder",api_data);
//OrderTime        = Now( 4 );
_TRACE("Order Response : " +resp);
_TRACE("Cancelled Time : " +Now());
}

//Automated Timer Based Cancellation
//If Trade is Placed then cancel the order after n seconds
if(StaticVarGet("IfOrderPlaced"))
{
diff = GetSecondNum() - StaticVarGet("OrderTime");
_TRACE("Timer Starts to Cancel Order: "+ diff);
if(diff >sectocancel) //cancel after n seconds
{

algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"uid\":\""+clnt_id+"\",\"NestOrd\":\""+StaticVarGetText("NestOrderId")+"\",\"sTradeSymbol\":\""+Tsym+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"sExch\":\""+exch+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"CancelOrder",api_data);
_TRACE("Cancelled Time : " +Now());
_TRACE("Order Response : " +resp);
StaticVarSet("IfOrderPlaced", 0); //reset the flag

}


}


_SECTION_END();

_SECTION_BEGIN("Price1");
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() ); 
_SECTION_END();

In the upcoming algomojo we will be studying more algorithmic execution features. If in case you are looking for a specific algo execution feature then comment your requirements down below.

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)

Stoploss, Multi Target, and Trailing Stoploss Module – Amibroker…

After Intraday V2.0 Amibroker Module - a readymade drag and drop module to convert any trading strategy into the intraday trading system with alerts,...
Rajandran R
6 min read

Line Trading – Algomojo Automation Module for Amibroker Users

The line Trading Automation tool is designed for Manual traders who want to perform level-based trade execution faster and also bring some advanced trade...
Rajandran R
58 sec read

Plotting Day Wise Equity Curve using Amibroker

We know that Amibroker provides an equity curve for the whole strategy. Is there a way where we can build a simple Day Wise...
Rajandran R
1 min read

2 Replies to “Algomojo Autocancellation of Limit Orders After N seconds”

  1. Alice Blue Broker not allowing me to place Market Orders in Stock options. How to fix the issue with Limit orders

    1. Hi many midsize to big brokers avoid the clients to send MKT orders in stock options due to liquidity concerns and mostly brings higher unnecessary trading cost to the clients in the form of higher slippage. It is not a good idea to trade stock options with market orders and hence brokers restrict. However while squaring off the positions then MKT orders will be used for exit purposes.

Leave a Reply

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