Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

How to Retrieve the Position Book Details from Algomojo

3 min read

This tutorial is for Algomojo users who want to retrieve the realtime position book details (Trading Symbol, Unrealized Profits, Realized Profits, MtoM for the particular traded symbol).

Retriving the data from the position book is particularly useful for the Algotraders who want to do the following

1)To set Symbol level stop loss
2)To set Symbol level stop/target exit from portfolio
3)MTM PNL based target exit
4)To retrieve the NetQty from the Position Book to check whether the position exists or not before placing orders.

Login to Algomojo.com with your trading credentials. In case if you are new to algomojo check out the video tutorials here on Introduction to Algomojo

Algomojo Position Book

Enable Amibroker Tracelog

1)Extract the Amibroker Tracelog by going to the Amibroker Menu -> Window -> Log

2)Goto the Trace tab in the Log Window

3)Enable the tracelog by right click over the Log Window and enable Trace Output for both internal and external options as shown below

Sample Amibroker Tracelog

Amibroker AFL Code to Extract from the Position Book

// Algomojo Bridge Position Book Extract Test AFL
// Developer: Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)
// Date: 28-Oct-2020
// Website: algomojo.com / marketcalls.in

_SECTION_BEGIN("Algomojo Bridge Position Book Extract");

PlaceOrder = ParamTrigger("PlaceOrder","PRESS");
PositionBook = True; //Keep the Position Book Running in the Background



user_apikey = ParamStr("user_apikey","xxxxxxxxx"); //Enter your API key here
api_secret = ParamStr("api_secret","yyyyyyyyy"); //Enter your API secret key here
clnt_id = ParamStr("Client ID","TS2499");
s_prdt_ali = ParamList("s_prdt_ali","BO:BO|CNC:CNC|CO:CO|MIS:MIS|NRML:NRML",3); //Type of order
Tsym = ParamStr("Tsym","RELIANCE-EQ"); //Enter the symbol name here
exch = ParamList("Exchange","NFO|NSE|BSE|CDS|MCX|NCDEX|BFO|MCXSXFO|MCXSX",1); 
Ret = ParamList("Ret","DAY|IOC",0);
Ttranstype = ParamList("Ttranstype","B|S",0);
prctyp = ParamList("prctyp","MKT|L|SL|SL-M",0);
Pcode = ParamList("Pcode","NRML|BO|CNC|CO|MIS",4);
Price = ParamList("Price","0");
TrigPrice = ParamList("TrigPrice","0");
qty = Param("Quatity",75,0,100000,1); 
discqty = ParamList("discqty","0");
AMO = ParamList("AMO","NO|YES",0); //After market order
stgy_name = ParamStr("Strategy Name", "Test Strategy Chart");

//Initialization
flag = 0;
possym = "";
posNetqty =0;
posupnl = 0;
posrpnl =0;
posmtm =0;




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

if (PositionBook) {
ThreadSleep(200);
algomojo=CreateObject("XLAMIBRIDGE.Main");
api_data ="{\"uid\":\""+clnt_id+"\",\"actid\":\""+clnt_id+"\",\"type\":\""+"DAY"+"\",\"s_prdt_ali\":\""+s_prdt_ali+"\"}";
resp=algomojo.AMDispatcher(user_apikey, api_secret,"PositionBook",api_data);

_TRACE("Trace Start  : ");

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,"Tsym"))
  {
   posdetails1 = StrExtract(posdetails,1,':');
   possym = StrTrim(posdetails1,"\"");
   _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");
}


}//end of position book loop



//Plot Correlation and CoIntegration in a Dashboard

GfxSetBkMode( 0 );
GfxSelectFont( "Tahoma", 13, 100 );
GfxSetTextColor( colorWhite );


GfxSelectPen( colorGreen, 2 ); 
GfxSelectSolidBrush( colorgreen ); 
GfxRectangle( 10, 20, 250, 250 );

GfxTextOut( "Position Book",23,23); 
GfxTextOut( "Symbol: " + possym,23,48); 
GfxTextOut( "Net Qty : " + NumToStr(posNetqty,1.2,separator=false),23,73);
GfxTextOut( "Unrealized Profits: " + posupnl,23,98); 
GfxTextOut( "Realized : " + NumToStr(posrpnl,1.2,separator=false),23,123);
GfxTextOut( "MTM PNL : " + NumToStr(posmtm,1.2),23,148);


_SECTION_END();

_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

Retrieving the Position Book Log from Algomojo

Now Apply the AFL code. Set the correct trading parameters from the parameter option by right-clicking over the charts

Log Window Output

If the symbol that you mentioned in the parameter box is present then automaitcally you will be able to see the position details from the log window as shown below

Position Book Response : [{"unrealisedprofitloss":"0.00","Fillsellqty":"10","PriceNumerator":"1","realisedprofitloss":"0.00","Type":"DAY1","Fillbuyqty":"0","BLQty":1,"s_NetQtyPosConv":"N","Sellavgprc":"28.20","Exchangeseg":"nse_cm","Opttype":"XX","Bqty":"0","Exchange":"NSE","Fillsellamt":"282.00","actid":"TS2499","GeneralDenomenator":"1","discQty":"10","Instname":"NA","Netqty":"-10","sSqrflg":"Y","LTP":"28.20","Tsym":"20MICRONS-EQ","Expdate":"NA","Buyavgprc":"0.00","Netamt":"282.00","Token":"16921","GeneralNumerator":"1","companyname":"20 MICRONS LTD","stat":"Ok","Sqty":"10","PriceDenomenator":"1","MtoM":"0.00","Symbol":"20MICRONS","posflag":"true","Series":"EQ","BEP":"28.20","Stikeprc":"0","Pcode":"MIS","Fillbuyamt":"0.00"},{"unrealisedprofitloss":"0.60","Fillsellqty":"0","PriceNumerator":"1","realisedprofitloss":"0.00","Type":"DAY1","Fillbuyqty":"2","BLQty":1,"s_NetQtyPosConv":"N","Sellavgprc":"0.00","Exchangeseg":"nse_cm","Opttype":"XX","Bqty":"2","Exchange":"NSE","Fillsellamt":"0.00","actid":"TS2499","Gen13:22:29.87

MTM PNL : -0.3	Formulas\Algomojo\Algomojo Position Book.afl	97	33	13:22:29.87

Symbol : YESBANK-EQ	Formulas\Algomojo\Algomojo Position Book.afl	71	32	13:22:29.87

NetQty : 6	Formulas\Algomojo\Algomojo Position Book.afl	78	34	13:22:29.87

 Realized PNL : 0	Formulas\Algomojo\Algomojo Position Book.afl	90	40	13:22:29.87

UnRealized PNL : -0.30	Formulas\Algomojo\Algomojo Position Book.afl	84	41	13:22:29.87
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in and Co-Creator of Algomojo (Algorithmic Trading Platform for DIY Traders)

Multi-Client Button Trading Amibroker AFL

Got frequent requirements from many traders to automate an Amibroker-based trading system where one single button click from charts could punch orders in multiple...
Rajandran R
7 min read

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

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

Line Trading – Algomojo Automation Module for Amibroker Users

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

Leave a Reply

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