private void OnSubscribe(BitfinexWebSocketWrapper webSocket, ChannelSubscription data)
        {
            try
            {
                lock (_locker)
                {
                    var channel = new Channel(data.Channel, _symbolMapper.GetLeanSymbol(data.Symbol));

                    BitfinexWebSocketChannels channels;
                    if (!_channelsByWebSocket.TryGetValue(webSocket, out channels))
                    {
                        _onSubscribeEvent.Set();
                        return;
                    }

                    channels.TryAdd(data.ChannelId, channel);

                    Log.Trace($"BitfinexSubscriptionManager.OnSubscribe(): Channel subscribed: Id:{data.ChannelId} {channel.Symbol}/{channel.Name}");

                    _onSubscribeEvent.Set();

                    webSocket.ConnectionHandler.EnableMonitoring(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
Exemplo n.º 2
0
        private void ProcessOrderBookSnapshot(BitfinexChannel channel, string[][] entries)
        {
            try
            {
                var symbol = _symbolMapper.GetLeanSymbol(channel.Symbol);

                DefaultOrderBook orderBook;
                if (!_orderBooks.TryGetValue(symbol, out orderBook))
                {
                    orderBook           = new DefaultOrderBook(symbol);
                    _orderBooks[symbol] = orderBook;
                }
                else
                {
                    orderBook.BestBidAskUpdated -= OnBestBidAskUpdated;
                    orderBook.Clear();
                }

                foreach (var entry in entries)
                {
                    var price  = decimal.Parse(entry[0], NumberStyles.Float, CultureInfo.InvariantCulture);
                    var amount = decimal.Parse(entry[2], NumberStyles.Float, CultureInfo.InvariantCulture);

                    if (amount > 0)
                    {
                        orderBook.UpdateBidRow(price, amount);
                    }
                    else
                    {
                        orderBook.UpdateAskRow(price, Math.Abs(amount));
                    }
                }

                orderBook.BestBidAskUpdated += OnBestBidAskUpdated;

                EmitQuoteTick(symbol, orderBook.BestBidPrice, orderBook.BestBidSize, orderBook.BestAskPrice, orderBook.BestAskSize);
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
Exemplo n.º 3
0
        private void OnSubscribe(BitfinexWebSocketWrapper webSocket, Messages.ChannelSubscription data)
        {
            try
            {
                lock (_locker)
                {
                    var channel = new Channel(data.Channel, _symbolMapper.GetLeanSymbol(data.Symbol));

                    _channels.AddOrUpdate(data.ChannelId, channel);
                    _onSubscribeEvent.Set();

                    webSocket.ConnectionHandler.EnableMonitoring(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets all orders not yet closed
        /// </summary>
        /// <returns></returns>
        public override List <Order> GetOpenOrders()
        {
            var list     = new List <Order>();
            var endpoint = GetEndpoint("orders");
            var request  = new RestRequest(endpoint, Method.POST);

            JsonObject payload = new JsonObject();

            payload.Add("request", endpoint);
            payload.Add("nonce", GetNonce().ToStringInvariant());

            request.AddJsonBody(payload.ToString());
            SignRequest(request, payload.ToString());

            var response = ExecuteRestRequest(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"BitfinexBrokerage.GetOpenOrders: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
            }

            var orders = JsonConvert.DeserializeObject <Messages.Order[]>(response.Content)
                         .Where(OrderFilter(_algorithm.BrokerageModel.AccountType));

            foreach (var item in orders)
            {
                Order order;
                if (item.Type.Replace("exchange", "").Trim() == "market")
                {
                    order = new MarketOrder {
                        Price = item.Price
                    };
                }
                else if (item.Type.Replace("exchange", "").Trim() == "limit")
                {
                    order = new LimitOrder {
                        LimitPrice = item.Price
                    };
                }
                else if (item.Type.Replace("exchange", "").Trim() == "stop")
                {
                    order = new StopMarketOrder {
                        StopPrice = item.Price
                    };
                }
                else
                {
                    OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode,
                                                        "BitfinexBrokerage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.Type));
                    continue;
                }

                order.Quantity = item.Side == "sell" ? -item.OriginalAmount : item.OriginalAmount;
                order.BrokerId = new List <string> {
                    item.Id
                };
                order.Symbol = _symbolMapper.GetLeanSymbol(item.Symbol);
                order.Time   = Time.UnixTimeStampToDateTime(item.Timestamp);
                order.Status = ConvertOrderStatus(item);
                order.Price  = item.Price;
                list.Add(order);
            }

            foreach (var item in list)
            {
                if (item.Status.IsOpen())
                {
                    var cached = CachedOrderIDs.Where(c => c.Value.BrokerId.Contains(item.BrokerId.First()));
                    if (cached.Any())
                    {
                        CachedOrderIDs[cached.First().Key] = item;
                    }
                }
            }

            return(list);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets all orders not yet closed
        /// </summary>
        /// <returns></returns>
        public override List <Order> GetOpenOrders()
        {
            var endpoint = GetEndpoint("auth/r/orders");
            var request  = new RestRequest(endpoint, Method.POST);

            var parameters = new JsonObject();

            request.AddJsonBody(parameters.ToString());
            SignRequest(request, endpoint, parameters);

            var response = ExecuteRestRequest(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"BitfinexBrokerage.GetOpenOrders: request failed: [{(int)response.StatusCode}] {response.StatusDescription}, Content: {response.Content}, ErrorMessage: {response.ErrorMessage}");
            }

            var orders = JsonConvert.DeserializeObject <Messages.Order[]>(response.Content)
                         .Where(OrderFilter(_algorithm.BrokerageModel.AccountType));

            var list = new List <Order>();

            foreach (var item in orders)
            {
                Order order;
                if (item.Type.Replace("EXCHANGE", "").Trim() == "MARKET")
                {
                    order = new MarketOrder {
                        Price = item.Price
                    };
                }
                else if (item.Type.Replace("EXCHANGE", "").Trim() == "LIMIT")
                {
                    order = new LimitOrder {
                        LimitPrice = item.Price
                    };
                }
                else if (item.Type.Replace("EXCHANGE", "").Trim() == "STOP")
                {
                    order = new StopMarketOrder {
                        StopPrice = item.Price
                    };
                }
                else
                {
                    OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, (int)response.StatusCode,
                                                        "BitfinexBrokerage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.Type));
                    continue;
                }

                order.Quantity = item.Amount;
                order.BrokerId = new List <string> {
                    item.Id.ToStringInvariant()
                };
                order.Symbol = _symbolMapper.GetLeanSymbol(item.Symbol);
                order.Time   = Time.UnixMillisecondTimeStampToDateTime(item.MtsCreate);
                order.Status = ConvertOrderStatus(item);
                order.Price  = item.Price;
                list.Add(order);
            }

            foreach (var item in list)
            {
                if (item.Status.IsOpen())
                {
                    var cached = CachedOrderIDs
                                 .FirstOrDefault(c => c.Value.BrokerId.Contains(item.BrokerId.First()));
                    if (cached.Value != null)
                    {
                        CachedOrderIDs[cached.Key] = item;
                    }
                }
            }

            return(list);
        }