Exemplo n.º 1
0
        public double GetTradeExecutionPrice(DateTime fromDate,
                                             DateTime toDate,
                                             InstrumentType instrumentType,
                                             string orderRefString)
        {
            double executionPrice = -1;

            BrokerErrorCode errorCode = BrokerErrorCode.Success;

            if (instrumentType.Equals(InstrumentType.Share))
            {
                errorCode = RefreshEquityTradeBook(this, fromDate, toDate, false);
                if (!errorCode.Equals(BrokerErrorCode.Success))
                {
                    return(executionPrice);
                }
                lock (lockObjectEquity)
                {
                    if (mEquityTradeBook.ContainsKey(orderRefString))
                    {
                        executionPrice = mEquityTradeBook[orderRefString].Price;
                    }
                }
            }

            return(executionPrice);
        }
Exemplo n.º 2
0
        public static bool HasOrderExecuted(
            IBroker broker,
            string stockCode,
            int quantity,
            double price,
            OrderPriceType orderType,
            OrderDirection orderDirection,
            InstrumentType instrumentType,
            DateTime expiryDate,
            out string orderReferenceNumber)
        {
            orderReferenceNumber = null;

            string contract   = String.Empty;
            string strExpDate = expiryDate.ToString("dd-MMM-yyyy");

            if (instrumentType == InstrumentType.FutureIndex || instrumentType == InstrumentType.FutureStock)
            {
                contract += "FUT-";
            }
            else
            {
                throw new NotSupportedException();
            }
            contract += (stockCode + "-" + strExpDate);
            // this loop is there just for potential retry purpose
            for (int count = 1; count <= 2; count++)
            {
                Dictionary <string, DerivativeTradeBookRecord> trades;
                BrokerErrorCode errorCode = broker.GetDerivativesTradeBook(DateTime.Now,
                                                                           DateTime.Now,
                                                                           instrumentType,
                                                                           true,
                                                                           out trades);

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

                foreach (DerivativeTradeBookRecord singleTrade in trades.Values)
                {
                    if (singleTrade.ContractName.ToUpperInvariant() != contract.ToUpperInvariant())
                    {
                        continue;
                    }
                    if (singleTrade.Quantity != quantity)
                    {
                        continue;
                    }
                    if (singleTrade.Direction != orderDirection)
                    {
                        continue;
                    }
                    orderReferenceNumber = singleTrade.OrderRefenceNumber;
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 3
0
        public DerivativeSymbolTick GetTick(bool getSpread, out BrokerErrorCode code)
        {
            DerivativeSymbolQuote  Q  = null;
            DerivativeSymbolSpread S  = null;
            DerivativeSymbolTick   T  = new DerivativeSymbolTick();
            StringBuilder          sb = new StringBuilder();

            code = _broker.GetDerivativeQuote(Instrument.Symbol, Instrument.InstrumentType, Instrument.ExpiryDate, Instrument.StrikePrice, out Q);
            // Check for exchange closed or contract disabled code
            if (code == BrokerErrorCode.Success)
            {
                T.Q = Q;
                sb.Append(Q.ToTickString());
            }
            if (getSpread)
            {
                code = _broker.GetDerivativeSpread(Instrument.Symbol, Instrument.InstrumentType, Instrument.ExpiryDate, Instrument.StrikePrice, out S);
                if (code == BrokerErrorCode.Success)
                {
                    T.S = S;
                    sb.Append(";" + S.ToString());
                }
            }
            if (code.Equals(BrokerErrorCode.Success) && (_writeTicks || MarketUtils.IsTimeTodayAfter915(Q.QuoteTime)))
            {
                _writeTicks = true;
                _ticksw.WriteLine(sb.ToString());
            }
            return(T);
        }
Exemplo n.º 4
0
        // Is logged in
        public BrokerErrorCode IsLoggedIn()
        {
            BrokerErrorCode errorCode = TouchServer();

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                mLoggedIn = true;
            }

            return(errorCode);
        }
Exemplo n.º 5
0
        public BrokerErrorCode GetOrderStatus(string orderNumber,
                                              InstrumentType instrumentType,
                                              DateTime fromDate,
                                              DateTime toDate,
                                              out OrderStatus orderStatus)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Success;

            orderStatus = OrderStatus.NOTFOUND;

            if (instrumentType == InstrumentType.Share)
            {
                Dictionary <string, EquityOrderBookRecord> orders;

                errorCode = GetEquityOrderBook(fromDate,
                                               toDate,
                                               false,
                                               false,
                                               null,
                                               out orders);

                if (errorCode.Equals(BrokerErrorCode.Success))
                {
                    foreach (KeyValuePair <string, EquityOrderBookRecord> orderPair in orders)
                    {
                        EquityOrderBookRecord order = orderPair.Value;
                        if (order.OrderRefenceNumber == orderNumber)
                        {
                            orderStatus = order.Status;
                            break;
                        }
                    }
                }
            }

            FileTracing.TraceOut(!errorCode.Equals(BrokerErrorCode.Success), "GetOrderStatus:" + errorCode.ToString(), TraceType.Error);
            return(errorCode);
        }
Exemplo n.º 6
0
        /////////////////////////////////////////////////////
        //////      ACCOUNT LOGIN FUNCTIONALITY       ///////
        /////////////////////////////////////////////////////

        // NOTE: Should be used only when logged-in status is mandatory
        // so that server contact time (which matters to maintain the login) can be updated
        // Do not use this (Use HttpHelper.GetWebPageResponse instaed) for GET QUOTE or similar where log-in is not needed

        private string IciciGetWebPageResponse(string url,
                                               string postdata,
                                               string referer,
                                               CookieContainer cookieContainer,
                                               out BrokerErrorCode errorCode)
        {
            errorCode = BrokerErrorCode.Success;
            string data = HttpHelper.GetWebPageResponse(url,
                                                        postdata,
                                                        referer,
                                                        cookieContainer);

            // refresh the time if data is valid login and url is of refresh type
            errorCode = CheckResponseDataValidity(data);
            if (ServerLoginTimeoutRefreshURLs.Contains(url) && errorCode.Equals(BrokerErrorCode.Success))
            {
                RefreshLastServerContactTime();
            }
            return(data);
        }
        // TOTEST
        // place margin order
        public BrokerErrorCode PlaceEquityMarginOrder(string stockCode,
                                                      int quantity,
                                                      string stopLossPrice,
                                                      string limitPrice,
                                                      OrderDirection orderDirection)
        {
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_ORD_XCHNG_CD_value   = "NSE";
            string FML_ORD_XCHNG_CD_C_value = FML_ORD_XCHNG_CD_value;
            // order direction
            string FML_ORD_ORDR_FLW_value   = null;
            string FML_ORD_ORDR_FLW_C_value = null;

            if (orderDirection == OrderDirection.BUY)
            {
                FML_ORD_ORDR_FLW_value   = "B";
                FML_ORD_ORDR_FLW_C_value = "S";
            }
            else if (orderDirection == OrderDirection.SELL)
            {
                FML_ORD_ORDR_FLW_value   = "S";
                FML_ORD_ORDR_FLW_C_value = "B";
            }
            // prices
            string FML_ORD_LMT_RT_value  = limitPrice;
            string FML_ORD_STP_LSS_value = stopLossPrice;
            //string FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_NSE_value;

            string query = ("FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                            "FML_ORD_ORDR_FLW_C=" + FML_ORD_ORDR_FLW_C_value +
                            "&FML_ACCOUNT=" + FML_ACCOUNT_value +
                            "&FML_STCK_CD=" + stockCode +
                            "&FML_STCK_CD_C=" + stockCode +
                            "&FML_DOTNET_FLG=Y&FML_URL_FLG=http%3A%2F%2Fgetquote.icicidirect.com%2Ftrading%2Fequity%2Ftrading_stock_quote.asp " +
                            "&FML_QTY=" + quantity.ToString() +
                            "&FML_QTY_C=" + quantity.ToString() +
                            "&FML_ORD_TYP=M" +
                            "&FML_ORD_TYP_C=L" +
                            "&FML_ORD_STP_LSS=" + FML_ORD_STP_LSS_value +
                            "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value +

                            "&FML_ORD_TRD_DT_BSE=" + FML_ORD_TRD_DT_BSE_value +
                            "&FML_ORD_TRD_DT_NSE=" + FML_ORD_TRD_DT_NSE_value +
                            "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_NSE_value +
                            "&FML_PRODUCT_INDEX=0&FML_ORD_PRD_HIDDEN=CASH&FML_ORD_CLM_MTCH_ACCNT=" +
                            "&FML_TRADING_LIMIT_NSE=" + FML_TRADING_LIMIT_NSE_value +
                            "&FML_TRADING_LIMIT_BSE=" + FML_TRADING_LIMIT_BSE_value +
                            "&FML_ORD_DP_CLNT_ID=&FML_ORD_DP_ID=&FML_TRN_PRDT_TYP=" +
                            "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                            "&FML_ORD_XCHNG_CD_C=" + FML_ORD_XCHNG_CD_C_value +
                            "&FML_ORD_XCHNG_CD_CHECK=&FML_PRCNTG_CHECK=3.0&FML_ARRAY_BOUND=1&FML_ARRAY_ELEMENT=&NicValue=&BrowserBack_Xchang=NSE&PWD_ENABLED=N&FML_LAS=Y");

            string orderPlacePageData = IciciGetWebPageResponse(
                URL_ICICI_EQT_CASHMARGIN_ORDER,
                query,
                URL_ICICI_REFERRER,
                mCookieContainer,
                out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                errorCode = GetEQTOrderPlacementCode(orderPlacePageData, EquityOrderType.MARGIN);
                if (BrokerErrorCode.Success == errorCode)
                {
                    // Get exchange reference number (primary key for an order)
                    // add the record to DB
                    // TODO: is it required since we already have parser of order & trade book
                    GetOrderConfirmationData(orderPlacePageData, EquityOrderType.MARGIN);
                }
            }

            return(errorCode);
        }
        // place margin or delivery order
        public BrokerErrorCode PlaceEquityMarginDeliveryFBSOrder(string stockCode,
                                                                 int quantity,
                                                                 string price,
                                                                 OrderPriceType orderPriceType,
                                                                 OrderDirection orderDirection,
                                                                 EquityOrderType orderType,
                                                                 Exchange exchange,
                                                                 out string orderRef)
        {
            orderRef = "";

            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_ORD_ORDR_FLW_value = orderDirection == OrderDirection.BUY ? "B" : "S";

            string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty;

            if (orderPriceType == OrderPriceType.MARKET)
            {
                FML_ORD_TYP_value = "M";
            }
            else if (orderPriceType == OrderPriceType.LIMIT)
            {
                FML_ORD_TYP_value    = "L";
                FML_ORD_LMT_RT_value = price;
            }

            string FML_ORD_TRD_DT_value   = null;
            string squareOffMode          = orderDirection == OrderDirection.SELL ? "S" : "M";
            string FML_ORD_XCHNG_CD_value = null;

            if (exchange == Exchange.BSE)
            {
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_BSE_value;
                FML_ORD_XCHNG_CD_value = "BSE";
            }
            else if (exchange == Exchange.NSE)
            {
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_NSE_value;
                FML_ORD_XCHNG_CD_value = "NSE";
            }

            string prdctType = orderType == EquityOrderType.DELIVERY ? "C" : "M";

            string query =
                "&FML_SQ_FLAG=" + (orderType == EquityOrderType.MARGIN ? squareOffMode : "") +  //Squareoff mode: M (for client) S (for broker), for BSE only S
                "&ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&FML_STCK_CD=" + stockCode +
                "&FML_QTY=" + quantity.ToString() +
                "&FML_ORD_DSCLSD_QTY=" +
                "&FML_POINT_TYPE=T" +
                "&GTCDate7=" + GTCDate7 +
                "&GTCDate=" + GTCDate +
                "&GTCDateHidden7=" + GTCDateHidden7 +
                "&FML_ORD_TYP=" + FML_ORD_TYP_value +
                "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value +
                "&FML_GMS_CSH_PRDCT_PRCNTG=" +
                "&FML_ORD_STP_LSS=" +
                "&FML_TRADING_PASSWD=" +
                "&Submit=Buy+Now" +
                "&FML_ORD_TRD_DT_BSE=" + FML_ORD_TRD_DT_BSE_value +
                "&FML_ORD_TRD_DT_NSE=" + FML_ORD_TRD_DT_NSE_value +
                "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&NSEStatus=" + NSEStatus +
                "&BSEStatus=" + BSEStatus +
                "&FML_PRCNTG_CHECK=" + FML_PRCNTG_CHECK +
                "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_value +
                "&FML_XCHNG_ST=" + NSEStatus +  // O or C  (open or closed)
                "&NicValue=" +
                "&FML_LAS=" +
                "&FML_ACCOUNT=" +
                "&FML_URQ_USR_RD_FLG=" +
                "&FML_ORD_PRDCT_TYP=" + prdctType +
                "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                "&pgname=eqfastbuy&ismethodcall=1&mthname=DoFinalSubmit";

            string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_FASTBUYSELL,
                                                                query,
                                                                URL_ICICI_REFERRER,
                                                                mCookieContainer,
                                                                out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                errorCode = GetEQTOrderPlacementCode(orderPlacePageData);
                if (BrokerErrorCode.Success == errorCode)
                {
                    orderRef = ExtractOrderReferenceNumber(orderPlacePageData);
                }
            }
            return(errorCode);
        }
Exemplo n.º 9
0
        // Stock algo worker thread
        public static void Background_StockWorkerThread(object obj)
        {
            BrokerErrorCode         errorCode      = BrokerErrorCode.Success;
            BrokerSymbolAlgosObject stockTraderObj = (BrokerSymbolAlgosObject)obj;
            IBroker broker = stockTraderObj.Broker;
            //EquityStockTradeStats stockInfo = stockTraderObj.stockInfo;
            ITradingAlgo algo = stockTraderObj.Algos[0];

            // Thread local params
            int threadRunCount  = 0;
            int threadFailCount = 0;

            //string stockCode = stockInfo.StockCode;
            string traceString;
            bool   bChecked = false;

            // On program re-run, cancel any previous outstanding orders
            // BUGBUGCD: is this infinite loop necessary or try only once
            // and come out on failure
            do
            {
                errorCode = algo.Prolog();
                if (!errorCode.Equals(BrokerErrorCode.Success))
                {
                    Thread.Sleep(1000 * 30);
                }
            } while (!stockTraderObj.DoStopThread && !errorCode.Equals(BrokerErrorCode.Success));


            while (!stockTraderObj.DoStopThread)
            {
                // Main Algo
                errorCode = algo.RunCoreAlgo();

                // thread stats
                if (!errorCode.Equals(BrokerErrorCode.Success))
                {
                    threadFailCount++;
                }
                threadRunCount++;

                // Check remote control
                //ProgramRemoteControl remoteControlValue = CheckRemoteControlInAlgo(ref bChecked);

                //if (remoteControlValue.Equals(ProgramRemoteControl.STOP) ||
                //       remoteControlValue.Equals(ProgramRemoteControl.HIBERNATE))
                //    break;

                // Check if login problem
                if (errorCode == BrokerErrorCode.NotLoggedIn)
                {
                    FileTracing.TraceOut("AlgoRunner: " + errorCode.ToString() + " Trying to login again\n");
                    // MGOYAL: TEMP SLEEP this is for external login to do some work .
                    // External logger will have 2 minute (CheckAndLoginIfNeeded) window to complete a work before he is logged out.
                    // Sleep for a minute

                    // It means someone has stolen session, so let it be. if they need for more time then will set remote to PAUSE
                    Thread.Sleep(120000);
                    broker.LogOut();
                    errorCode = broker.CheckAndLogInIfNeeded(true);
                    continue;
                }
                if (errorCode == BrokerErrorCode.InvalidLoginPassword || errorCode == BrokerErrorCode.ChangePassword)
                {
                    FileTracing.TraceOut("AlgoRunner: InvalidLoginPassword, Exiting");
                    break;
                }
                Thread.Sleep(algo.GetSleepTimeInMilliSecs());
            }

            errorCode = algo.Epilog();

            // Trace out Thread run stats
            // TODO: more such fancy stuff later

            traceString = string.Format("AlgoRunner: Thread Run Stats: \nTotalRuns: {0}\nFailures: {1}\nFailurePercentagH: {2}",
                                        threadRunCount, threadFailCount, (double)(threadFailCount / (threadRunCount > 0 ? threadRunCount : 1)) * 100);

            FileTracing.TraceOut(traceString);
        }
        // IBroker.GetEquityOrderBook
        public BrokerErrorCode GetEquityOrderBookToday(bool newOrdersOnly,
                                                       bool bOnlyOutstandingOrders,
                                                       string stockCode,
                                                       out Dictionary <string, EquityOrderBookRecord> orders)
        {
            orders = new Dictionary <string, EquityOrderBookRecord>();
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

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

            string orderBookData = IciciGetWebPageResponse(URL_ICICI_EQT_ORDERBOOK,
                                                           postData,
                                                           URL_ICICI_REFERRER,
                                                           mCookieContainer,
                                                           out errorCode);

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

                orderBookData = HtmlUtilities.EnsureHtmlParsable(orderBookData);

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

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

                //orders = new Dictionary<string, EquityOrderBookRecord>();
                for (int i = 1; i < table.RowCount; i++)
                {
                    EquityOrderBookRecord info = new EquityOrderBookRecord();
                    info.StockCode = table[i, 3].ToString().Trim();
                    info.StockCode = StringParser.GetStringBetween(info.StockCode, 0, "GetQuote('", "'", null);
                    // If stockCode parameter is empty/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);

                    string orderRefString = table[i, 14].ToString();
                    orderRefString = StringParser.GetStringBetween(orderRefString, 0, "FML_ORD_ORDR_RFRNC=", "&", null);
                    // Trim it
                    orderRefString = orderRefString.Trim();//(' ', '\t', '\r', '\n');

                    info.OrderRefenceNumber = orderRefString;
                    string tempStr = table[i, 4].ToString().ToUpperInvariant();
                    info.Direction = (OrderDirection)Enum.Parse(typeof(OrderDirection), tempStr);
                    info.Quantity  = int.Parse(table[i, 5].ToString());

                    string price = StringParser.GetStringBetween(table[i, 3].ToString(),
                                                                 0,
                                                                 ">",
                                                                 "<",
                                                                 new string[] { "onclick", "font" });

                    /*
                     * string price = StringParser.GetStringBetween(table[i, 3].ToString(),
                     *  0,
                     *  "<font color=\"blue\">",
                     *  "</font>",
                     *  new string[] { });
                     *
                     * if (String.IsNullOrEmpty(price))
                     * {
                     *  price = StringParser.GetStringBetween(table[i, 6].ToString(),
                     *  0,
                     *  "<font color=\"black\">",
                     *  "</font>",
                     *  new string[] { });
                     * }
                     *
                     * if (String.IsNullOrEmpty(price))
                     * {
                     *  price = StringParser.GetStringBetween(table[i, 6].ToString(),
                     *  0,
                     *  "\">",
                     *  "</a>",
                     *  new string[] { "onclick"});
                     * }
                     */

                    info.Price = double.Parse(price);

                    tempStr = table[i, 6].ToString().ToUpperInvariant();


                    // Executed orders have different string format, so ignore the clutter
                    if (tempStr.Contains("EXECUTED"))
                    {
                        tempStr = "EXECUTED";
                    }
                    else
                    {
                        tempStr = tempStr.Remove(tempStr.IndexOf("&"));
                    }

                    info.Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), tempStr);

                    info.OpenQty     = int.Parse(table[i, 8].ToString());
                    info.ExecutedQty = int.Parse(table[i, 9].ToString());

                    // Only add valid outstanding orders if bOnlyOutstandingOrders is true
                    // PARTEXEC is considered OUTSTANDING (i.e. not considered EXEC until fully executed)
                    if (!bOnlyOutstandingOrders ||
                        info.Status == OrderStatus.PARTEXEC ||
                        info.Status == OrderStatus.QUEUED ||
                        info.Status == OrderStatus.REQUESTED ||
                        info.Status == OrderStatus.ORDERED)
                    {
                        lock (lockObjectEquity)
                        {
                            if (mEquityOrderBook.ContainsKey(orderRefString))
                            {
                                if (newOrdersOnly)
                                {
                                }
                                else
                                {
                                    orders.Add(orderRefString, info);
                                }
                                // Update the order
                                mEquityOrderBook[orderRefString] = info;
                            }
                            else
                            {
                                mEquityOrderBook.Add(orderRefString, info);
                                orders.Add(orderRefString, info);
                            }
                        }
                    }
                }
            }
            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);
        }
        private BrokerErrorCode CancelEquityOrder(string orderRef, bool refreshOrderBook)
        {
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            if (refreshOrderBook)
            {
                // Make sure we have the latest order book data
                errorCode = RefreshEquityOrderBookToday();
                if (errorCode != BrokerErrorCode.Success)
                {
                    return(errorCode);
                }
            }

            EquityOrderBookRecord orderInfo;

            // Search for order in the Orders dictionary
            lock (lockObjectEquity)
            {
                if (mEquityOrderBook.ContainsKey(orderRef))
                {
                    orderInfo = mEquityOrderBook[orderRef];
                }
                else
                {
                    return(BrokerErrorCode.OrderDoesNotExist);
                }
            }

            if (orderInfo.Status != OrderStatus.ORDERED &&
                orderInfo.Status != OrderStatus.PARTEXEC &&
                orderInfo.Status != OrderStatus.REQUESTED)
            {
                if (orderInfo.Status == OrderStatus.QUEUED)
                {
                    errorCode = BrokerErrorCode.OrderQueuedCannotCancel;
                }
                else if (orderInfo.Status == OrderStatus.EXECUTED)
                {
                    errorCode = BrokerErrorCode.OrderExecutedCannotCancel;
                }
                else
                {
                    errorCode = BrokerErrorCode.InValidOrderToCancel;
                }
                return(errorCode);
            }

            // Instead of getting it actually from order book
            // We simply assume current day only
            DateTime currentDate = MarketUtils.GetMarketCurrentDate();
            string   orderStatus = IciciConstants.OrderStatusString[(int)orderInfo.Status];
            string   zipCode     = orderRef.Substring(8, 2);

            string postData = "Submit1=Yes&FML_PASS=1&NicValue=&m_pipeId=N9" +
                              "&pgname=CanOrd&ismethodcall=0&mthname=" +
                              "&m_status=" + orderStatus +
                              "&m_nsestatus=C" +
                              "&m_bsestatus=C" +
                              "&FML_ORDR_REF=" + orderRef +
                                                                                                              // TODO: C for CASH , currently hardcoded. needs to be handled.
                                                                                                              // Get it in order book stock info somehow
                              "&m_ProductType=C" +
                              "&m_ordFlow=" + IciciConstants.OrderDirectionString[(int)orderInfo.Direction] + // order direction S/B
                              "&m_exchCd=" + IciciConstants.ExchangeString[(int)orderInfo.Exchange] +         // get exchange
                              "";

            string orderBookData = IciciGetWebPageResponse(URL_ICICI_EQT_CANCEL_ORDER,
                                                           postData,
                                                           URL_ICICI_REFERRER,
                                                           mCookieContainer,
                                                           out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                string cancelConfirm = "Your order has been cancelled";
                string cancelRequestSentToExchange = "Your request for order cancellation has been sent to the exchange";

                // Either cancel confirm or cancellation request sent to exchange both are succes cases
                // Success
                if (orderBookData.Contains(cancelConfirm) || orderBookData.Contains(cancelRequestSentToExchange))
                {
                    // TODO: revist if any prob
                    // Delete the orderRef from mEquityOrderBook
                    // We ideally want it to remain in equity order book in cancelled state
                    // but right now remove it rather than update
                    // because let the GetEquityOrddrBook update it as per its protocol
                    lock (lockObjectEquity)
                    {
                        mEquityOrderBook.Remove(orderRef);
                    }
                    return(BrokerErrorCode.Success);
                }
            }

            return(BrokerErrorCode.OrderCancelFailed);
        }
        public BrokerErrorCode ConvertToDeliveryFromPendingForDelivery(string stockCode,
                                                                       int openQty,
                                                                       int toConvertQty,
                                                                       string settlementRef,
                                                                       Exchange exchange)
        {
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_XCHNG_SGMNT_CD     = "";
            string FML_ORD_XCHNG_CD_value = null;

            if (exchange == Exchange.BSE)
            {
                FML_XCHNG_SGMNT_CD     = "B";
                FML_ORD_XCHNG_CD_value = "BSE";
            }
            else if (exchange == Exchange.NSE)
            {
                FML_XCHNG_SGMNT_CD     = "N";
                FML_ORD_XCHNG_CD_value = "NSE";
            }

            string query =
                "&FML_QTY=" + toConvertQty.ToString() +
                "&NicValue=" +
                "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&FML_STCK_CD=" + stockCode +
                "&FML_OPEN_QTY=" + openQty.ToString() +
                "&FML_XCHNG_SGMNT_CD=" + FML_XCHNG_SGMNT_CD +
                "&FML_ORD_XCHNG_SGMNT_STTLMNT=" + settlementRef +
                "&Submit1=Convert+Now" +
                "&pgname=EquityPendingForDeliveryConvertToDelv" +
                "&ismethodcall=0" +
                "&mthname=";

            string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_BASE_ACTION,
                                                                query,
                                                                URL_ICICI_REFERRER,
                                                                mCookieContainer,
                                                                out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                errorCode = GetEQTOrderPlacementCode(orderPlacePageData);
                if (BrokerErrorCode.Success == errorCode)
                {
                    if (orderPlacePageData.IndexOf("You have successfully converted the specified quantity to delivery") > -1)
                    {
                        errorCode = BrokerErrorCode.Success;
                    }
                    else
                    {
                        errorCode = BrokerErrorCode.Unknown;
                    }
                }
            }
            return(errorCode);
        }
Exemplo n.º 14
0
        // place margin order
        public BrokerErrorCode PlaceEquityMarginPLUSOrder(string stockCode,
                                                          int quantity,
                                                          string stopLossPrice,
                                                          string limitPrice,
                                                          OrderDirection orderDirection)
        {
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_ORD_XCHNG_CD_value   = "NSE";
            string FML_ORD_XCHNG_CD_C_value = FML_ORD_XCHNG_CD_value;
            // order direction
            string FML_ORD_ORDR_FLW_value   = null;
            string FML_ORD_ORDR_FLW_C_value = null;
            string oppositeDirection        = "";
            string direction = "";

            if (orderDirection == OrderDirection.BUY)
            {
                FML_ORD_ORDR_FLW_value   = "B";
                FML_ORD_ORDR_FLW_C_value = "S";
                direction         = "BUY";
                oppositeDirection = "SELL";
            }
            else if (orderDirection == OrderDirection.SELL)
            {
                FML_ORD_ORDR_FLW_value   = "S";
                FML_ORD_ORDR_FLW_C_value = "B";
                direction         = "SELL";
                oppositeDirection = "BUY";
            }
            // prices
            string FML_ORD_LMT_RT_value  = limitPrice;
            string FML_ORD_STP_LSS_value = stopLossPrice;
            //string FML_ORD_TRD_DT_value = FML_ORD_TRD_DT_NSE_value;

            string query =
                "FML_XCHNG_ST0=O&FML_XCHNG_ST1=O" +
                "&FML_ACCOUNT=" + FML_ACCOUNT_value +
                "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&FML_STCK_CD=" + stockCode +
                "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                "&FML_DOTNET_FLG=Y&FML_URL_FLG=http%3A%2F%2Fgetquote.icicidirect.com%2FNewSiteTrading%2Ftrading%2Fequity%2Fincludes%2Ftrading_stock_quote.asp" +
                "&FML_QTY=" + quantity.ToString() +
                "&FML_ORD_TYP=M" +
                "&FML_ORD_XCHNG_CD_C=" + FML_ORD_XCHNG_CD_value +
                "&FML_STCK_CD_C=" + stockCode +
                "&FML_STCK_CD_HIDDEN=" + stockCode +
                "&FML_ORD_ORDR_FLW_C=" + oppositeDirection +
                "&FML_ORD_ORDR_FLW_HIDDEN=" + oppositeDirection +
                "&FML_ORD_TYP_C=L" +
                "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value +
                "&FML_ORD_DSCLSD_QTY=" +
                "&FML_ORD_STP_LSS=" + FML_ORD_STP_LSS_value +
                "&FML_QTY_C=" + quantity.ToString() +
                "&FML_QTY_HIDDEN=" + quantity.ToString() +
                "&FML_ORD_XCHNG_CD_P=" +
                "&FML_STCK_CD_P=" + stockCode +
                "&FML_ORD_ORDR_FLW_P=" + oppositeDirection +
                "&FML_ORD_TYP_P=L" +
                "&FML_ORD_LMT_RT_P=" +
                "&FML_QTY_P=" +
                "&Submit=Submit" +
                "&FML_ORD_TRD_DT_BSE=04-Apr-2012" +
                "&FML_ORD_TRD_DT_NSE=04-Apr-2012" +
                "&FML_ORD_TRD_DT=" +
                "&FML_SESSION_ID=85730071" + // GET Session ID
                "&FML_PRODUCT_INDEX=" +
                "&FML_ORD_PRD_HIDDEN=" +
                "&FML_ORD_ACCOUNT_HIDDEN=" +
                "&FML_ACCOUNT_INDEX=" +
                "&FML_XCHNG_ST=O" +
                "&FML_ORD_CLM_MTCH_ACCNT=" + ACCOUNTNUM +
                "&FML_ORD_DP_CLNT_ID=" + CLIENTID +
                "&FML_ORD_DP_ID=" + DPID +
                "&FML_TRN_PRDT_TYP=" +
                "&FML_ORD_XCHNG_CD_CHECK=" +
                "&FML_PRCNTG_CHECK=" +
                "&NicValue=" +
                "&BrowserBack_Xchang=" +
                "&FML_LAS=Y" +
                "&m_FML_AC_ACTIVATED_FROM=BSE" +
                "&m_FML_USR_ZIP_CD=B8" +
                "&m_FML_AC_ACTIVATED_FROM=NSE" +
                "&m_FML_USR_ZIP_CD=N2";


            string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_MARGINPLUS_ORDER,
                                                                query,
                                                                URL_ICICI_REFERRER,
                                                                mCookieContainer,
                                                                out errorCode);

            string time = DateTime.Now.ToString("dd-MMM-yyyy") + " " + DateTime.Now.ToString("hh:mm:ss");

            query =
                "m_TuxServerName:testjolt" +
                "&FML_QTY=" + quantity.ToString() +
                "&FML_STCK_CD=" + stockCode +
                "&FML_ORD_PRDCT_TYP=" +
                "&FML_ORD_TYP=M" +
                "&FML_REFNUM=" +
                "&FML_XCHNG_ST=O" +
                "&FML_ACCOUNT=" + FML_ACCOUNT_value +
                "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value +
                "&FML_ORD_DSCLSD_QTY=" +
                "&FML_ORD_STP_LSS=" + FML_ORD_STP_LSS_value +
                "&FML_ORD_TRD_DT=" + //FML_ORD_TRD_DT_NSE_value +
                "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                //"&FML_ORD_EXCTD_RT=" + FML_ORD_LMT_RT_value +
                "&FML_PASS=1" +
                "&FML_ORD_CLM_MTCH_ACCNT=" + ACCOUNTNUM +
                "&FML_ORD_DP_CLNT_ID=" + CLIENTID +
                "&FML_ORD_DP_ID=" + DPID +
                "&FML_XCHNG_SG=N" +
                //"&FML_ORD_XCHNG_SGMNT_STTLMNT=2012065" +
                //"&FML_DEMAT_IN_DT=08-Apr-2012&FML_DEMAT_OUT_DT=11-Apr-2012&FML_FUND_IN_DT=09-Apr-2012&FML_FUND_OUT_DT=10-Apr-2012" +
                "&FML_ISIN_NUMBER=" +
                "&FML_TM=" + time +
                "&FML_QUOTE_TIME=" + time +
                "&FML_CVR_QTY=0.0" +
                "&FML_STK_STCK_NM=XYZ" +
                "&FML_RQST_TYP=&FML_TRN_PRDT_TYP=&FML_SCHM_ID=&FML_RT=&FML_ORD_PRD_HIDDEN=" +
                "&FML_ORD_ORDR_FLW_HIDDEN=" + oppositeDirection +
                "&FML_GMS_CSH_PRDCT_PRCNTG=0&FML_PRODUCT_INDEX=&FML_ACCOUNT_INDEX=&FML_MULTI_ROW_CHECK=" +
                "&FML_TRADING_PASS_FLAG=N" +
                "&ATValue=&FML_TRADING_ALIAS=&x=&FML_ORD_LMT_RT_P=" +
                "&ProChk=&Submit=Proceed" +
                "&button=Back&button=Back";

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_MARGINPLUS_ORDER,
                                                             query,
                                                             URL_ICICI_REFERRER,
                                                             mCookieContainer,
                                                             out errorCode);

                if (errorCode.Equals(BrokerErrorCode.Success))
                {
                    errorCode = GetEQTOrderPlacementCode(orderPlacePageData, EquityOrderType.MARGIN);
                    if (BrokerErrorCode.Success == errorCode)
                    {
                        // Get exchange reference number (primary key for an order)
                        // add the record to DB
                        // TODO: is it required since we already have parser of order & trade book
                        GetOrderConfirmationData(orderPlacePageData, EquityOrderType.MARGIN);
                    }
                }
            }

            return(errorCode);
        }
Exemplo n.º 15
0
        // Stock algo worker thread
        public static void BG_StockWorkerThread_SingleSymbol(object obj)
        {
            BrokerSymbolAlgosObject stockTraderObj      = (BrokerSymbolAlgosObject)obj;
            IBroker                           broker    = stockTraderObj.Broker;
            List <ITradingAlgo>               algos     = stockTraderObj.Algos;
            BrokerErrorCode                   errorCode = BrokerErrorCode.Success;
            EquitySymbolLiveTickGenerator     ETicks    = stockTraderObj.ETicks;
            DerivativeSymbolLiveTickGenerator DTicks    = stockTraderObj.DTicks;
            bool     isDayNewTicksStarted           = false;
            bool     isAnyAlgoSquareOffRetryPending = false;
            DateTime quoteTime;

            foreach (ITradingAlgo algo in algos)
            {
                algo.ErrorCode = algo.Prolog();
                if (algo.ErrorCode != BrokerErrorCode.Success)
                {
                    errorCode = algo.ErrorCode;
                }
            }

            do
            {
                errorCode = BrokerErrorCode.Success;

                foreach (ITradingAlgo algo in algos)
                {
                    if (algo.ErrorCode != BrokerErrorCode.Success)
                    {
                        algo.ErrorCode = algo.Prolog();
                        if (algo.ErrorCode != BrokerErrorCode.Success)
                        {
                            errorCode = algo.ErrorCode;
                        }
                    }
                }

                if (!errorCode.Equals(BrokerErrorCode.Success))
                {
                    Thread.Sleep(1000 * 30);
                }
            } while (!stockTraderObj.DoStopThread && !errorCode.Equals(BrokerErrorCode.Success));

            SymbolTick tick = new SymbolTick();

            tick.I = stockTraderObj.Instrument;

            while (!stockTraderObj.DoStopThread)
            {
                if (stockTraderObj.Instrument.InstrumentType == InstrumentType.Share)
                {
                    tick.E = ETicks.GetTick(false, out errorCode);
                }
                else
                {
                    tick.D = DTicks.GetTick(false, out errorCode);
                }

                if (!errorCode.Equals(BrokerErrorCode.Success))
                {
                    Thread.Sleep(1000);
                    continue;
                }

                if (stockTraderObj.Instrument.InstrumentType == InstrumentType.Share)
                {
                    quoteTime = tick.E.Q[0].QuoteTime;
                }
                else
                {
                    quoteTime = tick.D.Q.QuoteTime;
                }


                // to guard against previous day's ticks
                if (!isDayNewTicksStarted)
                {
                    isDayNewTicksStarted = quoteTime.Date == DateTime.Now.Date;

                    if (!isDayNewTicksStarted)
                    {
                        Thread.Sleep(10 * 1000);
                        continue;
                    }
                }

                // Main Algo
                foreach (ITradingAlgo algo in algos)
                {
                    if (!algo.DoStopAlgo)
                    {
                        algo.IsExternallySuspended = false;
                        algo.ErrorCode             = errorCode = algo.RunCoreAlgoLive(tick);
                        if (algo.IsOrderExecutionPending)
                        {
                            isAnyAlgoSquareOffRetryPending = true;
                        }
                    }
                    else
                    {
                        algo.IsExternallySuspended = true;
                    }
                }

                if (!isAnyAlgoSquareOffRetryPending)
                {
                    Thread.Sleep(stockTraderObj.TickIntervalInMiliSeconds);//algo.GetSleepTimeInMilliSecs());
                }
                isAnyAlgoSquareOffRetryPending = false;
            }

            foreach (ITradingAlgo algo in algos)
            {
                algo.ErrorCode = algo.Epilog();
            }

            if (stockTraderObj.Instrument.InstrumentType == InstrumentType.Share)
            {
                ETicks.Close();
            }
            else
            {
                DTicks.Close();
            }
        }
Exemplo n.º 16
0
        // get important account related values once during login
        BrokerErrorCode GetImportantValues()
        {
            BrokerErrorCode errorCode = BrokerErrorCode.NotLoggedIn;

            var equityHomePageData = IciciGetWebPageResponse(URL_ICICI_BASE_ACTION,
                                                             "pgname=eqhome&ismethodcall=0&mthname=",
                                                             URL_ICICI_REFERRER,
                                                             mCookieContainer,
                                                             out errorCode);

            var equityFastBuySellPageData = IciciGetWebPageResponse(URL_ICICI_EQT_FASTBUYSELL,
                                                                    "pgname=eqfastbuy&ismethodcall=0&mthname=",
                                                                    URL_ICICI_REFERRER,
                                                                    mCookieContainer,
                                                                    out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                FML_ORD_TRD_DT_BSE_value = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                                         0,
                                                                         "<input type=\"hidden\" id=\"FML_ORD_TRD_DT_BSE\" value=\"",
                                                                         "\"",
                                                                         null);
                FML_ORD_TRD_DT_NSE_value = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                                         0,
                                                                         "<input type=\"hidden\" id=\"FML_ORD_TRD_DT_NSE\" value=\"",
                                                                         "\"",
                                                                         null);
                GTCDate = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                        0,
                                                        "<input type=\"hidden\" name=\"GTCDate\" id=\"GTCDate\" value=\"",
                                                        "\"",
                                                        null);
                GTCDate7 = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                         0,
                                                         "<input id=\"GTCDate7\" type=\"text\" style=\"width: 65px !important;\" value=\"",
                                                         "\"",
                                                         null);
                GTCDateHidden7 = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                               0,
                                                               "<input type=\"hidden\" name=\"GTCDateHidden7\" id=\"GTCDateHidden7\" value=\"",
                                                               "\"",
                                                               null);
                NSEStatus = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                          0,
                                                          "<input type=\"hidden\" id=\"NSEStatus\" value=\"",
                                                          "\"",
                                                          null);
                BSEStatus = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                          0,
                                                          "<input type=\"hidden\" id=\"BSEStatus\" value=\"",
                                                          "\"",
                                                          null);
                FML_XCHNG_ST = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                             0,
                                                             "<input type=\"hidden\" id=\"FML_XCHNG_ST\" value=\"",
                                                             "\"",
                                                             null);
                FML_PRCNTG_CHECK = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                                 0,
                                                                 "<input type=\"hidden\" id=\"FML_PRCNTG_CHECK\" value=\"",
                                                                 "\"",
                                                                 null);
                ACCOUNTNUM = StringParser.GetStringBetween(equityFastBuySellPageData,
                                                           0,
                                                           "A/C No:",
                                                           "')",
                                                           null);
            }

            return(errorCode);
        }
Exemplo n.º 17
0
        // Stock trading lot(qty) for orders
        //private int mStockTradingLot;
        //protected int StockTradingLot
        //{

        //    get { lock (lockObjectProperties) { return mStockTradingLot; } }
        //    set { lock (lockObjectProperties) { mStockTradingLot = value; } }
        //}


        public BrokerErrorCode RunCoreAlgo()
        {
            #region SimpleBuySellPairSquareAlgo

            bool   bCancelPairOrder = false;
            string stockCode        = stockInfo.StockCode;
            int    stockExchange    = stockInfo.MainExchange == Exchange.NSE ? 0 : 1;

            BrokerErrorCode errorCode = BrokerErrorCode.Unknown;

            int tryCnt = 0;
            while (errorCode != BrokerErrorCode.Success && tryCnt <= 5)
            {
                // refresh stock state (doesnt have price info)
                errorCode = EquityStockState.EquityRefreshStockStateToday(mBroker, stockInfo);

                if (errorCode == BrokerErrorCode.NotLoggedIn)
                {
                    mBroker.LogOut();
                    errorCode = mBroker.CheckAndLogInIfNeeded(true);
                    tryCnt++;
                }
            }

            string traceString = "RefreshEquityStockStateToday: " + errorCode.ToString();
            FileTracing.TraceOut(traceString);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                // If no buy or sell order pending, i.e. the square-off pair orders have executed
                // then place a pair of fresh buy-sell orders

                if (!(stockInfo.IsAnyOutstandingBuyOrder() ||
                      stockInfo.IsAnyOutstandingSellOrder()
                      ))
                {
                    // Place buy-sell order pair

                    // Get latest quote
                    EquitySymbolQuote[] stockPrice;

                    errorCode = mBroker.GetEquityQuote(stockCode, out stockPrice);

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

                    // Generate orders
                    List <EquityOrderRecord> generatedOrders = new List <EquityOrderRecord>();

                    string BidPrice;
                    string OfferPrice;

                    // price decision

                    // First orders, only if market not open and it is first order pair
                    if ((stockInfo.NumTrades == 0) && !MarketUtils.IsMarketOpen())
                    {
                        double closePrice = stockPrice[stockExchange].PreviousClosePriceDouble;

                        if (algoParams.initBidPrice > 0)
                        {
                            BidPrice = algoParams.initBidPrice.ToString();
                        }
                        else
                        {
                            decimal buy = (decimal)(closePrice - (2.0 / 100 * closePrice));//prevclose - 3%
                            buy      = decimal.Subtract(buy, 0.05M);
                            buy      = decimal.Round(buy, 1);
                            BidPrice = buy.ToString();
                        }

                        if (algoParams.initOfferPrice > 0)
                        {
                            OfferPrice = algoParams.initOfferPrice.ToString();
                        }
                        else
                        {
                            decimal sell = (decimal)(closePrice + (2.0 / 100 * closePrice));//prevclose + 3%
                            sell       = decimal.Add(sell, 0.05M);
                            sell       = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                            OfferPrice = sell.ToString();
                        }
                    }
                    // Subsequent orders
                    // TODO: May put time conditions or market volatility conditions here in else if
                    else
                    {
                        double ltp = stockPrice[stockExchange].LastTradePriceDouble;

                        decimal buy = (decimal)(ltp - ((double)(0.85 / 100) * ltp));//prevclose - 0.85%
                        buy      = decimal.Subtract(buy, 0.05M);
                        buy      = decimal.Round(buy, 1);
                        BidPrice = buy.ToString();

                        decimal sell = (decimal)(ltp + ((double)(0.85 / 100) * ltp));//prevclose + 0.85%
                        sell       = decimal.Add(sell, 0.05M);
                        sell       = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                        OfferPrice = sell.ToString();
                    }

                    // Buy
                    generatedOrders.Add(new EquityOrderRecord(stockCode, algoParams.StockTradingLot, BidPrice, OrderPriceType.LIMIT, OrderDirection.BUY, stockInfo.MainExchange, EquityOrderType.DELIVERY, "0", "0"));
                    if (!bGenerateASingleBuyOrderAtStart)
                    {
                        // Sell
                        generatedOrders.Add(new EquityOrderRecord(stockCode, algoParams.StockTradingLot, OfferPrice, OrderPriceType.LIMIT, OrderDirection.SELL, stockInfo.MainExchange, EquityOrderType.DELIVERY, "0", "0"));
                    }
                    List <BrokerErrorCode> errorCodes = null;

                    // Validate orders
                    List <EquityOrderRecord> ordersToPlace = stockInfo.ReturnFilteredValidOrders(generatedOrders);


                    // Place validated orders

                    errorCodes = mBroker.PlaceMultipleEquityOrders(ordersToPlace, 5);

                    traceString = "Stock: " + stockInfo.StockCode + " :PlaceMultipleEquityOrders: 2\n";
                    int o = 0;
                    foreach (BrokerErrorCode errCodeEach in errorCodes)
                    {
                        EquityOrderRecord order = ordersToPlace[o++];
                        traceString = traceString + order.OrderDirection.ToString() + "-" + order.Quantity.ToString() +
                                      " at " + order.Price + ": " + errCodeEach.ToString() + "\n";

                        // Place Order failed
                        if (!errCodeEach.Equals(BrokerErrorCode.Success))
                        {
                            // Cancel both the orders
                            bCancelPairOrder = true;
                        }
                    }
                    FileTracing.TraceOut(traceString);

                    // Even if any one of the orders failed to place, cancel the pair
                    if (bCancelPairOrder)
                    {
                        errorCode = BrokerUtils.CancelStockOutstandingOrdersAndTrace(mBroker, stockCode);
                    }
                }
            }

            return(errorCode);

            #endregion
        }
Exemplo n.º 18
0
        // Do login
        public BrokerErrorCode LogIn()
        {
            if (_fatalNoTryLogin)
            {
                FileTracing.TraceOut(Thread.CurrentThread.Name + "ERROR: Not trying Actual LogIn() because now in FatalNoLoginTry mode.");
                return(BrokerErrorCode.FatalNoLoginTry);
            }

            BrokerErrorCode errorCode = IsLoggedIn();

            if (!errorCode.Equals(BrokerErrorCode.Success))
            {
                mLoggedIn = false;
                //FileTracing.TraceOut(Thread.CurrentThread.Name + ": In Actual LogIn()");

                var postData =
                    string.Format("ctl00%24Hearder1%24drpStock=India&ctl00%24Hearder1%24txtTopSearch=Stock+Name+%2F+Stock+Code&ctl00%24Hearder1%24hidHandler=https%3A%2F%2Fsecure.icicidirect.com%2FIDirectTrading%2FBasemasterpage%2FHeaderDataHandler.ashx&__EVENTTARGET=lbtLogin&__EVENTARGUMENT=&npage=&ctl00%24ContentPlaceHolder1%24hisreen=1366x768&ctl00%24ContentPlaceHolder1%24lms_lnk=&ctl00%24ContentPlaceHolder1%24txtUserId={0}&ctl00%24ContentPlaceHolder1%24txtu=&ctl00%24ContentPlaceHolder1%24m_StartIn_Fld=&ctl00%24ContentPlaceHolder1%24txtPass={1}&ctl00%24ContentPlaceHolder1%24txtDOB={2}&ctl00%24ContentPlaceHolder1%24drpTrade=12&ctl00%24Footer1%24showplus=&ctl00%24hidIsTrade=1&__VIEWSTATEGENERATOR=241519BE",
                                  mUsername, mPassword, mDOB);

                // re-login
                mCookieContainer = new CookieContainer();
                // This GET is to populate session id in cookies
                string initGetResponse = HttpHelper.GetWebPageResponse(URL_ICICI_LOGON, null,
                                                                       URL_ICICI_LOGON_REFERRER,
                                                                       mCookieContainer);

                string loginResponse = HttpHelper.GetWebPageResponse(URL_ICICI_LOGON, postData,
                                                                     URL_ICICI_LOGON_REFERRER,
                                                                     mCookieContainer);

                if (String.IsNullOrEmpty(loginResponse))
                {
                    errorCode = BrokerErrorCode.Http;
                }

                else if ((loginResponse.IndexOf("You last accessed the site", StringComparison.OrdinalIgnoreCase) >= 0) || (IsLoggedIn() == BrokerErrorCode.Success))
                {
                    errorCode = GetImportantValues();
                    if (errorCode.Equals(BrokerErrorCode.Success))
                    {
                        mLoggedIn = true;
                        RefreshLastServerContactTime();
                    }
                }
                else
                {
                    if (loginResponse.IndexOf("customer_change_password", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        errorCode = BrokerErrorCode.ChangePassword;
                    }
                    if (loginResponse.IndexOf("echnical reason", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        errorCode = BrokerErrorCode.TechnicalReason;
                    }
                    else if (loginResponse.IndexOf("Locked", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        _fatalNoTryLogin = true;
                        errorCode        = BrokerErrorCode.Locked;
                    }
                    else if (loginResponse.IndexOf("Invalid Login Id or Password", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        _fatalNoTryLogin = true;
                        errorCode        = BrokerErrorCode.InvalidLoginPassword;
                    }
                    else
                    {
                        errorCode = BrokerErrorCode.Unknown;
                    }
                }
            }

            return(errorCode);
        }
Exemplo n.º 19
0
        public BrokerErrorCode Prolog()
        {
            BrokerErrorCode errorCode   = BrokerErrorCode.Success;
            string          traceString = "Algo1_SimplePairedBuySellDelivery.Prolog :: ENTER";

            FileTracing.TraceOut(traceString);

            if (algoParams.bCancelOutstandingOrdersAtStart)
            {
                errorCode = BrokerUtils.CancelStockOutstandingOrdersAndTrace(mBroker, stockCode);
            }
            if (!algoParams.bStartAFresh)
            {
                // Start from last run state and try to be in pair-execute state
                // There may be less than or equal to 1 lot of stock as long or short
                // Pick up the last trade from xml
                // TODO:
            }
            // Get latest quote
            EquitySymbolQuote[] stockPrice;

            errorCode = mBroker.GetEquityQuote(stockCode, out stockPrice);

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

            int stockExchange = stockInfo.MainExchange == Exchange.NSE ? 0 : 1;

            double buyOrderValue = (stockPrice[stockExchange].LastTradePriceDouble * algoParams.StockTradingLot);

            buyOrderValue += stockInfo.EstimatedBrokerage(buyOrderValue);


            // Erroneous conditions get out, do later
            // TODO: right now assume stock abvailable is at least = stock trading lot
            // and assume limit is available
            //if(stockInfo.StockAvailableAtStart <


            // TODO: find better alternative to fit this variable
            if ((stockInfo.StockAvailableAtStart < algoParams.StockTradingLot) && (stockInfo.FundLimitAtStart >= 2 * buyOrderValue))
            {
                // This means first buy the stock, then start trading it
                bGenerateASingleBuyOrderAtStart = true;
            }
            else if (stockInfo.StockAvailableAtStart < algoParams.StockTradingLot)
            {
                errorCode = BrokerErrorCode.InValidArg;
            }

            if (!bGenerateASingleBuyOrderAtStart && errorCode.Equals(BrokerErrorCode.Success))
            {
                // There should be suficient stock to place a sell order to generate limit first
                // and then for the pair-orders
                // stockavailable should be at least twice the trading lot
                if ((stockInfo.FundLimitAtStart < buyOrderValue) && (stockInfo.StockAvailableAtStart >= 2 * algoParams.StockTradingLot))
                {
                    // Generate a sell order
                    bGenerateASingleSellOrderAtStart = true;
                }
                else if (stockInfo.FundLimitAtStart < buyOrderValue)
                {
                    errorCode = BrokerErrorCode.InValidArg;
                }
            }

            string         price          = "1";
            bool           bGenerateOrder = false;
            OrderDirection orderDirection = OrderDirection.BUY;

            // BUY order
            if (bGenerateASingleBuyOrderAtStart)
            {
                // price decision
                if (algoParams.initBidPrice > 0)
                {
                    price = algoParams.initBidPrice.ToString();
                }
                // First orders, only if market not open and it is first order pair
                else if (!MarketUtils.IsMarketOpen())
                {
                    double closePrice = stockPrice[stockExchange].PreviousClosePriceDouble;

                    decimal buy = (decimal)(closePrice - ((double)(3.0 / 100) * closePrice));//prevclose - 3%
                    buy   = decimal.Subtract(buy, 0.05M);
                    buy   = decimal.Round(buy, 1);
                    price = buy.ToString();
                }
                // Subsequent orders
                // TODO: May put time conditions or market volatility conditions here in else if
                else
                {
                    double ltp = stockPrice[stockExchange].LastTradePriceDouble;

                    decimal buy = (decimal)(ltp - ((double)(0.65 / 100) * ltp));//prevclose - 0.65%
                    buy   = decimal.Subtract(buy, 0.05M);
                    buy   = decimal.Round(buy, 1);
                    price = buy.ToString();
                }
                orderDirection = OrderDirection.BUY;
                bGenerateASingleBuyOrderAtStart = false;
                bGenerateOrder = true;
            }


            // SELL order
            if (bGenerateASingleSellOrderAtStart)
            {
                // price decision
                if (algoParams.initOfferPrice > 0)
                {
                    price = algoParams.initOfferPrice.ToString();
                }
                // First orders, only if market not open and it is first order pair
                if (!MarketUtils.IsMarketOpen())
                {
                    double closePrice = stockPrice[stockExchange].PreviousClosePriceDouble;

                    decimal sell = (decimal)(closePrice + (3.0 / 100 * closePrice));//prevclose + 3%
                    sell  = decimal.Add(sell, 0.05M);
                    sell  = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                    price = sell.ToString();
                }
                // Subsequent orders
                // TODO: May put time conditions or market volatility conditions here in else if
                else
                {
                    double ltp = stockPrice[stockExchange].LastTradePriceDouble;

                    decimal sell = (decimal)(ltp + (0.65 / 100 * ltp));//prevclose + 0.65%
                    sell  = decimal.Add(sell, 0.05M);
                    sell  = decimal.Round(sell, 1, MidpointRounding.AwayFromZero);
                    price = sell.ToString();
                }

                orderDirection = OrderDirection.SELL;
                bGenerateASingleSellOrderAtStart = false;
                bGenerateOrder = true;
            }

            if (bGenerateOrder)
            {
                // Generate orders
                List <EquityOrderRecord> generatedOrders = new List <EquityOrderRecord>
                {
                    new EquityOrderRecord(stockCode,
                                          algoParams.StockTradingLot,
                                          price, OrderPriceType.LIMIT,
                                          orderDirection,
                                          stockInfo.MainExchange,
                                          EquityOrderType.DELIVERY, "0",
                                          "0")
                };

                List <BrokerErrorCode> errorCodes = null;

                // Validate orders
                List <EquityOrderRecord> ordersToPlace = stockInfo.ReturnFilteredValidOrders(generatedOrders);


                // Place validated orders

                errorCodes = mBroker.PlaceMultipleEquityOrders(ordersToPlace, 5);

                traceString = "Algo1_SimplePairedBuySellDelivery.Prolog\n" + "Stock: " + stockInfo.StockCode + " :PlaceMultipleEquityOrders: 1\n";
                int o = 0;
                foreach (BrokerErrorCode errCodeEach in errorCodes)
                {
                    EquityOrderRecord order = ordersToPlace[o++];
                    traceString = traceString + order.OrderDirection.ToString() + "-" + order.Quantity.ToString() +
                                  " at " + order.Price + ": " + errCodeEach.ToString() + "\n";

                    errorCode = errCodeEach;
                }
                FileTracing.TraceOut(traceString);
            }
            traceString = "Algo1_SimplePairedBuySellDelivery.Prolog :: EXIT";
            FileTracing.TraceOut(traceString);

            return(errorCode);
        }
Exemplo n.º 20
0
        // place deliver order
        public BrokerErrorCode PlaceEquityMarginDeliveryFBSOrder(string stockCode,
                                                                 int quantity,
                                                                 string price,
                                                                 OrderPriceType orderPriceType,
                                                                 OrderDirection orderDirection,
                                                                 EquityOrderType orderType,
                                                                 Exchange exchange)
        {
            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_ORD_ORDR_FLW_value = null;

            if (orderDirection == OrderDirection.BUY)
            {
                FML_ORD_ORDR_FLW_value = "B";
            }
            else if (orderDirection == OrderDirection.SELL)
            {
                FML_ORD_ORDR_FLW_value = "S";
            }
            string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty;

            if (orderPriceType == OrderPriceType.MARKET)
            {
                FML_ORD_TYP_value = "M";
            }
            else if (orderPriceType == OrderPriceType.LIMIT)
            {
                FML_ORD_TYP_value    = "L";
                FML_ORD_LMT_RT_value = price;
            }
            string FML_ORD_TRD_DT_value   = null;
            string squareOffMode          = "S";
            string FML_ORD_XCHNG_CD_value = null;

            if (exchange == Exchange.BSE)
            {
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_BSE_value;
                FML_ORD_XCHNG_CD_value = "BSE";
                squareOffMode          = "S";
            }
            else if (exchange == Exchange.NSE)
            {
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_NSE_value;
                FML_ORD_XCHNG_CD_value = "NSE";
                squareOffMode          = "M";
            }

            string prdctType = orderType == EquityOrderType.DELIVERY ? "CASH" : "MARGIN";

            string query = "FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                           "&FML_ACCOUNT=" + FML_ACCOUNT_value +
                           "&TEMP=" + FML_ORD_XCHNG_CD_value +
                           "&FML_ORD_PRDCT_TYP=" + prdctType +
                           (orderType == EquityOrderType.MARGIN ? "&FML_SQ_FLAG=" + squareOffMode : "") + //Squareoff mode: M (for client) S (for broker), for BSE only S
                           "&FML_STCK_CD=" + stockCode +
                           "&FML_QTY=" + quantity.ToString() +
                           "&FML_DOTNET_FLG=Y&FML_URL_FLG=http%3A%2F%2Fgetquote.icicidirect.com%2Ftrading%2Fequity%2Ftrading_stock_quote.asp " +
                           "&FML_ORD_TYP=" + FML_ORD_TYP_value +
                           "&FML_ORD_LMT_RT=" + FML_ORD_LMT_RT_value +
                           "&FML_ORD_DSCLSD_QTY=&FML_ORD_STP_LSS=" +
                           "&FML_ORD_TRD_DT_BSE=" + FML_ORD_TRD_DT_BSE_value +
                           "&FML_ORD_TRD_DT_NSE=" + FML_ORD_TRD_DT_NSE_value +
                           "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_value +
                           "&FML_PRODUCT_INDEX=0" +
                           "&FML_ORD_PRD_HIDDEN=" + prdctType +
                           "&FML_ORD_CLM_MTCH_ACCNT=" +
                           "&FML_TRADING_LIMIT_NSE=" + FML_TRADING_LIMIT_NSE_value +
                           "&FML_TRADING_LIMIT_BSE=" + FML_TRADING_LIMIT_BSE_value +
                           "&FML_ORD_DP_CLNT_ID=&FML_ORD_DP_ID=&FML_TRN_PRDT_TYP=" +
                           "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                           "&FML_ORD_XCHNG_CD_CHECK=" + (exchange == Exchange.BSE ? "NSE" : "") +
                           "&FML_PRCNTG_CHECK=3.0&FML_ARRAY_BOUND=1&FML_ARRAY_ELEMENT=&NicValue=&BrowserBack_Xchang=NSE&PWD_ENABLED=N&FML_LAS=Y" +
                           "&m_FML_AC_ACTIVATED_FROM=BSE&m_FML_USR_ZIP_CD=B3&m_FML_AC_ACTIVATED_FROM=NSE&m_FML_USR_ZIP_CD=N9";

            string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_EQT_FBS_CASHMARGIN_ORDER,
                                                                query,
                                                                URL_ICICI_REFERRER,
                                                                mCookieContainer,
                                                                out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                errorCode = GetEQTOrderPlacementCode(orderPlacePageData, EquityOrderType.DELIVERY);
                if (BrokerErrorCode.Success == errorCode)
                {
                    // ********** Get exchange reference number (primary key for an order)  ***********
                    // add the record to DB
                    GetOrderConfirmationData(orderPlacePageData, orderType);
                }
            }
            return(errorCode);
        }
        // place margin pending delivery square off order
        public BrokerErrorCode PlaceEquityMarginSquareOffOrder(string stockCode,
                                                               int quantity,
                                                               string price,
                                                               OrderPriceType orderPriceType,
                                                               OrderDirection orderDirection,
                                                               EquityOrderType orderType,
                                                               Exchange exchange,
                                                               out string orderRef)
        {
            orderRef = "";

            // Login If needed
            BrokerErrorCode errorCode = CheckAndLogInIfNeeded(false);

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

            string FML_ORD_ORDR_FLW_value = orderDirection == OrderDirection.BUY ? "B" : "S";
            string FML_XCHNG_SGMNT_CD     = "";

            string FML_ORD_TYP_value = null, FML_ORD_LMT_RT_value = String.Empty;

            if (orderPriceType == OrderPriceType.MARKET)
            {
                FML_ORD_TYP_value = "M";
            }
            else if (orderPriceType == OrderPriceType.LIMIT)
            {
                FML_ORD_TYP_value    = "L";
                FML_ORD_LMT_RT_value = price;
            }

            string FML_ORD_TRD_DT_value   = null;
            string squareOffMode          = orderDirection == OrderDirection.SELL ? "S" : "M";
            string FML_ORD_XCHNG_CD_value = null;

            if (exchange == Exchange.BSE)
            {
                FML_XCHNG_SGMNT_CD     = "B";
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_BSE_value;
                FML_ORD_XCHNG_CD_value = "BSE";
            }
            else if (exchange == Exchange.NSE)
            {
                FML_XCHNG_SGMNT_CD     = "N";
                FML_ORD_TRD_DT_value   = FML_ORD_TRD_DT_NSE_value;
                FML_ORD_XCHNG_CD_value = "NSE";
            }

            string prdctType = orderType == EquityOrderType.DELIVERY ? "C" : "M";

            string query =
                "&FML_ORD_XCHNG_CD=" + FML_ORD_XCHNG_CD_value +
                "&FML_STCK_CD=" + stockCode +
                "&FML_QTY=" + quantity.ToString() +
                "&FML_XCHNG_SGMNT_CD=" + FML_XCHNG_SGMNT_CD +
                "&FML_STTLMNT_NMBR=" +
                "&AvgPrc=" +
                "&FML_ORD_TRD_DT=" + FML_ORD_TRD_DT_NSE_value +
                "&FML_XCHNG_ST=" + NSEStatus +
                "&NicValue=" +
                "&m_IntPass=1" +
                "&FML_URQ_USR_RD_FLG=" +
                "&FML_ORD_ORDR_FLW=" + FML_ORD_ORDR_FLW_value +
                "&FML_ORD_DSCLSD_QTY=" +
                "&FML_SQROFF=" + quantity.ToString() +
                "&FML_POINT_TYPE=T" +
                "&FML_ORD_TYP=" + FML_ORD_TYP_value +
                "&FML_LM_RT=" + FML_ORD_LMT_RT_value +
                "&FML_GMS_CSH_PRDCT_PRCNTG=" +
                "&FML_ORD_STP_LSS=" +
                "&Submit1=Square Off" +
                "&Submit2=Clear" +
                "&FML_ORD_XCHNG_SGMNT_STTLMNT=" +
                "&FML_QUOTE=" +
                "&FML_QUOTE_TIME=" +
                "&FML_TRDNG_PSSWRD_FLG=N" +
                "&FML_RT=" +
                "&FML_ISIN_NMBR=" +
                "&FML_STK_STCK_NM=" +
                "&FML_TM=" +
                "&FML_QTY_OTH=" + quantity.ToString() +
                "&pgname=EquityPendingForDeliverySquareOff" +
                "&ismethodcall=1" +
                "&mthname=ValidateFormData";

            string orderPlacePageData = IciciGetWebPageResponse(URL_ICICI_BASE_ACTION,
                                                                query,
                                                                URL_ICICI_REFERRER,
                                                                mCookieContainer,
                                                                out errorCode);

            if (errorCode.Equals(BrokerErrorCode.Success))
            {
                errorCode = GetEQTOrderPlacementCode(orderPlacePageData);
                if (BrokerErrorCode.Success == errorCode)
                {
                    orderRef = ExtractOrderReferenceNumberMarginSqOffOrder(orderPlacePageData);
                }
            }
            return(errorCode);
        }