Ejemplo n.º 1
0
        //EXCHANGE,TOKEN,SYMBOL,PRODUCT,ORDER_TYPE,TRANSACTION_TYPE,TRADED_QUANTITY,EXCHANGE_ORDER_ID,ORDER_ID,EXCHANGE_TIME,TIME_IN_MICRO,TRADED_PRICE,TRADE_ID
        // consolidated all trades for a given order, and final trade list contains consolidated trade for each order
        public BrokerErrorCode GetTradeBook(bool getOnlyNewTrades, string stockCode, out Dictionary <string, EquityTradeBookRecord> trades)
        {
            lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode = BrokerErrorCode.Unknown;
                trades = new Dictionary <string, EquityTradeBookRecord>();

                int retryCount    = 0;
                int maxRetryCount = 3;

                while (errorCode != BrokerErrorCode.Success && retryCount++ < maxRetryCount)
                {
                    try
                    {
                        var response = upstox.GetTradeBook();

                        string[] lines = response.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

                        var uniqueconsolidatedTrades = new Dictionary <string, EquityTradeBookRecord>();

                        for (int i = 1; i < lines.Length; i++)
                        {
                            var line = lines[i].Split(',');

                            if (line.Length < 13)
                            {
                                continue;
                            }

                            if (!string.IsNullOrEmpty(stockCode) &&
                                !line[2].Equals(stockCode, StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            var trade = new EquityTradeBookRecord();
                            trade.OrderId         = line[8];
                            trade.TradeId         = line[12];
                            trade.Direction       = line[5] == "B" ? OrderDirection.BUY : OrderDirection.SELL;
                            trade.DateTime        = DateTime.Parse(line[9]);
                            trade.Quantity        = int.Parse(line[6]);
                            trade.NewQuantity     = trade.Quantity;
                            trade.Price           = double.Parse(line[11]);
                            trade.StockCode       = line[2];
                            trade.EquityOrderType = line[3] == "D" ? EquityOrderType.DELIVERY : EquityOrderType.MARGIN;
                            trade.Exchange        = line[0];

                            if (uniqueconsolidatedTrades.ContainsKey(trade.OrderId))
                            {
                                var consolidatedTrade = uniqueconsolidatedTrades[trade.OrderId];

                                var price = ((consolidatedTrade.Quantity * consolidatedTrade.Price) + (trade.Quantity * trade.Price)) / (trade.Quantity + consolidatedTrade.Quantity);
                                price = Math.Round(price, 2);
                                var quantity    = trade.Quantity + consolidatedTrade.Quantity;
                                var newQuantity = trade.NewQuantity + consolidatedTrade.NewQuantity;

                                if (trade.DateTime > consolidatedTrade.DateTime)
                                {
                                    trade.Price       = price;
                                    trade.Quantity    = quantity;
                                    trade.NewQuantity = newQuantity;
                                    uniqueconsolidatedTrades[trade.OrderId] = trade;
                                }
                                else
                                {
                                    consolidatedTrade.Price       = price;
                                    consolidatedTrade.Quantity    = quantity;
                                    consolidatedTrade.NewQuantity = newQuantity;
                                }
                            }
                            else
                            {
                                uniqueconsolidatedTrades.Add(trade.OrderId, trade);
                            }
                        }


                        foreach (var trade in uniqueconsolidatedTrades.Select(kv => kv.Value).ToList())
                        {
                            lock (lockObjectEquity)
                            {
                                // existing trade
                                if (mEquityTradeBook.ContainsKey(trade.OrderId))
                                {
                                    var prevTradeRecord = mEquityTradeBook[trade.OrderId];

                                    // for part exec, the NewQuantity gets updated with delta from previous
                                    trade.NewQuantity = trade.Quantity - prevTradeRecord.Quantity;

                                    if (getOnlyNewTrades)
                                    {
                                        // add if execution status change along with prev and current execution qty
                                        if (trade.NewQuantity > 0)
                                        {
                                            trades.Add(trade.OrderId, trade);
                                        }
                                    }
                                    else
                                    {
                                        trades.Add(trade.OrderId, trade);
                                    }
                                    // Update the trade
                                    // update required because PartExec may have become full exec
                                    mEquityTradeBook[trade.OrderId] = trade;
                                }
                                else
                                {
                                    // new trade
                                    mEquityTradeBook.Add(trade.OrderId, trade);
                                    trades.Add(trade.OrderId, trade);
                                }
                            }
                        }

                        errorCode = BrokerErrorCode.Success;
                    }
                    catch (Exception ex)
                    {
                        Trace(string.Format(genericErrorLogFormat, stockCode, GeneralUtils.GetCurrentMethod(), ex.Message, ex.StackTrace));
                        Trace(string.Format(retryLogFormat, retryCount, maxRetryCount));

                        if (retryCount >= maxRetryCount)
                        {
                            break;
                        }
                    }
                }

                return(errorCode);
            }
        }
        // IBroker.GetEquityTradeBook

        // Get trade book for a date range and for specific stock if stockCode is valid
        // else gets complete trade book fro the date range
        public BrokerErrorCode GetEquityTradeBookToday(bool newTradesOnly,
                                                       string stockCode,
                                                       out Dictionary <string, EquityTradeBookRecord> trades)
        {
            trades = new Dictionary <string, EquityTradeBookRecord>();
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

            if (errorCode != BrokerErrorCode.Success)
            {
                return(errorCode);
            }

            string postData = "pgname=eqTrdBook&ismethodcall=0&mthname=";

            string tradeBookData = IciciGetWebPageResponse(URL_ICICI_EQT_TRADEBOOK,
                                                           postData,
                                                           URL_ICICI_REFERRER,
                                                           mCookieContainer,
                                                           out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success) && !tradeBookData.Contains("No matching Trades"))
            {
                // Trim it
                tradeBookData = tradeBookData.Trim(' ', '\t', '\r', '\n');

                tradeBookData = HtmlUtilities.EnsureHtmlParsable(tradeBookData);

                string subTradeBookData = StringParser.GetStringBetween(tradeBookData,
                                                                        0,
                                                                        "<thead>",
                                                                        "</table>",
                                                                        new string[] { });

                ParsedTable table = (ParsedTable)HtmlTableParser.ParseHtmlIntoTables("<table>" + subTradeBookData + "</table>", true);

                //trades = new Dictionary<string, EquityTradeBookRecord>();

                for (int i = 1; i < table.RowCount - 1; i++)
                {
                    EquityTradeBookRecord info = new EquityTradeBookRecord();
                    info.StockCode = table[i, 1].ToString().Trim();
                    // If stockCode parameter is not null i.e. all stocks are intended
                    // and if stock specific orders are intended and current element's stockCode doesnt match then iterate to next element
                    if (!string.IsNullOrEmpty(stockCode) && !info.StockCode.Equals(stockCode, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var temp = StringParser.GetStringBetween(table[i, 0].ToString(), 0, "nowrap;\">", "<", null);
                    DateTime.TryParse(temp, out info.Date);

                    //if (bSuccess)
                    //{
                    //    info[0].UpdateTime = result;
                    //}
                    string tempStr = table[i, 2].ToString().ToUpperInvariant().StartsWith("B") ? "BUY" : "SELL";
                    info.Direction  = (OrderDirection)Enum.Parse(typeof(OrderDirection), tempStr);
                    info.Quantity   = int.Parse(table[i, 3].ToString());
                    info.Price      = double.Parse(table[i, 4].ToString());
                    info.TradeValue = double.Parse(table[i, 5].ToString());
                    //tempStr = StringParser.GetStringBetween(table[i, 6].ToString(), 0, "\">", "</a>", null);
                    info.Brokerage        = double.Parse(table[i, 6].ToString());
                    info.SettlementNumber = StringParser.GetStringBetween(table[i, 7].ToString(), 0, "setno=", "&", null);
                    string orderRefString = StringParser.GetStringBetween(table[i, 10].ToString(), 0, "FML_ORD_ORDR_RFRNC=", "&", null);
                    info.OrderRefenceNumber = orderRefString.Trim();
                    lock (lockObjectEquity)
                    {
                        if (mEquityTradeBook.ContainsKey(info.OrderRefenceNumber))
                        {
                            if (newTradesOnly)
                            {
                            }
                            else
                            {
                                trades.Add(info.OrderRefenceNumber, info);
                            }
                            // Update the trade
                            // update required because PartExec may have become full exec
                            mEquityTradeBook[info.OrderRefenceNumber] = info;
                        }
                        else
                        {
                            mEquityTradeBook.Add(info.OrderRefenceNumber, info);
                            trades.Add(info.OrderRefenceNumber, info);
                        }
                    }
                }
            }
            return(errorCode);
        }