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)

Algomojo Autocancellation of Limit Orders After N seconds

3 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 using Algomojo Platform. Let’s 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.

Supported Brokers – All Algomojo Supported Brokers

The below-mentioned code is just a prototype and for educational purposes 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
//Date : 18-Feb-2023

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

iPlaceOrder = ParamTrigger("PlaceOrder","PRESS");
iCancelOrder = ParamTrigger("CancelOrder","PRESS");
PositionBook = false; //ParamTrigger("PositionBook","PRESS");
global response;

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

_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","xxxxxxxxxxxxxxxxxx"); //Enter your API key here
apisecret = ParamStr("secretkey","xxxxxxxxxxxxxxxxxx"); //Enter your API secret key here

_SECTION_END();

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


_SECTION_BEGIN("Algomojo - Order Controls");

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

exchange = ParamList("Exchange","NSE|NFO|BSE|MCX",0); 
symbol = ParamStr("Trading Symbol","BHEL-EQ");
product = ParamList("Product","CNC|MIS|NRML",1);

pricetype = ParamList("Price Type","LIMIT|SL-M|SL",0);
quantity = Param("Quantity",1,1,100000,1);
price = Param("Limit Price",0,1,100000,1);
trigger_price = Param("Trigger Price",0,1,100000,1);
disclosed_quantity = 0;
amo = "NO";
splitorder = ParamList("To Split Orders","NO|YES",0);
split_quantity = Param("Split Quantity",500,1,100000,1);
sectocancel = Param("Sec to Cancel LMT order", 10, 3, 60,1);
VoiceAlert = ParamList("Voice Alert","Disable|Enable",1);


static_name_ = Name()+GetChartID()+interval(2)+strategy;
//Get the Order No

function getorderno(resp)
{

orderno = "";


orderno = StrExtract(resp,2,'{');
orderno = StrExtract(orderno,1,',');
orderno = StrExtract(orderno,1,':');
orderno = StrExtract(orderno,1,'"');

_TRACE("Order No is : "+orderno);

return orderno;

}



//PlaceOrder Sends Market Order Returns response on Succesful PlaceOrder

function PlaceOrder(action,orderqty) {

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data


api_data = "{ \"broker\": \""+broker+"\", 
            \"strategy\":\""+strategy+"\",
            \"exchange\":\""+exchange+"\",
            \"symbol\":\""+symbol+"\",
            \"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("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"PlaceOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

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

return resp;

}

function CancelOrder(orderid) 
{

//Creating the Trading Bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//Preparing the API data


api_data = "{ \"broker\": \""+broker+"\", \"order_id\":\""+orderid+"\"  }"; 

_TRACE("Broker API Request"+api_data);
resp=algomojo.AMDispatcher(apikey, apisecret,"CancelOrder",api_data,"am",ver);

_TRACE("API Response : "+resp);

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

return resp;

}





if(iPlaceOrder) 
{

response = PlaceOrder("BUY",quantity);
StaticVarSetText(static_name_+"NestOrderId", getorderno(response));


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

//Manual Cancellation
if(iCancelOrder)
{

CancelOrder(StaticVarGetText(static_name_+"NestOrderId"));
//OrderTime        = Now( 4 );
_TRACE("Cancelled Time : " +Now());
}

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

cancelorder(StaticVarGetText(static_name_+"NestOrderId"));
_TRACE("Cancelled Time : " +Now());
StaticVarSet(static_name_+"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)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

[Webinar] Understanding and Mitigating Curve Fitting in System Trading

"Understanding and Mitigating Curve Fitting in System Trading"! This dynamic session aims to equip novice to intermediate traders, quantitative analysts, and financial engineers with...
Rajandran R
1 min read

P-Signal Strategy Long Only Strategy – Amibroker AFL Code

This tutorial provides an overview of the P-Signal reversal strategy, a quantitative trading strategy that utilizes statistical parameters and error functions to generate probabilistic...
Rajandran R
2 min read

4 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