예제 #1
0
 private void RemoveOrder(BookDone removeOrder)
 {
     if (removeOrder.Side == SideType.Buy)
     {
         var offer = Buys.FirstOrDefault(a => a.OrderId == removeOrder.OrderId);
         if (offer != null)
         {
             Buys.Remove(offer);
         }
         else if (!RemoveReceiveOrder(removeOrder.OrderId))
         {
             Api.Log.Warning($"Order not found for {removeOrder.Reason} buy offer : {removeOrder.OrderId}");
         }
     }
     else
     {
         var offer = Sells.FirstOrDefault(b => b.OrderId == removeOrder.OrderId);
         if (offer != null)
         {
             Sells.Remove(offer);
         }
         else if (!RemoveReceiveOrder(removeOrder.OrderId))
         {
             Api.Log.Warning($"Order not found for {removeOrder.Reason} sell offer : {removeOrder.OrderId}");
         }
     }
 }
예제 #2
0
        public async Task InsertBuys(Buys model)
        {
            try
            {
                var items = await itemsRepository.GetItem(model.idItem);

                //Validation
                if (items == null)
                {
                    throw new GlobalException("El item no está registrado");
                }

                if (model.quantity > items.residue)
                {
                    throw new GlobalException("No es posible registrar compra, la cantidad es mayor al item.");
                }


                await BuysRepository.InsertBuy(model);
            }
            catch (Exception ex)
            {
                throw new GlobalException($"Excepción  no controlada debido a: {ex.Message}");
            }
        }
예제 #3
0
        public OrderTransaction RemoveBuy()
        {
            OrderTransaction transaction = null;

            Buys.TryDequeue(out transaction);
            return(transaction);
        }
예제 #4
0
 public int GetBuysQuantity(Symbol symbol)
 {
     if (!Buys.IsEmpty)
     {
         return(Buys.Sum(b => b.Quantity));
     }
     return(0);
 }
예제 #5
0
 public int GetBuysQuantity(Symbol symbol)
 {
     if (BuysCount() > 0)
     {
         return(Buys.Sum(b => b.Quantity));
     }
     return(0);
 }
예제 #6
0
        public ActionResult DeleteConfirmed(int id)
        {
            Buys buys = db.Buys.Find(id);

            db.Buys.Remove(buys);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #7
0
        public OrderTransaction RemoveBuy()
        {
            OrderTransaction transaction = null;

            if (Buys.Count > 0)
            {
                Buys.TryPop(out transaction);
            }
            return(transaction);
        }
예제 #8
0
 public ActionResult Edit([Bind(Include = "ID,ProductsID,MembersID,PriceBought,DateBought")] Buys buys)
 {
     if (ModelState.IsValid)
     {
         db.Entry(buys).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ProductsID = new SelectList(db.Products, "ID", "ProductName", buys.ProductsID);
     return(View(buys));
 }
예제 #9
0
        public async Task <bool> UpdateBuys(Buys model)
        {
            var Buys = await GetBuy(model.id);

            Buys.idItem   = model.idItem;
            Buys.quantity = model.quantity;
            Buys.dateBuy  = model.dateBuy;
            int rows = await dbc.SaveChangesAsync();

            return(rows > 0);
        }
예제 #10
0
 public async Task <bool> UpdateBuys(Buys model)
 {
     try
     {
         return(await BuysRepository.UpdateBuys(model));
     }
     catch (Exception ex)
     {
         throw new GlobalException($"Excepción  no controlada debido a: {ex.Message}");
     }
 }
예제 #11
0
        public ActionResult CreateBuy([Bind(Include = "ID,ProductsID,MembersID,PriceBought,DateBought")] Buys buys)
        {
            if (ModelState.IsValid)
            {
                db.Buys.Add(buys);
                db.SaveChanges();
                return(RedirectToAction("Index", "Home"));
            }

            // ViewBag.ProductsID = new SelectList(db.Products, "ID", "ProductName", buys.ProductsID);
            return(View(buys));
        }
예제 #12
0
 public void Add(OrderTransaction transaction)
 {
     Symbol = transaction.Symbol;
     if (transaction.Direction == OrderDirection.Buy)
     {
         Buys.Push(transaction);
     }
     if (transaction.Direction == OrderDirection.Sell)
     {
         Sells.Push(transaction);
     }
 }
예제 #13
0
        public OrderTransaction Remove(string queueName)
        {
            OrderTransaction transaction = null;

            if (queueName.Contains(Buy))
            {
                Buys.TryDequeue(out transaction);
            }
            if (queueName.Contains(Sell))
            {
                Sells.TryDequeue(out transaction);
            }
            return(transaction);
        }
예제 #14
0
        // GET: Buys/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Buys buys = db.Buys.Find(id);

            if (buys == null)
            {
                return(HttpNotFound());
            }
            return(View(buys));
        }
예제 #15
0
        internal void ApplyInternal(OptionDeleted deleted)
        {
            NumberOfContracts = 0;
            Transactions.Clear();
            Buys.Clear();
            Sells.Clear();
            FirstFill  = null;
            SoldToOpen = null;
            Closed     = null;
            Notes.Clear();
            Expirations.Clear();

            Deleted = true;
        }
예제 #16
0
        // GET: Buys/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Buys buys = db.Buys.Find(id);

            if (buys == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ProductsID = new SelectList(db.Products, "ID", "ProductName", buys.ProductsID);
            return(View(buys));
        }
예제 #17
0
        public static void Buys_Add(TimeSales_Content timeAndSales, int size)
        {
            var symbol = timeAndSales.key;
            var buy    = new Buys()
            {
                Symbol      = symbol,
                RunDateTime = timeAndSales.TimeDate,
                Price       = (decimal)timeAndSales.price,
                Size        = size,
                PriceLevel  = (byte)timeAndSales.level
            };

            db.Buys.Add(buy);
            db.SaveChanges();
        }
예제 #18
0
        internal void ApplyInternal(OptionPurchased purchased)
        {
            if (FirstFill == null)
            {
                ApplyFirstTransactionLogic(false, purchased.When);
            }

            if (Deleted == true)
            {
                Deleted = false;
            }

            if (NumberOfContracts == 0)
            {
                PremiumReceived = 0;
                PremiumPaid     = 0;
            }

            AddNoteIfNotEmpty(purchased.Notes);

            NumberOfContracts += purchased.NumberOfContracts;

            var debit = purchased.NumberOfContracts * purchased.Premium;

            PremiumPaid += debit;

            Buys.Add(purchased);

            var description = $"Bought {purchased.NumberOfContracts} x ${StrikePrice} {OptionType} {Expiration.ToString("MM/dd")} contracts for ${purchased.Premium}/contract";

            Transactions.Add(
                Transaction.DebitTx(
                    Id,
                    purchased.Id,
                    Ticker,
                    description,
                    debit,
                    purchased.When,
                    true
                    )
                );

            ApplyClosedLogicIfApplicable(purchased.When, purchased.Id);
        }
예제 #19
0
        private void UpdateOrder(BookChange changeOrder)
        {
            var offer = changeOrder.Side == SideType.Buy
                ? Buys.FirstOrDefault(a => a.OrderId == changeOrder.OrderId)
                : Sells.FirstOrDefault(b => b.OrderId == changeOrder.OrderId);

            if (offer != null)
            {
                offer.Price = changeOrder.Price;
                offer.Size  = changeOrder.NewSize;
            }
            else
            {
                Api.Log.Warning("Change receive for unknown order id");
                OpenOrder(new BookOpen {
                    OrderId = changeOrder.OrderId, Side = changeOrder.Side, Price = changeOrder.Price, RemainingSize = changeOrder.NewSize
                });
            }
        }
예제 #20
0
        public OrderTransaction Remove(string direction)
        {
            OrderTransaction transaction = null;

            if (direction.Contains(Buy))
            {
                if (Buys.Count > 0)
                {
                    Buys.TryPop(out transaction);
                }
            }

            if (direction.Contains(Sell))
            {
                if (Sells.Count > 0)
                {
                    Sells.TryPop(out transaction);
                }
            }
            return(transaction);
        }
예제 #21
0
        /// <summary>
        /// Calculate the VWAP price
        /// </summary>
        /// <returns></returns>
        private double GetVWAP(string Symbol, enumOrderType orderType, enumSide side)
        {
            double VWAP = 0;

            if (orderType.Equals(enumOrderType.Market))
            {
                VWAP = Convert.ToDouble(Int16.MinValue); // For a market type, return a -32768
            }
            else
            {
                List <ExchangeOrder> liveOrders = null;
                int qty = 0;
                if (side.Equals(enumSide.Buy) && Sells.ContainsKey(Symbol))
                {
                    liveOrders = Sells[Symbol];
                }
                if (side.Equals(enumSide.Sell) && Buys.ContainsKey(Symbol))
                {
                    liveOrders = Buys[Symbol];
                }
                if (liveOrders == null)
                {
                    VWAP = Convert.ToDouble(Int16.MaxValue);
                }
                foreach (ExchangeOrder eo in liveOrders)
                {
                    VWAP += eo.Offer * eo.Volume;
                    qty  += eo.Volume;
                }
                if (!qty.Equals(0.0))
                {
                    VWAP /= qty;
                }
                else
                {
                    throw new DivideByZeroException(string.Format("Quantity becomes ZERO in GetVWAP, how come! Sybmol {0}, Side {1}", Symbol, side));
                }
            }
            return(VWAP);
        }
예제 #22
0
        private void OpenOrder(BookOpen openOrder)
        {
            var offer = new ProductOffer
            {
                OrderId = openOrder.OrderId,
                Price   = openOrder.Price,
                Size    = openOrder.RemainingSize
            };

            if (openOrder.Side == SideType.Buy)
            {
                Buys.Add(offer);
            }
            else
            {
                Sells.Add(offer);
            }

            if (!RemoveReceiveOrder(openOrder.OrderId))
            {
                Api.Log.Warning($"No receive message for order id {openOrder.OrderId}");
            }
        }
        public async Task ResetStateWithFullOrderBookAsync()
        {
            if (resetInProgress)
            {
                return;
            }
            resetInProgress = true;
            currentSequence = -1;
            if (robsCreatedLocally)
            {
                this.RealtimeOrderBookSubscription.SubscribeAsync(                // don't await bc it won't complete until subscription ends
                    reConnectOnDisconnect: true);                                 // else should already be subscribed
            }
            //using (var blocker = new SemaphoreSlim(0))
            //{ // https://stackoverflow.com/questions/23442543/using-async-await-with-dispatcher-begininvoke
            await System.Windows.Application.Current.Dispatcher.Invoke <Task>(
                async() =>
            {                                     // change to UI thread to use UI dbContext
                var response = await productOrderBookClient.GetProductOrderBook(ProductString, 3);
                Sells.Clear();
                foreach (var order in response.Sells)
                {                                         // no need to lock here bc lock is in AddOrder()
                    AddOrder(order, Side.Sell);
                }
                Buys.Clear();
                foreach (var order in response.Buys)
                {
                    AddOrder(order, Side.Buy);
                }
                this.currentSequence = response.Sequence;
                //blocker.Release();
            });

            //	await blocker.WaitAsync();
            //}
            resetInProgress = false;
        }
예제 #24
0
 internal void AddBuy(TradeActionEvent trade)
 {
     Buys.Add(trade);
 }
예제 #25
0
        /// <summary>
        /// Place a buy order
        /// </summary>
        /// <param name="order"></param>
        public enumStatus PlaceBuy(Order order)
        {
            if (MatchMeDB.Instance.AddOrder(order).Equals(enumStatus.OrderPlaced))
            {
                order.OrderStatus = enumStatus.PendingNew;
                MatchMeDB.Instance.UpdateOrder(order);
            }
            if (!order.OrderSide.Equals(enumSide.Buy))
            {
                ServerLog.LogError("Exchange: This is for the buy Orders, don't insert Others to here");
                throw new InvalidOperationException("Exchange: This is for the Buy Orders, don't insert Others to here");
            }
            ExchangeOrder        newExOrder  = new ExchangeOrder(order.Volume, order.Price, order.Id, order.Created);
            List <ExchangeOrder> matchedSell = new List <ExchangeOrder>();

            MatchBuy(order.Symbol, newExOrder, out matchedSell);
            Order orderInDB       = new Order(MatchMeDB.Instance.Orders[order.Id]);
            int   matchedQuantity = matchedSell != null && matchedSell.Count > 0 ? matchedSell.Sum(a => a.Volume) : 0;

            if (newExOrder.Volume.Equals(matchedQuantity))
            {
                orderInDB.OrderStatus = enumStatus.Filled;
            }
            else
            {
                orderInDB.OrderStatus = matchedQuantity > 0 ? enumStatus.PartiallyFilled : enumStatus.New;
                if (!Buys.ContainsKey(order.Symbol))
                {
                    Buys[order.Symbol] = new List <ExchangeOrder>();
                }
                Buys[order.Symbol].Add(newExOrder);
            }
            MatchMeDB.Instance.UpdateOrder(orderInDB);
            if (matchedQuantity > 0)
            {
                //Update Balance and balance;
                User user = new User(MatchMeDB.Instance.Users[orderInDB.UserID]);
                user.Balance -= newExOrder.Volume.Equals(matchedQuantity) ? matchedQuantity * order.Price + Config.Commission
                                        : matchedQuantity * order.Price;
                MatchMeDB.Instance.UpdateUser(user);

                Position position = MatchMeDB.Instance.GetPosition(orderInDB.UserID, orderInDB.Symbol);
                position.Quantity += matchedQuantity;
                MatchMeDB.Instance.UpdatePosition(position);
            }

            foreach (ExchangeOrder matched in matchedSell)
            {
                Order matchedInDB = new Order(MatchMeDB.Instance.Orders[matched.OrderId]);
                if (matchedInDB.Volume.Equals(matched.Volume))
                {
                    matchedInDB.OrderStatus = enumStatus.Filled;
                    int index = sells[order.Symbol].Select(a => a.Id).ToList().IndexOf(matched.Id);
                    sells[order.Symbol].RemoveAt(index);
                }
                else
                {
                    int index = sells[order.Symbol].Select(a => a.Id).ToList().IndexOf(matched.Id);
                    sells[order.Symbol][index].Volume -= matched.Volume;
                    matchedInDB.OrderStatus            = enumStatus.PartiallyFilled;
                    matchedInDB.Volume -= matched.Volume;
                }
                User user = new User(MatchMeDB.Instance.Users[matchedInDB.UserID]);
                user.Balance -= user.UserName.Equals(Config.AdminUser) ? 0 :
                                matchedInDB.Volume.Equals(matched.Volume) ? (matched.Volume * matched.Offer + Config.Commission) : matched.Volume * matched.Offer;
                MatchMeDB.Instance.UpdateUser(user);
                MatchMeDB.Instance.UpdateOrder(matchedInDB);

                Position position = MatchMeDB.Instance.GetPosition(matchedInDB.UserID, matchedInDB.Symbol);
                position.Quantity -= matched.Volume;
                MatchMeDB.Instance.UpdatePosition(position);
            }
            return(enumStatus.OrderPlaced);
            //************Jing Mai ************
            //if (!buys.ContainsKey(order.Symbol))
            //{
            //    eo = new ExchangeOrder(1, order.Price, order.Id, order.Created);
            //    List<ExchangeOrder> orderList = new List<ExchangeOrder>();
            //    orderList.Add(eo);
            //    buys.Add(order.Symbol, orderList);
            //    for (int vol = 2; vol <= order.Volume; vol++)
            //    {
            //        buys[order.Symbol].Add(eo);
            //    }
            //}
            //else
            //{
            //    eo = new ExchangeOrder(1, order.Price, order.Id, order.Created);
            //    for (int vol = 1; vol <= order.Volume; vol++)
            //    {
            //        buys[order.Symbol].Add(eo);
            //    }
            //}
            //buys[order.Symbol].OrderBy(x => x.Offer).ThenBy(x => x.Created);
            //order.OrderStatus = enumStatus.PendingNew;
            //for (int vol = 1; vol <= order.Volume; vol++)
            //{
            //    string MatcherOrderId = MatchMe(eo, order);
            //    if (!string.IsNullOrEmpty(MatcherOrderId))
            //        FillOrders(order.Id, MatcherOrderId);
            //}
            //***********************************
        }
예제 #26
0
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Name                 = "Num Touches";
                Buys                 = new ConcurrentDictionary <double, long>();
                BackColor            = Brushes.Transparent;
                BarColor             = Application.Current.TryFindResource("brushVolumeColumnBackground") as Brush;
                BuyColor             = Brushes.Green;
                DefaultWidth         = 160;
                PreviousWidth        = -1;
                DisplayText          = true;
                ForeColor            = Application.Current.TryFindResource("brushVolumeColumnForeground") as Brush;
                ImmutableBarColor    = Application.Current.TryFindResource("immutableBrushVolumeColumnBackground") as Brush;
                ImmutableForeColor   = Application.Current.TryFindResource("immutableBrushVolumeColumnForeground") as Brush;
                IsDataSeriesRequired = true;
                LastVolumes          = new ConcurrentDictionary <double, long>();
                SellColor            = Brushes.Red;
                Sells                = new ConcurrentDictionary <double, long>();
                Bidask               = VolumeSide.bid;
            }
            else if (State == State.Configure)
            {
                if (UiWrapper != null && PresentationSource.FromVisual(UiWrapper) != null)
                {
                    Matrix m         = PresentationSource.FromVisual(UiWrapper).CompositionTarget.TransformToDevice;
                    double dpiFactor = 1 / m.M11;
                    gridPen      = new Pen(Application.Current.TryFindResource("BorderThinBrush") as Brush, 1 * dpiFactor);
                    halfPenWidth = gridPen.Thickness * 0.5;
                }

                if (SuperDom.Instrument != null && SuperDom.IsConnected)
                {
                    BarsPeriod bp = new BarsPeriod
                    {
                        MarketDataType = MarketDataType.Last,
                        BarsPeriodType = BarsPeriodType.Tick,
                        Value          = 1
                    };

                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.SetLoadingString());
                    clearLoadingSent = false;

                    if (BarsRequest != null)
                    {
                        BarsRequest.Update -= OnBarsUpdate;
                        BarsRequest         = null;
                    }

                    BarsRequest = new BarsRequest(SuperDom.Instrument,
                                                  Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now,
                                                  Cbi.Connection.PlaybackConnection != null ? Cbi.Connection.PlaybackConnection.Now : Core.Globals.Now);

                    BarsRequest.BarsPeriod   = bp;
                    BarsRequest.TradingHours = (TradingHoursData == TradingHours.UseInstrumentSettings || TradingHours.Get(TradingHoursData) == null) ? SuperDom.Instrument.MasterInstrument.TradingHours : TradingHours.Get(TradingHoursData);
                    BarsRequest.Update      += OnBarsUpdate;

                    BarsRequest.Request((request, errorCode, errorMessage) =>
                    {
                        // Make sure this isn't a bars callback from another column instance
                        if (request != BarsRequest)
                        {
                            return;
                        }

                        lastMaxIndex    = 0;
                        maxVolume       = 0;
                        totalBuyVolume  = 0;
                        totalLastVolume = 0;
                        totalSellVolume = 0;
                        Sells.Clear();
                        Buys.Clear();
                        LastVolumes.Clear();

                        if (State >= NinjaTrader.NinjaScript.State.Terminated)
                        {
                            return;
                        }

                        if (errorCode == Cbi.ErrorCode.UserAbort)
                        {
                            if (State <= NinjaTrader.NinjaScript.State.Terminated)
                            {
                                if (SuperDom != null && !clearLoadingSent)
                                {
                                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                    clearLoadingSent = true;
                                }
                            }

                            request.Update -= OnBarsUpdate;
                            request.Dispose();
                            request = null;
                            return;
                        }

                        if (errorCode != Cbi.ErrorCode.NoError)
                        {
                            request.Update -= OnBarsUpdate;
                            request.Dispose();
                            request = null;
                            if (SuperDom != null && !clearLoadingSent)
                            {
                                SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                clearLoadingSent = true;
                            }
                        }
                        else if (errorCode == Cbi.ErrorCode.NoError)
                        {
                            SessionIterator superDomSessionIt = new SessionIterator(request.Bars);
                            bool isInclude60 = request.Bars.BarsType.IncludesEndTimeStamp(false);
                            if (superDomSessionIt.IsInSession(Core.Globals.Now, isInclude60, request.Bars.BarsType.IsIntraday))
                            {
                                for (int i = 0; i < request.Bars.Count; i++)
                                {
                                    DateTime time = request.Bars.BarsSeries.GetTime(i);
                                    if ((isInclude60 && time <= superDomSessionIt.ActualSessionBegin) || (!isInclude60 && time < superDomSessionIt.ActualSessionBegin))
                                    {
                                        continue;
                                    }

                                    double ask   = request.Bars.BarsSeries.GetAsk(i);
                                    double bid   = request.Bars.BarsSeries.GetBid(i);
                                    double close = request.Bars.BarsSeries.GetClose(i);
                                    long volume  = request.Bars.BarsSeries.GetVolume(i);

                                    if (ask != double.MinValue && close >= ask)
                                    {
                                        Buys.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                                        totalBuyVolume += volume;
                                    }
                                    else if (bid != double.MinValue && close <= bid)
                                    {
                                        Sells.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                                        totalSellVolume += volume;
                                    }

                                    long newVolume;
                                    LastVolumes.AddOrUpdate(close, newVolume = volume, (price, oldVolume) => newVolume = 0);
                                    totalLastVolume += volume;

                                    if (newVolume > maxVolume)
                                    {
                                        maxVolume = newVolume;
                                    }
                                }

                                lastMaxIndex = request.Bars.Count - 1;

                                // Repaint the column on the SuperDOM
                                OnPropertyChanged();
                            }

                            if (SuperDom != null && !clearLoadingSent)
                            {
                                SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                                clearLoadingSent = true;
                            }
                        }
                    });
                }
            }
            else if (State == State.Active)
            {
                if (!DisplayText)
                {
                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseMove", OnMouseMove);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseEnter", OnMouseEnter);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .AddHandler(UiWrapper, "MouseLeave", OnMouseLeave);

                    mouseEventsSubscribed = true;
                }
            }
            else if (State == State.Terminated)
            {
                if (BarsRequest != null)
                {
                    BarsRequest.Update -= OnBarsUpdate;
                    BarsRequest.Dispose();
                }

                BarsRequest = null;

                if (SuperDom != null && !clearLoadingSent)
                {
                    SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                    clearLoadingSent = true;
                }

                if (!DisplayText && mouseEventsSubscribed)
                {
                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseMove", OnMouseMove);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseEnter", OnMouseEnter);

                    WeakEventManager <System.Windows.Controls.Panel, MouseEventArgs> .RemoveHandler(UiWrapper, "MouseLeave", OnMouseLeave);

                    mouseEventsSubscribed = false;
                }

                lastMaxIndex    = 0;
                maxVolume       = 0;
                totalBuyVolume  = 0;
                totalLastVolume = 0;
                totalSellVolume = 0;
                Sells.Clear();
                Buys.Clear();
                LastVolumes.Clear();
            }
        }
예제 #27
0
        private void OnBarsUpdate(object sender, BarsUpdateEventArgs e)
        {
            if (State == State.Active && SuperDom != null && SuperDom.IsConnected)
            {
                if (SuperDom.IsReloading)
                {
                    OnPropertyChanged();
                    return;
                }

                BarsUpdateEventArgs barsUpdate = e;
                lock (barsSync)
                {
                    int currentMaxIndex = barsUpdate.MaxIndex;

                    for (int i = lastMaxIndex + 1; i <= currentMaxIndex; i++)
                    {
                        if (barsUpdate.BarsSeries.GetIsFirstBarOfSession(i))
                        {
                            // If a new session starts, clear out the old values and start fresh
                            maxVolume       = 0;
                            totalBuyVolume  = 0;
                            totalLastVolume = 0;
                            totalSellVolume = 0;
                            Sells.Clear();
                            Buys.Clear();
                            LastVolumes.Clear();
                        }

                        double ask    = barsUpdate.BarsSeries.GetAsk(i);
                        double bid    = barsUpdate.BarsSeries.GetBid(i);
                        double close  = barsUpdate.BarsSeries.GetClose(i);
                        long   volume = barsUpdate.BarsSeries.GetVolume(i);

                        if (ask != double.MinValue && close >= ask)
                        {
                            Buys.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                            totalBuyVolume += volume;
                        }
                        else if (bid != double.MinValue && close <= bid)
                        {
                            Sells.AddOrUpdate(close, volume, (price, oldVolume) => oldVolume + volume);
                            totalSellVolume += volume;
                        }

                        long newVolume;
                        LastVolumes.AddOrUpdate(close, newVolume = volume, (price, oldVolume) => newVolume = oldVolume + volume);
                        totalLastVolume += volume;

                        if (newVolume > maxVolume)
                        {
                            maxVolume = newVolume;
                        }
                    }

                    lastMaxIndex = barsUpdate.MaxIndex;
                    if (!clearLoadingSent)
                    {
                        SuperDom.Dispatcher.InvokeAsync(() => SuperDom.ClearLoadingString());
                        clearLoadingSent = true;
                    }
                }
            }
        }
예제 #28
0
        protected override void OnRender(DrawingContext dc, double renderWidth)
        {
            // This may be true if the UI for a column hasn't been loaded yet (e.g., restoring multiple tabs from workspace won't load each tab until it's clicked by the user)
            if (gridPen == null)
            {
                if (UiWrapper != null && PresentationSource.FromVisual(UiWrapper) != null)
                {
                    Matrix m         = PresentationSource.FromVisual(UiWrapper).CompositionTarget.TransformToDevice;
                    double dpiFactor = 1 / m.M11;
                    gridPen      = new Pen(Application.Current.TryFindResource("BorderThinBrush") as Brush, 1 * dpiFactor);
                    halfPenWidth = gridPen.Thickness * 0.5;
                }
            }

            if (fontFamily != SuperDom.Font.Family ||
                (SuperDom.Font.Italic && fontStyle != FontStyles.Italic) ||
                (!SuperDom.Font.Italic && fontStyle == FontStyles.Italic) ||
                (SuperDom.Font.Bold && fontWeight != FontWeights.Bold) ||
                (!SuperDom.Font.Bold && fontWeight == FontWeights.Bold))
            {
                // Only update this if something has changed
                fontFamily         = SuperDom.Font.Family;
                fontStyle          = SuperDom.Font.Italic ? FontStyles.Italic : FontStyles.Normal;
                fontWeight         = SuperDom.Font.Bold ? FontWeights.Bold : FontWeights.Normal;
                typeFace           = new Typeface(fontFamily, fontStyle, fontWeight, FontStretches.Normal);
                heightUpdateNeeded = true;
            }

            double verticalOffset = -gridPen.Thickness;
            double pixelsPerDip   = VisualTreeHelper.GetDpi(UiWrapper).PixelsPerDip;

            lock (SuperDom.Rows)
                foreach (PriceRow row in SuperDom.Rows)
                {
                    if (renderWidth - halfPenWidth >= 0)
                    {
                        // Draw cell
                        Rect rect = new Rect(-halfPenWidth, verticalOffset, renderWidth - halfPenWidth, SuperDom.ActualRowHeight);

                        // Create a guidelines set
                        GuidelineSet guidelines = new GuidelineSet();
                        guidelines.GuidelinesX.Add(rect.Left + halfPenWidth);
                        guidelines.GuidelinesX.Add(rect.Right + halfPenWidth);
                        guidelines.GuidelinesY.Add(rect.Top + halfPenWidth);
                        guidelines.GuidelinesY.Add(rect.Bottom + halfPenWidth);

                        dc.PushGuidelineSet(guidelines);
                        dc.DrawRectangle(BackColor, null, rect);
                        dc.DrawLine(gridPen, new Point(-gridPen.Thickness, rect.Bottom), new Point(renderWidth - halfPenWidth, rect.Bottom));
                        dc.DrawLine(gridPen, new Point(rect.Right, verticalOffset), new Point(rect.Right, rect.Bottom));
                        //dc.Pop();

                        if (SuperDom.IsConnected &&
                            !SuperDom.IsReloading &&
                            State == NinjaTrader.NinjaScript.State.Active)
                        {
                            // Draw proportional volume bar
                            long buyVolume      = 0;
                            long sellVolume     = 0;
                            long totalRowVolume = 0;
                            long totalVolume    = 0;

                            if (VolumeType == VolumeType.Standard)
                            {
                                if (LastVolumes.TryGetValue(row.Price, out totalRowVolume))
                                {
                                    totalVolume = totalLastVolume;
                                }
                                else
                                {
                                    verticalOffset += SuperDom.ActualRowHeight;
                                    continue;
                                }
                            }
                            else if (VolumeType == VolumeType.BuySell)
                            {
                                bool gotBuy  = Sells.TryGetValue(row.Price, out sellVolume);
                                bool gotSell = Buys.TryGetValue(row.Price, out buyVolume);
                                if (gotBuy || gotSell)
                                {
                                    totalRowVolume = sellVolume + buyVolume;
                                    totalVolume    = totalBuyVolume + totalSellVolume;
                                }
                                else
                                {
                                    verticalOffset += SuperDom.ActualRowHeight;
                                    continue;
                                }
                            }

                            double totalWidth = renderWidth * ((double)totalRowVolume / maxVolume);
                            if (totalWidth - gridPen.Thickness >= 0)
                            {
                                if (VolumeType == VolumeType.Standard)
                                {
                                    dc.DrawRectangle(BarColor, null, new Rect(0, verticalOffset + halfPenWidth, totalWidth == renderWidth ? totalWidth - gridPen.Thickness * 1.5 : totalWidth - halfPenWidth, rect.Height - gridPen.Thickness));
                                }
                                else if (VolumeType == VolumeType.BuySell)
                                {
                                    double buyWidth = totalWidth * ((double)buyVolume / totalRowVolume);

                                    // Draw total volume, then draw buys on top
                                    if (totalWidth - halfPenWidth >= 0)
                                    {
                                        dc.DrawRectangle(SellColor, null, new Rect(0, verticalOffset + halfPenWidth, totalWidth == renderWidth ? totalWidth - gridPen.Thickness * 1.5 : totalWidth - halfPenWidth, rect.Height - gridPen.Thickness));
                                    }
                                    if (buyWidth - halfPenWidth >= 0)
                                    {
                                        dc.DrawRectangle(BuyColor, null, new Rect(0, verticalOffset + halfPenWidth, buyWidth - halfPenWidth, rect.Height - gridPen.Thickness));
                                    }
                                }
                            }
                            // Print volume value - remember to set MaxTextWidth so text doesn't spill into another column
                            if (totalRowVolume > 0)
                            {
                                string volumeString = string.Empty;
                                if (DisplayType == DisplayType.Volume)
                                {
                                    if (SuperDom.Instrument.MasterInstrument.InstrumentType == Cbi.InstrumentType.CryptoCurrency)
                                    {
                                        volumeString = Core.Globals.ToCryptocurrencyVolume(totalRowVolume).ToString(Core.Globals.GeneralOptions.CurrentCulture);
                                    }
                                    else
                                    {
                                        volumeString = totalRowVolume.ToString(Core.Globals.GeneralOptions.CurrentCulture);
                                    }
                                }
                                else if (DisplayType == DisplayType.Percent)
                                {
                                    volumeString = ((double)totalRowVolume / totalVolume).ToString("P1", Core.Globals.GeneralOptions.CurrentCulture);
                                }

                                if (renderWidth - 6 > 0)
                                {
                                    if (DisplayText || rect.Contains(Mouse.GetPosition(UiWrapper)))
                                    {
                                        FormattedText volumeText = new FormattedText(volumeString, Core.Globals.GeneralOptions.CurrentCulture, FlowDirection.LeftToRight, typeFace, SuperDom.Font.Size, ForeColor, pixelsPerDip)
                                        {
                                            MaxLineCount = 1, MaxTextWidth = renderWidth - 6, Trimming = TextTrimming.CharacterEllipsis
                                        };

                                        // Getting the text height is expensive, so only update it if something's changed
                                        if (heightUpdateNeeded)
                                        {
                                            textHeight         = volumeText.Height;
                                            heightUpdateNeeded = false;
                                        }

                                        textPosition.Y = verticalOffset + (SuperDom.ActualRowHeight - textHeight) / 2;
                                        dc.DrawText(volumeText, textPosition);
                                    }
                                }
                            }
                            verticalOffset += SuperDom.ActualRowHeight;
                        }
                        else
                        {
                            verticalOffset += SuperDom.ActualRowHeight;
                        }

                        dc.Pop();
                    }
                }
        }
예제 #29
0
 public async Task InsertBuy(Buys model)
 {
     dbc.Buys.Add(model);
     await dbc.SaveChangesAsync();
 }