Coppock Indicator is one of the investing style indicators to check whether to stick to the trends or not in the short term. Hull smoothing is applied in the indicator which will eventually reduce the lag component in the trend.
This tutorial demonstrates how to send orders from Amibroker to Algomojo using Simple GUI buttons using modern amibroker tools and also using the older versions of Amibroker less than Amibroker 6.22.
Button Trading using Amibroker 6.22 Version or Higher
GUI buttons are newer functions in Amibroker 6.22 version onwards. This AFL code requires Amibroker 6.22 version or higher and access to Algomojo API + Trading Account with Algomojo Partner Broker
Amibroker AFL Code for Amibroker 6.22 Version or Higher
/*
Created By : Rajandran R (Founder - Marketcalls / Co-Founder Algomojo )
Created on : 01 Oct 2020.
Website : www.marketcalls.in / www.algomojo.com
*/
_SECTION_BEGIN("Button Trading - Algomojo");
//Notes
//This afl code works only on Amibroker 6.22 and higher version
//Requires Algomojo API to place orders from button
//Replace the API Key and API Secrety key with yours
Version(6.22);
RequestTimedRefresh(1, False); // Send orders even if Amibroker is minimized or Chart is not active
user_apikey = ParamStr("user_apikey","xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey = ParamStr("api_secretkey","xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
s_prdt_ali = ParamList("product alias","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",3); //Product Alias
Tsym = ParamStr("Trading Symbol","RELIANCE-EQ"); //Symbol Name
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); //Exchange
Ret = ParamList("Ret","DAY|IOC",0); //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0); // Pricetype
Pcode = ParamList("Product code","NRML|BO|CNC|CO|MIS",4); // Product Code
qty = Param("Quantity",40,0,100000,1); // Quantity
AMO = ParamList("AMO Order","NO|YES",0); //AMO Order
placeordertype = ParamList("Place Order On","Realtime|CandleCompletion",0); // Place Order Type
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
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);
}
}
resp = "";
function Buyorder()
{
algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
Say( "Order Placed" );
}
function Sellorder()
{
algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
Say( "Order Placed" );
}
function GuiButtonTrigger( ButtonName, x, y, width, Height ) {
/// @link http://forum.amibroker.com/t/guibuttons-for-everyone/1716/4
/// by beaver & fxshrat
/// version 1.1
global IDset;
local id, event, clickeven;
if( typeof( IDset ) == "undefined" ) IDset = 0;
//_TRACEF( "IDset before: %g", IDset );
GuiButton( ButtonName, ++IDset, x, y, width, height, 7 );
//_TRACEF( "IDset after: %g", IDset );
result = 0;
id = GuiGetEvent( 0, 0 );// receiving button id
event = GuiGetEvent( 0, 1 );// receiving notifyflag
clickevent = event == 1;
BuyClicked = id == 1 && clickevent;
SellClicked = id == 2 && clickevent;
if( BuyClicked AND StaticVarGet(Name()+GetChartID()+"buyAlgo")==0 )
{
BuyOrder();
result = 1;
StaticVarSet(Name()+GetChartID()+"buyAlgo",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"buyAlgo",0);
}
if( SellClicked AND StaticVarGet(Name()+GetChartID()+"sellAlgo")==0 )
{
SellOrder();
result = -1;
StaticVarSet(Name()+GetChartID()+"sellAlgo",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"sellAlgo",0);
}
return result;
}
BuyTrigger = GuiButtonTrigger( "Buy "+qty+" Shares", 0, 100, 200, 30 );
SellTrigger = GuiButtonTrigger( "Sell "+qty+" Shares", 200, 100, 200, 30 );
GuiSetColors( 1, 3, 2, colorRed, colorBlack, colorRed, colorWhite, colorBlue, colorYellow, colorRed, colorBlack, colorYellow );
Title = "Trigger: " + WriteIf(BuyTrigger==1,"Buy Triggered",WriteIf(BuyTrigger==-1,"Sell Triggered","0"));
SetChartOptions(0 , chartShowArrows | chartShowDates);
Plot(Close,"Candle", colorDefault, styleCandle);
_SECTION_END();
Button Trading AFL Module for Older Versions less than Amibroker v6.22
/*
Created By : Rajandran R(Founder - Marketcalls / Co-Founder Algomojo )
Created on : 01 Oct 2020.
Website : www.marketcalls.in / www.algomojo.com
*/
_SECTION_BEGIN("Button Trading - Algomojo For Old Amibroker Versions");
//Notes
//This afl code works only on Amibroker 6.22 and higher version
//Requires Algomojo API to place orders from button
//Replace the API Key and API Secret key with yours
Title = " ";
RequestTimedRefresh(1, False); // Send orders even if Amibroker is minimized or Chart is not active
user_apikey = ParamStr("user_apikey","xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey = ParamStr("api_secretkey","xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
s_prdt_ali = ParamList("product alias","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",3); //Product Alias
Tsym = ParamStr("Trading Symbol","RELIANCE-EQ"); //Symbol Name
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); //Exchange
Ret = ParamList("Ret","DAY|IOC",0); //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0); // Pricetype
Pcode = ParamList("Product code","NRML|BO|CNC|CO|MIS",4); // Product Code
qty = Param("Quantity",40,0,100000,1); // Quantity
AMO = ParamList("AMO Order","NO|YES",0); //AMO Order
placeordertype = ParamList("Place Order On","Realtime|CandleCompletion",0); // Place Order Type
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
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);
}
}
resp = "";
function Buyorder()
{
algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
Say( "Order Placed" );
}
function Sellorder()
{
algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
Say( "Order Placed" );
}
X0 = 20;
Y0 = 100;
X1 = 100;
LBClick = GetCursorMouseButtons() == 9; // Click
MouseX = Nz(GetCursorXPosition(1)); //
MouseY = Nz(GetCursorYPosition(1)); //
procedure DrawButton (Text, x1, y1, x2, y2, colorFrom, colorTo)
{
GfxSetOverlayMode(0);
GfxSelectFont("Verdana", 9, 700);
GfxSetBkMode(1);
GfxGradientRect(x1, y1, x2, y2, colorFrom, colorTo);
GfxDrawText(Text, x1, y1, x2, y2, 32|1|4|16);
}
GfxSetTextColor(colorWhite);
if(EnableAlgo == "Enable")
{
DrawButton("Buy", X0, Y0, X0+X1, Y0+30, colorGreen, colorGreen);
CursorInBuyButton = MouseX >= X0 AND MouseX <= X0+X1 AND MouseY >= Y0 AND MouseY <= Y0+30;
BuyButtonClick = CursorInBuyButton AND LBClick;
DrawButton("Sell", X0, Y0+40, X0+X1, Y0+70, colorRed, colorRed);
CursorInSellButton = MouseX >= X0 AND MouseX <= X0+X1 AND MouseY >= Y0+40 AND MouseY <= Y0+70;
SellButtonClick = CursorInSellButton AND LBClick;
if( BuyButtonClick AND StaticVarGet(Name()+GetChartID()+"buyAlgo")==0 )
{
BuyOrder();
StaticVarSet(Name()+GetChartID()+"buyAlgo",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"buyAlgo",0);
}
if( SellButtonClick AND StaticVarGet(Name()+GetChartID()+"sellAlgo")==0 )
{
SellOrder();
StaticVarSet(Name()+GetChartID()+"sellAlgo",1);
}
else
{
StaticVarSet(Name()+GetChartID()+"sellAlgo",0);
}
}
_SECTION_END();
_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = "");
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();
Algomojo offers state of art multi-broker execution modules for Algotrading where traders can manage their multiple accounts across brokers and can send simultaneous orders using Multiple Trading Platforms to Multiple Brokers at no additional fees.
What are the Trading Platforms Supported by Algomojo?
Currently, Algomojo Supports Amibroker, Metatrader 4, Metatrader 5, Excel, Tradingview, C-sharp Based Trading Platforms, Python Based Algo Trading Platform, and any trading platform that supports http-rest APIs
What is a Trading Bridge
Trading Bridge is a connectivity layer between your trading platform and your broker. At Algomojo the bridge is designed to adapt multiple broker and can send/modify/cancel orders simultaneously using the Multi Broker Bridge Execution module.
This tutorial explains how to build a button trading right from scratch and with a click of a button how you can send orders simultaneously to 4 brokers.
This tutorial explores the requirements for building a multi-broker execution module using Amibroker. Algomojo Multi-Broker Bridge is required to send orders to multiple brokers simultaneously.
Here are the Building Blocks of Multi Broker Execution Module
1)RequestTimedRefresh
RequestTimedRefresh(1, False); // Send orders even if Amibroker is minimized or Chart is not active
2)Get API Key and API Secret Key of Multiple Brokers with Short Code
. use the ParamStr function to receive the inputs of User API Key, User API secret key, Broker Short code. Broker Short code is used to identify which broker you are sending the order.
ab – Aliceblue , tj – Tradejini , zb – Zebu, en – enrich
Pass the Version of the API used. Currently, version 1.0 is used as the default version. In the future if Algomojo is getting upgraded to a higher version then this parameter will be helpful to migrate to newer versions without much of a coding change.
Algomojo API and Trading Bridges are designed with backward compatibility. This means even if the future if newer Algomojo API versions are released still the traders can make use of the older versions.
//Broker Authentication Parameters
user_apikey1 = ParamStr("user_apikey1","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey1 = ParamStr("api_secretkey1","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
user_apikey2 = ParamStr("user_apikey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey2 = ParamStr("api_secretkey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
user_apikey3 = ParamStr("user_apikey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey3 = ParamStr("api_secretkey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
user_apikey4 = ParamStr("user_apikey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API key here
api_secretkey4 = ParamStr("api_secretkey2","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
broker1 = ParamStr("Broker Code1","tj"); //Broker Short code for Tradejini - tj
broker2 = ParamStr("Broker Code2","ab"); //Broker Short code for Aliceblue - ab
broker3 = ParamStr("Broker Code3","zb"); //Broker Short code for Zebu - zb
broker4 = ParamStr("Broker Code4","en"); //Broker Short code for Enrich - en
ver = ParamStr("version","1.0"); //Enter your API secret key here
3)Trading Parameters
The trading parameter section explains the list of parameters users have to send to their broker for example Exchange Type(NSE, NFO, BSE, MCX), Trading Symbol, order type(MKT, LMT,SL-MKT, SL-LMT), Order Retention Type, Product Code(NRML,MIS,BO,CO), Order Quantity, Order Disclosed Quantity, AMO Orders..etc
//Trading Parameters
s_prdt_ali = ParamList("product alias","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",3); //Product Alias
Tsym = ParamStr("Trading Symbol","RELIANCE-EQ"); //Symbol Name
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); //Exchange
Ret = ParamList("Ret","DAY|IOC",0); //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0); // Pricetype
Pcode = ParamList("Product code","NRML|BO|CNC|CO|MIS",4); // Product Code
qty = Param("Quantity",40,0,100000,1); // Quantity
AMO = ParamList("AMO Order","NO|YES",0); //AMO Order
placeordertype = ParamList("Place Order On","Realtime|CandleCompletion",0); // Place Order Type
EnableAlgo = ParamList("Algo Mode","Disable|Enable|LongOnly|ShortOnly",0); // Algo Mode
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
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) at a single click.
Features of the Excel Bridge
1)Low latency execution 2)Multi Brokers Connectivity 3)Bulk Order Placement with a click of a button. 4)Track the status of the execution of Multiple Orders
If the Excel Sheet is not working then consider try disabling the protected view in Excel. You can choose to disable the Protected View feature within Excel so that you no longer receive the warning upon opening any Excel file that has been downloaded. In Excel go to File > Options > Trust Center > Trust Center Settings > Protected View, and then uncheck Enabled Protected View for files originating from the Internet.
Building a Bracket Order Strategy is the most demanded request we got from most of the algomojo traders. This article explains the list of the key information you need to consider while building a bracket order based intraday trading strategy.
What is Bracket Order?
Bracket Orders are mostly intraday orders with immediate target and stop-loss orders. It is also called OCO (one cancels another). Means if the target level is touched by the current market profile then automatically stop-loss order is canceled and if the stop level is touched then the target order will be canceled automatically,
1)Ensure Latest Multi Broker Bridge is used
If you are deploying bracket order strategies then ensure you are using the latest bridge (Multi-Broker Bridge) from the Algomojo Portal. Ensure Proper Broker Short Code and Version is configured.
Login to the Algomojo Portal ->goto Watchlist -> Click on the symbol info as shown in the details and get the Token No
For example token no for reliance is 2885. Let this can be used as input to your trading strategy. If your broker is using NEST API then Token ID is mandatory for sending bracket orders.
3)Ensure Quick AFL is turned off
Ensure the quick AFL is turned off as you are likely to plot the target and stoploss level on the charts. you can disable the quick afl using the setbarsrequired function as shown below
SetBarsRequired(-2,-2); //diable quick AFL
4)Getting the Input Parameters
Since the Bracket Order based execution belong to pure intraday trading strategy then the following things need to be kept in the mind while getting input from the user.
1)Get the Target and Stoploss (% based stop is recommended) 2)Get the Tick size (as the stop level and target level needs to be rounded off to the nearest tick size while sending those stop and target levels to the Bracket Order 3)Use Time Based Sessions to Enter and Exit and Squareoff time for your trades.
//////////////////////////////////////////////////////////////////////
// Trade Input Parameters //
//Exit Criteria
stops = Param("Stoploss %", 0.25,0,20,0.01);
target = Param("Target %", 0.5,0,20,0.01);
TickSz = Param("TickSize",0.05); //round off the stops and target to nearest tick size
sigstarttime = ParamTime("Sig Start Time", "10:00:00"); //no fresh position before signal start time
sigendtime = ParamTime("Sig End Time", "15:00:00"); //no fresh position after signal end time
sqofftime = ParamTime("Squareoff Time", "15:15:00"); //broker square off time
5)Enable Proper Logs
Ensure _Trace logs are enabled for proper trouble shooting and that will help traders to find the mistakes if any in the newly built code. And definitely helps traders to build a better trading system
6)Code only the Entry Conditionand Compute Target and Stoploss Value
If you are coding for bracket orders obviously one should care about the entry logical condition as the exit is taken care ofwith the price either hitting the target levels or stop-loss levels.
If long only condition then ensure the sell, cover,short is maintained with zero intitalization.
Sell = Short = Cover = 0;
If the strategy contains both long and short condition then maintain the exit signals (Sell and Cover as zero)
Sell = Cover = 0;
Here is the sample code logic with macd positive crossover stratey where only long condition is coded. And hence only Buy Entry logic is coded for the standard viable Buy and the Exit Signal is not assigned to the Sell Entry logic.
//////////////////////////////////////////////////////////////////////
// Configure your trading condition here //
longtradingcondition = Cross(MACD(), Signal());
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Trading Logic One Intraday Trade Per Day //
Buy = longtradingcondition AND TimeNum() >= sigstarttime AND TimeNum() < sigendtime;
Buy = Buy AND Sum( Buy, BarsSince( newDay) +1 ) <= 1; //consider only the first signal for the day
entryprice = ValueWhen(Buy AND Sum( Buy, BarsSince( newDay) +1 )==1,Ref(Open,1)); //entry price at the next bar open and at the first signal
buystops1 = (100-stops)/100 * entryprice;
buytarget1 = (100+target)/100 * entryprice;
buystops = TickSz * round( buystops1 / TickSz );
buytarget = TickSz * round( buytarget1 / TickSz );
iSell = TimeNum() >= sqofftime OR Cross(High,buytarget) OR Cross(buystops,Low);
//Remove Excessive Signals
Buy = ExRem(Buy,iSell);
iSell = ExRem(iSell,Buy);
//Non Repainting - Signals happens only after the close of the current
Buy = Ref(Buy,-1);
BuyPrice = Open;
iSellPrice = IIf(Cross(High,buytarget), buytarget, IIf( Cross(buystops,Low), buystops, Open));
buycontinue = Flip(Buy,iSell) OR isell; //look for continuation of trades
targethit = iSell AND Cross(High,buytarget);
stophit = iSell AND Cross(buystops,Low);
sqofftime = iSell AND TimeNum() >= sqofftime;
//This code place order only on Long Entry
Sell = Short = Cover = 0;
//////////////////////////////////////////////////////////////////////
7)Plot the Tick Adjusted Stoploss and Target
This helps in visualizing the target and stoplevels during intraday.
9)Ensure the Condition for Exit is displayed properly.
And Exit can happen for the following reasons
1)Target is hit 2)Stop is hit 3)Square off time is reached
Below code module is configured to get the display of Entry and Exit price values with Profit and Loss data point from that particular trade.
fntsize = 8;// font size
dist = 65;// y-offset
bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );
bkcolor = -1;// text background color, -1 means default color (transparent)
PlotTextSetFont( "", "ARIAL", fntsize, BarCount-1, 0, -1 );
pnl = ValueWhen(iSell,iSellPrice - entryprice);
for ( i = fvb; i <= lvb; i++ ) {
if( Buy[i] || iSell[i] ) {
buyvar = "\n@" + BuyPrice[i];
sellvar = "\n@" + iSellPrice[i]+"\nPnl= "+pnl[i];
if( Buy[i] ) PlotText( "Long Entry" + buyvar, i, L[i], colorGreen, bkcolor, -dist-2*fntsize );
if( targethit[i] ) PlotText( "Target Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
if( stophit[i] ) PlotText( "Stop Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
if( sqofftime[i] ) PlotText( "SQoff.Time Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
}
}
10)Bracket Order Execution Module
Make sure only relevant information is got from the user and according to your strategy make sure all the rest of the parameters are configured default.
Refer the Algomojo Documentation for more detailed information about the parameters to be passed for PlaceBracketOrder API
It is recommended to use the Bracket Order Target and Stoploss Calculation in Absolute mode. Use Ticks mode if you are an advanced user.
It is recommended to send the Target and Stoploss information only after adjusting to the nearest tick size. Else Bracket Order could throw error while sending orders.
_SECTION_BEGIN("Algomojo Bracket Order Module");
uid = ParamStr("uid ID","TS2499"); //Enter your Trading Account Login ID
user_apikey = ParamStr("user_apikey","xxxxxxxxxxxxxxxxxxxxxx); //Enter your API key here
api_secret = ParamStr("api_secret","xxxxxxxxxxxxxxxxxxxxxx"); //Enter your API secret key here
broker = ParamStr("Broker Code1","tj"); //Enter your Broker Short Code here
ver = ParamStr("version","1.0"); //Enter your API version here
s_prdt_ali = ParamList("s_prdt_ali","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",0); //Type of order
Tsym = ParamStr("Tsym","RELIANCE-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);
Price = 0; //ParamList("Price","0");
qty = Param("Quatity",1,0,10000,1);
discqty = "0"; //ParamList("discqty","0");
AMO = "NO"; //ParamList("AMO","NO|YES",0); //After market order
TokenNo = ParamStr("TokenNo","11184"); //Enter the token number of the symbol here. Check the Algomojo Watchlist symbol info to get the relevant symbol token no.
ltpOratp = "LTP"; //ParamList("ltpOratp","LTP|ATP",0);
SqrOffAbsOrticks = "Absolute"; //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 = buytarget-entryprice; //ParamStr("SqrOffvalue","1");
SLAbsOrticks = "Absolute"; //ParamList("SLAbsOrticks","Absolute|Ticks",0);
SLvalue = entryprice-buystops ; //ParamStr("SLvalue","30");
trailingSL = "N"; //ParamList("trailingSL","Y|N",0);
tSLticks = 1000; //ParamStr("tSLticks","100"); //Trailing SL value in ticks if user has opted to use trailingSL
placeordertype = "Realtime"; //ParamList("Place Order On","Realtime|CandleCompletion",0); // Place Order Type
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
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(placeordertype == "Realtime")
{
AlgoBuy = lastvalue(Ref(Buy,0));
AlgoSell = lastvalue(Ref(Sell,0));
AlgoShort = lastvalue(Ref(Short,0));
AlgoCover = lastvalue(Ref(Cover,0));
}
if(placeordertype == "CandleCompletion")
{
AlgoBuy = lastvalue(Ref(Buy,-1));
AlgoSell = lastvalue(Ref(Sell,-1));
AlgoShort = lastvalue(Ref(Short,-1));
AlgoCover = lastvalue(Ref(Cover,-1));
}
resp = "";
function bracketorder_buy(orderqty)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+discqty+"\",\"Price\":\""+Price+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
_TRACE(resp);
}
function bracketorder_sell(orderqty)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+discqty+"\",\"Price\":\""+Price+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
_TRACE(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 )
{
// reverse Long Entry
bracketorder_buy(qty*2);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if ((AlgoBuy != True OR AlgoCover != True))
{
StaticVarSet(static_name_+"buyCoverAlgo",0);
}
if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 )
{
// Long Entry
bracketorder_buy(qty);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 )
{
// Long Exit
bracketorder_sell(qty);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
if (AlgoShort==True AND AlgoSell==True AND StaticVarGet(static_name_+"ShortSellAlgo")==0 )
{
// reverse Short Entry
bracketorder_sell(2*qty);
StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Short and Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if ((AlgoShort != True OR AlgoSell != True))
{
StaticVarSet(static_name_+"ShortSellAlgo",0);
}
if (AlgoShort==True AND AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 )
{
// Short Entry
bracketorder_sell(qty);
StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_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 AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 )
{
// Short Exit
bracketorder_buy(qty);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoCover != True )
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
}
Here is the complete Bracket order module for Long Only Execution with Target and Stoploss. And Trade got limited to only one trade per day. i.e only one long entry and one long exit will be triggered per trading symbol for any given day.
Here is the complete Amibroker AFL code with Bracket Order Module
_SECTION_BEGIN("Price");
SetBarsRequired(-2,-2); //diable quick AFL
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();
_SECTION_BEGIN("Simple MACD Intraday Trading System");
//Buy on MACD, Signals on Positive Crossover and also trade should be executed between 10a.m and 3p.m
//Exit on MACD, Signals negative crossover and also square off the position if time is 3.15p.m
// identify new day
dn = DateNum();
newDay = dn != Ref( dn,-1);
//////////////////////////////////////////////////////////////////////
// Trade Input Parameters //
//Exit Criteria
stops = Param("Stoploss %", 0.25,0,20,0.01);
target = Param("Target %", 0.5,0,20,0.01);
TickSz = Param("TickSize",0.05); //round off the stops and target to nearest tick size
sigstarttime = ParamTime("Sig Start Time", "10:00:00"); //no fresh position before signal start time
sigendtime = ParamTime("Sig End Time", "15:00:00"); //no fresh position after signal end time
sqofftime = ParamTime("Squareoff Time", "15:15:00"); //broker square off time
//////////////////////////////////////////////////////////////////////
// Configure your trading condition here //
longtradingcondition = Cross(MACD(), Signal());
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Trading Logic One Intraday Trade Per Day //
Buy = longtradingcondition AND TimeNum() >= sigstarttime AND TimeNum() < sigendtime;
Buy = Buy AND Sum( Buy, BarsSince( newDay) +1 ) <= 1; //consider only the first signal for the day
entryprice = ValueWhen(Buy AND Sum( Buy, BarsSince( newDay) +1 )==1,Ref(Open,1)); //entry price at the next bar open and at the first signal
buystops1 = (100-stops)/100 * entryprice;
buytarget1 = (100+target)/100 * entryprice;
buystops = TickSz * round( buystops1 / TickSz );
buytarget = TickSz * round( buytarget1 / TickSz );
iSell = TimeNum() >= sqofftime OR Cross(High,buytarget) OR Cross(buystops,Low);
//Remove Excessive Signals
Buy = ExRem(Buy,iSell);
iSell = ExRem(iSell,Buy);
//Non Repainting - Signals happens only after the close of the current
Buy = Ref(Buy,-1);
BuyPrice = Open;
iSellPrice = IIf(Cross(High,buytarget), buytarget, IIf( Cross(buystops,Low), buystops, Open));
buycontinue = Flip(Buy,iSell) OR isell; //look for continuation of trades
targethit = iSell AND Cross(High,buytarget);
stophit = iSell AND Cross(buystops,Low);
sqofftime = iSell AND TimeNum() >= sqofftime;
//This code place order only on Long Entry
Sell = Short = Cover = 0;
//////////////////////////////////////////////////////////////////////
Plot(IIf(buycontinue,buystops,Null),"Stops",colorRed);
Plot(IIf(buycontinue,buytarget,Null),"Target",colorgreen);
/* Plot Buy and Sell Signal Arrows */
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(iSell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(iSell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(iSell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
SetPositionSize(1*RoundLotSize,spsShares);
fntsize = 8;// font size
dist = 65;// y-offset
bi = Barindex();
fvb = FirstVisiblevalue( bi );
lvb = LastVisiblevalue( bi );
bkcolor = -1;// text background color, -1 means default color (transparent)
PlotTextSetFont( "", "ARIAL", fntsize, BarCount-1, 0, -1 );
pnl = ValueWhen(iSell,iSellPrice - entryprice);
for ( i = fvb; i <= lvb; i++ ) {
if( Buy[i] || iSell[i] ) {
buyvar = "\n@" + BuyPrice[i];
sellvar = "\n@" + iSellPrice[i]+"\nPnl= "+pnl[i];
if( Buy[i] ) PlotText( "Long Entry" + buyvar, i, L[i], colorGreen, bkcolor, -dist-2*fntsize );
if( targethit[i] ) PlotText( "Target Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
if( stophit[i] ) PlotText( "Stop Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
if( sqofftime[i] ) PlotText( "SQoff.Time Hit" + sellvar, i, H[i], colorRed, bkcolor, dist+4.5*fntsize );
}
}
_SECTION_END();
_SECTION_BEGIN("Algomojo Bracket Order Module");
uid = ParamStr("uid ID","TS2499"); //Enter your Trading Account Login ID
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","a256707821d7b97988eef6b90a230e35"); //Enter your API secret key here
broker = ParamStr("Broker Code1","tj"); //Enter your Broker Short Code here
ver = ParamStr("version","1.0"); //Enter your API version here
s_prdt_ali = ParamList("s_prdt_ali","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",0); //Type of order
Tsym = ParamStr("Tsym","RELIANCE-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);
Price = 0; //ParamList("Price","0");
qty = Param("Quatity",1,0,10000,1);
discqty = "0"; //ParamList("discqty","0");
AMO = "NO"; //ParamList("AMO","NO|YES",0); //After market order
TokenNo = ParamStr("TokenNo","11184"); //Enter the token number of the symbol here. Check the Algomojo Watchlist symbol info to get the relevant symbol token no.
ltpOratp = "LTP"; //ParamList("ltpOratp","LTP|ATP",0);
SqrOffAbsOrticks = "Absolute"; //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 = buytarget-entryprice; //ParamStr("SqrOffvalue","1");
SLAbsOrticks = "Absolute"; //ParamList("SLAbsOrticks","Absolute|Ticks",0);
SLvalue = entryprice-buystops ; //ParamStr("SLvalue","30");
trailingSL = "N"; //ParamList("trailingSL","Y|N",0);
tSLticks = 1000; //ParamStr("tSLticks","100"); //Trailing SL value in ticks if user has opted to use trailingSL
placeordertype = "Realtime"; //ParamList("Place Order On","Realtime|CandleCompletion",0); // Place Order Type
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
stgy_name = ParamStr("Strategy Name","Test Strategy Chart"); // Strategy Name
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
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(placeordertype == "Realtime")
{
AlgoBuy = lastvalue(Ref(Buy,0));
AlgoSell = lastvalue(Ref(Sell,0));
AlgoShort = lastvalue(Ref(Short,0));
AlgoCover = lastvalue(Ref(Cover,0));
}
if(placeordertype == "CandleCompletion")
{
AlgoBuy = lastvalue(Ref(Buy,-1));
AlgoSell = lastvalue(Ref(Sell,-1));
AlgoShort = lastvalue(Ref(Short,-1));
AlgoCover = lastvalue(Ref(Cover,-1));
}
resp = "";
function bracketorder_buy(orderqty)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+discqty+"\",\"Price\":\""+Price+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
_TRACE(resp);
}
function bracketorder_sell(orderqty)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"TokenNo\":\""+TokenNo+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+discqty+"\",\"Price\":\""+Price+"\",\"ltpOratp\":\""+ltpOratp+"\",\"SqrOffAbsOrticks\":\""+SqrOffAbsOrticks+"\",\"SqrOffvalue\":\""+SqrOffvalue+"\",\"SLAbsOrticks\":\""+SLAbsOrticks+"\",\"SLvalue\":\""+SLvalue+"\",\"trailingSL\":\""+trailingSL+"\",\"tSLticks\":\""+tSLticks+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceBOOrder",api_data,broker,ver);
_TRACE(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 )
{
// reverse Long Entry
bracketorder_buy(qty*2);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if ((AlgoBuy != True OR AlgoCover != True))
{
StaticVarSet(static_name_+"buyCoverAlgo",0);
}
if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 )
{
// Long Entry
bracketorder_buy(qty);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 )
{
// Long Exit
bracketorder_sell(qty);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
if (AlgoShort==True AND AlgoSell==True AND StaticVarGet(static_name_+"ShortSellAlgo")==0 )
{
// reverse Short Entry
bracketorder_sell(2*qty);
StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty*2 +" Signal : Short and Sell Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if ((AlgoShort != True OR AlgoSell != True))
{
StaticVarSet(static_name_+"ShortSellAlgo",0);
}
if (AlgoShort==True AND AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 )
{
// Short Entry
bracketorder_sell(qty);
StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_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 AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 )
{
// Short Exit
bracketorder_buy(qty);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
_TRACE("Strategy : "+ stgy_name +"AlgoStatus : "+ EnableAlgo +"Chart Symbol : "+ Name() +" Trading Symbol : "+ Tsym +" Quantity : "+ qty +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" Response : "+ resp +" ChardId : "+ GetChartID() + " Latest Price : "+LastValue(C));
}
else if (AlgoCover != True )
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
}
Presenting a functional python wrapper for algomojo trading api. Algomojo is a multi broker python library for the Algomojo Free API + Free Algo Trading Platform . It allows rapid trading algo development easily, with support for both REST-API interfaces.
Basic Features of Python Trading API
Execute Orders in Realtime
Single Client Execution Orders
Multi-Client Execution of Orders
Multi-Broker Execution of Orders
Place ATM/ITM/OTM Option Orders
Modify/Cancel Orders
Retrieve Orderbook
Retrieve Order History
Retrieve Open Positions
Square off Open Positions
Access Fund/Margin Details and many more functionalities.
It is highly recommended to use Python 3.x versions
How to Send Orders using Algomojo Python Library?
Once the Python Library is installed the next step is to import the python library using the import command and set the api_key and api_secret key with broker shortcode in your python program.
How to Send Bulk Orders using Algomojo
Here is the Jupyter notebook implementation of Transmitting Multiple Orders to Multiple Brokers. Sample code is provided for sending Bulk Market Orders and Bulk Bracket Orders
How to Send ATM/ITM/OTM Option Orders
How to Cancel/Modify Orders using Algomojo
Square off Open Positions
How to Retrieve Orderbook, Position Book, Order History
Google Colab also known as Google Colaboratory is a product from Google Research which allows user to run their python code from their browser with no installation setup.
Google Co-lab provides learners, researchers & data scientists a hosted Jupyter notebook service providing free access to computing resources including GPUs. Colab is a Python development environment that runs in the browser using Google Cloud.
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.
Colab allows you to use and share Jupyter notebooks with others without having to download, install, or run anything.
Colab notebooks are stored in Google Drive, or can be loaded from GitHub. Colab notebooks can be shared just as you would with Google Docs or Sheets
All Colab notebooks are stored in the open-source Jupyter notebook format ( .ipynb).
Code is executed in a virtual machine private to your account. Virtual machines are deleted when idle for a while, and have a maximum lifetime enforced by the Colab service.
Google also provides Colab Pro at 9.99 USD per month. Users of Google Colab pro will get priority access to the fastest GPUs (Nividia T4 and P100 GPUs) and free users of Google Colab gets access to K80s. It is to be noted that usage limits are much lower in the free version compared to the pro version.
With Colab Pro your notebooks can stay connected for up to 24 hours and whereas in the free version notebooks can stay connected up to 12 hours.
Quantzilla is 75+ hours of code mentoring program designed for noncoders who want to learn the coding program right from designing indicators, scanners, trading systems, trading dashboards, trading alerts and even automating their own trades.
What you will be Learning?
Learning How to Code using Amibroker. Learn to code quantitative trading systems, Testing those strategies, debugging techniques, optimizing the trading strategies and even validating and automating those strategies.
What are the Pre-Skills required for this Program?
Fair knowledge on Futures and Option Knowledge and Basic Technical Knowledge is a requisite with very good internet connectivity, mike and speakers.
Will I get the recorded version of the session?
Yes
Iam already a programmer does this course suits me?
If you are already a programmer then it will be an added advantage. However, the course will be taught right from scratch spending 3 hours every day and the course is primarily focused on non-coders who are traders/investors who want to learn coding in amibroker.
When does the course starts?
Course starts on November 23,2020 | 06.00 – 09.00 PM IST
When I will get a Course Graduation Certificate?
Participants have to go through both live sessions and the recorded sessions to earn their Course Graduation Certificate?
What are the Access I will be getting along with the course?
1)Lifetime access to Slack Community 2)Lifetime access to live community webinars 3)Complimentary access to TradeStudio Amibroker Plugin 4)Access to Presentation Materials and AFL Codes 5)Access to Recorded Session (Current and Previous Quantzilla sessions total covering 150+ hours of learning content)
If there are preview webinar where I get to know more about the program?
This tutorial helps you to convert your Metatrader 4 expert advisor to send automated orders to the Algomojo Platform. Currently, Algomojo supported brokers are Aliceblue, Enrich, Tradejini, Zebu are the partner brokers.
This Video tutorial is divided into two parts
1)Installing the Algmojo Multi Platform – Multi Broker Bridge 2)Configuring the Sample MT4 Expert advisor to send automated orders to Algomojo connected brokers (Aliceblue, Tradejini, Zebu, Enrich)
Installing the Algmojo Multi Platform – Multi Broker Bridge
Configuring the Sample MT4 Expert Advisor
MT4 Algomojo Modules to Send Automated Orders
//Algomojo Autotrading Modules
input string user_apikey = "xxxxxxxxxxxxxxxxxxxxxx"; //Enter your API key here
input string api_secretkey = "xxxxxxxxxxxxxxxxxxxxxx"; //Enter your API secret key here
input string s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
input string Tsym = "NIFTY20NOVFUT"; //Symbol Name
input string exch = "NFO"; //Exchange
input string Ret = "DAY"; //Retention
input string prctyp = "MKT"; // Pricetype
input string Pcode = "MIS"; // Product Code
input int qty = 150; // Quantity
input string AMO = "NO"; //AMO Order
input string stgy_name = "Metatrader Strategy"; // Strategy Name
input string broker = "ab"; //Broker Short code ab - aliceblue, tj- tradejini, zb - zebu , en - enrich
input string ver = "1.0"; //API Version
string response;
string api_data;
#import "AMMT4BRIDGE.dll"
string AMDispatcher(string api_key, string api_secret, string api_name, string api_data, string br_code, string version);
#import
Algomojo Buy (Double the quantity) to reverse your position
//Algomojo Place Buy Order
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"B"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty*2+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
response=AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);
Print("api : " ,api_data);
Print("Algomojo Buy Order response : " ,response);
Algomojo Sell (Double the quantity) to reverse your position
//Algomojo Place Sell Order
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty*2+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
response=AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);
Print("api : " ,api_data);
Print("Algomojo Sell Order response : " ,response);
Algomojo offers Free API + Free Trading Platform to algomojo users to Place, Modify, Cancel Orders. Currently, Algomojo API is free for the users who are opening a trading account with Algomojo Partner Brokers. Free API platform + Free Algo Trading platform is offered with no upfront fees, no minimum turnover, no special terms and conditions, no clauses, no strings attached.
What exactly is an API?
API stands for Application Programming Interface (API). Algomojo offers http-rest API and it basically a communication layer to Authenticate/transmit/receive information from your broker server and can be used to submit orders/cancel orders/modify orders to the broker’s server programmatically. You can use the API as a communicating layer between your trading software (Amibroker, Metatrader, Ninjatrader, Tradingview, Excel… etc
You can refer the Algomojo Documentation here for more detailed API functions & instructions.
So use Algomojo API it requires you to register for an API key & API secret key to communicate with your broker server. In order to get the API key you can log into Algomojo with your 2FA trading account login credentials and go to My API section and generate your API key and API secret key.
What is the Overall Cost Involved in Algomojo?
Traders opening a trading account via Algomojo with our partner brokers will be enjoying Free API + Free Platform Fee under both Discount Broking (Rs20 per order) / Percentage Based Broking Model (0.01%) or whatever the broking plan our partner broker offers).
Here are the List of Cost Involved while deploying Algos
1)Trading API Cost: Free (For Algomojo Account Opening Clients) 2)Algomojo Platform Fee: Free (For Algomojo Account Opening Clients) 3)Datafeed Cost: Optional 4)Data API Cost: Optional 4)Strategy Cost: Both Free Strategy and Proprietary Trading Strategies Available (Optional). Traders can deploy their own Trading Strategies 5)Supportive Platforms: Amibroker, Metatrader, Tradingview, Excel, C#, Python, Any Platforms that Supports Rest-HTTP APIs 6)Virtual Private Servers: Optional 7)Broking Charges: All F&O and equity trades would continue to be charged at Rs 20 or 0.01% according to your broking plan with our partner Broker and there are no restrictions on choosing on your broking plan with partner broker. Irrespective of the broking plan Algomojo client will enjoy Unlimited & Lifetime free access to Trading API and Algomojo Platform. 8)End to End Integration/Chat Support: Free.
Algomojo Provides data products for NSE Cash, NSE Futures, MCX Futures & NSE Currencies, and currently tied up with Authorized data vendors GlobalDatafeeds & Truedata to offer data & data API products to its customers.
What is the Pricing for Non-Algomojo Clients?
Currently, Non-Algomojo clients who wants to onboard Algomojo Platform with their existing broking account but not mapped under Algomojo will avail free Algomojo API access however there will be a platform fee of Rs 2000/ month or Rs12000/year will be charged and that platform fee will be completely waived off for those taking Tradestudio Subscription / Directly opening a Trading account under Algomojo.
7 Days of Free Trial is available for Non-Algomojo clients to test drive before paying Algomojo Platform Subscription fee.
Trading Terminal Access is totally free for Non-Algomojo Clients to send orders manually/retrieving the orderbook/tradebook/open positions/watchlists from Algomojo to their broker account.
What are the Type of Orders Supported at Algomojo?
All types of orders are supported at Algomojo (Market Order, Limit Order, SL-Limit Order SL-MKT order, Bracket Order, Cover Order, AMO orders).
Algomojo also supports rule based ATM, ITM, OTM Option Orders
Algomojo supports Order Placement, Order Modification, Order Execution, and Retrieval of Orderbook, Trade Book, Order History & Open Positions via API.
Is the Web-Based Bridge Slower than the Exe Based Bridge?
Nope. Both use Rest API as a communication layer to transmit or receive information from the broker server. The latency of execution mostly depends upon the client’s internet speed and Brokers’ server responsiveness. In another article will look into this information in detail. However, it is a myth that Web-Based Bridge is slower compared to Exe based Bridge. In-fact web-based bridge has more ease of use and no up-gradation/installation/maintenance is required from the client’s side.
If in case you are are having any queries always you can send a mail to support@algomojo.com
Postman is an API testing tool that started in 2012 as a side project by Abhinav Asthana to simplify API workflow in testing and development. If you are a developer who wants to test and deploy REST API-based algo trading solutions then postman comes in handy without the hassle of writing, not even a single line of code just to test an API’s functionality.
In Algomojo we use Postman a lot to test and deploy robust API solutions for algotrading. Here is a video tutorial that explains how to use Postman to test Algomojo API to send orders and retrieve the order book.
Where to Download Postman?
You can goto www.postman.com/downloads to download the postman application. currently postman supports web based version and desktop application for both Windows and Mac. Install the application in your desktop.
Working with Algomojo API – Get Requests
Currently all the APIs supported by Algomojo are POST Requests
What is a POST Request?
POST requests are used to send data to the Algomojo API server to send orders, modify/cancel orders, or to retrieve the order book/position book details. The data sent to the server is stored in the request body of the HTTP request. In case of Algomojo API the request body needs to be send in json format.
I am very much excited to announce the 5th Edition of Converge 2020. This time converge 2020 comes with 5 Days of Virtual Market Profile & Orderflow conference to learn from your desk at your place.
We are doing preview webinars to make traders understand some of the basic concepts before attending the Converge 2020 session. If in case you are curious about attending Converge 2020 then you can consider attending preview webinars.
Retail Vs Institutional Order Flow 28 Nov Saturday 5:00pm-6:00pm – Rajandran —————————————– Live Market Analysis Using Market profile and VSA 03 Dec Thu 10:00am-11am – Dean ——————————————- Deep Market Insight Using Market Profile and VSA 05 Dec Thu 5:00pm-6:00pm – Dean ——————————————– Beginners Guide to Orderflow and Price Action Strategies 10 Dec Thursday 5:00pm-6:00pm – Rajandran
The retail and Institutional Traders landscape is getting highly dynamic, increasingly competitive, and challenging day by day. The trading methods we use now in our day to day trading lifestyle had changed dramatically in recent years. There is a constant need to look out for the edge, hunt for new ideas & strategies to remain healthy and solvent in this trading field.
Converge 2020 is a virtual conference, typically five days long, which offers traders a powerful learning environment, unparalleled creative ideas, and access to recorded webinars.
Along with me, Mr. Dean (Aniruddha) will be talking on topics like Market Profile & VSA
What Will I Be Talking About?
I’ll be talking about my experience with order flow based studies and trading strategies on orderflow. And Pre Conference sessions will be conducting basic order flow sessions and a comprehensive explanation on Orderflow trading strategies for scalping and intraday trading.
If you haven’t already signed up, you can still get tickets from the converge site.
One can use VBscript inside excelsheet to create Macros to automate their trading ideas.
Getting the Algomojo API Key
Before Applying the code log into your Algomojo Account -> Go My API section and get the api key and api secret key and replace the API key and API secret key as mentioned in the code below
Here is the sample VBScript Macro which is connected to the Excel sheet Place Order Button to send Automated Orders on the click of the Button.
Sub Algomojo()
Dim apikey As String
Dim apisecret As String
Dim Broker As String
Dim Version As String
Dim stgy As String
Dim ClientID As String
Dim Symbol As String
Dim Exchange As String
Dim Ttranstype As String
Dim prctyp As String
Dim qty As String
Dim Price As String
Dim TrigPrice As String
Dim Pcode As String
Dim response As String
apikey = "xxxxxxxxxxxxxxxxxxxxxxx"
apisecret = "xxxxxxxxxxxxxxxxxxxxxxx"
Version = "1.0"
stgy = "Excel"
Broker = Cells(5, "B").Value
ClientID = Cells(5, "C").Value
Exchange = Cells(5, "D").Value
Symbol = Cells(5, "E").Value
Ttranstype = Cells(5, "F").Value
prctyp = Cells(5, "G").Value
qty = Cells(5, "H").Value
Price = Cells(5, "I").Value
TrigPrice = Cells(5, "J").Value
Pcode = Cells(5, "K").Value
response = PlaceOrder(apikey, apisecret, Broker, Version, stgy, ClientID, Symbol, Exchange, Ttranstype, prctyp, qty, Price, TrigPrice, Pcode)
Cells(9, "C") = response
MsgBox ("Order Placed")
End Sub
Public Function PlaceOrder(user_apikey As String, api_secret As String, Broker As String, Version As String, stgy_name As String, ClntID As String, Tsym As String, exch As String, Ttranstype As String, prctyp As String, qty As String, Price As String, TrigPrice As String, Pcode As String) As String
Dim InTD As String
Dim sOutput As String
Dim s_prdt_ali As String
Dim Ret As String
Dim discqty As String
Dim MktPro As String
Dim AMO As String
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML"
Ret = "DAY"
discqty = "0"
MktPro = "NA"
If (TrigPrice = "") Then
TrigPrice = "0"
End If
AMO = "NO"
InTD = "{""" _
& "strg_name" & """:""" & stgy_name & """,""" _
& "s_prdt_ali" & """:""" & s_prdt_ali & """,""" & "Tsym" & """:""" & Tsym & """,""" _
& "exch" & """:""" & exch & """,""" & "Ttranstype" & """:""" & Ttranstype & """,""" _
& "Ret" & """:""" & Ret & """,""" & "prctyp" & """:""" & prctyp & """,""" _
& "qty" & """:""" & qty & """,""" & "discqty" & """:""" & discqty & """,""" _
& "MktPro" & """:""" & MktPro & """,""" & "Price" & """:""" & Price & """,""" _
& "TrigPrice" & """:""" & TrigPrice & """,""" & "Pcode" & """:""" & Pcode & """,""" _
& "AMO" & """:""" & AMO & """}"
PlaceOrder = AMConnect(user_apikey, api_secret, Broker, Version, "PlaceOrder", InTD)
End Function
Private Function AMConnect(api_key As String, api_secret As String, Broker As String, Version As String, api_name As String, InTD As String) As String
Dim objHTTP As Object
Dim result As String
Dim postdate As String
Dim BrkPrefix As String
Dim BaseURL As String
BaseURL = "https://" & LCase(Broker) & "api.algomojo.com/" & Version & "/"
postdata = "{""" & "api_key" & """:""" & api_key & """,""" _
& "api_secret" & """:""" & api_secret & """,""" _
& "data" & """:" & InTD & "}"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
Url = BaseURL & api_name
objHTTP.Open "POST", Url, False
objHTTP.setRequestHeader "Content-type", "application/json"
objHTTP.send (postdata)
result = objHTTP.responseText
Set objHTTP = Nothing
AMConnect = result
End Function
If the Excel Sheet is not working then consider trying disabling the protected view in Excel. You can choose to disable the Protected View feature within Excel so that you no longer receive the warning upon opening any Excel file that has been downloaded. In Excel go to File > Options > Trust Center > Trust Center Settings > Protected View, and then uncheck Enabled Protected View for files originating from the Internet.
For Creating more functionalities like Placing Bracket Orders, Placing Multiple Orders and more visit Algomojo API documentation
Here is a video tutorial and button trading expert advisor code for MetaTrader 4 platform. You can use the expert advisor to send automated orders to the Algomojo Platform with just the click of the button.
How to Send Automated Orders to Metatrader 4 Platform
You have to follow the 6 steps to send automated orders
Step 1 : Make sure you have a trading account with Algomojo Partner Broker. If not get one. Login to your Algomojo Partner Broker Account. Currently Algmojo supports Aliceblue, Tradejini, Zebu & Enrich.
Step 3: Download the Algomojo Expert Advisor and Copy the Expert Advisor File AlgomojoButtons.ex4
Step 4: Open your Metatader 4 Platform and Goto File ->Open Data Folder->Open MQL4/Experts Folder->Paste the AlgomojoButtons.ex4 as shown below
Step 5:Configuring the Algomojo Expert Advisor
i)Drag and drop the Expert Advisor to the charts ii)Enable Allow DLL Imports from the common menu of Expert Advisor Properties
iii)Set the API key and API Secret key that you receive from the Algomojo My API section . Now set the appropriate exchange (NSE,NFO, MCX..etc) and select the appropriate symbol, order details , enter the broker shortcode and API version and Enable_Algo = True and Press the OK Button
Step 6 : Press the Buy or Sell Button to send Automated orders from Metatrader 4 to MQL4 trading terminal and check out the same in the expert advisor log section
Watch this video tutorial to configure AlgmojoButtons Expert Advisor and Send Automated Orders to your broker account.
In case if you need any assistance kindly check with Algomojo Tech support team or send a email at support@algomojo.com
Download Algomojo MQL4 code
//+------------------------------------------------------------------+
//| AlgomojoButtons.mq4 |
//| Copyright 2020, Marketcalls Financial Services Pvt Ltd |
//| https://www.marketcalls.in |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, Marketcalls Financial Services Pvt Ltd"
#property link "https://www.marketcalls.in"
#property version "1.00"
#property strict
//Algomojo Autotrading Modules
input string user_apikey = "xxxxxxxxxxxxxxxxxxxxxx"; //Enter your API key here
input string api_secretkey = "xxxxxxxxxxxxxxxxxxxxxx"; //Enter your API secret key here
input string s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
input string Tsym = "NIFTY20DECFUT"; //Symbol Name
input string exch = "NFO"; //Exchange
input string Ret = "DAY"; //Retention
input string prctyp = "MKT"; // Pricetype
input string Pcode = "MIS"; // Product Code
input int qty = 150; // Quantity
input string AMO = "NO"; //AMO Order
input string stgy_name = "Metatrader Strategy"; // Strategy Name
input string broker = "ab"; //Broker Short code ab - aliceblue, tj- tradejini, zb - zebu , en - enrich
input string ver = "1.0"; //API Version
string response;
string api_data;
#import "AMMT4BRIDGE.dll"
string AMDispatcher(string api_key, string api_secret, string api_name, string api_data, string br_code, string version);
#import
extern bool Enable_Algo = false;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//if(IsTesting())
{
string name;
string heading[2]={"Buy","Sell"};
int xc=5;
int yc=30;
int xsize = 750;
int ysize = 150;
for(int i=0;i<2;i++)
{
name=heading[i];
ObjectCreate(0,name,OBJ_BUTTON,0,0,0);
ObjectSetText(name,name,12,"Arial",clrWhite);
ObjectSetInteger(0,name,OBJPROP_XSIZE,xsize);
ObjectSetInteger(0,name,OBJPROP_XSIZE,ysize);
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,xc);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,yc);
ObjectSetInteger(0,name,OBJPROP_COLOR,clrWhite);
if(i==0)
{
ObjectSetInteger(0,name,OBJPROP_BGCOLOR,clrGreen);
}
if(i==1)
{
ObjectSetInteger(0,name,OBJPROP_BGCOLOR,clrTomato);
}
yc+=20;
}
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//Delete the Buttons
string ButtonName;
string heading[2]={"Buy","Sell"};
for(int i=0;i<2;i++)
{
ButtonName=heading[i];
ObjectDelete(ButtonName);
}
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
//| BuyOrder function |
//+------------------------------------------------------------------+
void BuyOrder()
{
//Algomojo Place Buy Order
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
response=AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);
Print("api : " ,api_data);
Print("Algomojo Sell Order response : " ,response);
}
//+------------------------------------------------------------------+
//| SellOrder function |
//+------------------------------------------------------------------+
void SellOrder()
{
//Algomojo Place Sell Order
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
response=AMDispatcher(user_apikey, api_secretkey,"PlaceOrder",api_data,broker,ver);
Print("api : " ,api_data);
Print("Algomojo Buy Order response : " ,response);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
if(id==CHARTEVENT_OBJECT_CLICK)
{
string name="Buy";
if(ObjectGetInteger(0,name,OBJPROP_STATE)==true)
{
if(Enable_Algo){
//Algomojo Place Buy Order - Double the Quantity
ObjectSetInteger(0,name,OBJPROP_STATE,false);
BuyOrder();
}
}
name="Sell";
if(ObjectGetInteger(0,name,OBJPROP_STATE)==true)
{
if(Enable_Algo){
//Algomojo Place Buy Order - Double the Quantity
SellOrder();
}
}
}
//---
}
You might think “Is it really possible to do send automated orders from Google Sheets? Are you crazy?” but hey thanks to Google Appscript which is an alternative to VBscript to automate your tasks in your Google Excel Sheets.
What is Google AppScript?
Apps Script lets you do more with Google Spreadsheets and with other Google Products, all on a modern JavaScript platform in the cloud. Build solutions to boost your collaboration and productivity.
You you access the Appscript Editor from Tools->Script Editor from your Google Spreadsheet.
Creating Button Controls
The Next Step is to Create the Datasheet that you want to transmit and PlaceOrder button to send transmit those orders to the Algomojo Platform as shown below.
Button Controls can be created by goto Insert Menu -> Drawings and create a Button Control with “PlaceOrder” as text in the button.
Writing the Google Appscript
Open the Script Editor and Paste the below appscript code and save the code as Algomojo Buttons.
Get the API Key and API Secret Key from Algomojo Platform and replace the apikey and apisecret key in the below code with yours.
function Algomojo() {
var apikey = "86cbef19e7e61ccee91e497690d5814e";
var apisecret = "8dbb8a1c91649810c82ccfc0ea9d715a";
var Version = "1.0";
var stgy = "Excel";
var Broker = SpreadsheetApp.getActiveSheet().getRange('B3').getValue();
var ClientID = SpreadsheetApp.getActiveSheet().getRange('C3').getValue();
var Exchange = SpreadsheetApp.getActiveSheet().getRange('D3').getValue();
var Symbol = SpreadsheetApp.getActiveSheet().getRange('E3').getValue();
var Ttranstype = SpreadsheetApp.getActiveSheet().getRange('F3').getValue();
var prctyp = SpreadsheetApp.getActiveSheet().getRange('G3').getValue();
var qty = SpreadsheetApp.getActiveSheet().getRange('H3').getValue();
var Price = SpreadsheetApp.getActiveSheet().getRange('I3').getValue();
var TrigPrice = SpreadsheetApp.getActiveSheet().getRange('J3').getValue();
var Pcode = SpreadsheetApp.getActiveSheet().getRange('K3').getValue();
var response = PlaceOrder(apikey, apisecret, Broker, Version, stgy, ClientID, Symbol, Exchange, Ttranstype, prctyp, qty, Price, TrigPrice, Pcode);
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange('C9').setValue(response);
}
function PlaceOrder(user_apikey, api_secret, Broker, Version, stgy_name, ClntID, Tsym, exch, Ttranstype, prctyp, qty, Price, TrigPrice, Pcode){
var s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
var Ret = "DAY";
var discqty = "0";
var MktPro = "NA";
if(TrigPrice == ""){
TrigPrice = "0";
}
var AMO = "NO";
var InTD = "{\""
+ "strg_name" + "\":\"" + stgy_name + "\",\""
+ "s_prdt_ali" + "\":\"" + s_prdt_ali + "\",\"" + "Tsym" + "\":\"" + Tsym + "\",\""
+ "exch" + "\":\"" + exch + "\",\"" + "Ttranstype" + "\":\"" + Ttranstype + "\",\""
+"Ret" + "\":\"" + Ret + "\",\"" + "prctyp" + "\":\"" + prctyp + "\",\""
+"qty" + "\":\"" + qty + "\",\"" + "discqty" + "\":\"" + discqty + "\",\""
+ "MktPro" + "\":\"" + MktPro + "\",\"" + "Price" + "\":\"" + Price + "\",\""
+ "TrigPrice" + "\":\"" + TrigPrice + "\",\"" + "Pcode" + "\":\"" + Pcode + "\",\""
+ "AMO" + "\":\"" + AMO + "\"}";
var result = AMConnect(user_apikey, api_secret, Broker, Version, "PlaceOrder", InTD);
return result;
}
function AMConnect(api_key, api_secret, Broker, Version, api_name, InTD){
var BaseURL = "https://" + Broker.toLowerCase() + "api.algomojo.com/" + Version + "/";
var postdata = "{\"" + "api_key" + "\":\"" + api_key + "\",\""
+ "api_secret" + "\":\"" + api_secret + "\",\""
+ "data" + "\":" + InTD + "}";
var Url = BaseURL + api_name;
var raw = postdata;
Logger.log(raw);
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : raw
};
var result = UrlFetchApp.fetch(Url, options);
return result.getContentText();
}
Run the code.gs with code execution set to Algomojo() function. There should not be any errors and you should be able to see the executions happening in your trading terminal.
Assinging the Button Controls to Google Appscript Function
1)Now right click over the button and click on the triple dots and select the Assign script option
2)Enter the Function Name as Algomojo in the Assign Script Popup Dialog box
Now come back to Google Spreadsheets and click on the Place Order button and check the orders got executed in the Algomojo Order Log section in realtime.
For sending a different type of orders in your Google Appscript kindly check with the latest algomojo API documentation
The possibilities of creating a Automated Trading task is endless creativity. Playaround with Google Appscript and if in case you are able to build something interesting with google appscript let us know here in the comment section.
This basic tutorial helps you to explore creating your own first trading system in Tradingview platform using pinescript programming language. If you are searching for how to create and backtesting your trading ideas then this is the first video tutorial that you have to start with.
Simple Trading Rules
Enter Long: Positive EMA Crossover of 20 and 50 Exit Long: Candle closes below 25 periods EMA
Enter Short: Negative EMA Crossover of 20 and 50 Exit Short: Candle Closes above 25 periods EMA
Video Tutorial on How to Create and Bactesting Tradingview Pinescript Programming
We are proud to partner with Upstox to provide Free API-based algotrading access to their trading clients who opens a trading account with Algomojo.
AlgoMojo is a trading technology platform that enables algorithmic traders to quickly deploy trading algorithms across multiple brokers. It provides the simplest API to build sophisticated trading strategies. It is designed to be used by developers, quants, and algorithmic traders.
Algomojo is a web-based automated trading platform built on the brokers API with a minimalistic design built by traders for the traders.
Algomojo comes with Integrated all-in-one solutions (API, free & proprietary Strategies, Datafeed, Virtual servers, and the end to end support at one single marketplace). It helps traders to simplify their Algo trading and makes life easier for the traders.
1. Amibroker 2. Metatrader 4 3. Metatrader 5 4. Excel, Google Spreadsheets 5. Python 5. Tradingview 5. C# based applications 6. Any custom programs that supports Rest API
How to Connect Upstox with Algomojo
1)Get the API from Upstox Team: If any Upstox user wants to avail of the services of Algomojo then they can send a mail (to support@upstox.com) for getting free access to API by providing the reference of Algomojo. Upstox will process the request and would create an app that will show up in developer.upstox.com
Note : Usage of the Free API will be reviewed periodically by upstox team every 6months. Based on the continuation of the usage upstox will grant further extended access.
Get the API Key and API secret key created by the upstox team from the developer portal.
2)Once you got the API Access then the next step is to log in to the developer portal and enter the redirect URI along with your client login id as shown below.
Traders opening a trading account via Algomojo with our partner brokers will be enjoying Free API + Free Platform Fee under both Discount Broking (Rs20 per order) / Percentage Based Broking Model (0.01%) or whatever the broking plan our partner broker offers).
Here are the List of Cost Involved while deploying Algos
1)Trading API Cost: Free (For Algomojo Account Opening Clients) 2)Algomojo Platform Fee: Free (For Algomojo Account Opening Clients) 3)Datafeed Cost: Optional 4)Data API Cost: Optional 4)Strategy Cost: Both Free Strategy and Proprietary Trading Strategies Available (Optional). Traders can deploy their own Trading Strategies 5)Supportive Platforms: Amibroker, Metatrader, Tradingview, Excel, C#, Python, Any Platforms that Supports Rest-HTTP APIs 6)Virtual Private Servers: Optional 7)Broking Charges: All F&O and equity trades would continue to be charged at Rs 20 or 0.01% according to your broking plan with our partner Broker and there are no restrictions on choosing on your broking plan with partner broker. Irrespective of the broking plan Algomojo client will enjoy Unlimited & Lifetime free access to Trading API and Algomojo Platform. 8)End to End Integration/Chat Support: Free.
Algomojo Provides data products for NSE Cash, NSE Futures, MCX Futures & NSE Currencies, and currently tied up with Authorized data vendors GlobalDatafeeds & Truedata to offer data & data API products to its customers.
What is the Pricing for Non-Algomojo Clients?
Currently, Non-Algomojo clients who wants to onboard Algomojo Platform with their existing broking account but not mapped under Algomojo will avail free Algomojo API access however there will be a platform fee of Rs 2000/ month or Rs12000/year will be charged and that platform fee will be completely waived off for those taking Tradestudio Subscription / Directly opening a Trading account under Algomojo.
7 Days of Free Trial is available for Non-Algomojo clients to test drive before paying Algomojo Platform Subscription fee.
Trading Terminal Access is totally free for Non-Algomojo Clients to send orders manually/retrieving the orderbook/tradebook/open positions/watchlists from Algomojo to their broker account.
Features of Algomojo
Watchlists
Supports lightweight watch-list with minimalistic design and easy to use interface to add symbols and multiple watchlists.
Dashboard to Track Funds, Positions, Orders, Holdings & MTM Profit/Loss
Manual Orders
One can place manual orders (Intraday,Delivery) and currently supports Limit Orders, Market Orders, Bracket Orders, Cover Orders.
AlgoMojo API
Algomojo comes with inbuilt API which also supports existing clients of partner broker with 7 days of free trial enabled by default.
Algomojo offers Free API + Free Trading Platform to algomojo users to Place, Modify, Cancel Orders. Currently, Algomojo API is free for the users who are opening a trading account with Algomojo Partner Brokers. Free API platform + Free Algo Trading platform is offered with no upfront fees, no minimum turnover, no special terms and conditions, no clauses, no strings attached.
Order Log
Order Log is provided to verify the timestamp and audit the difference between the executed trades and generated live signals in the trading software.
Note : Order log captures the trade execution in realtime and shows only orders which are sent via Automated Trading Platforms.
OrderBook : From the Orderbook one can get both the status(pending, executed, rejected) of manually punched orders and trading software-generated orders.
TradeBook : Tradebook shows executed orders.
Positions: Any open positions can be viewed in the positions section. One button square off is provided to close all the open positions and also positions can be closed on asymbol selection basis.
Positions also displays intraday and position MTM.
Holdings:
Demat account holdings can be viewed and managed under the holdings section.
Strategy Library
Algomojo also comes with a free & proprietary strategy library for the traders to take advantage of the market trend and momentum in the market.
Datafeed
Datafeed section provides users to subscribe for NSE Cash, NSE Futures, NSE Currencies and MCX Futures and Options.
Supports various charting platforms like Amibroker, Ninjatrader, Excel both desktop and server editions.
we partner with Both Globaldatafeeds & Truedata to distribute their products in our platform. 3 days of Datafeed Trial will be enabled to all the users of Algomojo to test run their strategies before live exection. To test drive datafeeds connect with the support team at support@algomojo.com or check with the Algomojo Chat support team.
Virtual Private Servers
VPS servers or Virtual Private Servers are the primary need for the algo traders who want 100% uptime with sufficient Internet and Power Backup. One can directly subscribe for windows VPS servers from the platform itself.
End to End Integration Support
One can get end to end integration support to configure, test & deploy trading strategies.
Following end to end support will be provided to the algomojo clients.
1)Integration of Algomojo Bridge for Autotrading. 2)Integration of Datafeed (Amibroker, Ninjatrader, Excel etc) 3)Integration of Windows VPS Servers. 3)Testing and Deploying the Trading Strategies.
And also in case, the trader needs a custom trading strategy to be coded in Amibroker/Metatrader/Tradingview then On-demand Freelancing support will be provided to onboard the client with their custom design strategies.
AlgoMojo API Documentation
AlgoMojo API documentation for Upstox is comprehensive to know about the various functionalities supported by the trading platform. It helps traders to build their own execution logic.
What are the Type of Orders Supported at Algomojo?
All types of orders are supported at Algomojo (Market Order, Limit Order, SL-Limit Order SL-MKT order, Bracket Order, Cover Order, AMO orders).
Algomojo also supports rule based ATM, ITM, OTM Option Orders
Algomojo supports Order Placement, Order Modification, Order Execution, and Retrieval of Orderbook, Trade Book, Order History & Open Positions via API.
Is the Web-Based Bridge Slower than the Exe Based Bridge?
Nope. Both use Rest API as a communication layer to transmit or receive information from the broker server. The latency of execution mostly depends upon the client’s internet speed and Brokers’ server responsiveness. In-fact web-based bridge has more ease of use and no up-gradation/installation/maintenance is required from the client’s side.
If in case you are are having any queries always you can send a mail to support@algomojo.com
When we talk about Hedging we are talking about minimizing the risk involved in the trade. In this webinar, you are going to learn effective techniques to reduce the directional risk in your trade setup when something goes wrong.
In this weekend webinar we are covering the concepts of hedging in details.
What is Covered?
What is Hedging?
How Hedging Works?
Understanding the Margin Regulations
Risk Management Techniques with Hedging
Date & Time: Dec 13, 2020 08:00 PM – 09.00 PM in India (IST)