Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

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

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

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

if (PositionBook) {
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++ )

   posdetails1 = StrExtract(posdetails,1,':');
   possym = StrTrim(posdetails1,"\"");
   _TRACE("\nSymbol : "+possym);

   posdetails = StrExtract(posdetails,1,':');
   posNetqty = StrToNum(StrTrim(posdetails,"\""));
   _TRACE("\nNetQty : "+posNetqty);
	posdetails = StrExtract(posdetails,1,':');
	posupnl = StrTrim(posdetails,"\"");
    _TRACE("\nUnRealized PNL : "+posupnl);
    posdetails = StrExtract(posdetails,1,':');
	posrpnl = StrToNum(StrTrim(posdetails,"\""));
    _TRACE("\n Realized PNL : "+posrpnl);
    posdetails = StrExtract(posdetails,1,':');
	posmtm = StrToNum(StrTrim(posdetails,"\""));
    _TRACE("\nMTM PNL : "+posmtm);

} //end of for loop

}//end of for loop

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


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

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 Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

AllinOneAlerts – Amibroker Alerts Module for Amibroker Users

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

How to improve your Amibroker Algo Trading Execution Speed

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

Introduction to QuantZilla 2.0

QuantZilla is a 75+ hours of immersive coding mentor-ship program on designing trading systems, converting trading ideas into indicators and trading strategies, automating the...
Rajandran R
4 min read

Leave a Reply

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