public override void StockBuySell()
        {
            try
            {
                myUpstoxWrapper.Upstox.TradeUpdateEvent    += new Upstox.TradeUpdateEventEventHandler(TradeUpdated);
                myUpstoxWrapper.Upstox.OrderUpdateEvent    += new Upstox.OrderUpdateEventEventHandler(OrderUpdated);
                myUpstoxWrapper.Upstox.PositionUpdateEvent += new Upstox.PositionUpdateEventEventHandler(PositionUpdated);
                Init(AlgoType.AverageTheBuyThenSell);
            }
            catch (Exception ex)
            {
                Trace(string.Format("{0} Error: {1} \nStacktrace:{2}", stockCode, ex.Message, ex.StackTrace));
                throw;
            }

            while (MarketUtils.IsMarketOpen())
            {
                try
                {
                    PlaceBuyOrderIfEligible();
                    HandleConversionAnytimeNew();

                    if (MarketUtils.IsTimeAfter3XMin(0))
                    {
                        NearEODSquareOffAndCancelBuyOrder();
                    }

                    if (MarketUtils.IsTimeAfter3XMin(29))
                    {
                        CancelOpenOrders();
                    }
                }
                catch (Exception ex)
                {
                    Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }

                MainLoopPause();
            }

            EODProcess(true); // EOD final update
        }
Exemplo n.º 2
0
        public override void StockBuySell()
        {
            try
            {
                Init(AlgoType.AverageTheBuyThenSell);
            }
            catch (Exception ex)
            {
                Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                throw;
            }

            while (MarketUtils.IsMarketOpen())
            {
                try
                {
                    // Try to convert to delivery pending open positions (nearing expiry) from previous days
                    ConvertToDeliveryPreviousDaysExpiringOpenPositions();

                    var holdingTradesRef = holdingsOrders.Select(h => h.OrderRef);

                    {
                        var newTrades = new Dictionary <string, EquityTradeBookRecord>();
                        // refresh trade book
                        errCode = broker.GetEquityTradeBookToday(true, stockCode, out newTrades);

                        foreach (var tradeKv in newTrades.OrderBy(t => t.Value.Direction).Reverse())
                        {
                            var tradeRef = tradeKv.Key;
                            var trade    = tradeKv.Value;

                            Trace(string.Format(tradeTraceFormat, stockCode, trade.Direction == OrderDirection.BUY ? "bought" : "sold", trade.NewQuantity, trade.Price,
                                                holdingTradesRef.Contains(tradeRef) ? "CASH" : "MARGIN"));

                            // if any holding sell executed
                            ProcessHoldingSellOrderExecution(newTrades);

                            // if sell executed, then update today outstanding to 0 , because sell order always contains the total outstanding qty and now all of it got sold with this trade
                            // but handle part executions using NewQuantity
                            if (tradeRef == todayOutstandingSellOrderRef)
                            {
                                todayOutstandingQty -= trade.NewQuantity;

                                if (todayOutstandingQty == 0)
                                {
                                    todayOutstandingPrice        = 0;
                                    todayOutstandingSellOrderRef = "";
                                }
                            }

                            // if buy executed, then place a corresponding updated sell order. assumption is that qty is completely executed.
                            // part executed qty will get considered only for first part, for later ones there is no update because we wont get it in newTrades again
                            if (tradeRef == todayOutstandingBuyOrderRef)
                            {
                                Dictionary <string, EquityOrderBookRecord> orders;
                                errCode = broker.GetEquityOrderBookToday(false, false, stockCode, out orders);

                                if (orders[todayOutstandingBuyOrderRef].Status == OrderStatus.EXECUTED)
                                {
                                    Trace(string.Format("Fully executed newqty {0} todayoutstandingqty {1} todayoutstandingprice {2} sellorderref {3} buyorderef {4} buyorderstatus {5}", trade.NewQuantity, todayOutstandingQty, todayOutstandingPrice, todayOutstandingSellOrderRef, todayOutstandingBuyOrderRef, orders[todayOutstandingBuyOrderRef].Status));
                                    todayOutstandingBuyOrderRef = "";
                                }
                                else
                                {
                                    Trace(string.Format("Partially executed newqty {0} todayoutstandingqty {1} todayoutstandingprice {2} sellorderref {3} buyorderef {4} buyorderstatus {5}", trade.NewQuantity, todayOutstandingQty, todayOutstandingPrice, todayOutstandingSellOrderRef, todayOutstandingBuyOrderRef, orders[todayOutstandingBuyOrderRef].Status));
                                }

                                // update outstanding qty and outstanding price to place updated sell order
                                todayOutstandingPrice = (todayOutstandingPrice * todayOutstandingQty) + (trade.NewQuantity * trade.Price);
                                todayOutstandingQty  += trade.NewQuantity;
                                if (todayOutstandingQty == 0)
                                {
                                    todayOutstandingPrice = 0;
                                }
                                else
                                {
                                    todayOutstandingPrice /= todayOutstandingQty;
                                }
                                todayOutstandingPrice = Math.Round(todayOutstandingPrice, 2);

                                if (todayOutstandingQty >= maxTodayOutstandingQtyAllowed)
                                {
                                    Trace(string.Format("TodayOutstandingQty reached the max. todayOutstandingQty: {0} maxTodayOutstandingQtyAllowed: {1}", todayOutstandingQty, maxTodayOutstandingQtyAllowed));
                                }

                                if ((todayOutstandingQty + holdingOutstandingQty) >= maxTotalOutstandingQtyAllowed)
                                {
                                    Trace(string.Format("TotalOutstandingQty reached the max. todayOutstandingQty: {0} holdingOutstandingQty: {1} maxTotalOutstandingQtyAllowed: {2}", todayOutstandingQty, holdingOutstandingQty, maxTotalOutstandingQtyAllowed));
                                }

                                settlementNumber = trade.SettlementNumber;

                                lastBuyPrice = useAvgBuyPriceInsteadOfLastBuyPriceToCalculateBuyPriceForNewOrder ? todayOutstandingPrice : trade.Price;

                                if (!string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                                {
                                    // cancel existing sell order if it exists
                                    errCode = CancelEquityOrder("[Buy Executed]", ref todayOutstandingSellOrderRef, EquityOrderType.MARGIN, OrderDirection.SELL);
                                }
                                if (errCode == BrokerErrorCode.Success || string.IsNullOrEmpty(todayOutstandingSellOrderRef))
                                {
                                    // place new sell order if previous cancelled or it was first one, update sell order ref
                                    var sellPrice = GetSellPrice(todayOutstandingPrice, false, false);
                                    errCode = PlaceEquityOrder(stockCode, OrderPositionTypeEnum.Margin, todayOutstandingQty, todayOutstandingQty, sellPrice.ToString(), OrderPriceType.LIMIT, OrderDirection.SELL, EquityOrderType.MARGIN, exchange, "", out todayOutstandingSellOrderRef);
                                }
                            }
                        }

                        PlaceBuyOrderIfEligible();
                    }

                    // Only relevant near EOD
                    TrySquareOffNearEOD(AlgoType.AverageTheBuyThenSell);
                }
                catch (Exception ex)
                {
                    Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }

                if (MarketUtils.IsTimeAfter3XMin(28))
                {
                    CancelHoldingSellOrders();
                    ConvertToDeliveryAndUpdatePositionFile();
                }

                PauseBetweenTradeBookCheck();
            }

            // for safety call conversion once more if the conversion call in the above loop was missed due to Pause and loop's time check
            //CancelHoldingSellOrders();
            ConvertToDeliveryAndUpdatePositionFile(true); // EOD final update
        }