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.

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

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

//Manual Cancellation

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
diff = GetSecondNum() - StaticVarGet("OrderTime");
_TRACE("Timer Starts to Cancel Order: "+ diff);
if(diff >sectocancel) //cancel after n seconds

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




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

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

AllinOneAlerts – Amibroker Alerts Module for Amibroker Users

AllinOneAlerts is one of the most important and most requested modules to bring all sorts of alerts with no extra coding efforts. Now even...
Rajandran R
5 min read

How to improve your Amibroker Algo Trading Execution Speed

When comes to Automated Trading speed of execution plays a dominant role in executing at better prices. Here I would like to list three...
Rajandran R
1 min read

Introduction to QuantZilla 2.0

QuantZilla is a 75+ hours of immersive coding mentor-ship program on designing trading systems, converting trading ideas into indicators and trading strategies, automating the...
Rajandran R
4 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