private static BrokerErrorCode EquityRefreshStockState(
            IBroker broker,
            DateTime fromDate,
            DateTime toDate,
            EquityStockTradeStats stockInfo)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Unknown;

            if (stockInfo == null)
            {
                return(BrokerErrorCode.InValidArg);
            }
            Dictionary <string, EquityOrderBookRecord> orders = new Dictionary <string, EquityOrderBookRecord>();
            Dictionary <string, EquityTradeBookRecord> trades = new Dictionary <string, EquityTradeBookRecord>();

            // Get stock filtered Order book
            errorCode = broker.GetEquityOrderBook(fromDate, toDate, false, true, stockInfo.StockCode, out orders);

            if (errorCode == BrokerErrorCode.Success)
            {
                // Get stock filtered Trade book
                errorCode = broker.GetEquityTradeBook(fromDate, toDate, false, stockInfo.StockCode, out trades);
            }

            if (errorCode == BrokerErrorCode.Success)
            {
                // Call stock refresh method to update its state
                stockInfo.RefreshState(orders, trades);
            }

            return(errorCode);
        }
示例#2
0
        public BrokerErrorCode GetLTP(out double ltp)
        {
            EquitySymbolQuote[] quote;
            BrokerErrorCode     errCode = BrokerErrorCode.Unknown;
            int retryCount = 0;

            ltp = 0.0;

            while (errCode != BrokerErrorCode.Success && retryCount++ < 3)
            {
                try
                {
                    errCode = broker.GetEquityQuote(stockCode, out quote);
                    var idx = exchange == Exchange.NSE ? 0 : 1;
                    ltp = quote[idx].LastTradePriceDouble;
                }
                catch (Exception ex)
                {
                    Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                    if (retryCount >= 3)
                    {
                        break;
                    }
                }
            }

            return(errCode);
        }
示例#3
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);
        }
示例#4
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);
        }
示例#5
0
        public int GetBoughtQty(string exchange, string stockCode)
        {
            //lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode     = BrokerErrorCode.Unknown;
                int             retryCount    = 0;
                int             maxRetryCount = 3;

                while (errorCode != BrokerErrorCode.Success && retryCount++ < maxRetryCount)
                {
                    try
                    {
                        return(upstox.GetBoughtQty(exchange, stockCode));
                    }
                    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(0);
            }
        }
示例#6
0
        //EXCHANGE,SYMBOL,TOKEN,PRODUCT,COLLATERAL_TYPE ,CNC_USED_QUANTITY,QUANTITY,COLLATERAL_QTY,HAIRCUT,AVG_PRICE
        //NSE_EQ,BAJFINANCE,317,D,WC,0,605,0,25,1625.9508
        public BrokerErrorCode GetHoldings(string stockCode, out List <EquityDematHoldingRecord> holdings)
        {
            lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode = BrokerErrorCode.Unknown;
                holdings = new List <EquityDematHoldingRecord>();

                int retryCount    = 0;
                int maxRetryCount = 3;

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

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

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

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

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

                            var holding = new EquityDematHoldingRecord();
                            holding.BlockedQuantity   = int.Parse(line[5]);
                            holding.Quantity          = int.Parse(line[6]);
                            holding.AvailableQuantity = holding.Quantity - holding.BlockedQuantity;
                            holding.StockCode         = line[1];
                            holding.Exchange          = line[0];

                            holdings.Add(holding);
                        }

                        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);
            }
        }
示例#7
0
        public BrokerErrorCode GetPositions(string stockCode, out List <EquityPositionRecord> positions)
        {
            lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode = BrokerErrorCode.Unknown;
                positions = new List <EquityPositionRecord>();
                int retryCount    = 0;
                int maxRetryCount = 3;

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

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

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

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

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

                            var position = new EquityPositionRecord();

                            position.Exchange        = line[0];
                            position.EquityOrderType = line[1] == "D" ? EquityOrderType.DELIVERY : EquityOrderType.MARGIN;
                            position.StockCode       = line[2];
                            position.BuyQuantity     = int.Parse(line[6]);
                            position.SellQuantity    = int.Parse(line[7]);
                            position.NetQuantity     = int.Parse(line[14]);

                            positions.Add(position);
                        }

                        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);
            }
        }
示例#8
0
        // Check Last Refresh time & if past 3 minutes then login
        // Even if someone else acquired login Session by weblogin etc.
        // Still this should work as the LastLoginRefreshTime becomes stale eventually and
        // resulting into relogin trigger

        // Keep calling this in a separate thread
        public BrokerErrorCode CheckAndLogInIfNeeded(bool bForceLogin, bool bCheckRemoteControl = false)
        {
            TimeSpan        maxTimeWithoutRefresh = new TimeSpan(0, 3, 0);
            BrokerErrorCode errorCode             = TouchServer();

            lock (lockLoginMethod)
            {
                if (bForceLogin || (errorCode != BrokerErrorCode.Success) || ((DateTime.Now - LastLoginRefreshTime) > maxTimeWithoutRefresh))
                {
                    ProgramRemoteControl remoteControlValue = ProgramRemoteControl.RUN;

                    if (bCheckRemoteControl)
                    {
                        remoteControlValue = RemoteUtils.GetProgramRemoteControlValue();
                    }
                    // keep looping until PAUSE status is reset
                    if (remoteControlValue.Equals(ProgramRemoteControl.PAUSE) ||
                        remoteControlValue.Equals(ProgramRemoteControl.STOP) ||
                        remoteControlValue.Equals(ProgramRemoteControl.HIBERNATE))
                    {
                        string traceString = string.Format("CheckAndLogInIfNeeded: Remote Control {0} the LOGIN\n", remoteControlValue.ToString());
                        FileTracing.TraceOut(traceString);
                        errorCode = BrokerErrorCode.RemotePausedOrStopped;
                    }
                    else
                    {
                        string traceString = string.Format("CheckAndLogInIfNeeded: Need to do actual LogIn. ");
                        errorCode    = LogIn();
                        traceString += "LogIn() returned: " + errorCode.ToString();
                        FileTracing.TraceOut(traceString);
                    }
                }
            }
            return(errorCode);
        }
示例#9
0
        public void CancelHoldingSellOrders()
        {
            if (!holdingsOrders.Any())
            {
                return;
            }

            BrokerErrorCode errCode = BrokerErrorCode.Unknown;
            var             holdingsOrdersToRemove = new List <HoldingOrder>();

            foreach (var holdingOrder in holdingsOrders)
            {
                if (!string.IsNullOrEmpty(holdingOrder.OrderRef))
                {
                    errCode = CancelEquityOrder(string.Format("[Holding EOD] {0} {1}", holdingOrder.Type, holdingOrder.SettlementNumber), ref holdingOrder.OrderRef, EquityOrderType.DELIVERY, OrderDirection.SELL);

                    if (errCode == BrokerErrorCode.Success)
                    {
                        // instead of removing the order make the qty 0
                        holdingOrder.Qty    = 0;
                        holdingOrder.Status = OrderStatus.CANCELLED;
                        //holdingsOrdersToRemove.Add(holdingOrder);
                    }
                }
            }

            holdingsOrders.RemoveAll(h => holdingsOrdersToRemove.Contains(h));
            UpdatePositionFile();
        }
示例#10
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);
        }
示例#11
0
        public void StartCapturingMarketTrend()
        {
            try
            {
                EquitySymbolQuote quote;
                errCode = myUpstoxWrapper.GetSnapQuote(exchStr, stockCode, out quote);

                myUpstoxWrapper.Upstox.QuotesReceivedEvent += new Upstox.QuotesReceivedEventEventHandler(QuoteReceived);
                var substatus = myUpstoxWrapper.Upstox.SubscribeQuotes(exchStr, stockCode);
                Trace(string.Format("SubscribeQuotes status={0}", substatus));
            }
            catch (Exception ex)
            {
                Trace(string.Format("{0} Error: {1} \nStacktrace:{2}", stockCode, ex.Message, ex.StackTrace));
                throw;
            }

            while (MarketUtils.IsMarketOpen())
            {
                try
                {
                    if (quote != null)
                    {
                        var changePct = (quote.LTP - quote.Close) / quote.Close;

                        var prevmktTrendFactorForBuyMarkdown = mktTrendFactorForBuyMarkdown;

                        if (changePct < -0.005)
                        {
                            mktTrendFactorForBuyMarkdown = 1.2;
                        }
                        else if (changePct < -0.01)
                        {
                            mktTrendFactorForBuyMarkdown = 1.5;
                        }
                        else if (changePct < -0.015)
                        {
                            mktTrendFactorForBuyMarkdown = 2;
                        }
                        else
                        {
                            mktTrendFactorForBuyMarkdown = 1;
                        }

                        if (prevmktTrendFactorForBuyMarkdown != mktTrendFactorForBuyMarkdown)
                        {
                            Trace(string.Format("MarketTrendForBuyMarkdown changed from {0} to {1}. Nifty changePct={2}", prevmktTrendFactorForBuyMarkdown, mktTrendFactorForBuyMarkdown, Math.Round(changePct, 5)));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }

                Thread.Sleep(1000 * 15);
            }
        }
示例#12
0
        public BrokerErrorCode GetSnapQuote(string exchange, string stockCode, out EquitySymbolQuote quote)
        {
            quote = new EquitySymbolQuote();

            //lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode     = BrokerErrorCode.Unknown;
                int             retryCount    = 0;
                int             maxRetryCount = 3;

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

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

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

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

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

                            quote.ExchangeStr       = line[1];
                            quote.StockCode         = line[2];
                            quote.ClosePrice        = double.Parse(line[7]);
                            quote.ATP               = double.Parse(line[9]);
                            quote.LowerCircuitPrice = double.Parse(line[14]);
                            quote.UpperCircuitPrice = double.Parse(line[15]);
                            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);
            }
        }
示例#13
0
        public void ConvertToDeliveryPreviousDaysExpiringOpenPositions()
        {
            if (!MarketUtils.IsTimeAfter2XMin(50))
            {
                return;
            }

            BrokerErrorCode errCode = BrokerErrorCode.Unknown;

            // Get holding order matching this. check expiry date. if today then cancel holding order and convert it
            List <EquityPendingPositionForDelivery> pendingPositions;

            errCode = broker.GetOpenPositionsPendingForDelivery(stockCode, out pendingPositions);

            var positionsExpiringToday = pendingPositions.Where(p => p.ExpiryDate <= DateTime.Today.Date);

            var holdingsOrdersToRemove = new List <HoldingOrder>();

            foreach (var position in positionsExpiringToday)
            {
                var holdingOrder = holdingsOrders.Where(h => h.Type == OrderPositionTypeEnum.OpenPendingDelivery && h.SettlementNumber == position.SettlementNumber && !string.IsNullOrEmpty(h.OrderRef) && h.Qty == position.BlockedQuantity && h.Qty > 0).FirstOrDefault();
                var qtyToConvert = holdingOrder.Qty;

                // free up the blocked qty to go ahead with conversion
                errCode = CancelEquityOrder(string.Format("[Holding Conversion EOD] {0} {1}", holdingOrder.Type, holdingOrder.SettlementNumber), ref holdingOrder.OrderRef, EquityOrderType.DELIVERY, OrderDirection.SELL);
                if (errCode == BrokerErrorCode.Success)
                {
                    // instead of removing the order mark the status as Cancelled and set Qty to 0
                    holdingOrder.Qty    = 0;
                    holdingOrder.Status = OrderStatus.CANCELLED;
                    //holdingsOrdersToRemove.Add(holdingOrder);
                }

                int retryCount = 0;
                errCode = BrokerErrorCode.Unknown;
                while (errCode != BrokerErrorCode.Success && retryCount++ < 3)
                {
                    // Just to ensure the qty is freed up and some time before retry
                    Thread.Sleep(5000);
                    // convert to delivery
                    errCode = ConvertToDeliveryFromPendingForDelivery(stockCode, qtyToConvert, qtyToConvert, position.SettlementNumber, position.Exchange);
                    if (errCode != BrokerErrorCode.Success)
                    {
                        // Conversion fails.. log the parameters
                        Trace(string.Format("Previous ConversionToDelivery Failed: {5} {0} {1} qty expiring on {2} {3} {4}", stockCode, qtyToConvert, position.ExpiryDate.Date, position.SettlementNumber, position.Exchange, errCode));
                    }
                }
            }

            if (holdingsOrdersToRemove.Any())
            {
                holdingsOrders.RemoveAll(h => holdingsOrdersToRemove.Contains(h));
                UpdatePositionFile();
            }
        }
示例#14
0
        // Is logged in
        public BrokerErrorCode IsLoggedIn()
        {
            BrokerErrorCode errorCode = TouchServer();

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

            return(errorCode);
        }
示例#15
0
        public static bool IsErrorFatal(BrokerErrorCode errorCode)
        {
            if (errorCode == BrokerErrorCode.NullResponse || errorCode == BrokerErrorCode.OrderCancelFailed ||
                errorCode == BrokerErrorCode.Http || errorCode == BrokerErrorCode.ServerError ||
                errorCode == BrokerErrorCode.TechnicalReason ||
                errorCode == BrokerErrorCode.Success)
            {
                return(false);
            }

            return(true);
        }
示例#16
0
        // Helper function to cancel stock specific all outstanding orders and trace it out
        public static BrokerErrorCode CancelStockOutstandingOrdersAndTrace(IBroker broker, string stockCode)
        {
            Dictionary <string, BrokerErrorCode> cancelOrderErrCodes;
            BrokerErrorCode errorCode   = broker.CancelAllOutstandingEquityOrders(stockCode, out cancelOrderErrCodes);
            string          traceString = Thread.CurrentThread.Name + ": CancelStockAllOutstandingEquityOrders: " + errorCode.ToString() + "\n";

            foreach (KeyValuePair <string, BrokerErrorCode> errCodePair in cancelOrderErrCodes)
            {
                traceString += "Order: " + errCodePair.Key + ": Cancel status code is " + "\"" + errCodePair.Value.ToString() + "\"\n";
            }
            FileTracing.TraceOut(traceString);

            return(errorCode);
        }
示例#17
0
        private BrokerErrorCode CheckResponseDataValidity(string isLoggedInCheckData)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Success;

            if (String.IsNullOrEmpty(isLoggedInCheckData))
            {
                errorCode = BrokerErrorCode.NullResponse;
            }
            else if (isLoggedInCheckData.IndexOf("have faced some technical or connectivity") > -1)
            {
                errorCode = BrokerErrorCode.TechnicalReason;
            }
            else if (isLoggedInCheckData.IndexOf("close your browser and try again") > -1)
            {
                errorCode = BrokerErrorCode.TechnicalReason;
            }
            else if ((isLoggedInCheckData.IndexOf("Invalid User:The Login Id entered is not valid", StringComparison.OrdinalIgnoreCase) >= 0) ||
                     (isLoggedInCheckData.IndexOf("Bad connection", StringComparison.OrdinalIgnoreCase) >= 0) ||
                     (isLoggedInCheckData.IndexOf("login id", StringComparison.OrdinalIgnoreCase) > 0) ||
                     (isLoggedInCheckData.IndexOf("Invalid User", StringComparison.OrdinalIgnoreCase) >= 0) ||
                     (isLoggedInCheckData.IndexOf(/*"Session has */ "Timed Out", StringComparison.OrdinalIgnoreCase) >= 0) ||
                     (isLoggedInCheckData.IndexOf("Please Login again", StringComparison.OrdinalIgnoreCase) >= 0) ||
                     (isLoggedInCheckData.Length < 2000 && isLoggedInCheckData.IndexOf("location.href=chttps + \"/customer/logon.asp\"", StringComparison.OrdinalIgnoreCase) >= 0)
                     )
            {
                mLoggedIn = false;
                errorCode = BrokerErrorCode.NotLoggedIn;
            }
            else
            {
                //resultString = Regex.Replace(subjectString, @"(?:(?:\r?\n)+ +){2,}", @"\n");
                string isLoggedInCheckData1 = Regex.Replace(isLoggedInCheckData, @"\s", "");
                //isLoggedInCheckData = isLoggedInCheckData.Replace(" ", "").Replace("\n", "").Replace("\t", "");
                if (isLoggedInCheckData1 == _noLoginNonNullResponse)
                {
                    errorCode = BrokerErrorCode.NotLoggedIn;
                    mLoggedIn = false;
                }
            }

            if (errorCode != BrokerErrorCode.Success)
            {
                string desc    = string.Format("CheckResponseValidity Failed-Code-{0}", errorCode);
                string content = string.Format("<b>{0}\n\n\n\n{1}\n<b>", desc, isLoggedInCheckData);
                File.WriteAllText(SystemUtils.GetErrorFileName(desc, true), content);
            }

            return(errorCode);
        }
示例#18
0
        public BrokerErrorCode Epilog()
        {
            // While exiting the thread, cancel all the outstanding orders
            // Before cancel, store the state of any imbalanced outstanding order, i.e. 1-side executed(fully or partly) trade
            BrokerErrorCode errorCode   = BrokerErrorCode.Success;
            string          traceString = "Algo1_SimplePairedBuySellDelivery.Epilog :: ENTER";

            FileTracing.TraceOut(traceString);
            if (algoParams.bCancelOutstandingOrdersAtEnd)
            {
                errorCode = BrokerUtils.CancelStockOutstandingOrdersAndTrace(mBroker, stockCode);
            }
            traceString = "Algo1_SimplePairedBuySellDelivery.Epilog :: EXIT";
            FileTracing.TraceOut(traceString);
            return(errorCode);
        }
示例#19
0
        // Login worker thread
        public static void Background_LoginCheckerThread(object obj)
        {
            BrokingAccountObject brokerAccountObj = (BrokingAccountObject)obj;
            IBroker         iciciDirectAccount    = brokerAccountObj.Broker;
            BrokerErrorCode errorCode             = BrokerErrorCode.Success;

            while (!brokerAccountObj.DoStopThread)
            {
                // SIMPLETODO uncomment the below line
                errorCode = iciciDirectAccount.CheckAndLogInIfNeeded(false);
                string traceString = "Periodic login check: " + errorCode.ToString();
                FileTracing.TraceOut(traceString);

                // sleep of 3 minutes
                Thread.Sleep(3000 * 60);
            }
        }
示例#20
0
        public BrokerErrorCode PlaceEquityOrder(string stockCode,
                                                OrderPositionTypeEnum holdingType,
                                                int availableQty,
                                                int quantity,
                                                string price,
                                                OrderPriceType orderPriceType,
                                                OrderDirection orderDirection,
                                                EquityOrderType orderType,
                                                Exchange exchange,
                                                string settlementNumber,
                                                out string orderRef)
        {
            BrokerErrorCode errCode = BrokerErrorCode.Unknown;

            orderRef = "";

            // Only OrderPositionTypeEnum.Margin is Buy/Sell, rest all others are only sell orders
            if (holdingType == OrderPositionTypeEnum.Btst)  //  only a sell order
            {
                errCode = broker.PlaceEquityDeliveryBTSTOrder(stockCode, quantity, price, orderPriceType, orderDirection, orderType, exchange, settlementNumber, out orderRef);
            }
            else if (holdingType == OrderPositionTypeEnum.Demat || holdingType == OrderPositionTypeEnum.Margin)
            {
                errCode = broker.PlaceEquityMarginDeliveryFBSOrder(stockCode, quantity, price, orderPriceType, orderDirection, orderType, exchange, out orderRef);
            }
            else if (holdingType == OrderPositionTypeEnum.OpenPendingDelivery) // only square off sell order
            {
                errCode = broker.PlaceEquityMarginSquareOffOrder(stockCode, availableQty, quantity, price, orderPriceType, orderDirection, orderType, settlementNumber, exchange, out orderRef);
            }

            var orderTypeStr = orderType == EquityOrderType.DELIVERY ? ("CASH " + holdingType) : "MARGIN";

            Trace(string.Format(orderTraceFormat, stockCode, orderDirection, quantity, price, orderTypeStr, errCode, orderPriceType, settlementNumber));

            if (errCode == BrokerErrorCode.Success && orderDirection == OrderDirection.BUY)
            {
                todayBuyOrderCount++;
                if (todayBuyOrderCount >= maxBuyOrdersAllowedInADay)
                {
                    Trace(string.Format("Buy order count reached is: {0}. Max buy orders allowed: {1}", todayBuyOrderCount, maxBuyOrdersAllowedInADay));
                }
            }

            return(errCode);
        }
示例#21
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);
        }
示例#22
0
        //stockCode only for logging
        private BrokerErrorCode GetOrderStatus(string orderId, string stockCode, out OrderStatus upstoxOrderStatus)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Unknown;

            upstoxOrderStatus = OrderStatus.UNKNOWN;

            int retryCount    = 0;
            int maxRetryCount = 3;

            while (!(errorCode == BrokerErrorCode.Success || errorCode == BrokerErrorCode.OrderRejected) && retryCount++ < maxRetryCount)
            {
                try
                {
                    var status = upstox.GetOrderStatus(orderId);

                    Trace(string.Format("{0} OrderId:{1}, UpstoxOrderStatus:{2}", stockCode, orderId, status));

                    if (status.ToLower() == "rejected")
                    {
                        errorCode         = BrokerErrorCode.OrderRejected;
                        upstoxOrderStatus = OrderStatus.REJECTED;
                    }
                    else
                    {
                        errorCode         = BrokerErrorCode.Success;
                        upstoxOrderStatus = OrderStatus.ORDERED;
                    }
                }
                catch (Exception ex)
                {
                    Trace(string.Format(genericErrorLogFormat, orderId, GeneralUtils.GetCurrentMethod(), ex.Message, ex.StackTrace));
                    Trace(string.Format(retryLogFormat, retryCount, maxRetryCount));

                    if (retryCount >= maxRetryCount)
                    {
                        break;
                    }
                }
            }
            return(errorCode);
        }
示例#23
0
        // holding is merged with today's outtsanding and an avg price is arrived at. this then is updated as holding into positions file
        public void ConvertToDeliveryAndUpdatePositionFile(bool isEODLast = false)
        {
            // convert to delivery any open buy position
            if (todayOutstandingQty > 0)
            {
                // convert to delivery, update holding qty and write to positions file
                errCode = ConvertPendingMarginPositionsToDelivery(stockCode, todayOutstandingQty, todayOutstandingQty, settlementNumber, OrderDirection.BUY, exchange);

                if (errCode == BrokerErrorCode.Success || isEODLast)
                {
                    holdingOutstandingPrice  = (todayOutstandingPrice * todayOutstandingQty) + (holdingOutstandingQty * holdingOutstandingPrice);
                    holdingOutstandingQty   += todayOutstandingQty;
                    holdingOutstandingPrice /= holdingOutstandingQty;
                    holdingOutstandingPrice  = Math.Round(holdingOutstandingPrice, 2);

                    UpdatePositionFile(holdingOutstandingQty, holdingOutstandingPrice, "");

                    todayOutstandingQty = 0;
                }
            }
        }
示例#24
0
        public BrokerErrorCode CancelOrder(string orderId)
        {
            //lock (lockSingleThreadedUpstoxCall)
            {
                BrokerErrorCode errorCode     = BrokerErrorCode.Unknown;
                int             retryCount    = 0;
                int             maxRetryCount = 3;

                while (errorCode != BrokerErrorCode.Success && retryCount++ < maxRetryCount)
                {
                    try
                    {
                        var status = upstox.CancelSimpleOrder(orderId);

                        if (status.Contains("Cancellation sent for"))
                        {
                            errorCode = BrokerErrorCode.Success;
                        }
                        else
                        {
                            Trace(string.Format("Cancellation failed for order: {0} with status {1}", orderId, status));
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace(string.Format(genericErrorLogFormat, orderId, GeneralUtils.GetCurrentMethod(), ex.Message, ex.StackTrace));
                        Trace(string.Format(retryLogFormat, retryCount, maxRetryCount));

                        if (retryCount >= maxRetryCount || ex.Message.Contains("No open orders to cancel"))
                        {
                            break;
                        }

                        Thread.Sleep(500);
                    }
                }

                return(errorCode);
            }
        }
        // IBroker.CancelAllOutstandingEquityOrders
        // Stock-specific Cancellation of all outstanding orders
        public BrokerErrorCode CancelAllOutstandingEquityOrders(
            string stockCode,
            out Dictionary <string, BrokerErrorCode> cancelOrderErrCodes)
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Success;

            cancelOrderErrCodes = new Dictionary <string, BrokerErrorCode>();
            Dictionary <string, EquityOrderBookRecord> stockOrdersToCancel;

            // Make sure we have the latest order book data filtered by stockcode
            errorCode = GetEquityOrderBookToday(false, true, stockCode, out stockOrdersToCancel);
            if (errorCode != BrokerErrorCode.Success)
            {
                return(errorCode);
            }

            foreach (KeyValuePair <string, EquityOrderBookRecord> orderPair in stockOrdersToCancel)
            {
                // Try to cancel only cancellable orders
                if (orderPair.Value.Status == OrderStatus.ORDERED ||
                    orderPair.Value.Status == OrderStatus.PARTEXEC ||
                    orderPair.Value.Status == OrderStatus.REQUESTED)
                {
                    // Trim it
                    string orderRef = orderPair.Key.Trim(' ', '\t', '\r', '\n');

                    BrokerErrorCode tmpErrCode = CancelEquityOrder(orderRef, false);

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

                    cancelOrderErrCodes[orderRef] = tmpErrCode;
                }
            }

            return(errorCode);
        }
示例#26
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);
        }
示例#27
0
        public BrokerErrorCode TouchServer()
        {
            BrokerErrorCode errorCode = BrokerErrorCode.Success;

            string data = IciciGetWebPageResponse(URL_ICICI_MODIFYALLOCATION,
                                                  "pgname=ModAlloc&ismethodcall=0&mthname=",
                                                  URL_ICICI_REFERRER,
                                                  mCookieContainer,
                                                  out errorCode);

            if (string.IsNullOrEmpty(data))
            {
                return(BrokerErrorCode.NullResponse);
            }

            if (data.Contains("Bank Account No. "))
            {
                return(BrokerErrorCode.Success);
            }

            //if (data == "Y<script> window.location.href = 'https://secure.icicidirect.com/IDirectTrading/customer/login.aspx'</script>")
            return(BrokerErrorCode.NotLoggedIn);
        }
示例#28
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);
        }
示例#29
0
        // holding is merged with today's outtsanding and an avg price is arrived at. this then is updated as holding into positions file
        public void ConvertToDeliveryAndUpdatePositionFile(bool isEODLast = false)
        {
            var  errCode = BrokerErrorCode.Unknown;
            bool isConversionSuccessful = false;

            // convert to delivery any open buy position
            if (todayOutstandingQty > 0 && doConvertToDeliveryAtEOD)
            {
                // cancel outstanding order to free up the qty for conversion
                if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                {
                    errCode = CancelEquityOrder("[Margin Conversion EOD]", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);
                }

                // convert to delivery, update holding qty and write to positions file
                // may need to seperate out and convert each position seperately. currently all outstanding for the stock is tried to convert in single call
                if (string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                {
                    errCode = ConvertPendingMarginPositionsToDelivery(stockCode, todayOutstandingQty, todayOutstandingQty, settlementNumber, OrderDirection.BUY, exchange);
                }

                if (errCode != BrokerErrorCode.Success)
                {
                    // Conversion fails.. log the parameters
                    Trace(string.Format("Today ConversionToDelivery Failed: {0} {1} {2} {3} {4} {5}", stockCode, todayOutstandingQty, todayOutstandingQty, settlementNumber, OrderDirection.BUY, exchange));
                }

                if (errCode == BrokerErrorCode.Success)
                {
                    isConversionSuccessful = true;
                }

                // if insufficient limit, then try to squareoff
                // bought qty needs square off. there is outstanding sell order, revise the price to try square off
                if (errCode == BrokerErrorCode.InsufficientLimit && doSquareOffIfInsufficientLimitAtEOD)
                {
                    BrokerErrorCode errCode1 = BrokerErrorCode.Success;

                    // cancel existing sell order
                    if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                    {
                        errCode1 = CancelEquityOrder("[Margin EOD] Insufficient Limit to convert. Try to Squareoff", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);
                    }

                    if (errCode1 == BrokerErrorCode.Success)
                    {
                        // place new sell order, update sell order ref
                        var sellPrice = GetSellPrice(todayOutstandingPrice, false, false, true);
                        errCode1 = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Margin, todayOutstandingQty, todayOutstandingQty, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, "", out todayOutstandingSellOrderRef);
                    }
                }
            }

            if (isConversionSuccessful || isEODLast)
            {
                holdingOutstandingPrice = (todayOutstandingPrice * todayOutstandingQty) + (holdingOutstandingQty * holdingOutstandingPrice);
                holdingOutstandingQty  += todayOutstandingQty;
                if (holdingOutstandingQty == 0)
                {
                    holdingOutstandingPrice = 0;
                }
                else
                {
                    holdingOutstandingPrice /= holdingOutstandingQty;
                }
                holdingOutstandingPrice = Math.Round(holdingOutstandingPrice, 2);

                UpdatePositionFile(isEODLast);

                todayOutstandingQty = 0;
            }
        }
示例#30
0
        // Try min profit squareoff first between 3 - 3.10 time.
        // From 3.10 to 3.15 time if squareoff of all positions is set to true and the ltp diff meets threshold for max loss pct, then do a market order squareoff
        public void TrySquareOffNearEOD(AlgoType algoType)
        {
            // if after 3 pm, then try to square off in at least no profit no loss if possible. cancel the outstanding buys anyway
            if (MarketUtils.IsTimeAfter310())
            {
                var ordPriceType   = OrderPriceType.LIMIT;
                var doUpdateOrders = false;

                // 3.20 - 3.25 pm time. market order type for forced square off given pct loss is within acceptable range
                // do it before 3.15, otherwise broker will try to squareoff on its own anytime between 3.15 - 3.30
                if (MarketUtils.IsTimeAfter320() && !MarketUtils.IsTimeAfter325() && squareOffAllPositionsAtEOD && !isEODMinLossSquareOffMarketOrderUpdated)
                {
                    double ltp;
                    var    errCode = GetLTP(out ltp);

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

                    ordPriceType = OrderPriceType.MARKET;

                    var diff = (ltp - todayOutstandingPrice) / ltp;

                    Trace(string.Format("[Margin EOD]: diff {0} ltp {1} outstandingprice {2} pctMaxLossSquareOffPositions {3} goodPrice {4} ", diff, ltp, todayOutstandingPrice, pctMaxLossSquareOffPositions, goodPrice));

                    if ((Math.Abs(diff) < pctMaxLossSquareOffPositions || diff > 0) && todayOutstandingPrice > goodPrice)
                    {
                        Trace(string.Format("[Margin EOD]: max loss {0}% is less than {1}% and avg outstanding price {2} is greater than good price of {3}. LTP is {4}. Place squareoff @ MARKET.", diff, pctMaxLossSquareOffPositions, todayOutstandingPrice, goodPrice, ltp));
                        doUpdateOrders = true;
                        isEODMinLossSquareOffMarketOrderUpdated = true;
                    }
                }

                // 3.10 - 3.20 pm time. try simple limit order with min profit price. watch until 3.10 pm
                else if (!isEODMinProfitSquareOffLimitOrderUpdated)
                {
                    Trace(string.Format("[Margin EOD]: MinProfit Squareoff and cancel outstanding buy orders"));
                    ordPriceType = OrderPriceType.LIMIT;
                    isEODMinProfitSquareOffLimitOrderUpdated = true;
                    doUpdateOrders = true;
                }

                if (doUpdateOrders)
                {
                    if (algoType == AlgoType.AverageTheBuyThenSell)
                    {
                        // just cancel the outstanding buy order
                        if (!string.IsNullOrEmpty(todayOutstandingBuyOrderRef))
                        {
                            // cancel existing buy order
                            errCode = CancelEquityOrder("[Margin EOD]", ref todayOutstandingBuyOrderRef, EquityOrderType.MARGIN, OrderDirection.BUY);
                        }

                        // bought qty needs square off. there is outstanding sell order, revise the price to try square off
                        if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                        {
                            // cancel existing sell order
                            errCode = CancelEquityOrder("[Margin EOD]", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);

                            if (errCode == BrokerErrorCode.Success)
                            {
                                // place new sell order, update sell order ref
                                var sellPrice = GetSellPrice(todayOutstandingPrice, false, true);
                                errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Margin, todayOutstandingQty, todayOutstandingQty, sellPrice.ToString(), ordPriceType, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, "", out todayOutstandingSellOrderRef);
                            }
                        }
                    }
                }
            }
        }