Exemplo n.º 1
0
        public void SubscribeToTickerUpdates_Should_TriggerWithTickerUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            HuobiSymbolDatas result = null;
            var subTask             = client.SubscribeToSymbolTickerUpdatesAsync((test => result = test));

            socket.InvokeMessage($"{{\"subbed\": \"test\", \"id\": \"{BaseClient.LastId}\", \"status\": \"ok\"}}");
            var subResult = subTask.Result;

            var expected = new List <HuobiSymbolData>
            {
                new HuobiSymbolData()
                {
                    Amount     = 0.1m,
                    Close      = 0.2m,
                    Low        = 0.3m,
                    High       = 0.4m,
                    Volume     = 0.5m,
                    Open       = 0.6m,
                    TradeCount = 12
                }
            };

            // act
            socket.InvokeMessage(SerializeExpected("market.tickers", expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected[0], result.Ticks.ToList()[0]));
        }
Exemplo n.º 2
0
        public void PlacingAnFOKOrder_Should_SucceedIfSuccessResponse()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);

            var expected = new BitfinexOrder()
            {
                Price         = 0.1m,
                Amount        = 0.2m,
                Symbol        = "tBTCUSD",
                Type          = OrderType.ExchangeFillOrKill,
                ClientOrderId = 1234,
                StatusString  = "CANCELED"
            };

            // act
            var placeTask = client.PlaceOrderAsync(OrderType.ExchangeFillOrKill, "tBTCUSD", 1, price: 1, clientOrderId: 1234);

            socket.InvokeMessage(new BitfinexAuthenticationResponse()
            {
                Event = "auth", Status = "OK"
            });
            Thread.Sleep(100);
            socket.InvokeMessage($"[0, \"n\", [0, \"on-req\", 0, 0, {JsonConvert.SerializeObject(expected)}, 0, \"SUCCESS\", \"Submitted\"]]");
            var result = placeTask.Result;

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result.Data));
        }
Exemplo n.º 3
0
        public void SubscribeToDetailUpdates_Should_TriggerWithDetailUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            HuobiMarketData result  = null;
            var             subTask = client.SubscribeToMarketDetailUpdatesAsync("test", test => result = test);

            socket.InvokeMessage("{\"subbed\": \"test\", \"status\": \"ok\"}");
            var subResult = subTask.Result;

            var expected = new HuobiMarketData()
            {
                Amount     = 0.1m,
                Close      = 0.2m,
                Low        = 0.3m,
                High       = 0.4m,
                Volume     = 0.5m,
                Open       = 0.6m,
                TradeCount = 12
            };

            // act
            socket.InvokeMessage(SerializeExpected(expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result));
        }
Exemplo n.º 4
0
        public void SubscribingToPositionUpdates_Should_TriggerWithPositionUpdate(string updateType, BitfinexEventType eventType, bool single = true)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);

            var rstEvent = new ManualResetEvent(false);
            BitfinexSocketEvent <IEnumerable <BitfinexPosition> > result = null;
            var expected = new BitfinexSocketEvent <IEnumerable <BitfinexPosition> >(eventType, new[] { new BitfinexPosition()
                                                                                                        {
                                                                                                        } });

            client.SubscribeToTradingUpdatesAsync(null, null, data =>
            {
                result = data;
                rstEvent.Set();
            });

            // act
            socket.InvokeMessage(new BitfinexAuthenticationResponse()
            {
                Event = "auth", Status = "OK"
            });
            socket.InvokeMessage(single ? new object[] { 0, updateType, new BitfinexPosition() } : new object[] { 0, updateType, new[] { new BitfinexPosition() } });
            rstEvent.WaitOne(1000);

            // assert
            Assert.IsTrue(TestHelpers.AreEqual(result.Data.First(), expected.Data.First()));
        }
Exemplo n.º 5
0
        public void PlacingAnOrder_Should_FailIfErrorResponse()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);
            var order  = new BitfinexOrder()
            {
                ClientOrderId = 123
            };

            // act
            var placeTask = client.PlaceOrderAsync(OrderType.ExchangeLimit, "tBTCUSD", 1, price: 1, clientOrderId: 123);

            socket.InvokeMessage(new BitfinexAuthenticationResponse()
            {
                Event = "auth", Status = "OK"
            });
            Thread.Sleep(100);
            socket.InvokeMessage($"[0, \"n\", [0, \"on-req\", 0, 0, {JsonConvert.SerializeObject(order)}, 0, \"error\", \"order placing failed\"]]");
            var result = placeTask.Result;

            // assert
            Assert.IsFalse(result.Success);
            Assert.IsTrue(result.Error.Message.Contains("order placing failed"));
        }
Exemplo n.º 6
0
        public void SubscribingToRawBookUpdates_Should_TriggerWithRawBookUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            BitfinexRawOrderBookEntry[] result = null;
            var subTask = client.SubscribeToRawBookUpdatesAsync("tBTCUSD", 10, data => result = data.ToArray());

            var subResponse = new BookSubscriptionResponse()
            {
                Channel   = "book",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "tBTCUSD",
                Pair      = "BTCUSD",
                Frequency = "F0",
                Precision = "R0",
                Length    = 10
            };

            socket.InvokeMessage(subResponse);
            subTask.Wait(5000);
            BitfinexRawOrderBookEntry[] expected = new [] { new BitfinexRawOrderBookEntry() };

            // act
            socket.InvokeMessage($"[1, {JsonConvert.SerializeObject(expected)}]");

            // assert
            Assert.IsTrue(TestHelpers.AreEqual(result[0], expected[0]));
        }
Exemplo n.º 7
0
        public void SubscribingToTradeUpdates_Should_TriggerWithTradeUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            BitfinexTradeSimple[] result = null;
            var subTask = client.SubscribeToTradeUpdatesAsync("BTCUSD", data => result = data.ToArray());

            var subResponse = new TradesSubscriptionResponse()
            {
                Channel   = "trades",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "BTCUSD",
                Pair      = "BTCUSD"
            };

            socket.InvokeMessage(subResponse);
            subTask.Wait(5000);
            BitfinexTradeSimple[] expected = new[] { new BitfinexTradeSimple() };

            // act
            socket.InvokeMessage($"[1, {JsonConvert.SerializeObject(expected)}]");

            // assert
            Assert.IsTrue(TestHelpers.AreEqual(result[0], expected[0]));
        }
Exemplo n.º 8
0
        public void SubscribingToTickerUpdates_Should_TriggerWithTickerUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            BitfinexStreamSymbolOverview result = null;
            var subTask = client.SubscribeToTickerUpdatesAsync("tBTCUSD", data => result = data);

            var subResponse = new TickerSubscriptionResponse()
            {
                Channel   = "ticker",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "tBTCUSD",
                Pair      = "BTCUSD"
            };

            socket.InvokeMessage(subResponse);
            subTask.Wait(5000);
            BitfinexStreamSymbolOverview expected = new BitfinexStreamSymbolOverview();

            // act
            socket.InvokeMessage($"[1, {JsonConvert.SerializeObject(expected)}]");

            // assert
            Assert.IsTrue(TestHelpers.AreEqual(result, expected));
        }
Exemplo n.º 9
0
        public void SubscribingToCandleUpdates_Should_TriggerWithCandleUpdate(TimeFrame timeframe)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            BitfinexKline[] result  = null;
            var             subTask = client.SubscribeToKlineUpdatesAsync("tBTCUSD", timeframe, data => result = data.ToArray());

            var subResponse = new CandleSubscriptionResponse()
            {
                Channel   = "candles",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "BTCUSD",
                Key       = "trade:" + JsonConvert.SerializeObject(timeframe, new TimeFrameConverter(false)) + ":tBTCUSD"
            };

            socket.InvokeMessage(subResponse);
            subTask.Wait(5000);
            BitfinexKline[] expected = new[] { new BitfinexKline() };

            // act
            socket.InvokeMessage($"[1, {JsonConvert.SerializeObject(expected)}]");

            // assert
            Assert.IsTrue(TestHelpers.AreEqual(result[0], expected[0]));
        }
Exemplo n.º 10
0
        public void SubscribeToAccountUpdates_Should_TriggerWithAccountUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);

            HuobiAccountUpdate result = null;
            var subTask = client.SubscribeToAccountUpdatesAsync(test => result = test);

            socket.InvokeMessage("{\"ch\": \"auth\", \"code\": 200, \"action\": \"req\"}");
            Thread.Sleep(10);
            socket.InvokeMessage($"{{\"action\": \"sub\", \"code\": 200, \"ch\": \"accounts.update#1\"}}");
            var subResult = subTask.Result;

            var expected = new HuobiAccountUpdate()
            {
                AccountId   = 123,
                AccountType = HuobiBalanceType.Frozen,
                Available   = 456,
                Balance     = 789,
                ChangeTime  = new DateTime(2020, 11, 25),
                ChangeType  = HuobiAccountEventType.Deposit,
                Currency    = "usdt"
            };

            // act
            socket.InvokeMessage(SerializeExpectedAuth("accounts.update#1", expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result));
        }
Exemplo n.º 11
0
        public void SubscribeToKlineUpdates_Should_TriggerWithKlineUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            HuobiSymbolData result  = null;
            var             subTask = client.SubscribeToKlineUpdatesAsync("ETHBTC", HuobiPeriod.FiveMinutes, test => result = test);

            socket.InvokeMessage($"{{\"subbed\": \"ethbtc\", \"id\": \"{BaseClient.LastId}\", \"status\": \"ok\"}}");
            var subResult = subTask.Result;

            var expected = new HuobiSymbolData()
            {
                Amount     = 0.1m,
                Close      = 0.2m,
                Low        = 0.3m,
                High       = 0.4m,
                Volume     = 0.5m,
                Open       = 0.6m,
                TradeCount = 12
            };

            // act
            socket.InvokeMessage(SerializeExpected("market.ethbtc.kline.5min", expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result));
        }
Exemplo n.º 12
0
        public async Task ReceivingAReconnectMessage_Should_PreventOperationsBeforeReconnect()
        {
            // arrange
            CallResult <UpdateSubscription> subResultWhenPaused = null;
            var socket = new TestSocket();

            socket.CanConnect = true;
            socket.CloseTime  = TimeSpan.FromMilliseconds(1000);
            socket.OpenTime   = TimeSpan.FromMilliseconds(100);
            socket.Url        = "wss://api.bitfinex.com/ws/2";
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket, new BitfinexSocketClientOptions()
            {
                LogLevel          = LogLevel.Debug,
                ReconnectInterval = TimeSpan.FromMilliseconds(10)
            });

            var rstEvent = new ManualResetEvent(false);
            var subTask  = client.SpotStreams.SubscribeToKlineUpdatesAsync("tBTCUSD", KlineInterval.FiveMinutes, data => { });

            socket.OnOpen += async() =>
            {
                await Task.Delay(10);

                socket.InvokeMessage(new CandleSubscriptionResponse()
                {
                    Channel   = "candles",
                    Event     = "subscribed",
                    ChannelId = 1,
                    Symbol    = "tBTCUSD",
                    Key       = "trade:" + JsonConvert.SerializeObject(KlineInterval.FiveMinutes, new KlineIntervalConverter(false)) +
                                ":tBTCUSD"
                });
            };
            var subResult = await subTask;

            subResult.Data.ActivityPaused += async() =>
            {
                subResultWhenPaused = await client.SpotStreams.SubscribeToKlineUpdatesAsync("tBTCUSD", KlineInterval.FiveMinutes, data => { });

                rstEvent.Set();
            };

            // act
            socket.InvokeMessage("{\"event\":\"info\", \"code\": 20051}");

            rstEvent.WaitOne(1000);

            // assert
            Assert.IsTrue(subResultWhenPaused?.Error?.Message.Contains("Socket is paused"));
        }
Exemplo n.º 13
0
        public void SubscribingToCandleUpdates_Should_SubscribeSuccessfully(KlineInterval timeframe)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket, new BitfinexSocketClientOptions()
            {
                LogLevel = LogLevel.Debug
            });

            var subTask = client.SpotStreams.SubscribeToKlineUpdatesAsync("tBTCUSD", timeframe, data => { });

            var subResponse = new CandleSubscriptionResponse()
            {
                Channel   = "candles",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "BTCUSD",
                Key       = "trade:" + JsonConvert.SerializeObject(timeframe, new KlineIntervalConverter(false)) + ":tBTCUSD"
            };

            // act
            socket.InvokeMessage(subResponse);

            subTask.Wait(5000);

            // assert
            Assert.IsTrue(subTask.Result.Success);
        }
Exemplo n.º 14
0
        public void SubscribingToUserStream_Should_TriggerWhenAccountUpdateStreamMessageIsReceived()
        {
            // arrange
            var socket = new TestSocket();
            var client = TestHelpers.CreateSocketClient(socket);

            BinanceStreamBalanceUpdate result = null;

            client.Spot.SubscribeToUserDataUpdates("test", null, null, null, (test) => result = test);

            var data = new BinanceStreamBalanceUpdate()
            {
                Event        = "balanceUpdate",
                EventTime    = new DateTime(2017, 1, 1),
                Asset        = "BTC",
                BalanceDelta = 1,
                ClearTime    = new DateTime(2018, 1, 1),
            };

            // act
            socket.InvokeMessage(data);

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.AreEqual(data, result));
        }
Exemplo n.º 15
0
        public void SubscribingToAllSymbolTicker_Should_TriggerWhenAllSymbolTickerStreamMessageIsReceived()
        {
            // arrange
            var socket = new TestSocket();
            var client = TestHelpers.CreateSocketClient(socket);

            IBinanceTick[] result = null;
            client.Spot.SubscribeToAllSymbolTickerUpdates((test) => result = test.ToArray());

            var data = new[]
            {
                new BinanceStreamTick()
                {
                    FirstTradeId      = 1,
                    HighPrice         = 0.7m,
                    LastTradeId       = 2,
                    LowPrice          = 0.8m,
                    OpenPrice         = 0.9m,
                    PrevDayClosePrice = 1.0m,
                    PriceChange       = 1.1m,
                    Symbol            = "test",
                    BaseVolume        = 1.3m,
                    QuoteVolume       = 1.4m,
                    TotalTrades       = 3
                }
            };

            // act
            socket.InvokeMessage(data);

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.AreEqual(data[0], result[0]));
        }
Exemplo n.º 16
0
        public void SubscribingToTradeStream_Should_TriggerWhenTradeStreamMessageIsReceived()
        {
            // arrange
            var socket = new TestSocket();
            var client = TestHelpers.CreateSocketClient(socket);

            BinanceStreamTrade result = null;

            client.Spot.SubscribeToTradeUpdates("ETHBTC", (test) => result = test);

            var data = new BinanceCombinedStream <BinanceStreamTrade>()
            {
                Stream = "test",
                Data   = new BinanceStreamTrade()
                {
                    Event         = "TestTradeStream",
                    EventTime     = new DateTime(2017, 1, 1),
                    Symbol        = "ETHBTC",
                    BuyerIsMaker  = true,
                    BuyerOrderId  = 10000000000000,
                    SellerOrderId = 2000000000000,
                    Price         = 1.1m,
                    Quantity      = 2.2m,
                    TradeTime     = new DateTime(2017, 1, 1)
                }
            };

            // act
            socket.InvokeMessage(data);

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.AreEqual(data.Data, result));
        }
Exemplo n.º 17
0
        public void PlacingAnOrder_Should_FailIfNoResponse()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket, new BitfinexSocketClientOptions()
            {
                ApiCredentials        = new ApiCredentials("Test", "Test"),
                LogVerbosity          = LogVerbosity.Debug,
                SocketResponseTimeout = TimeSpan.FromMilliseconds(100)
            });

            // act
            var placeTask = client.PlaceOrderAsync(OrderType.ExchangeLimit, "tBTCUSD", 1, price: 1, clientOrderId: 123);

            socket.InvokeMessage(new BitfinexAuthenticationResponse()
            {
                Event = "auth", Status = "OK"
            });
            var result = placeTask.Result;

            // assert
            Assert.IsFalse(result.Success);
        }
Exemplo n.º 18
0
        public void SubscribingToMarketSummariesLite_Should_ReceiveUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.SetProxyResponse(true);
            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            List <BittrexStreamSymbolSummaryLite> result = null;
            var subResponse = client.SubscribeToSymbolSummariesLiteUpdate((test) => result = test.ToList());

            var data =
                new BittrexStreamMarketSummariesLite()
            {
                Deltas = new List <BittrexStreamSymbolSummaryLite>
                {
                    new BittrexStreamSymbolSummaryLite()
                    {
                        BaseVolume = 0.2m,
                        Last       = 0.5m,
                        Symbol     = "TestMarket"
                    }
                }
            };


            // act
            socket.InvokeMessage(WrapResult("uL", data));

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.AreEqual(data.Deltas.ToList()[0], result[0]));
        }
Exemplo n.º 19
0
        public void SubscribingToRawBookUpdates_Should_SubscribeSuccessfully()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            var subTask = client.SubscribeToRawBookUpdatesAsync("Test", 10, data => { });

            var subResponse = new BookSubscriptionResponse()
            {
                Channel   = "book",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "Test",
                Pair      = "Test",
                Frequency = "F0",
                Precision = "R0",
                Length    = 10
            };

            // act
            socket.InvokeMessage(subResponse);

            subTask.Wait(5000);

            // assert
            Assert.IsTrue(subTask.Result.Success);
        }
Exemplo n.º 20
0
        public void SubscribingToTradeUpdates_Should_SubscribeSuccessfully()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            var subTask = client.SubscribeToTradeUpdatesAsync("Test", data => { });

            var subResponse = new TradesSubscriptionResponse()
            {
                Channel   = "trades",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "Test",
                Pair      = "Test"
            };

            // act
            socket.InvokeMessage(subResponse);

            subTask.Wait(5000);

            // assert
            Assert.IsTrue(subTask.Result.Success);
        }
Exemplo n.º 21
0
        public void SubscribingToCandleUpdates_Should_SubscribeSuccessfully(TimeFrame timeframe)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            var subTask = client.SubscribeToCandleUpdatesAsync("Test", timeframe, data => { });

            var subResponse = new CandleSubscriptionResponse()
            {
                Channel   = "candles",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "Test",
                Key       = "trade:" + JsonConvert.SerializeObject(timeframe, new TimeFrameConverter(false)) + ":Test"
            };

            // act
            socket.InvokeMessage(subResponse);

            subTask.Wait(5000);

            // assert
            Assert.IsTrue(subTask.Result.Success);
        }
Exemplo n.º 22
0
        public void SubscribingToBookUpdates_Should_SubscribeSuccessfully(Precision prec, Frequency freq)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            BitfinexOrderBookEntry[] result;
            var subTask = client.SubscribeToBookUpdatesAsync("Test", prec, freq, 10, data => result = data);

            var subResponse = new BookSubscriptionResponse()
            {
                Channel   = "book",
                Event     = "subscribed",
                ChannelId = 1,
                Frequency = JsonConvert.SerializeObject(freq, new FrequencyConverter(false)),
                Length    = 10,
                Pair      = "Test",
                Precision = JsonConvert.SerializeObject(prec, new PrecisionConverter(false)),
                Symbol    = "Test"
            };

            // act
            socket.InvokeMessage(subResponse);

            subTask.Wait(5000);

            // assert
            Assert.IsTrue(subTask.Result.Success);
        }
Exemplo n.º 23
0
        public async Task SubscribingToBookUpdates_Should_SubscribeSuccessfully(Precision prec, Frequency freq)
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket, new BitfinexSocketClientOptions()
            {
                LogVerbosity = LogVerbosity.Debug
            });

            BitfinexOrderBookEntry[] result;
            var subTask = client.SubscribeToBookUpdatesAsync("tBTCUSD", prec, freq, 25, data => result = data.ToArray());

            var subResponse = new BookSubscriptionResponse()
            {
                Channel   = "book",
                Event     = "subscribed",
                ChannelId = 1,
                Frequency = JsonConvert.SerializeObject(freq, new FrequencyConverter(false)),
                Length    = 25,
                Pair      = "BTCUSD",
                Precision = JsonConvert.SerializeObject(prec, new PrecisionConverter(false)),
                Symbol    = "tBTCUSD"
            };

            // act
            socket.InvokeMessage(subResponse);

            var taskResult = await subTask.ConfigureAwait(false);

            // assert
            Assert.IsTrue(taskResult.Success);
        }
Exemplo n.º 24
0
        public void ReceivingAReconnectMessage_Should_ReconnectWebsocket()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket, new BitfinexSocketClientOptions()
            {
                LogVerbosity      = LogVerbosity.Debug,
                ReconnectInterval = TimeSpan.FromMilliseconds(10)
            });

            var rstEvent = new ManualResetEvent(false);
            var subTask  = client.SubscribeToKlineUpdatesAsync("tBTCUSD", TimeFrame.FiveMinute, data => { });

            socket.InvokeMessage(new CandleSubscriptionResponse()
            {
                Channel   = "candles",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "tBTCUSD",
                Key       = "trade:" + JsonConvert.SerializeObject(TimeFrame.FiveMinute, new TimeFrameConverter(false)) + ":tBTCUSD"
            });
            var subResult = subTask.Result;

            subResult.Data.ConnectionRestored += (t) => rstEvent.Set();

            // act
            socket.InvokeMessage("{\"event\":\"info\", \"code\": 20051}");
            Thread.Sleep(100);
            socket.InvokeMessage(new CandleSubscriptionResponse()
            {
                Channel   = "candles",
                Event     = "subscribed",
                ChannelId = 1,
                Symbol    = "tBTCUSD",
                Key       = "trade:" + JsonConvert.SerializeObject(TimeFrame.FiveMinute, new TimeFrameConverter(false)) + ":tBTCUSD"
            });

            var triggered = rstEvent.WaitOne(1000);

            // assert
            Assert.IsTrue(triggered);
        }
Exemplo n.º 25
0
        public void SubscribeV2_Should_FailIfErrorResponse()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            // act
            var subTask = client.SubscribeToAccountUpdatesAsync(test => { });

            socket.InvokeMessage("{\"op\": \"auth\"}");
            Thread.Sleep(10);
            socket.InvokeMessage($"{{\"op\": \"sub\", \"cid\": \"{BaseClient.LastId}\", \"status\": \"error\", \"err-code\": 1, \"err-msg\": \"failed\"}}");
            var subResult = subTask.Result;

            // assert
            Assert.IsFalse(subResult.Success);
        }
Exemplo n.º 26
0
        public void SubscribeV2_Should_SucceedIfSubbedResponse()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);

            // act
            var subTask = client.SubscribeToAccountUpdatesAsync(test => { });

            socket.InvokeMessage("{\"op\": \"auth\"}");
            Thread.Sleep(10);
            socket.InvokeMessage($"{{\"op\": \"sub\", \"cid\": \"{BaseClient.LastId}\"}}");
            var subResult = subTask.Result;

            // assert
            Assert.IsTrue(subResult.Success);
        }
        public void SubscribingToUserStream_Should_TriggerWhenOcoOrderUpdateStreamMessageIsReceived()
        {
            // arrange
            var socket = new TestSocket();
            var client = TestHelpers.CreateSocketClient(socket, new BinanceSocketClientOptions()
            {
                LogLevel = LogLevel.Debug
            });

            BinanceStreamOrderList result = null;

            client.Spot.SubscribeToUserDataUpdatesAsync("test", null, (test) => result = test.Data, null, null);

            var data = new BinanceCombinedStream <BinanceStreamOrderList>
            {
                Stream = "test",
                Data   = new BinanceStreamOrderList()
                {
                    Event             = "listStatus",
                    EventTime         = new DateTime(2017, 1, 1),
                    Symbol            = "BNBUSDT",
                    ContingencyType   = "OCO",
                    ListStatusType    = ListStatusType.Done,
                    ListOrderStatus   = ListOrderStatus.Done,
                    OrderListId       = 1,
                    ListClientOrderId = "2",
                    TransactionTime   = new DateTime(2018, 1, 1),
                    Orders            = new[]
                    {
                        new BinanceStreamOrderId()
                        {
                            Symbol        = "BNBUSDT",
                            OrderId       = 2,
                            ClientOrderId = "3"
                        },
                        new BinanceStreamOrderId()
                        {
                            Symbol        = "BNBUSDT",
                            OrderId       = 3,
                            ClientOrderId = "4"
                        }
                    }
                }
            };

            // act
            socket.InvokeMessage(data);

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(TestHelpers.AreEqual(data.Data, result, "Orders"));
            Assert.IsTrue(TestHelpers.AreEqual(data.Data.Orders.ToList()[0], result.Orders.ToList()[0]));
            Assert.IsTrue(TestHelpers.AreEqual(data.Data.Orders.ToList()[1], result.Orders.ToList()[1]));
        }
Exemplo n.º 28
0
        public void QueryingOrders_Should_ReturnOrders()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateAuthenticatedSocketClient(socket);

            var expected = new List <HuobiOrder>
            {
                new HuobiOrder()
                {
                    Id               = 123,
                    Amount           = 0.1m,
                    Type             = HuobiOrderType.IOCBuy,
                    Price            = 0.2m,
                    Symbol           = "ethusdt",
                    State            = HuobiOrderState.Canceled,
                    Source           = "API",
                    AccountId        = 1543,
                    FilledAmount     = 0.3m,
                    CreatedAt        = new DateTime(2018, 1, 1),
                    FilledFees       = 0.4m,
                    CanceledAt       = new DateTime(2018, 1, 2),
                    FilledCashAmount = 0.5m,
                    FinishedAt       = new DateTime(2018, 1, 3)
                }
            };

            // act
            var subTask = client.GetOrdersAsync(123, "ethusdt", new [] { HuobiOrderState.Canceled });

            socket.InvokeMessage("{\"op\": \"auth\"}");
            Thread.Sleep(10);
            socket.InvokeMessage(SerializeExpectedQuery(expected));
            var subResult = subTask.Result;

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected[0], subResult.Data.ToList()[0]));
        }
Exemplo n.º 29
0
        public void SubscribeToTradeUpdates_Should_TriggerWithTradeUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            HuobiSymbolTrade result = null;
            var subTask             = client.SubscribeToTradeUpdatesAsync("ethusdt", test => result = test.Data);
            var id = JToken.Parse(socket.LastSendMessage)["id"];

            socket.InvokeMessage($"{{\"subbed\": \"test\", \"id\": \"{id}\", \"status\": \"ok\"}}");
            var subResult = subTask.Result;

            var expected =
                new HuobiSymbolTrade()
            {
                Id        = 123,
                Timestamp = new DateTime(2018, 1, 1),
                Details   = new List <HuobiSymbolTradeDetails>()
                {
                    new HuobiSymbolTradeDetails()
                    {
                        Id        = "123",
                        Quantity  = 0.1m,
                        Price     = 0.2m,
                        Timestamp = new DateTime(2018, 2, 1),
                        Side      = HuobiOrderSide.Buy
                    }
                }
            };

            // act
            socket.InvokeMessage(SerializeExpected("market.ethusdt.trade.detail", expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected, result, "Details"));
            Assert.IsTrue(TestHelpers.AreEqual(expected.Details.ToList()[0], result.Details.ToList()[0]));
        }
Exemplo n.º 30
0
        public void SubscribeToDepthUpdates_Should_TriggerWithDepthUpdate()
        {
            // arrange
            var socket = new TestSocket();

            socket.CanConnect = true;
            var client = TestHelpers.CreateSocketClient(socket);

            HuobiOrderBook result  = null;
            var            subTask = client.SubscribeToPartialOrderBookUpdates1SecondAsync("ETHBTC", 1, test => result = test.Data);
            var            id      = JToken.Parse(socket.LastSendMessage)["id"];

            socket.InvokeMessage($"{{\"subbed\": \"ethbtc\", \"status\": \"ok\", \"id\": \"{id}\"}}");
            var subResult = subTask.Result;

            var expected = new HuobiOrderBook()
            {
                Asks = new List <HuobiOrderBookEntry>()
                {
                    new HuobiOrderBookEntry()
                    {
                        Quantity = 0.1m, Price = 0.2m
                    }
                },
                Bids = new List <HuobiOrderBookEntry>()
                {
                    new HuobiOrderBookEntry()
                    {
                        Quantity = 0.3m, Price = 0.4m
                    }
                }
            };

            // act
            socket.InvokeMessage(SerializeExpected("market.ethbtc.depth.step1", expected));

            // assert
            Assert.IsTrue(subResult.Success);
            Assert.IsTrue(TestHelpers.AreEqual(expected.Asks.ToList()[0], result.Asks.ToList()[0]));
            Assert.IsTrue(TestHelpers.AreEqual(expected.Bids.ToList()[0], result.Bids.ToList()[0]));
        }