예제 #1
0
        private void HandleBookItem(object sender, MessageData item)
        {
            var data = JsonSerializer.Deserialize <OrderBook>(item.Data);

            Debug.WriteLine(JsonSerializer.ToJsonString(data));
            OrderBookEvent?.Invoke(sender, data);
        }
예제 #2
0
        private void MarketDataUpdate(OrderBookEvent onOrderBookEvent)
        {
            Console.WriteLine(onOrderBookEvent);

            // React to price updates from the exchange.
            HandleBidPrice(onOrderBookEvent.BidPrices);
            HandleAskPrice(onOrderBookEvent.AskPrices);
        }
예제 #3
0
        private void MarketDataUpdate(OrderBookEvent orderBookEvent)
        {
            long placeOrderInstructionId = NextInstructionId();

            _orderInstructions.Add(placeOrderInstructionId);
            _session.PlaceLimitOrder(new LimitOrderSpecification(placeOrderInstructionId, _instrumentId, 10m, 10m, TimeInForce.GoodForDay),
                                     instructionId => Console.WriteLine("limit order placed with instruction id " + instructionId),
                                     FailureCallback("Place order failed for instruction ID " + placeOrderInstructionId));
        }
        public async Task SaveAsync(OrderBookEvent orderBookEvent)
        {
            if (_lastSavedMinute == default)
            {
                _lastSavedMinute = DateTime.UtcNow.TruncSeconds();
            }

            foreach (var orderItem in orderBookEvent.OrderItems)
            {
                _orderBookEventEntities.Enqueue(new OrderBookEventEntity(
                                                    orderBookEvent.SnapshotId,
                                                    orderBookEvent.OrderEventTimestamp, orderItem.Id)
                {
                    OrderId   = orderItem.Id,
                    IsBuy     = orderItem.IsBuy,
                    Symbol    = orderItem.Symbol,
                    EventType = (int)orderBookEvent.EventType,
                    Price     = orderItem.Price,
                    Size      = orderItem.Size
                });
            }

            var currentTimeMinute = DateTime.UtcNow.TruncSeconds();
            var isDifferentMinute = currentTimeMinute != _lastSavedMinute;
            var isQueueMaxLength  = _orderBookEventEntities.Count > _desiredQueueLength;

            // Save on certain amount of time or items count
            if (!isDifferentMinute && !isQueueMaxLength)
            {
                return;
            }

            var tableEntityBatches = _orderBookEventEntities
                                     .DequeueChunk(_desiredQueueLength)
                                     .GroupBy(ee => ee.PartitionKey);

            foreach (var currentBatch in tableEntityBatches)
            {
                try
                {
                    await _tableStorage.InsertOrReplaceBatchAsync(currentBatch);

                    _lastSavedMinute = currentTimeMinute;
                }
                catch (Exception ex)
                {
                    _orderBookEventEntities.AddRange(currentBatch);    // Queue the list back
                    await _log.WriteErrorAsync(_className,
                                               $"Can't write to Azure Table {_tableStorage.Name} for snapshot {currentBatch.Key}, " +
                                               $"will try later. Now in queue: {_orderBookEventEntities.Count}", ex);
                }
            }
        }
예제 #5
0
        private void MarketDataUpdate(OrderBookEvent orderBookEvent)
        {
            long    instrumentId = orderBookEvent.InstrumentId;
            decimal bestBid      = GetBestPrice(orderBookEvent.BidPrices);
            decimal bestAsk      = GetBestPrice(orderBookEvent.AskPrices);

            if (_instrumentInfoById.ContainsKey(instrumentId))
            {
                InstrumentInfo instrument;
                _instrumentInfoById.TryGetValue(instrumentId, out instrument);
                instrument.Update(bestBid, bestAsk);
            }
        }
예제 #6
0
        public void MarketDataUpdate(OrderBookEvent orderBookEvent)
        {
            Invoke((MethodInvoker)(() => label18.Text = "$ " + HelperClass.balance.ToString()));

            if (bws.lastID != null && bws.lastEPOCH != null && bws.lastQUOTE != null && bws.lastQUOTE[0] > 0 && bws.active_trading)
            {
                decimal lmax_diff  = (orderBookEvent.ValuationAskPrice + orderBookEvent.ValuationBidPrice) / 2; // LMAX(ASK+BID)/2
                decimal binary     = bws.lastQUOTE[0];                                                          // 1.11111
                decimal diff_input = decimal.Parse(textBox3.Text);                                              // 0.00010
                decimal lmax_bin   = (lmax_diff - binary);                                                      //
                decimal bin_lmax   = (binary - lmax_diff);                                                      //

                Invoke((MethodInvoker)(() => label8.Text = lmax_diff.ToString()));
                Invoke((MethodInvoker)(() => label10.Text = binary.ToString()));
                Invoke((MethodInvoker)(() => label11.Text = lmax_bin.ToString()));

                if (DateTime.Now > HelperClass.delayTime)
                {
                    if (lmax_diff > diff_input) //
                    {
                        var buyOrder  = "{\"parameters\": { \"amount\": \"" + bws.PAYMENT_AMNT + "\", \"basis\": \"stake\", \"contract_type\": \"CALL\", \"currency\": \"USD\", \"duration\": \"5\", \"duration_unit\": \"t\", \"symbol\": \"frxEURUSD\" }, \"buy\":\"" + bws.lastID[0] + "\", \"price\":\"" + int.Parse(textBox5.Text).ToString(CultureInfo.CreateSpecificCulture("en-US")) + "\"}";
                        var sellOrder = "{\"parameters\": { \"amount\": \"" + bws.PAYMENT_AMNT + "\", \"basis\": \"stake\", \"contract_type\": \"PUT\", \"currency\": \"USD\", \"duration\": \"5\", \"duration_unit\": \"t\", \"symbol\": \"frxEURUSD\" }, \"buy\":\"" + bws.lastID[0] + "\", \"price\":\"" + int.Parse(textBox5.Text).ToString(CultureInfo.CreateSpecificCulture("en-US")) + "\"}";

                        if (lmax_bin > diff_input) // 0.00020 > 0.00010
                        {
                            bws.websocket.Send(buyOrder);
                            HelperClass.addDelay(60);
                            HelperClass.addLog("ATTEMPTING CALL ORDER @ " + bws.lastQUOTE[0] + ", Delaying 60s...");
                            Invoke((MethodInvoker)(() => dataGridView1.Rows.Add(lmax_diff, binary, lmax_bin, "CALL", "$" + bws.PAYMENT_AMNT, DateTime.Now, bws.lastID[0])));
                            Invoke((MethodInvoker)(() => dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1));
                            Console.WriteLine("CALL @ LMAX: " + lmax_diff + " Binary: " + binary + " Diff: " + lmax_bin);
                        }
                        else if (bin_lmax > diff_input) // -0.00020 > 0.00010
                        {
                            bws.websocket.Send(sellOrder);
                            HelperClass.addDelay(60);
                            HelperClass.addLog("ATTEMPTING PUT ORDER @ " + bws.lastQUOTE[0] + ", Delaying 60s...");
                            Invoke((MethodInvoker)(() => dataGridView1.Rows.Add(lmax_diff, binary, lmax_bin, "PUT", "$" + bws.PAYMENT_AMNT, DateTime.Now, bws.lastID[0])));
                            Invoke((MethodInvoker)(() => dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1));
                            Console.WriteLine("PUT @ LMAX: " + lmax_diff + " Binary: " + binary + " Diff: " + bin_lmax);
                        }
                    }
                }
            }

            Console.WriteLine("[" + DateTime.Now.ToString("HH:mm:ss.fff") + "] " + orderBookEvent);
            Invoke((MethodInvoker)(() => listBox1.Refresh()));
            Invoke((MethodInvoker)(() => listBox1.TopIndex = listBox1.Items.Count - 1));
        }
예제 #7
0
        private void MarketDataUpdate(OrderBookEvent data)
        {
            _securities.TryGetValue((int)data.InstrumentId, out var instrument);
            if (instrument == null)
            {
                Logger.Warning($"Available {Name} instruments does not contain instrument #{data.InstrumentId} passed to MarketDataUpdate");
                return;
            }

            if (NewTick != null && data.BidPrices.Any() && data.AskPrices.Any())
            {
                var date   = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(data.Timestamp);
                var bids   = data.BidPrices;
                var asks   = data.AskPrices;
                var level2 = new List <MarketLevel2>();

                if (bids.Count > 1)
                {
                    for (var i = 0; i < bids.Count && i < asks.Count; i++)
                    {
                        level2.Add(new MarketLevel2
                        {
                            DomLevel = i + 1,
                            AskPrice = asks[i].Price,
                            AskSize  = asks[i].Quantity,
                            BidPrice = bids[i].Price,
                            BidSize  = bids[i].Quantity
                        });
                    }
                }

                NewTick(new Tick
                {
                    DataFeed = Name,
                    Ask      = asks[0].Price,
                    Bid      = bids[0].Price,
                    AskSize  = (long)asks[0].Quantity,
                    BidSize  = (long)bids[0].Quantity,
                    Date     = TimeZoneInfo.ConvertTimeToUtc(date, TimeZoneInfo),
                    Price    = bids[0].Price,
                    Symbol   = instrument,
                    Volume   = asks[0].Quantity + bids[0].Quantity,
                    Level2   = level2
                });
            }
        }
예제 #8
0
    private void a1(OrderBookEvent A_0)
    {
        long   instrumentId = A_0.InstrumentId;
        string s1           = this.openKeyInst(instrumentId, "bid");
        string s2           = this.openKeyInst(instrumentId, "ask");
        int    num          = this.i.InstrumentIDs.IndexOf(instrumentId.ToString());

        if (num < 0)
        {
            return;
        }
        this.i.SendDataToBus(num, double.Parse(s2), double.Parse(s1));
        if (this.i.ShowQuotes)
        {
            this.i.SetDataGridValue(num, 2, s2.ToString());
            this.i.SetDataGridValue(num, 3, s1.ToString());
        }
    }
        private void OnSessionMarketDataChanged(OrderBookEvent orderBookEvent)
        {
            var time  = TimeHelper.GregorianStart.AddMilliseconds(orderBookEvent.Timestamp).ApplyTimeZone(TimeZoneInfo.Utc);
            var secId = new SecurityId {
                Native = orderBookEvent.InstrumentId
            };

            var l1Msg = new Level1ChangeMessage
            {
                ServerTime = time,
                SecurityId = secId,
            };

            if (orderBookEvent.HasMarketClosePrice)
            {
                l1Msg.Add(Level1Fields.ClosePrice, orderBookEvent.MktClosePrice);
            }

            if (orderBookEvent.HasDailyHighestTradedPrice)
            {
                l1Msg.Add(Level1Fields.HighPrice, orderBookEvent.DailyHighestTradedPrice);
            }

            if (orderBookEvent.HasDailyLowestTradedPrice)
            {
                l1Msg.Add(Level1Fields.LowPrice, orderBookEvent.DailyLowestTradedPrice);
            }

            if (orderBookEvent.HasLastTradedPrice)
            {
                l1Msg.Add(Level1Fields.LastTradePrice, orderBookEvent.LastTradedPrice);
            }

            SendOutMessage(l1Msg);

            SendOutMessage(new QuoteChangeMessage
            {
                SecurityId = secId,
                Bids       = orderBookEvent.BidPrices.Select(p => new QuoteChange(Sides.Buy, p.Price, p.Quantity)),
                Asks       = orderBookEvent.AskPrices.Select(p => new QuoteChange(Sides.Sell, p.Price, p.Quantity)),
                ServerTime = time
            });
        }
예제 #10
0
        /// <summary>
        /// обновились стаканы и тики
        /// </summary>
        private void ClientOnUpdateMarketDepth(OrderBookEvent data)
        {
            try
            {
                lock (_depthLocker)
                {
                    if (_depths == null)
                    {
                        _depths = new List <MarketDepth>();
                    }

                    MarketDepth needDepth = null;

                    var needSecName = _securities.Find(s => s.NameId == data.InstrumentId.ToString()).Name;

                    if (needSecName != null)
                    {
                        needDepth = _depths.Find(depth => depth.SecurityNameCode == needSecName);
                    }

                    if (needDepth == null)
                    {
                        needDepth = new MarketDepth();
                        needDepth.SecurityNameCode = _securities.Find(sec => sec.NameId == data.InstrumentId.ToString()).Name;
                        _depths.Add(needDepth);
                    }

                    needDepth.Asks = new List <MarketDepthLevel>();
                    needDepth.Bids = new List <MarketDepthLevel>();

                    for (int i = 0; data.AskPrices != null && i < data.AskPrices.Count; i++)
                    {
                        needDepth.Asks.Add(new MarketDepthLevel()
                        {
                            Ask   = data.AskPrices[i].Quantity,
                            Price = data.AskPrices[i].Price,
                        });
                    }

                    for (int i = 0; data.BidPrices != null && i < data.BidPrices.Count; i++)
                    {
                        needDepth.Bids.Add(new MarketDepthLevel()
                        {
                            Bid   = data.BidPrices[i].Quantity,
                            Price = data.BidPrices[i].Price,
                        });
                    }

                    needDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(data.Timestamp);

                    if (needDepth.Time == DateTime.MinValue)
                    {
                        return;
                    }

                    if (MarketDepthEvent != null)
                    {
                        MarketDepthEvent(needDepth.GetCopy());
                    }

                    if (data.LastTradedPrice != Decimal.MinValue)
                    {
                        Trade trade = new Trade();
                        trade.SecurityNameCode = needDepth.SecurityNameCode;
                        trade.Price            = data.LastTradedPrice;
                        trade.Time             = needDepth.Time;

                        if (NewTradesEvent != null)
                        {
                            NewTradesEvent(trade);
                        }
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
예제 #11
0
        private void HandleBookItem(object sender, MessageData item)
        {
            var data = JsonSerializer.Deserialize <OrderBook>(item.Data);

            OrderBookEvent?.Invoke(sender, data);
        }
예제 #12
0
 /// <summary>
 /// обновился стакан и тики
 /// </summary>
 private void SessionOnMarketDataChanged(OrderBookEvent orderBook)
 {
     UpdateMarketDepth?.Invoke(orderBook);
 }
예제 #13
0
 private void WsClient_OnOrderBook(OrderBookEvent orderBookEvent)
 {
     Console.WriteLine(orderBookEvent);
     //here you can make your trade decision
 }
예제 #14
0
        private void OrderBookReceived(Message message)
        {
            OrderBookData orderBookFutures = new OrderBookData(message);

            OrderBookEvent?.Invoke(orderBookFutures);
        }