Beispiel #1
0
 private void onTradeUpdateHandler(object sender, TradeUpdateEventArgs args)
 {
     lock (tradeRowsLock)
     {
         // Update the trade row
         tradeRows.Find(tradeRow => tradeRow.TradeId == args.TradeId)?.Update();
     }
 }
Beispiel #2
0
        /// <summary>
        /// Event handler for the <see cref="OnTradeUpdated"/> event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void OnTradeUpdated(object sender, TradeUpdateEventArgs args)
        {
            // Ignore updates for trades other than this one
            if (args.TradeId != tradeId)
            {
                return;
            }

            // Update both our and their offers
            UpdateOffers();

            // Check if there is a token we can process
            if (!string.IsNullOrEmpty(args.Token))
            {
                lock (pendingItemStacksLock)
                {
                    // Check if there are pending item stacks for this token
                    if (pendingItemStacks.ContainsKey(args.Token))
                    {
                        if (args.Success)
                        {
                            // Destroy and remove the pending items, they have been received by the server
                            foreach (Thing thing in pendingItemStacks[args.Token].Things)
                            {
                                thing.Destroy();
                            }

                            pendingItemStacks.Remove(args.Token);
                        }
                        else
                        {
                            // Server failed to update the trade
                            // Get all of the selected things from the item stacks and drop them
                            IEnumerable <Thing> things = pendingItemStacks[args.Token].Things;
                            Instance.DropPods(things);
                        }
                    }
                }
            }
        }
        public void TradeUpdated(object sender, TradeUpdateEventArgs args)
        {
            lock (lockRunEitherPlaceBuyOrTradeUpdated)
            {
                try
                {
                    var trade = ConvertTradeUpdateArgsToTradeRecord(args);

                    if (stockCode != trade.StockCode)
                    {
                        return;
                    }

                    var isSellExecutedFully = false;

                    Trace(string.Format(tradeTraceFormat, stockCode, trade.Direction == OrderDirection.BUY ? "bought" : "sold", args.TradedQty, args.TradedPrice,
                                        holdingSellOrder.OrderId == trade.OrderId ? "DELIVERY" : "MARGIN", trade.OrderId, trade.TradeId, trade.DateTime, args.ExchTime, args.TimeStamp));

                    // if any holding sell executed
                    if (trade.OrderId == holdingSellOrder.OrderId)
                    {
                        ProcessHoldingSellOrderExecution(trade.NewQuantity);
                    }

                    // if SELL executed, then update today outstanding with executed qty (handle part executions using NewQuantity)
                    // If it is after 3.15 and broker did auto sq off, then broker's order ref is not with us and wont match with our sq off order. Our sqoff order will be cancelled by the broker
                    if (trade.OrderId == outstandingSellOrder.OrderId || ((MarketUtils.IsTimeAfter315() && trade.EquityOrderType == EquityOrderType.MARGIN && trade.Direction == OrderDirection.SELL)))
                    {
                        if (!string.IsNullOrEmpty(outstandingSellOrder.OrderId) && trade.OrderId != outstandingSellOrder.OrderId)
                        {
                            // If broker initiated market squareoff then Cancel the known sell order to avoid extra execution
                            errCode = CancelEquityOrder("[Broker SquareOff Executed]", ref outstandingSellOrder.OrderId, orderType, OrderDirection.SELL);
                        }

                        todayOutstandingQty -= trade.NewQuantity;

                        if (todayOutstandingQty == 0)
                        {
                            todayOutstandingPrice        = 0;
                            outstandingSellOrder.OrderId = "";
                            todayOutstandingTradeCount   = 0;
                            isSellExecutedFully          = true;
                        }
                    }

                    // if BUY executed, then place a corresponding updated sell order.
                    if (trade.OrderId == outstandingBuyOrder.OrderId)
                    {
                        currentBuyOrdExecutedQty += trade.NewQuantity;

                        if (currentBuyOrdExecutedQty == currentBuyOrdQty)
                        {
                            Trace(string.Format("[Trade Execution] Fully executed NewQty={0} TotalQty={1}", trade.NewQuantity, currentBuyOrdQty));
                            outstandingBuyOrder.OrderId = "";
                            todayOutstandingTradeCount++;
                        }
                        else
                        {
                            Trace(string.Format("[Trade Execution] Partially executed NewQty={0} TotalQty={1}", trade.NewQuantity, currentBuyOrdQty));
                        }

                        // update outstanding qty and outstanding price to place updated sell order
                        todayOutstandingPrice = (todayOutstandingPrice * todayOutstandingQty) + (trade.NewQuantity * trade.Price);
                        todayOutstandingQty  += trade.NewQuantity;
                        todayOutstandingPrice = todayOutstandingQty == 0 ? 0 : todayOutstandingPrice / todayOutstandingQty;

                        UpdatePnLStats();

                        if (todayOutstandingQty >= maxTodayOutstandingQtyAllowed)
                        {
                            Trace(string.Format("[Trading Limits Hit] TodayOutstandingQty reached the max. todayOutstandingQty: {0} maxTodayPositionValueMultiple: {1}", todayOutstandingQty, maxTodayOutstandingQtyAllowed));
                        }

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

                        lastBuyPrice = trade.Price;

                        var sellPrice = GetSellPrice(todayOutstandingPrice, false, false);

                        if (!string.IsNullOrEmpty(outstandingSellOrder.OrderId))
                        {
                            // modify existing sell order if it exists
                            errCode = ModifyEquityOrder("NewBuy modify squareoff", stockCode, outstandingSellOrder.OrderId, OrderPriceType.LIMIT, todayOutstandingQty, sellPrice, out upstoxOrderStatus);

                            // cancel existing sell order if it exists
                            //errCode = CancelEquityOrder("[Buy Executed]", ref outstandingSellOrder.OrderId, orderType, OrderDirection.SELL);
                        }
                        if (string.IsNullOrEmpty(outstandingSellOrder.OrderId))
                        {
                            // place new sell order if previous cancelled or it was first one, update sell order ref
                            errCode = PlaceEquityOrder(exchStr, stockCode, OrderDirection.SELL, OrderPriceType.LIMIT, todayOutstandingQty, orderType, sellPrice, out outstandingSellOrder.OrderId, out upstoxOrderStatus);
                        }
                    }

                    if (isSellExecutedFully)
                    {
                        // Cancel existing Buy order which might be an average seeking order, as the pricecalc might have changed
                        if (!string.IsNullOrEmpty(outstandingBuyOrder.OrderId))
                        {
                            // cancel existing buy order
                            errCode = CancelEquityOrder("[Sell Executed Fully]", ref outstandingBuyOrder.OrderId, orderType, OrderDirection.BUY);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace("Error:" + ex.Message + "\nStacktrace:" + ex.StackTrace);
                }
            }
        }