public void should_receive_limit_order_notification()
        {
            try
            {
                // arrange
                var connected = Sut.Connect();
                var @params   = OrderPOSTRequestParams.CreateSimpleHidenLimit("XBTUSD", 3, _xbtAvgPrice - 500, OrderSide.Buy);

                // act
                IList <OrderDto> dtos = null;
                var dataReceived      = new ManualResetEvent(false);

                Sut.OrderResponseReceived += (sender, args) =>
                {
                    if (args.Response.Data.Any(b => b.Symbol == "XBTUSD") && args.Response.Action == BitmexActions.Insert)
                    {
                        dtos = args.Response.Data;
                        dataReceived.Set();
                    }
                };

                var subscription = new SubscriptionRequest(SubscriptionType.order);

                Subscription = subscription;

                Sut.Subscribe(subscription);
                var result = _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, @params).Result.Result;
                result.Should().NotBeNull();
                //result.OrdType.Should().Be("Limit");
                result.OrdStatus.Should().Be("New");
                result.OrderId.Should().NotBeNull();

                Thread.Sleep(2000);
                var received = dataReceived.WaitOne(TimeSpan.FromSeconds(20));

                // assert
                // no exception raised
                connected.Should().BeTrue();
                received.Should().BeTrue();
                dtos.Should().NotBeNull();
                dtos.Count().Should().BeGreaterThan(0);
                dtos[0].OrdType.Should().Be("Limit");
                dtos[0].OrdStatus.Should().Be("New");
                dtos[0].OrderId.Should().Be(result.OrderId);
            }
            catch (BitmexWebSocketLimitReachedException)
            {
                Assert.Fail("connection limit reached");
            }
        }
        public override void TestInitialize()
        {
            base.TestInitialize();
            _bitmexApiService = Container.Resolve <IBitmexApiService>();
            var paramCloseAfter = new OrderCancelAllAfterPOSTRequestParams
            {
                Timeout = int.MaxValue
            };

            _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrderCancelAllAfter, paramCloseAfter).Wait();
            _xbtAvgPrice = _bitmexApiService.Execute(BitmexApiUrls.OrderBook.GetOrderBookL2, new OrderBookL2GETRequestParams()
            {
                Symbol = "XBTUSD", Depth = 1
            }).Result.First()
                           .Price;
        }
Beispiel #3
0
        public void should_receive_position_change_notification()
        {
            // arrange
            var connected = Sut.Connect();
            var @params   = OrderPOSTRequestParams.CreateSimpleMarket("XBTUSD", 3, OrderSide.Buy);

            // act
            IList <PositionDto> dtos = null;
            var dataReceived         = new ManualResetEvent(false);

            Sut.Subscribe(BitmexApiSubscriptionInfo <IEnumerable <PositionDto> > .Create(SubscriptionType.position, a =>
            {
                dtos = a.ToList();
                dataReceived.Set();
            }));

            var result = _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, @params).Result;

            result.Should().NotBeNull();
            result.OrdType.Should().Be("Market");
            result.OrdStatus.Should().Be("Filled");
            result.OrderId.Should().NotBeNull();

            var received = dataReceived.WaitOne(TimeSpan.FromSeconds(20));

            // assert
            // no exception raised
            connected.Should().BeTrue();
            received.Should().BeTrue("data hasn't received");
            dtos.Should().NotBeNull();
            dtos.Count().Should().BeGreaterThan(0);
        }
        private async void FetchTradeBins(Object source, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine("Fetching bins.");
            Debug.WriteLine("Fetching bins.");
            using (var context = new CollectorContext())
            {
                try
                {
                    var latestBin = context.TradeBins.OrderByDescending(x => x.Timestamp).FirstOrDefault();
                    var @params   = new TradeBucketedGETRequestParams
                    {
                        BinSize = "1m",
                        Symbol  = "XBTUSD",
                        Count   = 200,
                        Reverse = true
                    };

                    // act
                    var result = new List <TradeBucketedDto>();
                    try
                    {
                        result = _bitmexApiService.Execute(BitmexApiUrls.Trade.GetTradeBucketed, @params).Result;
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }

                    foreach (var bin in result)
                    {
                        if (latestBin == null || bin.Timestamp.LocalDateTime > latestBin.Timestamp)
                        {
                            await context.TradeBins.AddAsync(new TradeBin()
                            {
                                Symbol          = bin.Symbol,
                                Timestamp       = bin.Timestamp.UtcDateTime,
                                Open            = bin.Open.Value,
                                High            = bin.High.Value,
                                Low             = bin.Low.Value,
                                Close           = bin.Close.Value,
                                Trades          = bin.Trades,
                                Volume          = bin.Volume.Value,
                                ForeignNotional = bin.ForeignNotional,
                                HomeNotional    = bin.HomeNotional
                            });
                        }
                    }

                    await context.SaveChangesAsync();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }
        }
        public override void TestInitialize()
        {
            base.TestInitialize();
            _bitmexApiService = Container.Resolve <IBitmexApiService>();
            var paramCloseAfter = new OrderCancelAllAfterPOSTRequestParams
            {
                Timeout = int.MaxValue
            };

            _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrderCancelAllAfter, paramCloseAfter).Wait();
        }
        private async Task <string> Trade(TradeInfo tradeInfo)
        {
            await PrepareForMarketShift(tradeInfo);

            var orderDto = await ExecuteMarketOrder(tradeInfo);

            Logger.Info($"Market {tradeInfo.EntryOrder} {tradeInfo.Quantity} at {orderDto.Price}, status {orderDto.OrdStatus}");

            var openPositions = await _bitmexApiService.Execute(BitmexApiUrls.Position.GetPosition, new PositionGETRequestParams { Count = 10 });

            var     currentPosition = openPositions.FirstOrDefault(o => o.Symbol == tradeInfo.Symbol && o.IsOpen);
            decimal stopLossPrice;

            if (currentPosition != null)
            {
                var diff      = orderDto.Price.GetValueOrDefault() - currentPosition.LiquidationPrice.GetValueOrDefault();
                var lossLimit = diff * 0.8M * (-1);
                stopLossPrice = RoundPrice(orderDto.Price.GetValueOrDefault() + lossLimit, 0, tradeInfo.DecimalCount);
                var limitPrice = RoundPrice(orderDto.Price.GetValueOrDefault() + (lossLimit / 4), 0, tradeInfo.DecimalCount);
                var limitDto   = await ExecuteLimitOrder(tradeInfo, limitPrice);

                Logger.Info($"Limit {tradeInfo.EntryOrder} {tradeInfo.Quantity} at {limitDto.Price}, status {limitDto.OrdStatus}");
            }
            else
            {
                stopLossPrice = RoundPrice(orderDto.Price.GetValueOrDefault(), tradeInfo.StopLossPercentage, tradeInfo.DecimalCount);
            }

            int takeProfitQuantity = (int)(tradeInfo.Quantity * 0.5M);

            var(takeProfitPrice, takeProfitTrigger, takeProfitOrder) = await CreateTakeProfitOrders(orderDto.Price.GetValueOrDefault(), tradeInfo, (int)takeProfitQuantity, tradeInfo.TakeProfitPercentage);
            await CreateTakeProfitOrders(orderDto.Price.GetValueOrDefault(), tradeInfo, (int)(RoundPrice(takeProfitQuantity, -25, tradeInfo.DecimalCount)), tradeInfo.TakeProfitPercentage / 2);

            var stopLossTrigger = stopLossPrice + tradeInfo.TriggerDistanceUnits;

            var stopLossOrder = await ExecuteStopLossOrder(tradeInfo.Symbol, tradeInfo.Quantity, stopLossPrice, stopLossTrigger, tradeInfo.ExitOrder.ToBitmexOrder());

            Logger.Info($"Status for stop loss: {stopLossOrder.OrdStatus}");

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"{tradeInfo.EntryOrder} {orderDto.OrderQty} {tradeInfo.Symbol}");
            stringBuilder.AppendLine($"Entry price: {orderDto.Price}, {orderDto.OrdStatus}");
            stringBuilder.AppendLine($"Take profit price: {takeProfitPrice}, {takeProfitOrder.OrdStatus}");
            stringBuilder.AppendLine($"Take profit trigger: {takeProfitTrigger}");
            stringBuilder.AppendLine($"Stop loss price: {stopLossPrice}, {stopLossOrder.OrdStatus}");
            stringBuilder.AppendLine($"Stop loss trigger: {stopLossTrigger}");

            return(stringBuilder.ToString());
        }
Beispiel #7
0
        public async Task <string> GoLong(MarketInfo marketInfo)
        {
            await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.ClosePositionByMarket(marketInfo.Market));

            await SetLeverage(marketInfo.Market, marketInfo.Leverage);

            var buyPrice = await GetCurrentPrice(marketInfo.Market);

            var orderDto = await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder,
                                                           OrderPOSTRequestParams.CreateSimpleLimit(marketInfo.Market, marketInfo.Quantity, buyPrice, OrderSide.Buy));

            var stopPrice = Math.Round((decimal)orderDto.Price * 1.005M, 0);
            //await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.CreateSimpleHidenLimit(marketInfo.Market, marketInfo.Quantity, buyPrice - 50, OrderSide.Buy));
            await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.CreateSimpleHidenLimit(marketInfo.Market, marketInfo.Quantity, stopPrice, OrderSide.Sell));

            return($"Bought {orderDto.OrderQty} {marketInfo.Market} at {orderDto.Price}, stop order set to {stopPrice}");
        }
Beispiel #8
0
        private void btn1_Click(object sender, EventArgs e)
        {
            LabelOnOff.Text = (LabelOnOff.Text == "OFF") ? "ON" : "OFF";



            var posOrderParamsA = OrderPOSTRequestParams.CreateMarketStopOrder("XBTUSD", 150, 8000, OrderSide.Buy);

            bitmexApiServiceA = BitmexApiService.CreateDefaultApi(_bitmexAuthorizationA);
            bitmexApiServiceA.Execute(BitmexApiUrls.Order.PostOrder, posOrderParamsA).ContinueWith(ProcessPostOrderResult);

            var posOrderParamsB = OrderPOSTRequestParams.CreateMarketStopOrder("XBTUSD", 150, 6500, OrderSide.Sell);

            bitmexApiServiceB = BitmexApiService.CreateDefaultApi(_bitmexAuthorizationB);
            bitmexApiServiceB.Execute(BitmexApiUrls.Order.PostOrder, posOrderParamsB).ContinueWith(ProcessPostOrderResult);
        }
Beispiel #9
0
        private static async Task PlayWithBitmex()
        {
            try
            {
                const string market = "XBTUSD";
                var          bitmexAuthorization = new BitmexAuthorization();
                bitmexAuthorization.BitmexEnvironment = BitmexEnvironment.Test;
                bitmexAuthorization.Key    = "wcZtcAiFMff8kLWaSLl8U877";
                bitmexAuthorization.Secret = "uOtP5-0sEtiis5d1_Qv1-LW8FLsV3qW9Qsmsf_OWBXVzw-c3";
                _bitmexApiService          = BitmexApiService.CreateDefaultApi(bitmexAuthorization);

                await _bitmexApiService.Execute(BitmexApiUrls.Order.DeleteOrderAll, new OrderAllDELETERequestParams
                {
                    Symbol = "BCHU18"
                });

                var bitcoinOrderBook = await _bitmexApiService.Execute(BitmexApiUrls.OrderBook.GetOrderBookL2,
                                                                       new OrderBookL2GETRequestParams { Depth = 1, Symbol = market });

                var currentPrice  = Math.Round((bitcoinOrderBook[0].Price + bitcoinOrderBook[1].Price) / 2);
                var stopSellOrder = await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.CreateLimitStopOrder(market, 1500, 6500, 6467, OrderSide.Buy));

                var positions = await _bitmexApiService.Execute(BitmexApiUrls.Position.GetPosition, new PositionGETRequestParams { Count = 50 });

                var positionLeveragePostRequestParams = new PositionLeveragePOSTRequestParams();
                positionLeveragePostRequestParams.Leverage = 50;
                positionLeveragePostRequestParams.Symbol   = market;

                /*var positionDto = await bitmexApiService.Execute(BitmexApiUrls.Position.PostPositionLeverage,
                 *  positionLeveragePostRequestParams);*/
                foreach (var position in positions)
                {
                    await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.ClosePositionByMarket(market));
                }
                var positionDto = await _bitmexApiService.Execute(BitmexApiUrls.Position.PostPositionLeverage, positionLeveragePostRequestParams);

                var initialOrder = await CreateLimitOrder(market, 1500, currentPrice, OrderSide.Sell);

                var round     = Math.Round((decimal)initialOrder.Price * 0.9M, 0);
                var stopOrder = await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, OrderPOSTRequestParams.CreateSimpleHidenLimit(market, 1500, round, OrderSide.Buy));

                var stopLoss = await CreateLimitOrder(market, 1500, currentPrice + 40, OrderSide.Sell);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public void should_receive_position_change_notification()
        {
            try
            {
                // arrange
                var connected            = Sut.Connect();
                var @params              = OrderPOSTRequestParams.CreateSimpleMarket("XBTUSD", 3, OrderSide.Buy);
                IList <PositionDto> dtos = null;
                var dataReceived         = new ManualResetEvent(false);
                Sut.PositionResponseReceived += (sender, args) =>
                {
                    dtos = args.Response.Data;
                    dataReceived.Set();
                };
                var subscription = new SubscriptionRequest(SubscriptionType.position);

                Subscription = subscription;

                // act

                Sut.Subscribe(subscription);

                var result = _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, @params).Result.Result;
                result.Should().NotBeNull();
                result.OrdType.Should().Be("Market");
                result.OrdStatus.Should().Be("Filled");
                result.OrderId.Should().NotBeNull();

                var received = dataReceived.WaitOne(TimeSpan.FromSeconds(20));

                // assert
                // no exception raised
                connected.Should().BeTrue();
                received.Should().BeTrue("data hasn't received");
                dtos.Should().NotBeNull();
                dtos.Count().Should().BeGreaterThan(0);
            }
            catch (BitmexWebSocketLimitReachedException)
            {
                Assert.Fail("connection limit reached");
            }
        }
Beispiel #11
0
        public void should_subscribe_on_executions()
        {
            try
            {
                // arrange
                var connected = Sut.Connect();
                IEnumerable <ExecutionDto> dtos = null;
                var dataReceived = new ManualResetEvent(false);

                Sut.ExecutionResponseReceived += (sender, args) =>
                {
                    if (args.Response.Data.Any())
                    {
                        dtos = args.Response.Data;
                        dataReceived.Set();
                    }
                };

                var subscription = new SubscriptionRequest(SubscriptionType.execution);

                Subscription = subscription;
                // act

                Sut.Subscribe(subscription);
                _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder,
                                          OrderPOSTRequestParams.CreateSimpleMarket("XBTUSD", 10, OrderSide.Buy)).Wait();
                var received = dataReceived.WaitOne(TimeSpan.FromSeconds(30));

                // assert
                // no exception raised
                connected.Should().BeTrue();
                received.Should().BeTrue();
                dtos.Should().NotBeNull();
                dtos.Count().Should().BeGreaterThan(0);
            }
            catch (BitmexWebSocketLimitReachedException)
            {
                Assert.Fail("connection limit reached");
            }
        }
Beispiel #12
0
 private static async Task <OrderDto> ExecuteOrder(string market, int quantity, decimal price, OrderSide orderSide)
 {
     return(await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder,
                                            OrderPOSTRequestParams.CreateSimpleLimit(market, quantity, price, orderSide)));
 }
Beispiel #13
0
 private async void Sell()
 {
     var posOrderParams = OrderPOSTRequestParams.CreateSimpleMarket("XBTUSD", Size, OrderSide.Sell);
     await _bitmexApiService.Execute(BitmexApiUrls.Order.PostOrder, posOrderParams).ContinueWith(ProcessPostOrderResult);
 }
Beispiel #14
0
        async Task <OrderDto> Buy(string symbol, int quantity, decimal price)
        {
            var cmd = OrderPOSTRequestParams.CreateSimpleLimit(symbol, quantity, price, OrderSide.Buy);

            return(await _bitmexSvc.Execute(BitmexApiUrls.Order.PostOrder, cmd));
        }