Exemplo n.º 1
0
        public void TestNash()
        {
            NashClientConfig config = NashClientConfig.Authenticated(
                Environment.GetEnvironmentVariable("NASH_API_KEY"),
                Environment.GetEnvironmentVariable("NASH_API_SECRET"),
                0,
                NashEnvironment.Sandbox,
                1000
                );

            var client = new ExchangeClient(config);

            TestContext.Progress.WriteLine("Orderbook " + client.Orderbook("btc_usdc"));
            TestContext.Progress.WriteLine("ReceivePairs " + client.ReceivePairs());
            TestContext.Progress.WriteLine("GetAccountBalances " + client.GetAccountBalances());
            TestContext.Progress.WriteLine("GetHistoricRates: " + client.GetHistoricTrades(new GetHistoricTradesRequest("btc_usdc")));
            TestContext.Progress.WriteLine("GetOrderHistory btc_usdc: " + client.GetOrderHistory(new GetOrderHistoryRequest("btc_usdc")));
            client.CancelAllOrders("btc_usdc");
            var order = client.LimitSell(LimitOrderRequest.goodTillCancelled("6500.0", "0.01000", "btc_usdc"));

            TestContext.Progress.WriteLine("Limit sell: " + order);
            TestContext.Progress.WriteLine("Get order", client.GetOrder(order.id, order.marketPair));
            TestContext.Progress.WriteLine("Limit buy: " + client.LimitBuy(LimitOrderRequest.goodTillCancelled("6500.0", "0.01000", "btc_usdc")));
            TestContext.Progress.WriteLine("Limit buy fok: " + client.LimitSell(LimitOrderRequest.fillOrKill("6500.0", "0.01000", "btc_usdc")));
            TestContext.Progress.WriteLine("Limit buy ioc: " + client.LimitSell(LimitOrderRequest.immediateOrCancel("6500.0", "0.01000", "btc_usdc")));
            TestContext.Progress.WriteLine("Market sell: " + client.MarketSell(new MarketOrderRequest("0.01000", "btc_usdc")));
            TestContext.Progress.WriteLine("Market sell inverse: " + client.MarketSell(new MarketOrderRequest("20", "usdc_btc")));
            client.CancelAllOrders("btc_usdc");

            var order2 = client.LimitSell(LimitOrderRequest.goodTillCancelled("8000.0", "1.0000", "btc_usdc"));

            TestContext.Progress.WriteLine("Limit sell: " + order2);
            client.CancelOrder(order2.id, order2.marketPair);
        }
Exemplo n.º 2
0
        public void PostOrdersLimitCancel()
        {
            var orderId     = "not exist";
            var assetPairId = "not found";

            Step("Make GET /api/AssetPairs and find BTCUSD assetPairId", () =>
            {
                var response = apiV2.AssetPairs.GetAssetPairs();
                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
                assetPairId = response.GetResponseObject().AssetPairs.ToList().FirstOrDefault(a => { return(a.BaseAssetId.ToLower() == "btc" && a.QuotingAssetId.ToLower() == "usd"); })?.Id;
            });

            Step("Make POST /api/orders/limit and get orderId", () =>
            {
                var model = new LimitOrderRequest
                {
                    AssetPairId = "BTCUSD",
                    OrderAction = OrderAction.Sell,
                    Price       = 5800,
                    Volume      = 0.100
                };

                var response = apiV2.Orders.PostOrdersLimit(model, token);
                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            });

            Step("Make POST /api/orders/limit/{orderId}/cancel", () =>
            {
                var response = apiV2.Orders.PostOrdersLimitOrderCancel("", token);
                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            });
        }
Exemplo n.º 3
0
        /// <summary>
        /// execute orders in the exchange
        /// исполнить ордер на бирже
        /// </summary>
        public async void ExecuteOrder(Order order)
        {
            if (_isConnected == false)
            {
                return;
            }

            _orders.Add(order);

            try
            {
                string expiry = ConvertDateTimeToAcceptDateFormat(DateTime.Now.AddMonths(1));

                decimal volume = order.Volume;

                if (order.Side == Side.Sell)
                {
                    volume = -order.Volume;
                }
                string price = order.Price.ToString(new CultureInfo("en-US"));

                Instrument myInstrument = _allInstruments.Find(inst => inst.name == order.SecurityNameCode);

                // create new pending order
                var request = new LimitOrderRequest(myInstrument)
                {
                    instrument  = order.SecurityNameCode,
                    units       = Convert.ToInt64(volume),
                    timeInForce = TimeInForce.GoodUntilDate,
                    gtdTime     = expiry,
                    price       = price.ToDecimal(),

                    clientExtensions = new ClientExtensions()
                    {
                        id      = order.NumberUser.ToString(),
                        comment = "",
                        tag     = ""
                    },
                    tradeClientExtensions = new ClientExtensions()
                    {
                        id      = order.NumberUser.ToString(),
                        comment = "",
                        tag     = ""
                    }
                };

                var response = await Rest20.PostOrderAsync(Credentials.GetDefaultCredentials().DefaultAccountId, request);

                var orderTransaction = response.orderCreateTransaction;

                if (orderTransaction.id > 0)
                {
                    order.NumberMarket = orderTransaction.id.ToString();
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }
Exemplo n.º 4
0
        public void TestBinance()
        {
            BinanceClientConfig config = BinanceClientConfig.Authenticated(
                Environment.GetEnvironmentVariable("BINANCE_API_KEY"),
                Environment.GetEnvironmentVariable("BINANCE_API_SECRET"),
                true
                );

            var client = new ExchangeClient(config);

            TestContext.Progress.WriteLine("Testing error handling");
            Assert.Throws <BinanceError>(
                delegate {
                client.GetHistoricRates(new GetHistoricRatesRequest("sadsdqwe", Interval.OneHour));
            }
                );

            TestContext.Progress.WriteLine("Orderbook " + client.Orderbook("BNBBTC"));
            TestContext.Progress.WriteLine("GetAccountBalances " + client.GetAccountBalances());
            TestContext.Progress.WriteLine("GetHistoricRates: " + client.GetHistoricRates(new GetHistoricRatesRequest("BNBBTC", Interval.OneHour)));
            TestContext.Progress.WriteLine("GetHistoricRates: " + client.GetHistoricRates(new GetHistoricRatesRequest("BNBBTC", Interval.OneHour)));
            TestContext.Progress.WriteLine("GetAllOpenOrders: " + client.GetAllOpenOrders());
            TestContext.Progress.WriteLine("GetOrderHistory BNBBTC: " + client.GetOrderHistory(new GetOrderHistoryRequest("BNBBTC")));
            TestContext.Progress.WriteLine("Limit buy: " + client.LimitBuy(LimitOrderRequest.goodTillCancelled("0.001", "1", "BNBBTC")));
            TestContext.Progress.WriteLine("Limit sell: " + client.LimitSell(LimitOrderRequest.goodTillCancelled("0.001", "1", "BNBBTC")));
            TestContext.Progress.WriteLine("Limit buy fok: " + client.LimitBuy(LimitOrderRequest.fillOrKill("0.001", "1", "BNBBTC")));
            TestContext.Progress.WriteLine("Limit buy ioc: " + client.LimitBuy(LimitOrderRequest.immediateOrCancel("0.001", "1", "BNBBTC")));
            TestContext.Progress.WriteLine("Market buy: " + client.MarketBuy(new MarketOrderRequest("1", "BNBBTC")));
            TestContext.Progress.WriteLine("Market sell: " + client.MarketSell(new MarketOrderRequest("1", "BNBBTC")));
        }
        public async Task <string> PlaceOrderAsync(string symbol, decimal price, decimal size, MarketSide side)
        {
            try
            {
                var request = new LimitOrderRequest()
                {
                    AssetPairId = symbol,
                    Price       = price.ToString(CultureInfo.InvariantCulture),
                    Side        = side == MarketSide.Long ? Side.Buy : Side.Sell,
                    Volume      = size.ToString(CultureInfo.InvariantCulture)
                };
                var result = await Client.PrivateApi.PlaceLimitOrderAsync(request);

                if (result.Error != null)
                {
                    Console.WriteLine($"ERROR: Cannot place limit order: {result.Error.Message}");
                    return(string.Empty);
                }

                return(result.Payload.OrderId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Cannot place limit order:");
                Console.WriteLine(ex);
                return(string.Empty);
            }
        }
Exemplo n.º 6
0
            public void AskSellLOSpotTest()
            {
                (var newMinSellPrice, var newMaxBuyPrice) = newMinMaxPrices();

                var requestSell = new LimitOrderRequest()
                {
                    Price = newMinSellPrice, AssetPairId = AssetPairId, OrderAction = OrderAction.Sell, Volume = tradingVolume
                };
                var responseSell = hft.Orders.PostOrdersLimitOrder(requestSell, ApiKey);

                responseSell.Validate.StatusCode(HttpStatusCode.OK);

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(7));

                var candlesBid = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Bid, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var candlesAsk = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Ask, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var candlesMid = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Mid, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                Assert.Multiple(() =>
                {
                    Assert.That(candlesAsk.History.Select(c => c.Low), Does.Contain(newMinSellPrice), "Low is not as in order");
                    Assert.That(candlesAsk.History.Select(c => c.High), Does.Contain(newMinSellPrice), "High is not as in order");
                    Assert.That(candlesAsk.History.Select(c => c.Open), Does.Contain(newMinSellPrice), "Open is not as in order");
                });
            }
Exemplo n.º 7
0
 public IResponse PostOrdersLimitOrder(LimitOrderRequest request, string apiKey)
 {
     return(Request.Post($"/Orders/limit")
            .AddJsonBody(request)
            .WithHeaders("api-key", apiKey)
            .Build().Execute());
 }
Exemplo n.º 8
0
            public void PostOrdersLimitNegativeTest()
            {
                var request1 = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = AssetPair, OrderAction = OrderAction.Buy
                };
                var request2 = new LimitOrderRequest()
                {
                    Price = 1.0, OrderAction = OrderAction.Buy, Volume = 0.1
                };
                var request3 = new LimitOrderRequest()
                {
                    AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = 0.1
                };
                var request4 = new LimitOrderRequest()
                {
                };

                Assert.Multiple(() =>
                {
                    Assert.That(hft.Orders.PostOrdersLimitOrder(request1, ApiKey).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                    Assert.That(hft.Orders.PostOrdersLimitOrder(request2, ApiKey).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                    Assert.That(hft.Orders.PostOrdersLimitOrder(request3, ApiKey).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                    Assert.That(hft.Orders.PostOrdersLimitOrder(request4, ApiKey).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
                });
            }
Exemplo n.º 9
0
        public override async Task <OrderIdResponse> CreateLimitOrderAsync([FromBody] LimitOrderRequest request)
        {
            var shortOrder = await Api.PlaceOrder(request.Instrument, request.ToCommand());

            return(new OrderIdResponse {
                OrderId = shortOrder?.Id
            });
        }
Exemplo n.º 10
0
        /// <summary>
        /// Generates an Oanda order request
        /// </summary>
        /// <param name="order">The LEAN order</param>
        /// <returns>The request in JSON format</returns>
        private string GenerateOrderRequest(Order order)
        {
            var instrument = SymbolMapper.GetBrokerageSymbol(order.Symbol);

            string request;

            switch (order.Type)
            {
            case OrderType.Market:
                var marketOrderRequest = new MarketOrderRequest
                {
                    Type       = MarketOrderRequest.TypeEnum.MARKET,
                    Instrument = instrument,
                    Units      = order.Quantity.ToStringInvariant()
                };
                request = JsonConvert.SerializeObject(new { order = marketOrderRequest });
                break;

            case OrderType.Limit:
                var limitOrderRequest = new LimitOrderRequest
                {
                    Type       = LimitOrderRequest.TypeEnum.LIMIT,
                    Instrument = instrument,
                    Units      = order.Quantity.ToStringInvariant(),
                    Price      = ((LimitOrder)order).LimitPrice.ToString(CultureInfo.InvariantCulture)
                };
                request = JsonConvert.SerializeObject(new { order = limitOrderRequest });
                break;

            case OrderType.StopMarket:
                var marketIfTouchedOrderRequest = new MarketIfTouchedOrderRequest
                {
                    Type       = MarketIfTouchedOrderRequest.TypeEnum.MARKETIFTOUCHED,
                    Instrument = instrument,
                    Units      = order.Quantity.ToStringInvariant(),
                    Price      = ((StopMarketOrder)order).StopPrice.ToString(CultureInfo.InvariantCulture)
                };
                request = JsonConvert.SerializeObject(new { order = marketIfTouchedOrderRequest });
                break;

            case OrderType.StopLimit:
                var stopOrderRequest = new StopOrderRequest
                {
                    Type       = StopOrderRequest.TypeEnum.STOP,
                    Instrument = instrument,
                    Units      = order.Quantity.ToStringInvariant(),
                    Price      = ((StopLimitOrder)order).StopPrice.ToString(CultureInfo.InvariantCulture),
                    PriceBound = ((StopLimitOrder)order).LimitPrice.ToString(CultureInfo.InvariantCulture)
                };
                request = JsonConvert.SerializeObject(new { order = stopOrderRequest });
                break;

            default:
                throw new NotSupportedException("The order type " + order.Type + " is not supported.");
            }

            return(request);
        }
Exemplo n.º 11
0
        internal static FSharpOption <Match> SendOrder(Exchange exchange,
                                                       LimitOrder limitOrder,
                                                       Market market)
        {
            var nonMakerOnlyLimitOrder =
                new LimitOrderRequest(limitOrder, LimitOrderRequestType.Normal);

            return(exchange.SendLimitOrder(nonMakerOnlyLimitOrder, market));
        }
Exemplo n.º 12
0
        internal static void SendOrder(Exchange exchange,
                                       LimitOrder limitOrder,
                                       Market market)
        {
            var nonMakerOnlyLimitOrder =
                new LimitOrderRequest(limitOrder, LimitOrderRequestType.Normal);

            exchange.SendLimitOrder(nonMakerOnlyLimitOrder, market);
        }
Exemplo n.º 13
0
        private static void SendOrder(Exchange exchange,
                                      LimitOrder limitOrder,
                                      Market market)
        {
            var makerOnlyLimitOrder =
                new LimitOrderRequest(limitOrder, LimitOrderRequestType.MakerOnly);

            exchange.SendLimitOrder(makerOnlyLimitOrder, market);
        }
Exemplo n.º 14
0
        public override async Task <OrderIdResponse> CreateLimitOrderAsync([FromBody] LimitOrderRequest request)
        {
            Guid orderId = await Api.CreateLimitOrderAsync(
                request.Instrument, request.Price, request.Volume, request.TradeType.ToDomainTradeType());

            return(new OrderIdResponse
            {
                OrderId = orderId.ToString()
            });
        }
Exemplo n.º 15
0
        public void TipIsReplaced()
        {
            var quantity = 1;
            var price    = 10000;
            var side     = Side.Bid;
            var market   = new Market(Currency.BTC, Currency.USD);

            var firstLimitOrder =
                new LimitOrder(new OrderInfo(Guid.NewGuid(),
                                             side, quantity), price);

            var exchange = CreateExchangeAndSendFirstLimitOrder(firstLimitOrder);

            var secondLimitOrder =
                new LimitOrder(new OrderInfo(Guid.NewGuid(),
                                             side, quantity), price + 1);
            var orderReq = new LimitOrderRequest(secondLimitOrder,
                                                 LimitOrderRequestType.Normal);

            exchange.SendLimitOrder(orderReq, market);


            var nonTipQuery = new MarketQuery(market, side, false);

            //e.g. {"Market":{"BuyCurrency":{"Case":"BTC"},"SellCurrency":{"Case":"USD"}},"Side":{"Case":"Buy"},"Tip":true}"
            string nontipQueryStr = JsonConvert.SerializeObject(nonTipQuery);

            using (var redis = ConnectionMultiplexer.Connect("localhost"))
            {
                var db = redis.GetDatabase();

                var values = db.StringGet(nontipQueryStr);
                Assert.That(String.IsNullOrEmpty(values), Is.False,
                            "should have nontip tail(not null) in this market");
                var orders = JsonConvert.DeserializeObject <List <string> >(values);
                Assert.That(orders.Count, Is.EqualTo(1),
                            "should have nontip tail of 2 elements in this market now");

                Assert.That(orders[0],
                            Is.EqualTo(firstLimitOrder.OrderInfo.Id.ToString()),
                            "first order in tail should now be first order");

                var theOrder = db.StringGet(orders[0]);
                Assert.That(theOrder.HasValue, Is.EqualTo(true),
                            "should have the second order content");
                Assert.That(theOrder.IsNull, Is.EqualTo(false),
                            "should have the second order content(not null)");
                var firstLimitOrderSerialized =
                    JsonConvert.SerializeObject(firstLimitOrder);
                Assert.That(theOrder.ToString(),
                            Is.EqualTo(firstLimitOrderSerialized),
                            "received second order should have same content");
            }
        }
Exemplo n.º 16
0
            public void GetOrderBooksUnknowAssetStatusTest()
            {
                var limitRequest = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = "BLRBTS", OrderAction = OrderAction.Buy, Volume = 0.1
                };

                var limitResponse = hft.Orders.PostOrdersLimitOrder(limitRequest, ApiKey);

                Assert.That(limitResponse.Content, Does.Contain("Unknown asset").IgnoreCase);
            }
Exemplo n.º 17
0
            public void MOSellInvertedTest()
            {
                (var newMinSellPrice, var newMaxBuyPrice) = newMinMaxPrices();
                (var marketSell, var marketBuy)           = currentMinMaxPrices();

                //
                var candlesAsk1 = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Ask, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var candlesBid1 = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Bid, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();
                //

                var requestSell1user = new LimitOrderRequest()
                {
                    Price = newMinSellPrice, AssetPairId = AssetPairId, OrderAction = OrderAction.Sell, Volume = 0.1
                };

                var responseSell1user = hft.Orders.PostOrdersLimitOrder(requestSell1user, ApiKey);

                responseSell1user.Validate.StatusCode(HttpStatusCode.OK);

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(7));

                var requestSell = new MarketOrderRequest()
                {
                    AssetPairId = AssetPairId, OrderAction = OrderAction.Sell, Volume = tradingVolume / 2, Asset = SecondAssetId
                };

                var responseSell = hft.Orders.PostOrdersMarket(requestSell, SecondWalletApiKey);

                responseSell.Validate.StatusCode(HttpStatusCode.OK);

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(7));

                var candlesTrades = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Trades, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var candlesAsk = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Ask, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var candlesBid = lykkeApi.CandleHistory.GetCandleHistory(AssetPairId, CandlePriceType.Bid, CandleTimeInterval.Sec, fromMoment, DateTime.Now.ToUniversalTime()).GetResponseObject();

                var prices = new List <decimal>();

                candlesTrades.History.ForEach(p => {
                    prices.Add(Decimal(p.Close));
                    prices.Add(Decimal(p.Open));
                    prices.Add(Decimal(p.High));
                    prices.Add(Decimal(p.Low));
                });

                Assert.Multiple(() =>
                {
                    Assert.That(prices, Does.Contain(Decimal(newMinSellPrice)), "Close price does not contain new min sell price");
                    Assert.That(candlesTrades.History.Select(c => Decimal(c.TradingOppositeVolume)), Does.Contain(Decimal(tradingVolume / 2)), "does not contain trading volume");
                });
            }
Exemplo n.º 18
0
            public void PostOrdersLimitSellTest()
            {
                var request = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = 0.1
                };

                var response = hft.Orders.PostOrdersLimitOrder(request, ApiKey);

                response.Validate.StatusCode(HttpStatusCode.OK);
            }
Exemplo n.º 19
0
        public static async Task <LimitOrderRequest> TestCreateWillBuy()
        {
            var order = new LimitOrderRequest
                        (
                InstrumentName.EurUsd,
                5,
                new decimal(2),
                DateTime.Today + new TimeSpan(1, 0, 0)
                        );

            return(await repo.CreateOrder(order));
        }
Exemplo n.º 20
0
        public static PlaceOrderCommand ToCommand(this LimitOrderRequest loRequest)
        {
            if (loRequest == null)
            {
                throw new ArgumentNullException(nameof(loRequest));
            }

            return(new PlaceOrderCommand(
                       loRequest.Instrument,
                       loRequest.Price,
                       loRequest.Volume,
                       loRequest.TradeType.ToOrderType()));
        }
 public static TradingSignal ToLimitOrder(this LimitOrderRequest request, bool isMarginOrder)
 {
     return(new TradingSignal(
                new Instrument(request.Instrument),
                orderId: null,
                command: OrderCommand.Create,
                tradeType: request.TradeType,
                price: request.Price,
                volume: request.Volume,
                time: DateTime.UtcNow,
                isMarginOrder: isMarginOrder,
                orderType: OrderType.Limit
                ));
 }
Exemplo n.º 22
0
            public void GetOrderByValidIdTest()
            {
                var request = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = 0.1
                };

                var responseOrder = hft.Orders.PostOrdersLimitOrder(request, ApiKey);

                responseOrder.Validate.StatusCode(HttpStatusCode.OK);

                var id       = responseOrder.Content.Replace("\"", "");
                var response = hft.Orders.GetOrderById(id, ApiKey);

                response.Validate.StatusCode(HttpStatusCode.OK);
            }
Exemplo n.º 23
0
            public void PostOrdersCancelLimitTest()
            {
                var request = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = AssetPair, OrderAction = OrderAction.Sell, Volume = 0.5
                };

                var limit = hft.Orders.PostOrdersLimitOrder(request, ApiKey);

                var id = "";

                try { id = limit.JObject.Property("Result").Value.ToString(); } catch (Exception) { }

                var response = hft.Orders.PostOrdersCancelOrder(id, ApiKey);

                response.Validate.StatusCode(HttpStatusCode.OK);
            }
Exemplo n.º 24
0
            public void GetOrderBooksInOrderBookStatusTest()
            {
                var limitRequest = new LimitOrderRequest()
                {
                    Price = 1.0, AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = 0.1
                };

                var limitResponse = hft.Orders.PostOrdersLimitOrder(limitRequest, ApiKey);

                limitResponse.Validate.StatusCode(HttpStatusCode.OK);
                var id = limitResponse.Content.Replace("\"", "");

                var response = hft.Orders.GetOrderById(id, ApiKey);

                response.Validate.StatusCode(HttpStatusCode.OK);
                Assert.That(response.GetResponseObject().Status, Does.Contain(OrderStatus.InOrderBook.ToString()).IgnoreCase);
            }
Exemplo n.º 25
0
            public void GetOrderBooksNotEnoughFundsStatusTest()
            {
                var limitRequest = new LimitOrderRequest()
                {
                    Price = 100000.0, AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = 0.1
                };

                var limitResponse = hft.Orders.PostOrdersLimitOrder(limitRequest, ApiKey);

                limitResponse.Validate.StatusCode(HttpStatusCode.BadRequest);
                var id = limitResponse.JObject.Property("Result").Value.ToString();

                var response = hft.Orders.GetOrderById(id, ApiKey);

                response.Validate.StatusCode(HttpStatusCode.OK);
                Assert.That(response.GetResponseObject().Status, Does.Contain(OrderStatus.NotEnoughFunds.ToString()).IgnoreCase);
            }
Exemplo n.º 26
0
        public void PostOrdersLimit()
        {
            Step("Make POST /api/orders/limit and validate reqeust", () =>
            {
                var model = new LimitOrderRequest
                {
                    AssetPairId = "BTCUSD",
                    OrderAction = OrderAction.Buy,
                    Price       = 1,
                    Volume      = 1
                };

                var response = apiV2.Orders.PostOrdersLimit(model, token);

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            });
        }
Exemplo n.º 27
0
            public void GetOrderBooksGetNewOrderTest()
            {
                var ordersBefore = hft.OrderBooks.GetOrderBooks(AssetPair);

                ordersBefore.Validate.StatusCode(HttpStatusCode.OK);

                double         price  = default(double);
                var            volume = 1000;
                int            i      = 0;
                HttpStatusCode code   = HttpStatusCode.BadRequest;

                do
                {
                    price = double.Parse(TestData.GenerateNumbers(3)) / Math.Pow(10, 3);
                    var request = new LimitOrderRequest()
                    {
                        Price = price, AssetPairId = AssetPair, OrderAction = OrderAction.Buy, Volume = volume
                    };

                    var response = hft.Orders.PostOrdersLimitOrder(request, ApiKey);
                    code = response.StatusCode;
                    i++;
                }while (i < 5 && code != HttpStatusCode.OK);

                Stopwatch sw = new Stopwatch();

                sw.Start();
                while (sw.Elapsed < TimeSpan.FromMinutes(5))
                {
                    if (ordersBefore.GetResponseObject().FindAll(r => r.IsBuy == true).First().Timestamp != hft.OrderBooks.GetOrderBooks(AssetPair).GetResponseObject().FindAll(r => r.IsBuy == true).First().Timestamp)
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(2);
                }
                sw.Stop();

                // check that it appear into ordersbook
                Assert.That(() =>
                {
                    var order = hft.OrderBooks.GetOrderBooks(AssetPair).GetResponseObject().FindAll(r => r.IsBuy == true).First();
                    return(order.Prices.Any(o => o.Price == price) && order.Prices.Any(o => o.Volume == volume));
                }, Is.True.After(5 * 60 * 1000, 2 * 1000), "Order does not appear in orderbook");
            }
Exemplo n.º 28
0
        public async Task <OrderIdResponse> CreateLimitOrderAsync([FromBody] LimitOrderRequest request)
        {
            try
            {
                string orderId = await _internalOrderService.CreateOrderAsync(GetWalletId(), request.Instrument,
                                                                              request.TradeType == Common.ExchangeAdapter.Contracts.TradeType.Sell
                                                                              ?LimitOrderType.Sell
                                                                              : LimitOrderType.Buy,
                                                                              request.Price, request.Volume, true);

                return(new OrderIdResponse {
                    OrderId = orderId
                });
            }
            catch (InvalidOperationException exception)
            {
                throw new ValidationApiException(exception.Message);
            }
        }
Exemplo n.º 29
0
        public override async Task <OrderIdResponse> CreateLimitOrderAsync([FromBody] LimitOrderRequest request)
        {
            InstrumentsConverter instrumentsConverter = await _informationService.LatestConverter;

            var result = await Api.CreateLimitOrder(
                instrumentsConverter.FromLykkeInstrument(new LykkeInstrument(request.Instrument)),
                request.TradeType,
                request.Price,
                request.Volume);

            if (result.Txid.Length != 1)
            {
                _log.Warning($"Expected single txid, got: [{string.Join("; ", result.Txid)}]");
            }

            return(new OrderIdResponse {
                OrderId = result.Txid[0]
            });
        }
        public override async Task <OrderIdResponse> CreateLimitOrderAsync([FromBody] LimitOrderRequest request)
        {
            var limitOrder = new PlaceOrderCommand
            {
                Price  = request.Price,
                Amount = request.Volume,
                Asset  = request.Instrument
            };

            string orderId;

            switch (request.TradeType)
            {
            case TradeType.Buy:
                orderId = (await Api.CreateBuyLimitOrderAsync(limitOrder)).Id;
                break;

            case TradeType.Sell:
                orderId = (await Api.CreateSellLimitOrderAsync(limitOrder)).Id;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            await _limitOrderRepository.InsertAsync(new LimitOrder(
                                                        orderId,
                                                        limitOrder.Asset,
                                                        request.Price,
                                                        executedAmount : 0M,
                                                        amount : request.Volume,
                                                        createdUtc : DateTime.UtcNow,
                                                        modifiedUtc : DateTime.UtcNow,
                                                        tradeType : request.TradeType,
                                                        status : OrderStatus.Active,
                                                        avgExecutionPrice : null,
                                                        remainingAmount : request.Volume), Api.InternalApiKey);

            return(new OrderIdResponse {
                OrderId = orderId
            });
        }
Exemplo n.º 31
0
        public void SendPendingSellCommand(int p_Volume, double p_Price, double p_Stoploss, double p_TakeProfit)
        {
            Print("Pending Sell command");
            PendingOrderRequest l_Request = null;
            if (p_Price < Symbol.Bid)
                l_Request = new StopOrderRequest(TradeType.Sell, p_Volume, p_Price);
            else
                l_Request = new LimitOrderRequest(TradeType.Sell, p_Volume, p_Price);

            l_Request.StopLoss = p_Stoploss;
            l_Request.TakeProfit = p_TakeProfit;
            Trade.Send(l_Request);
        }