This Introductory Session on Algomojo platform helps Upstox users to explore the full potential of Algomoj platform right from automating their trades in a Multi-Platform Environment.
If in case you are planning to Automated Trading using Platforms like Amibroker, Tradingview, Metatrader, Python, Excel sheet , C-sharp based platforms then this webinar is for you.
Date & Time : Dec 19, 2020 10:00 AM – 11:00 AM (IST)
What is Covered in the Webinar
How to Create your First Automated Trading with Amibroker & Tradingview Understanding Algomojo API How to Send Bracket & Cover Orders How to Send Multi Orders How to Send Option Orders (ATM, ITM, OTM) How to Send Orders from Metatrader Platform How to Send Orders from the Excel sheet and Spreadsheets
Kickstarting your market profile learning? then you cannot miss this webinar where you get to know the basic building blocks of Market Profile and learn how to use market profile properly and avoid common mistakes made by many entry-level traders.
Webinar Date & Time: Dec 19, 2020 08:00 PM – 09.00 PM in India (IST)
What is Covered in the Live Webinar?
1)How to Read Market Profile Charts? 2)How to use market profile for intraday & short term trading? 3)Why market profile should be in the trading arsenal for full-time traders? 4)How to discover your trading edge using a market profile? 5)Nifty and Bank Nifty Trading Analysis using Market Profile
This tutorial helps you to understand the options trading module and the requirements to set up and send and exit option orders from Amibroker in a systematic way. This coding framework provides the basic foundation to entry and exit option order from Amibroker for Algomojo Trading Platform
Understanding PlaceFOOptionsOrderAPI
PlaceFOOptionsOrder api is used to send ATM, ITM, OTM Options Order. Currently PlaceFOOptionsOrder is supported by brokers like Aliceblue,Tradejini,Zebu & Enrich.
Here is the sample request and response for PlaceFOOptionsOrder
For detailed information on Algomojo API’s visit the API Documentation section
one can use the offset to select the ATM, ITM,OTM Options.
In order to make the execution logic smoother and smarter following Execution Logic is preferred for Option Order Entry and Exit. One can modify the Execution Logic to their comfort. The below logic is just a prototype.
Execution Logic is coded only for
1) Long Call Option Entry, 2) Long Put Option Entry 3) Exit Long Call Option (Square off Based on the Qty from Position Book) 4) Exit Long Put Option (Square off Based on the Qty from Position Book)
Execution Logic for Placing Options Order
Execution Logic for Exiting Options Order
Setting up the Options Test Execution AFL File
1)Copy the AFL under the name Algomojo Options Test Module.afl and keep it under Amibroker\Formulas\Algomojo folder
#include < algomojooptions.afl >
_SECTION_BEGIN("Algomojo Options Test Module");
trigger = ParamTrigger("Place Option Order","PRESS");
longcall = ParamTrigger("Place Long Call Order","PRESS");
longput = ParamTrigger("Place Long Put Order","PRESS");
exitcall = ParamTrigger("Exit Call","PRESS");
exitput = ParamTrigger("Exit Put","PRESS");
spot_sym = ParamStr("spot_sym","NIFTY"); //Enter the symbol name here
expiry_dt = ParamStr("expiry_dt", "28JAN21");
strike_int = ParamStr("strike_int","50");
Ttranstype = ParamList("Transaction Type","B|S");
opt_type = ParamList("opt_type","CE|PE",0);
offset = ParamStr("Offset","0"); //No. of strikes away from ATM Strike
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
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")
{
SetChartBkColor(ColorBlend(colorGrey40,colorBlack));
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 == "Enable"){
if (trigger)
{
//Place Options Order
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,Ttranstype,opt_type,offset);
_TRACEF("\nExecuted Symbol :"+orderresponse);
}
if (longcall)
{
//Place Options Order
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
_TRACEF("\nExecuted Symbol :"+orderresponse);
}
if (longput)
{
//Place Options Order
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
_TRACEF("\nExecuted Symbol :"+orderresponse);
}
if (Exitcall)
{
//Place Options Order
sqoffstatus = squareoffoptions("CE");
_TRACEF("\nExit Call Response :"+sqoffstatus);
}
if (ExitPut)
{
sqoffstatus = squareoffoptions("PE");
_TRACEF("\nExit Put Response :"+sqoffstatus);
}
}
_SECTION_END();
_SECTION_BEGIN("Price");
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();
2)Copy the AFL under the name algomojooptions.afl under the path Amibroker\formulas\include folder
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 30/12/2020
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Options");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
qty = Param("Quatity",75,0,100000,1);
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 3; //3 seconds for providing delay after placing order
RequestTimedRefresh(1,False);
function getnestorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Trsym"))
{
Trsym = StrExtract(ohistory,1,':');
Trsym = StrTrim(Trsym,"\"");
}
}
}
}
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Status"))
{
orderstatus = StrExtract(ohistory,1,':');
orderstatus = StrTrim(orderstatus,"\"");
}
}
}
}
return orderstatus;
}//end function
function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
data = sym;
for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ofetch,"symbol_token"))
{
stoken = StrExtract(ofetch,1,':');
stoken = StrTrim(stoken,"\"");
}
}
}
return stoken;
}
function writetofile(filepath,ordno,symbol,ostatus)
{
result =0;
if(ostatus=="complete" OR ostatus=="rejected")
{
fh = fopen( filepath, "w"); //Filepath of csv file with symbols
if(fh)
{
fputs(ordno + ",", fh);
fputs(symbol + ",", fh);
fputs(ostatus+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
function placeoptionorder(spot_sym,expiry_dt,strike_int,Ttranstype,opt,off)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;
}
function getquantity(Tsym)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
//Initialization
flag = 0;
possym = "";
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
data = sym;
_TRACE(" Position Book : " +data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}
return posNetqty;
}
function squareoffoptions(opt)
{
ordno = "";
Symbol = "";
ostatus ="";
if(opt=="CE")
{
fpath = fpath+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+"AlgomojoPE.csv";
}
fh = fopen(fpath, "r");
if(fh)
{
read = fgets(fh);
ordno = StrTrim(StrExtract(read,0)," ");
Symbol = StrTrim(StrExtract(read,1)," ");
ostatus = StrTrim(StrExtract(read,2)," ");
fclose(fh);
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
if(ostatus=="complete" AND exitqty!=0)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
}
else
{
resp = "Not Squared Off. Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
3)Apply the Algomojo Options Test Module.afl on the Charts
4)Now right click over the charts and set the Client ID, user_apikey, api_secretkey and set the required quantity
5)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.
AlgomojoCE.csv and AlgomojoPE.csv will be saved separately only if the execution status is in complete mode. If the order is rejected then the file will not be saved with an executed symbol.
6)Enable the Algo Mode
Aliceblue Monthly Option Expiry Settings
And If in case you are using Aliceblue Weekly Options then you have to use YYMDD format
Now you can send Long Call and Long Put Orders from the press of the button from the properties box and also exit the positions by pressing the Exit Call and Exit Put Buttons which will eventually squareoff the positions based on current open positions.
This tutorial helps you to understand how to connect your simple Buy and Sell Trading signals to send ATM option orders in the Algomojo Platform. This kind of system helps traders to mitigate the risk especially when a sudden fall/rise is expected and that brings the system free from extreme black swan risk. Big Gap up and Gap down risk while carry forwarding your positions.
1)Trading System with Buy/Sell/Short/Cover Signals 2)Main Option Execution Module that needs to be drag and dropped over the Trading System 3)Header Option Execution Module that needs to be placed inside the Amibroker\Formulas\Include folder
1)Building your Trading System
Apply the Trading System with your Buy/Sell/Short/Cover variables on the charts.
Here is the sample EMA Crossover Trading System with Buy,Sell,Short,Cover variables.
Note: Buy/Sell/Short/Cover parameters are mandatory without that execution will not happen properly
If in case your trading system supports only Buy and Sell and you don’t want to use short and cover variables, in that case, use the below-mentioned logic where initialize short and cover variables to zero.
Buy = your buy trading logic ;
Sell = your sell trading logic ;
short =0;
cover =0;
2)Main Option Execution Module
Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Algomojo Spot Or Future Signals to Option Orders.afl
Now Drag and Drop the Module on top of your Charting with Buy/Sell Trading System
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Kalaiselvan - Algomojo Developer
//Date : 30/12/2020
//////////////////////////////////////////////
#include < algomojooptions.afl >
//Note : First Trade in Pure Long/Short Strategy is always manual.
// Send orders even if Amibroker is minimized or Chart is not active
RequestTimedRefresh(1, False);
//Initialization
spot_sym = ParamStr("spot_sym","NIFTY"); //Enter the symbol name here
expiry_dt = ParamStr("expiry_dt", "28JAN21");
strike_int = ParamStr("strike_int","50");
//Ttranstype = ParamList("Transaction Type","B|S");
opt_type = ParamList("opt_type","CE|PE",0);
offset = ParamStr("Offset","0"); //No. of strikes away from ATM Strike
tradedelay = Param("Trade Delay",0);
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
//Configure Trade Execution Delay
AlgoBuy = lastvalue(Ref(Buy,-tradedelay));
AlgoSell = lastvalue(Ref(Sell,-tradedelay));
AlgoShort = lastvalue(Ref(Short,-tradedelay));
AlgoCover = lastvalue(Ref(Cover,-tradedelay));
//Static Varibales for Order Protection
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
//Algo Dashboard
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);
}
}
//Execution Module
if(EnableAlgo != "Disable")
{
lasttime = StrFormat("%0.f",LastValue(BarIndex()));
SetChartBkColor(colorDarkGrey);
if(EnableAlgo == "Enable")
{
if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
{
// Buy Call and Exit Long Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
sqoffstatus = squareoffoptions("PE");
_TRACEF("\nExit Put Response :"+sqoffstatus);
StaticVarSetText(static_name_+"buyCoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if ((AlgoBuy != True OR AlgoCover != True))
{
StaticVarSet(static_name_+"buyCoverAlgo",0);
}
if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
{
// Buy Call Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
{
// Exit Long Call Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
sqoffstatus = squareoffoptions("CE");
_TRACEF("\nExit Call Response :"+sqoffstatus);
StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
if (AlgoShort==True AND AlgoSell==True AND StaticVarGet(static_name_+"ShortSellAlgo")==0 AND StaticVarGetText(static_name_+"ShortSellAlgo_barvalue") != lasttime)
{
// Long Put Options and Exit Long Call Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Short and Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
sqoffstatus = squareoffoptions("CE");
_TRACEF("\nExit Call Response :"+sqoffstatus);
StaticVarSetText(static_name_+"ShortsellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if ((AlgoShort != True OR AlgoSell != True))
{
StaticVarSet(static_name_+"ShortSellAlgo",0);
}
if (AlgoShort==True AND AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
{
// Buy Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Short Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoShort != True )
{
StaticVarSet(static_name_+"ShortAlgo",0);
}
if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
{
// Exit Long Put
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
sqoffstatus = squareoffoptions("PE");
_TRACEF("\nExit Put Response :"+sqoffstatus);
StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoCover != True )
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
else if(EnableAlgo == "LongOnly")
{
if (AlgoBuy==True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
{
// Buy Call Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","CE",offset);
_TRACEF("\nLong Call Executed Symbol :"+orderresponse);
StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
{
// Exit Long Call Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
sqoffstatus = squareoffoptions("CE");
_TRACEF("\nExit Call Response :"+sqoffstatus);
StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
}
else if(EnableAlgo == "ShortOnly")
{
if (AlgoShort==True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
{
// Long Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : ShortSignal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
orderresponse = placeoptionorder(spot_sym,expiry_dt,strike_int,"B","PE",offset);
_TRACEF("\nLong Put Executed Symbol :"+orderresponse);
StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime);
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 StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
{
// Exit Long Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
sqoffstatus = squareoffoptions("PE");
_TRACEF("\nExit Put Response :"+sqoffstatus);
StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoCover != True)
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
}//end main if
_SECTION_END();
3)Header Include Option Execution Module
Copy the Main Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojooptions.afl
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 30/12/2020
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Options");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
qty = Param("Quatity",75,0,100000,1);
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 3; //3 seconds for providing delay after placing order
RequestTimedRefresh(1,False);
function getnestorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Trsym"))
{
Trsym = StrExtract(ohistory,1,':');
Trsym = StrTrim(Trsym,"\"");
}
}
}
}
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Status"))
{
orderstatus = StrExtract(ohistory,1,':');
orderstatus = StrTrim(orderstatus,"\"");
}
}
}
}
return orderstatus;
}//end function
function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
data = sym;
for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ofetch,"symbol_token"))
{
stoken = StrExtract(ofetch,1,':');
stoken = StrTrim(stoken,"\"");
}
}
}
return stoken;
}
function writetofile(filepath,ordno,symbol,ostatus)
{
result =0;
if(ostatus=="complete" OR ostatus=="rejected")
{
fh = fopen( filepath, "w"); //Filepath of csv file with symbols
if(fh)
{
fputs(ordno + ",", fh);
fputs(symbol + ",", fh);
fputs(ostatus+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
function placeoptionorder(spot_sym,expiry_dt,strike_int,Ttranstype,opt,off)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;
}
function getquantity(Tsym)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
//Initialization
flag = 0;
possym = "";
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
data = sym;
_TRACE(" Position Book : " +data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}
return posNetqty;
}
function squareoffoptions(opt)
{
ordno = "";
Symbol = "";
ostatus ="";
if(opt=="CE")
{
fpath = fpath+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+"AlgomojoPE.csv";
}
fh = fopen(fpath, "r");
if(fh)
{
read = fgets(fh);
ordno = StrTrim(StrExtract(read,0)," ");
Symbol = StrTrim(StrExtract(read,1)," ");
ostatus = StrTrim(StrExtract(read,2)," ");
fclose(fh);
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
if(ostatus=="complete" AND exitqty!=0)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
}
else
{
resp = "Not Squared Off. Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity
5)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.
AlgomojoCE.csv and AlgomojoPE.csv will be saved separately only if the execution status is in complete mode. If the order is rejected then the file will not be saved with an executed symbol.
6)Ensure Log Window is open to capture the Trace Logs
7)Bingo Now you can Send ATM Option Orders from Amibroker by connecting any of your Buy/Sell Trading System. To Send ITM/OTM Option Orders to adjust the offset parameters from the Properties section
Last Thursday Elon Musk (Tesla CEO) urged his Twitter followers to use Signal App instead of Whatsapp over privacy issues. Elon Musk tweeted after WhatsApp’s updated terms of service raised concerns on social media.
However Investors took it in a wrong way and investors started purchasing shares of an obscure and unrelated company called Signal Advance, Texas-based biotechnology company.
Signal, the encrypted messasing platform, isn’t a publicly traded company. However till to date the Biotech company continue to advance more than 10000%
Usually, it is just a pump and dump scheme run by the operators and finally dumped to the common retailers who attempt to chase the momentum for faster gains.
Accoding to CNBC,
During Monday’s trading session(11th Jan), the stock rose 438% and reached a high of $70.85, up from a closing price of 60 cents on Jan. 6, a day before Musk’s tweet. The stock saw its highest trading volume since going public in 2014 on Monday; more than 2 million shares changed hands, while on Jan. 4, not a single share of the stock was traded. Signal Advance, which reported receiving no revenue in 2015 and 2016, is now worth more than $3 billion.
Source : CNBC
Is this the first time such wrong stocks are purchased?
Of course not. Last month 3rd Dec 2020 a public company named Luminar Technologies surged more than 3000%. Investors started buying the wrong company name Luminar Media Group (LRGR) instead of Luminar Technologies (LAZR) just because of the mistaken identity
Right now at the time of writing this article, Luminar Media Group (LRGR) is trading at 18 cents.
Investors Bought the Wrong Zoom
Back in Apr 2020 when most of the countries went for a lockdown and online apps like zoom are getting popular investors went frenzy over buying the wrong zoom stock once because of the mistaken identity.
Investors bought $ZOOM (Zoom Technologies – Chinese company making mobile devices) instead of the ticker $ZM (Video Chat Platform).The accidental purchase of the wrong Zoom shares rocketed the price of the lesser-known company up by 1800%. Subsequently, the SEC (US Regulator) stepped in and removed $ZOOM from the stock market
and right now Zoom Technologies is trading around 20 cents.
So What do you think? Is investors are really idiots when comes to purchasing the stocks without doing any basic due diligence or they just get caught in buying the stocks with extraordinary momentum? Let me know your thoughts in comments.
This tutorial provides you a basic framework for sending multi-legged options module and how to exit the multi-legged option module using a simple button trading based example. However, this module can be extended to trade any sort of neutral trading strategy using Amibroker.
This button trading module also comes with providing priority to execute the Long Option Orders followed by Option Selling Orders in order to effectively manage the Margin as per the new margin framework for Derivatives.
Supported Brokers : Aliceblue, Tradejini, Zebu
Supported Amibroker Version : Amibroker Version 6.22 onwards
To Build Button Trading module we need 2 Major components
1)Header Option Execution Module that needs to be placed inside the Amibroker\Formulas\Include folder
2)Main Options Entry/Exit Button Execution Module that needs to be drag and dropped over the Blank Charts
1)Header Multi Legged Options Execution Module
Copy the Header Multi Leg Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojomultioptions.afl
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 30/12/2020
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Multi legged Options");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","ab"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 1; //3 seconds for providing delay after placing order
RequestTimedRefresh(1,False);
function getnestorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Trsym"))
{
Trsym = StrExtract(ohistory,1,':');
Trsym = StrTrim(Trsym,"\"");
}
}
}
}
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Status"))
{
orderstatus = StrExtract(ohistory,1,':');
orderstatus = StrTrim(orderstatus,"\"");
}
}
}
}
return orderstatus;
}//end function
function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
data = sym;
for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ofetch,"symbol_token"))
{
stoken = StrExtract(ofetch,1,':');
stoken = StrTrim(stoken,"\"");
}
}
}
return stoken;
}
function writetofile(filepath,ordno,symbol,ostatus)
{
result =0;
if(ostatus=="complete" OR ostatus=="rejected")
{
fh = fopen( filepath, "w"); //Filepath of csv file with symbols
if(fh)
{
fputs(ordno + ",", fh);
fputs(symbol + ",", fh);
fputs(ostatus+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
function placeoptionorder(spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off,leg)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
_TRACE("\n"+api_data);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+leg+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;
}
function getquantity(Tsym)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
//Initialization
flag = 0;
possym = "";
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
data = sym;
_TRACE(" Position Book : " +data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}
return posNetqty;
}
function squareoffoptions(opt,leg)
{
ordno = "";
Symbol = "";
ostatus ="";
if(opt=="CE")
{
fpath = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+leg+"AlgomojoPE.csv";
}
fh = fopen(fpath, "r");
if(fh)
{
read = fgets(fh);
ordno = StrTrim(StrExtract(read,0)," ");
Symbol = StrTrim(StrExtract(read,1)," ");
ostatus = StrTrim(StrExtract(read,2)," ");
fclose(fh);
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
if(ostatus=="complete" AND exitqty!=0)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+"S"+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
}
else
{
resp = "Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
2)Main Options Enty/Exit Button Execution Module
Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Algomojo Button Trading Multi Legged Options.afl
Now drag and Drop the Module on top of your Charting with Buy/Sell Trading System
/*
Created By : Rajandran R(Founder - Marketcalls / Co-Founder Algomojo)
Created on : 01 Apr 2020.
Website : www.marketcalls.in
*/
#include < algomojomultioptions.afl >
_SECTION_BEGIN("Button Trading - Multi Broker - Algomojo");
//Notes
//This afl code works only on Amibroker 6.22 and higher version
//Requires Algomojo Trading account
//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
spot_sym = ParamStr("spot_sym","NIFTY"); //Enter the symbol name here
strike_int = ParamStr("strike_int","50");
lotsize = Param("Symbol Lot Size",75,1,50000);
leg1 = ParamToggle("1st Leg","Enable|Disable");
leg1expiry_dt = ParamStr("Leg 1 expiry_dt", "28JAN21");
leg1qty = Param("Leg 1 Lot Size",1)*lotsize;
leg1Ttranstype = ParamList("Leg 1 Transaction Type","B|S");
leg1opt_type = ParamList("Leg 1 Option Type","CE|PE",0);
leg1offset = ParamStr("Leg 1 Offset","0");
leg2 = ParamToggle("2ng Leg","Enable|Disable");
leg2expiry_dt = ParamStr("Leg 2 expiry_dt", "28JAN21");
leg2qty = Param("Leg 2 Lot Size",1)*lotsize;
leg2Ttranstype = ParamList("Leg 2 Transaction Type","B|S");
leg2opt_type = ParamList("Leg 2 Option Type","CE|PE",0);
leg2offset = ParamStr("Leg 2 Offset","0");
leg3 = ParamToggle("3rd Leg","Enable|Disable");
leg3expiry_dt = ParamStr("Leg 3 expiry_dt", "28JAN21");
leg3qty = Param("Leg 3 Lot Size",1)*lotsize;
leg3Ttranstype = ParamList("Leg 3 Transaction Type","B|S");
leg3opt_type = ParamList("Leg 3 Option Type","CE|PE",0);
leg3offset = ParamStr("Leg 3 Offset","0");
leg4 = ParamToggle("4th Leg","Enable|Disable");
leg4expiry_dt = ParamStr("Leg 4 expiry_dt", "28JAN21");
leg4qty = Param("Leg 4 Lot Size",1)*lotsize;
leg4Ttranstype = ParamList("Leg 4 Transaction Type","B|S");
leg4opt_type = ParamList("Leg 4 Option Type","CE|PE",0);
leg4offset = ParamStr("Leg 4 Offset","0");
tradedelay = Param("Trade Delay",0);
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
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()
{
if(leg1 AND leg1Ttranstype=="B")
{
placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,leg1opt_type,leg1offset,1);
_TRACE("Leg 1 Buy Order Placed Successfully");
}
if(leg2 AND leg2Ttranstype=="B")
{
leg2response = placeoptionorder(spot_sym,leg2expiry_dt,strike_int,leg2qty,leg2Ttranstype,leg2opt_type,leg2offset,2);
_TRACE("Leg 2 Buy Order Placed Successfully");
}
if(leg3 AND leg3Ttranstype=="B")
{
leg3response = placeoptionorder(spot_sym,leg3expiry_dt,strike_int,leg3qty,leg3Ttranstype,leg3opt_type,leg3offset,3);
_TRACE("Leg 3 Buy Order Placed Successfully");
}
if(leg4 AND leg4Ttranstype=="B")
{
leg4response = placeoptionorder(spot_sym,leg4expiry_dt,strike_int,leg4qty,leg4Ttranstype,leg4opt_type,leg4offset,4);
_TRACE("Leg 4 Buy Order Placed Successfully");
}
if(leg1 AND leg1Ttranstype=="S")
{
leg1response = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,leg1opt_type,leg1offset,1);
_TRACE("Leg 1 Sell Order Placed Successfully");
}
if(leg2 AND leg2Ttranstype=="S")
{
leg2response = placeoptionorder(spot_sym,leg2expiry_dt,strike_int,leg2qty,leg2Ttranstype,leg2opt_type,leg2offset,2);
_TRACE("Leg 2 Sell Order Placed Successfully");
}
if(leg3 AND leg3Ttranstype=="S")
{
leg3response = placeoptionorder(spot_sym,leg3expiry_dt,strike_int,leg3qty,leg3Ttranstype,leg3opt_type,leg3offset,3);
_TRACE("Leg 3 Sell Order Placed Successfully");
}
if(leg4 AND leg4Ttranstype=="S")
{
leg4response = placeoptionorder(spot_sym,leg4expiry_dt,strike_int,leg4qty,leg4Ttranstype,leg4opt_type,leg4offset,4);
_TRACE("Leg 4 Sell Order Placed Successfully");
}
Say( "Order Placed" );
}
function Sellorder()
{
sqoff1status = squareoffoptions(leg1opt_type,1);
_TRACE("Leg 1 Exit Response :"+sqoff1status);
sqoff2status = squareoffoptions(leg2opt_type,2);
_TRACE("Leg 2 Exit Response :"+sqoff2status);
sqoff3status = squareoffoptions(leg3opt_type,3);
_TRACE("Leg 3 Exit Response :"+sqoff3status);
sqoff4status = squareoffoptions(leg4opt_type,4);
_TRACE("Leg 4 Exit Response :"+sqoff4status);
_TRACE("Order Placed Successfully");
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( "Enter Options", 0, 100, 200, 30 );
SellTrigger = GuiButtonTrigger( "Exit Options", 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();
3)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity
4)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.
5)Enable/Disable Multiple Leg Options, Set the Symbol, Lot Size, Strike Interval (Difference between two immediate strike price), Set the Expiry Date, Lot Size and Offset for Multiple Legs as shown below
Ensure while entering the Option Expiry Format. Login to Algomojo Terminal and check out the weekly and monthly option format and enter the expiry date accordingly.
For Aliceblue account holders Monthly Option Symbol Format: NIFTY21JAN14500CE
Hence the Expiry Date needs to be entered as 21JAN
For Aliceblue Account holders weekly Option Symbol Format: NIFTY2111414500CE
Hence the Expiry Date needs to be entered as 21114
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY28JAN2114500CE
Hence the Expiry Date needs to be entered as 28JAN21
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY14JAN2114500CE
Hence the Expiry Date needs to be entered as 14JAN21
6)Ensure Log Window is open to capture the Trace Logs
7)Enable Algo Mode : Enable State
7)Bingo Now on the click of Enter Options you will be able to send Multi legged options as per your settings and you can also see that long option orders take priority in execution compared to short legged options to effectively manage the margin.
8)on the Press of Exit Options button automatically all the multi-legged option orders get squared off. Square off happens only if the position exists in the position book. If no position is found one will get the following log notification
Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State
This module can be extended further to place multi legged option orders autmatically from Amibroker by doing customization according to traders requirement.
If in case you need a customized multi legged options requirement you can send your requirement to support@algomojo.com
Market Profile is one trading tool that professional traders would never like to miss in their trading arsenal. This Mini-Course on Market Profile gets you the basic building blocks, trading strategies & get to know more about the trading tools.
Tools Used
Ninjatrader 8 + Bell TPO Market Profile Addon for Ninjatrader
Who Should Attend the Course?
Traders who want to learn the art of Market Profile based context building approach, discretionary traders who wants to know more about the behavior of price distribution and price action, Full Time Traders, Part Time traders, Prop Desk Traders, Dealers, Students, Brokers, Sub-Brokers, Research Analyst & Investment Advisors
Live Webinar – 16-01-2021 – 08pm IST – – Introduction to Market Profile (Basic Terminologies & Building Blocks), Importance of Halfback, Value Area & Point of Control
-Introduction to Market Profile -Introduction to Auction Market Theory -Understanding Point of Control & Value Area -Importance of Point of Control & Value Area -Market Profile vs Volume Profile which one to use? -Setting the TPO Size
Live Webinar – 23-01-2021 – 08pm IST – – Different Types of Profile Structure and How to the importance of Day Types
-Different Profile Structure -Trading Strategies using Profile Structure -Identifying New Money/Old Money from Profile Structure -Understanding Liquidation and visualizing using Market Profile
Live Webinar – 30-01-2021 – 08pm IST – – Market Open Types and How to Read Market Confidence from Open Types
-Market Open Types & Trading Strategies using Market Open Types -Measuring Market Confidence from Market Open Type -Balanced Vs Imbalanced Structure -Poor Structure Vs Symmetric Structure
Live Webinar – 06-02-2021 – 08pm IST – – Simple Trading Strategies using Market Profile
-Point of Control Based Strategies -Open Drive Setup -Breakout Failure Trade Setups -Failed Auction Based Trade Setups -Weaker References -How to Prepare for the Trading Day
These days for Retail Traders trading in futures trading requires a huge margin. Approximately 1.65 Lakh per lot is required for carrying forward future trades. However with the New Margin regulations with Hedged Futures, one can bring down the Margin Requirement drastically as low as Rs25,000 – 70,000 per lot depends upon the selection of Option Strike Price.
What is a Hedged Futures?
We know that trading futures involve unlimited reward and unlimited risk. However by adding out of the money option one can convert unlimited risk to limited risk and exchange also provides more margin benefit since the risk for the trader is controlled.
For Long Futures – OTM Put Option is used as a hedge For Short Futures – OTM Call Option is used as a hedge
Hedging with Deep OTM Call Option
Will it Affect Profitability?
Remember Hedging comes at a cost. And If you are buying 10 strike wide option. You are most likely to buy cheaper OTM calls and hence tiny amount of your profitability is likely to be impacted.
Hedging with Near ATM Call Option
However if in case you are selecting near ATM strikes and more premium has to be paid in that case Margin comes down drastically as shown above however more the margin comes down more it impacts the profitability.
Which Strike Price to Select
If you are looking for a reasonable reduction in Margin then consider deep OTM Options with 8 strikes or 10 strike wide from ATM Options that brings a net portfolio Delta maintained well above 0.75-0.85 levels which compensate tiny to moderate effect on profitability compared to naked futures trading.
If you are looking for a drastic reduction in margin then consider ATM Options with 1-2 strike wide from ATM Options that brings net portfolio anywhere between 0.5 – 0.65 levels which compensates the profitability to a greater extent compared to naked futures trading.
Which Hedges to Consider Weekly or Monthly?
Of course Weekly OTM Strikes are cheaper and there is no significant change is premium irrespective of whether you are selection weekly option as hedge or monthly option as a hedge.
Weekly Option always act as cheaper hedges compared to monthly options. However point to be noted that Weekly Options erodes faster in time compared to monthly options because of the theta decay factor.
Tips for Small Account Holder
If you are a small account holder always Buy your hedge first followed by the directional futures position. This way margin will be effectively reduced for the small account holders.
This way you can bring down the cost of your margin requirements in your directional trades and thereby reducing the drastic risk if any due to unforseen events in the markets.
In the next tutorial I will be explaining how to automate your Buy or Sell Signal trades with Hedged Futures to carry forward your positional systematic trading strategies. Stay Tuned!
In the last tutorial, we learn the importance of Hedging Futures Position with OTM Options for Reduced Margin. This tutorial focus on how to automate your positional buy and sell signal ideas with Hedged Index Futures to reduce your trading margin significantly
Trading Signal in Spot/Futures
Orders to be Placed
Buy Signal
Long Futures and Long OTM Put Options
Sell Signal
Short Futures and Exit OTM Put Options
Short Signal
Short Futures and Long OTM Call Options
Cover Signal
Long Futures and Exit OTM Call Options
Buy and Cover Signal
2 times of Long Futures, Long OTM Put Options and Exit OTM Call Options
Short and Cover Signal
2 times of Short Futures, Long OTM Call Options, and Exit OTM Put Options
Bringing Smartness in Execution
While Placing Orders to the System it checks the Position Book and Executes Trades smartly. Always hedge is executed first to get an effective margin and if no positions are there in the open positions then the system will not take reverse trade.
Supported Brokers : Aliceblue, Tradejini, Zebu Supported Trading Instruments : Index Futures (Nifty, Bank Nifty, Finnifty) with Long Options as a Hedge
To Build this module we need 3 components
1)Trading System with Buy/Sell/Short/Cover Signals 2)Header Option Execution Module that needs to be placed inside the Amibroker\Formulas\Include folder 3)Main Option Execution Module that needs to be drag and dropped over the Trading System
1)Building your Trading System
Apply the Trading System with your Buy/Sell/Short/Cover variables on the charts.
Here is the sample EMA Crossover Trading System with Buy,Sell,Short,Cover variables.
Note: Buy/Sell/Short/Cover parameters are mandatory without that execution will not happen properly
If in case your trading system supports only Buy and Sell and you don’t want to use short and cover variables, in that case, use the below-mentioned logic where initialize short and cover variables to zero.
Buy = your buy trading logic ;
Sell = your sell trading logic ;
short =0;
cover =0;
2)Header Include Option Execution Module
Copy the Header Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojohedgedfutures.afl
/////////////////////////////////////////////////////////
//Multi Broker Amibroker Hedged Futures Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 10/12/2020
////////////////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Hedged Futures- Include Module");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
exch = "NFO"; //Exchange
Ret = "DAY"; //Retention
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
AMO = "NO"; //AMO Order
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","ab"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 1; //3 seconds for providing delay after placing order
RequestTimedRefresh(1,False);
function futuresorder(Tsym,orderqty,transactiontype)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Tsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+transactiontype+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
_TRACE("");
_TRACE("API Request"+api_data);
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
Say( "Buy Order Placed" );
return resp;
}
function NetOpenPositions(Tsym)
{
flag = 0;
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
_TRACE("Position Book Response : " +resp);
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
for( jitem = 0; ( posdetails = StrExtract( sym, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Tsym"))
{
posdetails = StrExtract(posdetails,1,':');
possym = StrTrim(posdetails,"\"");
_TRACE("\nSymbol : "+possym);
}
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
if(Strfind(posdetails,"unrealisedprofitloss"))
{
posdetails = StrExtract(posdetails,1,':');
posupnl = StrTrim(posdetails,"\"");
_TRACE("\nUnRealized PNL : "+posupnl);
}
if(Strfind(posdetails,"realisedprofitloss"))
{
posdetails = StrExtract(posdetails,1,':');
posrpnl = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\n Realized PNL : "+posrpnl);
}
if(Strfind(posdetails,"MtoM"))
{
posdetails = StrExtract(posdetails,1,':');
posmtm = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nMTM PNL : "+posmtm);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
//posNetqty =0;
_TRACE("\nNetQty : "+posNetqty);
}
return posNetqty;
}//end of Net Open Positions
function getnestorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Trsym"))
{
Trsym = StrExtract(ohistory,1,':');
Trsym = StrTrim(Trsym,"\"");
}
}
}
}
return Trsym;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Status"))
{
orderstatus = StrExtract(ohistory,1,':');
orderstatus = StrTrim(orderstatus,"\"");
}
}
}
}
return orderstatus;
}//end function
function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
data = sym;
for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ofetch,"symbol_token"))
{
stoken = StrExtract(ofetch,1,':');
stoken = StrTrim(stoken,"\"");
}
}
}
return stoken;
}
function writetofile(filepath,ordno,symbol,ostatus)
{
result =0;
if(ostatus=="complete" OR ostatus=="rejected")
{
fh = fopen( filepath, "w"); //Filepath of csv file with symbols
if(fh)
{
fputs(ordno + ",", fh);
fputs(symbol + ",", fh);
fputs(ostatus+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
function placeoptionorder(spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off,leg)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
_TRACE("\n"+api_data);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+leg+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;
}
function getquantity(Tsym)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
//Initialization
flag = 0;
possym = "";
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
data = sym;
_TRACE(" Position Book : " +data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}
return posNetqty;
}
function squareoffoptions(opt,Ttranstype,leg)
{
ttype="";
if(Ttranstype=="B")
{
ttype = "S";
}
if(Ttranstype=="S")
{
ttype = "B";
}
ordno = "";
Symbol = "";
ostatus ="";
if(opt=="CE")
{
fpath = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+leg+"AlgomojoPE.csv";
}
fh = fopen(fpath, "r");
if(fh)
{
read = fgets(fh);
ordno = StrTrim(StrExtract(read,0)," ");
Symbol = StrTrim(StrExtract(read,1)," ");
ostatus = StrTrim(StrExtract(read,2)," ");
fclose(fh);
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
if(ostatus=="complete" AND exitqty!=0)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+ttype+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
}
else
{
resp = "Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
3)Main Option Execution Module
Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Algomojo Hedged Futures Module to Save Margin.afl
Now drag and Drop the Module on top of your Charting with Buy/Sell Trading System
//////////////////////////////////////////////
//Multi Broker Amibroker Option Execution Module
//Coded by Kalaiselvan - Algomojo Developer
//Date : 30/12/2020
//////////////////////////////////////////////
#include < algomojohedgedfutures.afl >
//Note : First Trade in Pure Long/Short Strategy is always manual.
_SECTION_BEGIN("Hedged Index Futures - Main Module");
// Send orders even if Amibroker is minimized or Chart is not active
RequestTimedRefresh(1, False);
//Initialization
spot_sym = ParamStr("spot_sym","NIFTY"); //Enter the symbol name here
strike_int = ParamStr("strike_int","50");
lotsize = Param("Symbol Lot Size",75,1,50000);
//Leg 2 is enabled by default
leg2symbol = ParamStr("Futures Symbol","NIFTY28JAN21FUT");
leg2qty = Param("Futures Lot Size",1)*lotsize;
//Option Buying Leg for Reduced Margin
//Leg 1 is optional for Hedging Purpose
leg1 = ParamToggle("Hedge","Disable|Enable"); //Enable the Hedge
leg1expiry_dt = ParamStr("Leg 1 expiry_dt", "21JAN21"); //Always prefer using weekly expiry so reduce your margin exposure
leg1qty = Param("Leg 1 Lot Size",1)*lotsize;
leg1Ttranstype = ParamStr("Leg 1 Transaction Type","B");
//leg1opt_type = ParamList("Leg 1 Option Type","CE|PE",0);
leg1offset = Param("Leg 1 Offset",10); //need to handle positive offset for long call option and negative offset for long put option
tradedelay = Param("Trade Delay",0);
EnableAlgo = ParamList("Algo Mode","Disable|Enable",0); // Algo Mode
//Configure Trade Execution Delay
AlgoBuy = lastvalue(Ref(Buy,-tradedelay));
AlgoSell = lastvalue(Ref(Sell,-tradedelay));
AlgoShort = lastvalue(Ref(Short,-tradedelay));
AlgoCover = lastvalue(Ref(Cover,-tradedelay));
//Static Varibales for Order Protection
static_name_ = Name()+GetChartID()+interval(2)+stgy_name;
static_name_algo = Name()+GetChartID()+interval(2)+stgy_name+"algostatus";
//StaticVarSet(static_name_algo, -1);
//Algo Dashboard
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);
}
}
//Execution Module
if(EnableAlgo != "Disable")
{
lasttime = StrFormat("%0.f",LastValue(BarIndex()));
SetChartBkColor(colorDarkGrey);
if(EnableAlgo == "Enable")
{
if (AlgoBuy==True AND AlgoCover == True AND StaticVarGet(static_name_+"buyCoverAlgo")==0 AND StaticVarGetText(static_name_+"buyCoverAlgo_barvalue") != lasttime )
{
// Buying Put Option as Hedge + Long Futures + Exiting Call Option
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy and Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
_TRACE("\nNo Open Positions");
}
else if(NetOpenPositions(leg2symbol) == -leg2qty)
{
NewQty = 2*leg2qty;
}
else
{
NewQty = 2*leg2qty;
_TRACE("\nReversal signal will be taken with 2 times of Trading Quantity");
_TRACE("\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
_TRACEF("\nLong Futures Response :"+enterlongresponse);
//Exit Call Option
if(leg1)
{
sqoff1status = squareoffoptions("CE","S",1);
_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"buyCoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyCoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if ((AlgoBuy != True OR AlgoCover != True))
{
StaticVarSet(static_name_+"buyCoverAlgo",0);
}
if (AlgoBuy==True AND AlgoCover != True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
{
// Buy Long Put Option as Hedge + Long Futures
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
_TRACEF("\nLong Futures Response :"+enterlongresponse);
StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND AlgoShort != True AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
{
// Short Futures + Exit Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = 0;
_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
}
else if(NetOpenPositions(leg2symbol) == leg2qty)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
_TRACEF("\nShort Futures Response :"+enterlongresponse);
if(leg1)
{
sqoff1status = squareoffoptions("PE","S",1);
_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
if (AlgoShort==True AND AlgoSell==True AND StaticVarGet(static_name_+"ShortSellAlgo")==0 AND StaticVarGetText(static_name_+"ShortSellAlgo_barvalue") != lasttime)
{
// Long Call Options + Short Futures and Exit Long Put Options
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Short and Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
_TRACE("\nNo Open Positions");
}
else if(NetOpenPositions(leg2symbol) == leg2qty)
{
NewQty = 2*leg2qty;
}
else
{
NewQty = 2*leg2qty;
_TRACE("\nReversal signal will be taken with 2 times of Trading Quantity");
_TRACE("\nWarning Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
_TRACEF("\nShort Futures Response :"+enterlongresponse);
//Exit Put Option
if(leg1)
{
sqoff1status = squareoffoptions("PE","S",1);
_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"ShortsellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"ShortSellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if ((AlgoShort != True OR AlgoSell != True))
{
StaticVarSet(static_name_+"ShortSellAlgo",0);
}
if (AlgoShort==True AND AlgoSell != True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
{
// Buy Long Call as Hedge + Short Futures
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Short Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
_TRACEF("\nShort Futures Response :"+enterlongresponse);
StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"ShortAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoShort != True )
{
StaticVarSet(static_name_+"ShortAlgo",0);
}
if (AlgoCover==true AND AlgoBuy != True AND StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
{
// Buy the Futures + Exit Call Option
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = 0;
_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
}
else if(NetOpenPositions(leg2symbol) == -leg2qty)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
_TRACEF("\nLong Futures Response :"+enterlongresponse);
if(leg1)
{
sqoff1status = squareoffoptions("CE","S",1);
_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoCover != True )
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
else if(EnableAlgo == "LongOnly")
{
if (AlgoBuy==True AND StaticVarGet(static_name_+"buyAlgo")==0 AND StaticVarGetText(static_name_+"buyAlgo_barvalue") != lasttime)
{
// Buy Put Option as Hedge and Long Futures
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Buy Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"PE",-1*leg1offset,1);
_TRACEF("\nLong Put Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
_TRACEF("\nLong Futures Response :"+enterlongresponse);
StaticVarSetText(static_name_+"buyAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"buyAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoBuy != True)
{
StaticVarSet(static_name_+"buyAlgo",0);
}
if (AlgoSell==true AND StaticVarGet(static_name_+"sellAlgo")==0 AND StaticVarGetText(static_name_+"sellAlgo_barvalue") != lasttime)
{
// Short Futures and Exit Put Option
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Sell Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = 0;
_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
}
else if(NetOpenPositions(leg2symbol) == leg2qty)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
_TRACEF("\nShort Futures Response :"+enterlongresponse);
if(leg1)
{
sqoff1status = squareoffoptions("PE","S",1);
_TRACE("Leg 1 Put Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"sellAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"sellAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoSell != True )
{
StaticVarSet(static_name_+"sellAlgo",0);
}
}
else if(EnableAlgo == "ShortOnly")
{
if (AlgoShort==True AND StaticVarGet(static_name_+"ShortAlgo")==0 AND StaticVarGetText(static_name_+"ShortAlgo_barvalue") != lasttime)
{
// Long Call Option and Short Futures
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : ShortSignal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(leg1)
{
orderresponse = placeoptionorder(spot_sym,leg1expiry_dt,strike_int,leg1qty,leg1Ttranstype,"CE",leg1offset,1);
_TRACEF("\nLong Call Hedge Executed Symbol :"+orderresponse);
}
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"S");
_TRACEF("\nShort Futures Response :"+enterlongresponse);
StaticVarSetText(static_name_+"ShortAlgo_barvalue",lasttime);
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 StaticVarGet(static_name_+"CoverAlgo")==0 AND StaticVarGetText(static_name_+"CoverAlgo_barvalue") != lasttime)
{
// Long Futures and Exit Call Option
_TRACE("Strategy : "+ stgy_name +"Chart Symbol : "+ Name() +" Signal : Cover Signal TimeFrame : "+ Interval(2)+" ChardId : "+ GetChartID());
if(NetOpenPositions(leg2symbol) == 0)
{
NewQty = 0;
_TRACE("\nWarning: No Trading Positions Already Exists. Short Exit Signal(Cover Signal) will be discarded");
}
else if(NetOpenPositions(leg2symbol) == -leg2qty)
{
NewQty = leg2qty;
}
else
{
NewQty = leg2qty;
_TRACE("\nWarning: Reversal signal will be taken with 1 times of Trading Quantity. However Trading Positions Already Exists");
_TRACE("\nWarning: Mismatch in Trading Positions. Check the Open Positions and Trade Quantity and Take Necessary Actions Manually if required.");
}
enterlongresponse = futuresorder(leg2symbol,NewQty,"B");
_TRACEF("\nLong Futures Response :"+enterlongresponse);
if(leg1)
{
sqoff1status = squareoffoptions("CE","S",1);
_TRACE("Leg 1 Call Exit Response :"+sqoff1status);
}
StaticVarSetText(static_name_+"CoverAlgo_barvalue",lasttime);
StaticVarSet(static_name_+"CoverAlgo",1); //Algo Order was triggered, no more order on this bar
}
else if (AlgoCover != True)
{
StaticVarSet(static_name_+"CoverAlgo",0);
}
}
}//end main if
_SECTION_END();
4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity
5)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.
Ensure while entering the Option Expiry Format. Login to Algomojo Terminal and check out the weekly and monthly option format and enter the expiry date accordingly.
For Aliceblue account holders Monthly Option Symbol Format: NIFTY21JAN14500CE
Hence the Expiry Date needs to be entered as 21JAN
For Aliceblue Account holders weekly Option Symbol Format: NIFTY2111414500CE
Hence the Expiry Date needs to be entered as 21114
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY28JAN2114500CE
Hence the Expiry Date needs to be entered as 28JAN21
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY14JAN2114500CE
Hence the Expiry Date needs to be entered as 14JAN21
1AlgomojoCE.csv and 1AlgomojoPE.csv will be saved whenever the hedged option traders are executed and files will be saved only if the execution status is in complete or in rejected mode.
6)Enable the Hedge Option, Enter the Futures Symbol, Enter the Option Hedging Expiry, Lot Size, Transaction Type and Offset (To Select OTM/ATM. Keep the value as zero for ATM Option selection)
7)Ensure Log Window is open to capture the Trace Logs
8)Bingo Now you can Send Hedged Orders from Amibroker by connecting any of your Buy/Sell Trading System. To Send ATM/ITM/OTM Option Orders, adjust the offset parameters from the Properties section.
Automated Trading not only involves automating your trading strategies but also every tiny possible manual task that needs to be automated to achieve one hundred percent automation. This tutorial discusses how one can automate the daily manual login process.
Requirements
Latest Chrome Browser Windows 7, 8 or 10, Windows Server 2008, 2012, 2016 or higher versions
Algomojo AutoLogin.exe – Main File Config.yaml – Password Configuration File Chrome Driver – Automating the Browser Instructions Readme.txt – Help Instruction to Configure the login id , password and 2FA credentials
4) Open the Config.yaml in notepad to Configure your Broker Shortcode, Login Credentials, 2fa1pwd , 2fa2pwd
6)Bingo! Now you are able to do an Automated Login with Algomojo. Now in the next tutorial, we will be learning how to schedule the Automated Login for all the trading days and How to Automate your Login at the scheduled time using Task Manager.
Modern-day trading communications rely on APIs and getting access to costlier APIs for the retail traders is gone long back and these days modern-day communication tools come at the ease of use and help us solve our automation requirement easier at a reduced trading cost.
What is Upstox Interactive API?
Upstox Interactive API offers Real Time market updates, orders, positions, holdings, balance APIs and can be used to automate your trading ideas using tools like Algomojo, Amibroker, Metatrader, Ninjatrader , Excel and Tradingview.
What is Historical Data API?
Upstox Historical API package offers OHLC (Open High Low Close) historical data for different intervals—1 min, 3 mins, 5 mins, 10 mins, 15 mins, 30 mins, 60 mins, 1 day, 1 week, 1 month.
You can use these APIs to build your trading strategy using programming languages like Python, Java, Nodejs etc. Now users of Algomojo users can get access to both Free Upstox Interactive API and Historical Data API by open a trading account under Algomojo and start building your trading system at no additional fee.
What is Algomojo?
Algomojo is a Web-Based Free Trading Platform that helps users to Automate their trading ideas on various platforms like Amibroker, Metatrader, Tradingview, C# Based Trading Platforms, Excel and Custom Programming Languages like Python, Java, Nodejs. etc. If you are an Algomojo – Upstox User then access the Trading Platform here
How to Get Free Access to Upstox Interactive API and Historical Data API?
Once your trading account is opened. You can log into your upstox trading portal and raise a ticket. Alternatively, you can also goto Upstox Ticketing Tool and raise a direct ticket.
Ticket Subject: Request for FREE API to access Algomojo Trading Platform
Dear Upstox Team, I would like to use Upstox API with Algomojo API trading platform. Hence grant me free API access to avail Algomojo Trading Platform Services. My Upstox Client ID : (enter your Upstox ID)
(Your Name) (Your Mobile Number)
Note: After submitting the ticket. You will be receiving free credit to access Upstox APIs for 6 months and Usage of the Free API will be reviewed periodically by the Upstox team every 6months. Based on the continuation of the usage Upstox will grant further extended access.
In the last tutorial, we learn how to automate the algomojo login process and in this video tutorial, we are going to learn with a click of an Amibroker button how one can automatically log in to the Algomojo trading platform.
2)Unzip the files to your local machine and copy the files Algomojo AutoLogin.exe, chromedriver.exe, config.yaml &Readme.txt files and move to your Amibroker Installation Path,
3)Open config.yaml and configure the Login Credentials and 2 FA credentials as per the Readme.txt file format.
4)Copy the below Amibroker AFL Files and Save the File as Algomojo AutoButtonLogin.afl
5)Open a New Blank Charts and Drag and Drop the AFL Code
6)Now Press the Broker Login button to Make your Login Automatically. If in case you want to change the broker then re-configure the config.yaml file accordingly
7)Use the Reset Button if in case you need to Relogin
This tutorial focus on how to automate your index straddle/strangle strategy with intraday stop-loss levels with time-based entry and exits using Algomojo Platform and Amibroker.
Trading Activity
Orders to be Placed
Time Based Entry
Enter Straddle/Strangle at 9.30a.m (Two legged Order)
Calculate the Short Call Average Price
Calculate the Short call Stoploss
Calculate the Short Put Average Price
Calculate the Short Put Stoploss
Place Stoploss Orders
Place the Stoploss for both Short call and Short Put if the entry order status is completed
Check Open Positions
Check the Open Positions for the Qty traded
Time Based Exit
Square of Short Call and Short Put legs for the qty present in the open positions around 3.15p.m.
1)Header Option Execution Module that needs to be placed inside the Amibroker\Formulas\Include folder 2)Main Option Execution Module that needs to be drag and dropped over the Blank Chart
1)Header Include Option Execution Module
Copy the Header Execution Module to Amibroker\Formulas\include folder. Save the AFL under the name algomojostraddle.afl
//////////////////////////////////////////////
//Multi Broker Amibroker Option Straddle Execution Module
//Coded by Rajandran - Algomojo Co-Founder
//Date : 18/01/2021
//////////////////////////////////////////////
//Use this code only for Single Legged Long Only Options and Exiting Long Only Options
_SECTION_BEGIN("Algomojo Multi legged Options");
uid = ParamStr("Client ID","TS2499");
user_apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
api_secret = ParamStr("api_secret","4a94db82ea4fa140afaa2f039efffd18"); //Enter your API secret key here
s_prdt_ali = "BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML";
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|CO|MIS",2);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
exch = "NFO"; //Exchange
Ret = "DAY"; //Retention
AMO = "NO"; //AMO Order
stgy_name = ParamStr("Strategy Name", "Options");
broker = ParamStr("Broker","ab"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich
ver = ParamStr("API Version","1.0");
fpath = ParamStr("Symbol Filepath", "C:\\Program Files (x86)\\AmiBroker\\Formulas\\Algomojo\\");
timer = 1; //3 seconds for providing delay after placing order
RequestTimedRefresh(1,False);
function placestoplossorder(SLTsym,orderaction,averageprice,stoppercent,orderqty)
{
//rounded of to nearest tick
TickSize = 0.05;
slprice = int(StrToNum(averageprice) + (StrToNum(averageprice) * stoppercent/100));
slprice = Prec(slprice,2);
rem = slprice % TickSize;
slprice = slprice - rem; //rounded of to nearest tick size
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"stgy_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+SLTsym+"\",\"exch\":\""+exch+"\",\"Ttranstype\":\""+orderaction+"\",\"Ret\":\""+Ret+"\",\"prctyp\":\""+"SL-M"+"\",\"qty\":\""+orderqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+slprice+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+AMO+"\"}";
_TRACE("");
_TRACE("API Request"+api_data);
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
Say( "Stoploss Order is Placed" );
return resp;
}
function getnestorderno(response)
{
NOrdNo = "";
if(StrFind(response,"NOrdNo")) //Matches the orderstatus
{
NOrdNo = StrTrim( response, "{\"NOrdNo\":" );
NOrdNo = StrTrim( NOrdNo, "\",\"stat\":\"Ok\"}" );
}
return NOrdNo;
}
function getorderhistory(orderno)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"uid\":\""+uid+"\",\"NOrdNo\":\""+orderno+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"OrderHistory",api_data,broker,ver);
return resp;
}
function getsymbol(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
Trsym="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Trsym"))
{
Trsym = StrExtract(ohistory,1,':');
Trsym = StrTrim(Trsym,"\"");
}
}
}
}
return Trsym;
}
function getaverageprice(orderno)
{
ordresp = getorderhistory(orderno);
data = "";
averageprice="";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"averageprice"))
{
averageprice = StrExtract(ohistory,1,':');
averageprice = StrTrim(averageprice,"\"");
}
}
}
}
if(averageprice=="0.0")
{
averageprice = "100";
}
return averageprice;
}
function getorderstatus(orderno)
{
orderstatus="";
ordresp = getorderhistory(orderno);
data = "";
for( item = 0; ( sym = StrExtract( ordresp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
if(StrFind(sym,"complete") OR StrFind(sym,"rejected")) //Matches the orderstatus
{
flag = 1; //turn on the flag
data = sym;
for( jitem = 0; ( ohistory = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ohistory,"Status"))
{
orderstatus = StrExtract(ohistory,1,':');
orderstatus = StrTrim(orderstatus,"\"");
}
}
}
}
return orderstatus;
}//end function
function gettoken(symbol)
{
stoken="";
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"s\":\""+symbol+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"fetchsymbol",api_data,broker,ver);
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," "); //Trim Whitespaces
data = sym;
for( jitem = 0; ( ofetch = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(ofetch,"symbol_token"))
{
stoken = StrExtract(ofetch,1,':');
stoken = StrTrim(stoken,"\"");
}
}
}
return stoken;
}
function writetofile(filepath,ordno,symbol,ostatus,averageprice)
{
result =0;
if(ostatus=="complete" OR ostatus=="rejected")
{
fh = fopen( filepath, "w"); //Filepath of csv file with symbols
if(fh)
{
fputs(ordno + ",", fh);
fputs(symbol + ",", fh);
fputs(ostatus+",", fh);
fputs(averageprice+",", fh);
fclose(fh);
result =1;
}
}
return result;
}
function placeoptionorder(spot_sym,expiry_dt,strike_int,qty,Ttranstype,opt,off,leg,stoppercent)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"spot_sym\":\""+spot_sym+"\",\"expiry_dt\":\""+expiry_dt+"\",\"opt_type\":\""+opt+"\",\"Ttranstype\":\""+Ttranstype+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+qty+"\",\"Price\":\""+Price+"\",\"TrigPrice\":\""+TrigPrice+"\",\"Pcode\":\""+Pcode+"\",\"strike_int\":\""+strike_int+"\",\"offset\":\""+off+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceFOOptionsOrder",api_data,broker,ver);
_TRACE("\n"+api_data);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
if(orderstatus=="complete" OR orderstatus=="rejected")
{
averageprice = getaverageprice(nestorderno);
_TRACE("Average Price: "+averageprice);
}
if(orderstatus=="complete") //changed to complete in a live environment and rejected for testing purpose
{
//Stoploss order x% from the average price
slresponse = placestoplossorder(Tsym,"B",averageprice,stoppercent,qty);
_TRACE("Leg "+leg+" Stoploss Response: "+slresponse);
}
//Get Token Number
//token = gettoken(Tsym);
//_TRACE("\nSymbol Token : "+token);
if(opt=="CE")
{
path = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
path = fpath+leg+"AlgomojoPE.csv";
}
writestatus = writetofile(path,nestorderno,Tsym,orderstatus,averageprice);
_TRACEF(WriteIf(writestatus,"\nWriting to File - Success","\nWriting to File - Failure"));
//resp = resp+"\nNest Order No : "+nestorderno+"\nTrading Symbol : "+Tsym+"\nOrder Status : "+orderstatus+"\nSymbol Token : "+token;
return Tsym;
}
function getquantity(Tsym)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data ="{\"uid\":\""+uid+"\",\"actid\":\""+uid+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data,broker,ver);
//Initialization
flag = 0;
possym = "";
posNetqty =0;
for( item = 0; ( sym = StrExtract( resp, item,'{' )) != ""; item++ )
{
sym = StrTrim(sym," ");
Tsym = StrTrim(Tsym," ");
if(Strfind(sym,Tsym) AND StrFind(sym,Pcode)) //Matches the symbol and //Matches the Order Type
{
flag = 1; //turn on the flag
data = sym;
_TRACE(" Position Book : " +data);
for( jitem = 0; ( posdetails = StrExtract( data, jitem,',' )) != ""; jitem++ )
{
if(Strfind(posdetails,"Netqty"))
{
posdetails = StrExtract(posdetails,1,':');
posNetqty = StrToNum(StrTrim(posdetails,"\""));
_TRACE("\nNetQty : "+posNetqty);
}
} //end of for loop
}
}//end of for loop
if(flag==0)
{
_TRACE("\nTrading Symbol Not Found");
}
return posNetqty;
}
function squareoffoptions(opt,Ttranstype,leg)
{
ttype="";
if(Ttranstype=="B")
{
ttype = "S";
}
if(Ttranstype=="S")
{
ttype = "B";
}
ordno = "";
Symbol = "";
ostatus ="";
if(opt=="CE")
{
fpath = fpath+leg+"AlgomojoCE.csv";
}
if(opt=="PE")
{
fpath = fpath+leg+"AlgomojoPE.csv";
}
fh = fopen(fpath, "r");
if(fh)
{
read = fgets(fh);
ordno = StrTrim(StrExtract(read,0)," ");
Symbol = StrTrim(StrExtract(read,1)," ");
ostatus = StrTrim(StrExtract(read,2)," ");
averageprice = StrTrim(StrExtract(read,3)," ");
fclose(fh);
}
exitqty = getquantity(Symbol);
_TRACE("Net Quantity in the OrderBook for the Symbol : "+Symbol+" is : "+exitqty);
if(ostatus=="complete" AND exitqty!=0)
{
algomojo=CreateObject("AMAMIBRIDGE.Main");
api_data = "{\"strg_name\":\""+stgy_name+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\",\"Tsym\":\""+Symbol+"\",\"exch\":\""+"NFO"+"\",\"Ttranstype\":\""+ttype+"\",\"Ret\":\""+"DAY"+"\",\"prctyp\":\""+prctyp+"\",\"qty\":\""+exitqty+"\",\"discqty\":\""+"0"+"\",\"MktPro\":\""+"NA"+"\",\"Price\":\""+"0"+"\",\"TrigPrice\":\""+"0"+"\",\"Pcode\":\""+Pcode+"\",\"AMO\":\""+"NO"+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PlaceOrder",api_data,broker,ver);
//Get Nest Order Number
nestorderno = getnestorderno(resp);
_TRACE("\nNest Order No : "+nestorderno);
tradetime=GetPerformanceCounter()/1000;
while ((GetPerformanceCounter()/1000 - tradetime) < timer)
{
//Get Trading Symbol
Tsym = getsymbol(nestorderno);
}
_TRACE("\nTrading Symbol : "+Tsym);
//Get Order Status
orderstatus = getorderstatus(nestorderno);
_TRACE("\nOrder Status : "+orderstatus);
}
else
{
resp = "Not Squared Off. Either No Open Position Exist or Prev Signal Status Not in Completed State";
}
return resp;
}
_SECTION_END();
3)Main Option Execution Module
Copy the Main Execution Module to Amibroker\Formulas\Algomojo Platform. Save the AFL under the name Short Straddle - Strangle Execution.afl
Now drag and Drop the Module on top of your Charting with Buy/Sell Trading System
4)Now right-click over the charts and set the Client ID, user_apikey, api_secretkey,broker and set the required quantity
5)Ensure the Symbol File Path Exists. This is the path where the executed symbols CE and PE Options will get saved in a CSV file for later squareoff.
Ensure while entering the Option Expiry Format. Login to Algomojo Terminal and check out the weekly and monthly option format and enter the expiry date accordingly.
For Aliceblue account holders Monthly Option Symbol Format: NIFTY21JAN14500CE
Hence the Expiry Date needs to be entered as 21JAN
For Aliceblue Account holders weekly Option Symbol Format: NIFTY2111414500CE
Hence the Expiry Date needs to be entered as 21114
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY28JAN2114500CE
Hence the Expiry Date needs to be entered as 28JAN21
For Tradejini and Zebu Account Holders Monthly Option Symbol Format: NIFTY14JAN2114500CE
Hence the Expiry Date needs to be entered as 14JAN21
1AlgomojoCE.csv and 1AlgomojoPE.csv and 2AlgomojoCE.csv and 2AlgomojoPE.csv will be saved whenever the straddle or strangle are executed and files will be saved only if the execution status is in complete or in rejected mode
7)Ensure Log Window is open to capture the Trace Logs
8)Bingo Now you have setup the complete end to end automated straddle/strangle execution. Straddle/Strangle Control can be controlled via offset parameters.
9)Code is designed such a way that stoploss is placed for individual price legs and not for the combined premium of Straddle/Strangle Spreads
10)Make the Algo Enable and send time based straddle execution (Supports both entry and exit conditions).
Recently Febinars, an Online Learning Platform for traders launched Android APP for learners to attend live mentoring and recorded training sessions directly from their Android App.
Febinars is an online learning platform for wannabe professional traders. It’s the go-to place to find out core trading skills, automating your trading ideas, resources for traders to learn, share and improve their trading skills.
Features of Febinars
1)Access to Live Mentoring Sessions 2)Access to Certification Courses 3)Access to Learning Materials 4)Access to Weekly Webinars
all from your mobile app.
Febinars provides a live mentoring experience with a professional trader who is ready to guide you to your trading success. The entire live mentoring training session is recorded so you can learn at your own pace.
The goal of the service is to create a community of traders where they can meet others, learn new ideas and get the support they need to be successful.
New Algomojo API functionalities added to support the user’s requirements to automate their trading requirements and the same can be accessed via Amibroker, Metatrader, Python, c# based platforms, Excel.
This API Function retrieves the trading symbol token value which helps user to access the token in order to send Bracket order and Modify Pending Limit Orders/Stop Orders
Game Stop Corporation a brick and motor video game retailer is been in the limelight for the last few days and thanks to Robinhood Traders and Reddit’s wallstreetbets mad investors/traders start humiliating the $GME short sellers to the core.
During Mar 2020 when Pandemic tensions heightened $GME stocks dropped down to 4 dollar per share. And lot more institutional investors thought Game Stop Corporation will eventually go bust and started adding shorts in Gamestop Corp.
However during Aug 2020 Ryan Cohen Billionaire & Founder – Chewy started accumulating stocks in GameStop and by December 2020 Cohen’s RC Ventures bought 9 million shares and increased his stake in the video game retailer to almost 13%.
And in the mean time Microsoft also released its most anticipated PS5 and X-Box series X marking the beginning of the new console cycle and also During Nov 2020 Game stop signed a deal with Microsoft that Microsoft will give Gamestop a share of Xbox’s digital revenues.
On January 11, 2021, Ryan Cohen recommended changes in the business model of Gamestop to modernize the business, including adding three new directors to the board. And thats the turning point of the stock which caught the eye of retail investors to buy this stock
On the other side the institutional short sellers went crazy because of poor fundamentals and decided to buy more shorts. i.e. averaging their short bets to defend their existing market positions.
Short Interest in GameStop
Short interest for GameStop has estimated at almost 140% of its float i.e short interest exceeded more than the total outstanding shares. That’s extremely high and more investors are still over-pessimistic about the stock despite the stock running high.
Short interest is the total number of shorted shares divided by the number of shares outstanding.
Institutional Shorts from Melvin Capital and Citron Research
As of Jan 22nd, 2021 on the biggest insitutional short seller Melvin Capital is down by 30% an approximate loss of 3.9 billion dollars.
It is to be noted that Gabe Plotkin’s Melvin Capital and Andrew Left’s Citron Research are the notable short sellers in Gamestop
Ken Griffin’s Citadel and Steve Cohen’s Point72 Asset Management are investing 2.7 billion dollars into Melvin Capital to help stabilize the fund that has been hammered by bad short bets this year.
Citadel and its partners are investing $2 billion and Point72, which already had more than $1 billion invested in Melvin as of 2019, is investing an additional $750 million
It Means Melvin capital is ridiculously adamant about this short position in Gamestop and showing higher interest in accumulating the shorts at higher levels. And as of 26th Jan 2021 close Gamestop closed at 147.98 USD per share.
Unlike many other hedge funds, Melvin has an aggressive short book. Melvin Capital, since its 2014 founding, has returned an average of 30% a year.
Gamestop Crazyness among Social Media Celebrities.
Recent tweets from Social Media celebrities and Billionaires like Chamath Palihapitiya and Elon Musk added more investing interest among the common retailers.
Minutes after tweet from Elon Musk made new investors to go crazy all over GameStop
Robinhood traders and the Reddit Wallstreetbets are likely to break the Hedgefund Melvin capital if the price of game stop further keep rising from here.
What do you think Melvin Capital should respect the risk and wait for right opportunity? Or they will be rewarded their extraordinary risk what they are taking by shorting Gamestop at higher price levels?
This tutorial helps you to understand how to send cover orders from the Tradingview platform using the webhook method to Algomojo Trading Platform.
Supported Brokers
Aliceblue, Upstox, Tradejini, Zebu
What is a Cover Order?
Cover Order is a 2 legged Intraday order 1)Leg 1 is the main Buy or Sell Order (Market Order / SL-Limit Order) 2)Leg 2 is a compulsory stop-loss Order (SL-Market Order)
Benefit of Cover Order
1)Intraday Risk is Pre-Defined and Controlled 2)Order Goes to the Exchange and rest there. Even if the Broker Server goes for Outage or Even if the traders internet goes down no matter what Cover Order gets a fill.
TradingView Webhook
Tradingview Webhooks allow you to send a POST request to a certain URL every time the alert is triggered. This feature can be enabled when you create or edit an alert
Various Modes One can send Alerts from Tradingview Platform
Both free version and paid version support real-time data for NSE Cash, NSE Futures, MCX Futures with Alerts. However, Webhook Alerts are available in the Tradingview Pro version onwards.
Tradingview Strategy to Place Cover Orders
Tradingview Supports strategies which contains rules in pinescript language which instructs the system when to Buy/Sell orders, Modify, Cancel Orders.
Supertrend with Cover-Order Stoploss Plot
CoverOrder Price for Buy = closing value when buy got triggered – stoploss CoverOrder Price for Sell = closing value when short got triggered – stoploss
Tradingview Alerts Settings
Supertrend Pinescript Code for Placing Cover Orders
Strategies allow you to perform backtesting (emulation of a strategy trading on historical data) and forwardtesting (emulation of a strategy trading on real-time data) according to your algorithms.
In order to send market orders from Tradingview to Algomojo in the last tutorial, we seen how to use Tradingview webhook feature to configure Automated orders using the Tradingview Alert Option.
Now this time we are going to use tradingview placeholders in the webhook Alert option to dynamically send Buy Orders when there is a Buy Signal in Supertrend and Sell Signal when there is a Sell Signal in Supertrend
Among All the Place Holders we are going to use {{strategy.order.comment}} and {{plot(“tradestop”)}} which reads the comment from the strategy section and dynamic tradestop to change the order type dynamically based on the supertrend Buy or Sell Signal with a pre-determined stop loss.
{{strategy.order.comment}} - Which dynamically transmits "B" or "S " values
{{plot("tradestop")}} - Which Dynamically transmits the stop Price. The stop price is computed and plotted using the plot function as shown below
Where to Check the Order in Realtime in Algomojo
You can use order logs to check for any incoming automated orders generating from Tradingview Webhooks in Realtime and can also download the logs for later use.
Let me know in comments if you find this tutorial useful or incase if you need more details about algomojo integration with tradingview you can comment your inputs below.
In the previous session, we learned how Algomojo users can Get Free Upstox Interactive API and Historical Data API and in this tutorial, we are going to learn how to use Historical Intraday API, how to test the historical data API, and how to fetch Upstox Historical Intraday API Data into Excel sheet using Microsoft power query.
How to Test using Postman
Postman is an innovative tool to understand the API and 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 fetch historical data and helps understand the API data format much better before designing your trading strategies using the APIs.
Fetch Upstox Historical Intraday API Data into Excel sheet
Once you test the Historical API then next solution is to bring the historical data API into excel. Inorder to bring a Rest API with post method it is highly recommended to use Microsoft power query to fetch the historical data.
According to Microsoft portal, Power Query is a data connection technology that enables you to discover, connect, combine, and refine data sources to meet your analysis needs. Features in Power Query are available in Excel and Power BI Desktop.
Video Tutorial on Fetching Free Upstox API data
Microsoft Power Query
let
url = "https://upapi.algomojo.com/1.0/Historical",
body = "{
""api_key"":""8dedb0aae13f84107fa22651e4c53284"",
""api_secret"":""8bc7d9166092522db22da9c345345345"",
""data"":
{
""symbol"":""RELIANCE"",
""exchange"":""NSE_EQ"",
""interval"":""5"",
""start_date"":""24-01-2021"",
""end_date"":""29-01-2021"",
""format"":""json""
}
}",
Source = Json.Document(Web.Contents(url, [Headers=[#"Content-Type"="application/json"],Content =Text.ToBinary(body)])),
data = Source[data],
#"Converted to Table" = Table.FromList(data, Splitter.SplitTextByDelimiter(","), null, null, ExtraValues.Error),
#"Changed Type" = Table.TransformColumnTypes(#"Converted to Table",{{"Column1", Int64.Type}, {"Column2", type number}, {"Column3", type number}, {"Column4", type number}, {"Column5", type number}, {"Column6", Int64.Type}}),
#"Renamed Columns" = Table.RenameColumns(#"Changed Type",{{"Column1", "DateTime"}, {"Column2", "Open"}, {"Column3", "High"}, {"Column4", "Low"}, {"Column5", "Close"}, {"Column6", "Volume"}}),
#"Added Custom" = Table.AddColumn(#"Renamed Columns", "Timestamp", each #datetime(1970,1,1,0,0,0) + #duration(0, 5,30, [DateTime]/1000)),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"DateTime"}),
#"Reordered Columns" = Table.ReorderColumns(#"Removed Columns",{"Timestamp", "Open", "High", "Low", "Close", "Volume"}),
#"Renamed Columns1" = Table.RenameColumns(#"Reordered Columns",{{"Timestamp", "DateTime"}})
in
#"Renamed Columns1"
This tutorial explores how to build your very first execution module in Amibroker and How to transmit orders from Amibroker to Algomojo trading platoform.
What is a Execution Logic?
Traders who want to automate their Buy and Sell logic they often needs to decide how they want to execute their orders or automate their orders that they are sending to their broker server.
Here a simple button based control is discussed where with a press of the button order gets punched automatically to your broker sever.
What is a Algomojo Bridge?
Algmojo comes with Multi Broker Bridge which provides access to send your automated orders from Amibroker to your broker server
What is AM Dispatcher?
AM Dispatcher is a simple function inside Algomojo Multi Broker Bridge which transports the data from Amibroker to your broker server.
Here is a video tutorial where I explained how to create Amibroker Execution module right from the scratch.
Simple Execution Module – Amibroker AFL
_SECTION_BEGIN("Simple Execution Module");
SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
//plot the candles
Plot(Close,"Close",colorDefault,GetPriceStyle() | styleNoTitle);
apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
apisecret = ParamStr("api_secret","6d5acaca5714131814125f8216098782"); //Enter your API secret key here
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich, an - angel broking, up - upstox
ver = ParamStr("API Version","1.0");
trigger = ParamTrigger("PlaceOrder","Send Order");
if(trigger)
{
//send order to the broker
api_data = "{
\"strg_name\":\"Test Strategy\",
\"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\",
\"Tsym\":\"LUPIN-EQ\",
\"exch\":\"NSE\",
\"Ttranstype\":\"B\",
\"Ret\":\"DAY\",
\"prctyp\":\"MKT\",
\"qty\":\"100\",
\"discqty\":\"0\",
\"MktPro\":\"NA\",
\"Price\":\"0\",
\"TrigPrice\":\"0\",
\"Pcode\":\"MIS\",
\"AMO\":\"NO\"
}";
algomojo=CreateObject("AMAMIBRIDGE.Main");
response = algomojo.AMDispatcher(apikey,apisecret,"PlaceOrder",api_data,broker,ver);
_TRACE("Broker Server Response : "+ response);
}
_SECTION_END();
Building your First Cover Order Execution Module using Amibroker and Creating Execution Controls
Simple Cover Order Execution Module – Amibroker AFL
_SECTION_BEGIN("Simple Cover Order Module");
SetChartOptions(0, chartShowArrows | chartShowDates); //x-Axis will be plottted
//plot the candles
Plot(Close,"Close",colorDefault,GetPriceStyle() | styleNoTitle);
apikey = ParamStr("user_apikey","86cbef19e7e61ccee91e497690d5814e"); //Enter your API key here
apisecret = ParamStr("api_secret","6d5acaca5714131814125f8216098782"); //Enter your API secret key here
broker = ParamStr("Broker","tj"); //Broker Short Code - ab - aliceblue, tj - tradejini, zb - zebu, en - enrich, an - angel broking, up - upstox
ver = ParamStr("API Version","1.0");
symbol = ParamStr("Symbol Name","RELIANCE-EQ");
stoplevel = Param("Stop Levels",1900,1,10000,1);
trigger = ParamTrigger("PlaceOrder","Send Order");
if(trigger)
{
//send order to the broker
api_data = "{
\"strg_name\":\"Test Strategy\",
\"s_prdt_ali\":\"BO:BO||CNC:CNC||CO:CO||MIS:MIS||NRML:NRML\",
\"Tsym\":\""+symbol+"\",
\"exch\":\"NSE\",
\"Ttranstype\":\"B\",
\"Ret\":\"DAY\",
\"prctyp\":\"MKT\",
\"qty\":\"100\",
\"discqty\":\"0\",
\"MktPro\":\"NA\",
\"Price\":\"0\",
\"TrigPrice\":\""+stoplevel+"\",
\"Pcode\":\"CO\",
\"AMO\":\"NO\"
}";
//Create the object to access the algomojo bridge
algomojo=CreateObject("AMAMIBRIDGE.Main");
//sending the data using AM Dispatcher to the broker server
response = algomojo.AMDispatcher(apikey,apisecret,"PlaceOrder",api_data,broker,ver);
_TRACE("Broker Server Response : "+ response);
}
_SECTION_END();
Now with a click of the Send Order button you should be able to test your orders during live market. See you in the next tutorial with even concepts on building your automated trading using algomojo platform.
We know that google spreadsheets support an inbuilt function google finance to fetch real-time stock quotes for Equities markets. However, do you know how to get Futures and Options Data, Commodities Data into Google Spreadsheet?
In this tutorial, we are going to use Google Appscript to fetch real-time stock quotes using your Brokers API for NSE Cash, NSE Futures & Options, MCX, NSE Currency, BSE Currency Data into the Google Spreadsheet.
Requirements
1)Algomojo API 2)Google Spreadsheets 3)Trading Account with Algomojo Supported Brokers (Currently, Algomojo Supports Aliceblue, Tradejini, Upstox & Zebu)
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 can access the Appscript Editor from Tools->Script Editor from your Google Spreadsheet.
What is Algomojo?
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 Connected 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.
Open the Script Editor and Paste the below appscript code and save the code as Algomojo
Get the API Key and API Secret Key, Broker Shortcode from Algomojo Platform and replace the apikey and apisecret key & Broker in the below code with yours.
Now after setting the Apikey, Apusecret & Broker short code one have to start accessing the quotes using algomojo user defined function. Here is the formula to access the quotes
=Algomojo("Symbol", "Exchange", "Field");
Symbol Formatting
Where symbol is the ticker name as the broker symbol format. If not sure about the symbol. Log into the Algomojo trading platform and checkout the symbol format. Symbol format varies and different broker adapts different formatting when comes to the Symbol Format.
For example the symbol for Reliance in Tradejini, Aliceblue, Zebu is “Reliance-EQ” and for upstox brokers the symbol format is only “RELIANCE”
Supported Exchanges Parameter
Exchange
Description
NSE
NSE Equities
BSE
BSE Equities
NFO
NSE Futures & Options
NCD
NSE Currencies
BCD
BSE Currencies
MCX
MCX Futures & Options
NSE_IDX
NSE Index
BSE_IDX
BSE Index
Exchange Parameter supported by Algomojo
Field Parameter‘
Field parameter defines what information about the stock quotes one want to extract. Following are the supported field parameters
Field
Description
ltp
Last Traded Price
open
Todays Open
High
Todays High
Low
Low
prevclose
Prev Close
volume
Todays Total Volume
oi
Open Interest
change
Todays Price Change
perchange
Today Price Percentage Change
Fields Parameter supported by Algomojo
Calling the Algomojo Functions from Google Spreadsheets to access Last Traded Price
=Algomojo("NIFTY21FEBFUT","NFO","ltp")
Calling the Algomojo Functions from Google Spreadsheets to access Options Open Interest Data
=Algomojo("NIFTY2121115000CE","NFO","oi")
Calling the Algomojo Functions from Google Spreadsheets to access Commodities Last Traded Price
With these information you should be able to get any traded quote from Indian Markets into Google Spreadsheet in Realtime. And to update the Algomojo Functions frequently one can consider adding triggers.
How to Add Triggers
1)From the Google Spreadsheet goto Tools -> Script Editor ensure that Algomojo.gs appscript is open and the Apikey, Apisecret key and broker shortcode is set properly
2)One the Left hand side select the Triggers option 3)Click on Add Trigger button
4)Now select the following values from the dialog box as shown below i)select event source as Time-Driven ii)Select type of time-based trigger as Minutes timer iii)Select minute interval as Every minute or any other value from the list depends upon your frequency of data access and the minimum possible interval is 1-minute
Press save to save the values
Once the Trigger is saved you will be able to access the Triggers details as shown below
Note
Avoid Calling too many symbols. Limit yourself upto 25-50 algomojo functions as most of the brokers does rate limiting on API calls. Rate limiting defines limits on how many API calls can be made within a specified time period. Rate limits are imposed on every app.
If the Limit exceeds the API function might throw an error to the user. And many brokers also impose 1 request/second rate limit on accessing the stock quotes.