Ejemplo n.º 1
0
        private ExchangeOrderBook ParseOrderBookWebSocket(JToken token)
        {
            var exchangeOrderBook = new ExchangeOrderBook();

            foreach (JArray jarray in token["asks"])
            {
                var exchangeOrderPrice = new ExchangeOrderPrice
                {
                    Price  = jarray[0].ConvertInvariant(new decimal()),
                    Amount = jarray[1].ConvertInvariant(new decimal())
                };
                exchangeOrderBook.Asks[exchangeOrderPrice.Price] = exchangeOrderPrice;
            }

            foreach (JArray jarray in token["bids"])
            {
                var exchangeOrderPrice = new ExchangeOrderPrice
                {
                    Price  = jarray[0].ConvertInvariant(new decimal()),
                    Amount = jarray[1].ConvertInvariant(new decimal())
                };
                exchangeOrderBook.Bids[exchangeOrderPrice.Price] = exchangeOrderPrice;
            }

            return(exchangeOrderBook);
        }
Ejemplo n.º 2
0
        public override IEnumerable <KeyValuePair <string, ExchangeOrderBook> > GetOrderBooks(int maxCount = 100)
        {
            List <KeyValuePair <string, ExchangeOrderBook> > books = new List <KeyValuePair <string, ExchangeOrderBook> >();
            JObject obj = MakeJsonRequest <JObject>("/public?command=returnOrderBook&currencyPair=all&depth=" + maxCount);

            CheckError(obj);
            foreach (JProperty token in obj.Children())
            {
                ExchangeOrderBook book = new ExchangeOrderBook();
                foreach (JArray array in token.First["asks"])
                {
                    book.Asks.Add(new ExchangeOrderPrice {
                        Amount = (decimal)array[1], Price = (decimal)array[0]
                    });
                }
                foreach (JArray array in token.First["bids"])
                {
                    book.Bids.Add(new ExchangeOrderPrice {
                        Amount = (decimal)array[1], Price = (decimal)array[0]
                    });
                }
                books.Add(new KeyValuePair <string, ExchangeOrderBook>(token.Name, book));
            }
            return(books);
        }
Ejemplo n.º 3
0
        public override ExchangeOrderBook GetOrderBook(Coin baseCoin, Coin coin, int maxCount = 100)
        {
            string  symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}");
            JObject obj    = MakeJsonRequest <Newtonsoft.Json.Linq.JObject>("public/getorderbook?market=" + symbol + "&type=both&limit_bids=" + maxCount + "&limit_asks=" + maxCount);

            CheckError(obj);
            JToken book = obj["result"];

            if (book == null)
            {
                return(null);
            }
            ExchangeOrderBook orders = new ExchangeOrderBook();
            JToken            bids   = book["buy"];

            foreach (JToken token in bids)
            {
                ExchangeOrderPrice order = new ExchangeOrderPrice {
                    Amount = token["Quantity"].Value <decimal>(), Price = token["Rate"].Value <decimal>()
                };
                orders.Bids.Add(order);
            }
            JToken asks = book["sell"];

            foreach (JToken token in asks)
            {
                ExchangeOrderPrice order = new ExchangeOrderPrice {
                    Amount = token["Quantity"].Value <decimal>(), Price = token["Rate"].Value <decimal>()
                };
                orders.Asks.Add(order);
            }
            return(orders);
        }
Ejemplo n.º 4
0
        public static OrderBookViewModel ToOrderBookViewModel(this ExchangeOrderBook source)
        {
            var asksList = new List <OrderPriceAndQuantityViewModel>();
            var bidsList = new List <OrderPriceAndQuantityViewModel>();


            foreach (var order in source.Asks)
            {
                asksList.Add(new OrderPriceAndQuantityViewModel
                {
                    price    = Decimal.Parse(order.Value.Price.ToString()),
                    quantity = Decimal.Parse(order.Value.Amount.ToString())
                });
            }

            foreach (var order in source.Bids)
            {
                bidsList.Add(new OrderPriceAndQuantityViewModel
                {
                    price    = Decimal.Parse(order.Value.Price.ToString()),
                    quantity = Decimal.Parse(order.Value.Amount.ToString())
                });
            }

            return(new OrderBookViewModel
            {
                asks = asksList,
                bids = bidsList
            });
        }
Ejemplo n.º 5
0
        protected override async Task <ExchangeOrderBook> OnGetOrderBookAsync(string symbol, int maxCount = 100)
        {
            var tuple = await MakeRequestOkexAsync(symbol, "/depth.do?symbol=$SYMBOL$", null);

            var exchangeOrderBook = new ExchangeOrderBook();

            foreach (var jToken in tuple.Item1["asks"])
            {
                var jarray             = (JArray)jToken;
                var exchangeOrderPrice = new ExchangeOrderPrice
                {
                    Amount = jarray[1].ConvertInvariant(new decimal()),
                    Price  = jarray[0].ConvertInvariant(new decimal())
                };
                exchangeOrderBook.Asks[exchangeOrderPrice.Price] = exchangeOrderPrice;
            }

            foreach (JArray jarray in tuple.Item1["bids"])
            {
                var exchangeOrderPrice = new ExchangeOrderPrice
                {
                    Amount = jarray[1].ConvertInvariant(new decimal()),
                    Price  = jarray[0].ConvertInvariant(new decimal())
                };
                exchangeOrderBook.Bids[exchangeOrderPrice.Price] = exchangeOrderPrice;
            }

            return(exchangeOrderBook);
        }
Ejemplo n.º 6
0
        public static async Task RunShowExchangeStats(Dictionary <string, string> dict)
        {
            string       marketSymbol  = "BTC-USD";
            string       marketSymbol2 = "XXBTZUSD";
            IExchangeAPI apiCoinbase   = new ExchangeCoinbaseAPI();
            IExchangeAPI apiGemini     = new ExchangeGeminiAPI();
            IExchangeAPI apiKraken     = new ExchangeKrakenAPI();
            IExchangeAPI apiBitfinex   = new ExchangeBitfinexAPI();

            while (true)
            {
                ExchangeTicker ticker = await apiCoinbase.GetTickerAsync(marketSymbol);

                ExchangeOrderBook orders = await apiCoinbase.GetOrderBookAsync(marketSymbol);

                decimal askAmountSum = orders.Asks.Values.Sum(o => o.Amount);
                decimal askPriceSum  = orders.Asks.Values.Sum(o => o.Price);
                decimal bidAmountSum = orders.Bids.Values.Sum(o => o.Amount);
                decimal bidPriceSum  = orders.Bids.Values.Sum(o => o.Price);

                ExchangeTicker ticker2 = await apiGemini.GetTickerAsync(marketSymbol);

                ExchangeOrderBook orders2 = await apiGemini.GetOrderBookAsync(marketSymbol);

                decimal askAmountSum2 = orders2.Asks.Values.Sum(o => o.Amount);
                decimal askPriceSum2  = orders2.Asks.Values.Sum(o => o.Price);
                decimal bidAmountSum2 = orders2.Bids.Values.Sum(o => o.Amount);
                decimal bidPriceSum2  = orders2.Bids.Values.Sum(o => o.Price);

                ExchangeTicker ticker3 = await apiKraken.GetTickerAsync(marketSymbol2);

                ExchangeOrderBook orders3 = await apiKraken.GetOrderBookAsync(marketSymbol2);

                decimal askAmountSum3 = orders3.Asks.Values.Sum(o => o.Amount);
                decimal askPriceSum3  = orders3.Asks.Values.Sum(o => o.Price);
                decimal bidAmountSum3 = orders3.Bids.Values.Sum(o => o.Amount);
                decimal bidPriceSum3  = orders3.Bids.Values.Sum(o => o.Price);

                ExchangeTicker ticker4 = await apiBitfinex.GetTickerAsync(marketSymbol);

                ExchangeOrderBook orders4 = await apiBitfinex.GetOrderBookAsync(marketSymbol);

                decimal askAmountSum4 = orders4.Asks.Values.Sum(o => o.Amount);
                decimal askPriceSum4  = orders4.Asks.Values.Sum(o => o.Price);
                decimal bidAmountSum4 = orders4.Bids.Values.Sum(o => o.Amount);
                decimal bidPriceSum4  = orders4.Bids.Values.Sum(o => o.Price);

                Console.Clear();
                Console.WriteLine("GDAX: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker.Last, ticker.Volume.QuoteCurrencyVolume, askAmountSum, askPriceSum, bidAmountSum, bidPriceSum);
                Console.WriteLine("GEMI: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker2.Last, ticker2.Volume.QuoteCurrencyVolume, askAmountSum2, askPriceSum2, bidAmountSum2, bidPriceSum2);
                Console.WriteLine("KRAK: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker3.Last, ticker3.Volume.QuoteCurrencyVolume, askAmountSum3, askPriceSum3, bidAmountSum3, bidPriceSum3);
                Console.WriteLine("BITF: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker4.Last, ticker4.Volume.QuoteCurrencyVolume, askAmountSum4, askPriceSum4, bidAmountSum4, bidPriceSum4);
                Thread.Sleep(5000);
            }
        }
Ejemplo n.º 7
0
        public void BidsSorted_Descending()
        {
            var exchangeOrderBook = new ExchangeOrderBook();

            exchangeOrderBook.Bids.Add(1.123m, new ExchangeOrderPrice());
            exchangeOrderBook.Bids.Add(0.24m, new ExchangeOrderPrice());
            exchangeOrderBook.Bids.Add(2.85m, new ExchangeOrderPrice());

            exchangeOrderBook.Bids.First().Key.Should().Be(2.85m);
            exchangeOrderBook.Bids.Last().Key.Should().Be(0.24m);
        }
Ejemplo n.º 8
0
        private static void OrderBookCallback(ExchangeOrderBook msg)
        {
            var(_, bid) = msg.Bids.FirstOrDefault();
            var(_, ask) = msg.Asks.FirstOrDefault();

            Console.WriteLine(
                $"[{msg.MarketSymbol,-8}:{msg.SequenceId,10}] "
                + $"{bid.Price,10} ({bid.Amount,9:N2}) | "
                + $"{ask.Price,10} ({ask.Amount,9:N})"
                );
        }
Ejemplo n.º 9
0
        protected override async Task <IWebSocket> OnGetDeltaOrderBookWebSocketAsync(Action <ExchangeOrderBook> callback, int maxCount = 20, params string[] marketSymbols)
        {
            /*
             * request:
             * {"op": "subscribe", "args": ["swap/depth:BTC-USD-SWAP"]}
             *
             * response-snapshot:
             * {
             *  "table": "swap/depth",
             *  "action": "partial",
             *  "data": [{
             *      "instrument_id": "BTC-USD-SWAP",
             *      "asks": [["3983", "888", 10, 3],....],
             *      "bids": [
             *          ["3983", "789", 0, 3],....
             *      ],
             *      "timestamp": "2018-12-04T09:38:36.300Z",
             *      "checksum": 200119424
             *  }]
             * }
             *
             * response-update:
             * {
             *  "table": "swap/depth",
             *  "action": "update",
             *  "data": [{
             *      "instrument_id": "BTC-USD-SWAP",
             *      "asks": [],
             *      "bids": [
             *          ["3983", "789", 0, 3]
             *      ],
             *      "timestamp": "2018-12-04T09:38:36.300Z",
             *      "checksum": -1200119424
             *  }]
             * }
             *
             */

            return(await ConnectWebSocketOkexAsync(async (_socket) =>
            {
                marketSymbols = await AddMarketSymbolsToChannel(_socket, "/depth_l2_tbt:{0}", marketSymbols); // level 2 = 400 levels
            }, (_socket, symbol, sArray, token) =>
            {
                ExchangeOrderBook book = ExchangeAPIExtensions.ParseOrderBookFromJTokenArrays(token, maxCount: 400 * 2); // add/update + remove, so maxCount * 2
                book.MarketSymbol = symbol;
                book.MaxCount = 400;                                                                                     // must match subscription count
                callback(book);
                return Task.CompletedTask;
            }));
        }
Ejemplo n.º 10
0
        private static void RunShowExchangeStats(Dictionary <string, string> dict)
        {
            string       symbol      = "BTC-USD";
            string       symbol2     = "XXBTZUSD";
            IExchangeAPI apiGDAX     = new ExchangeGdaxAPI();
            IExchangeAPI apiGemini   = new ExchangeGeminiAPI();
            IExchangeAPI apiKraken   = new ExchangeKrakenAPI();
            IExchangeAPI apiBitfinex = new ExchangeBitfinexAPI();

            while (true)
            {
                ExchangeTicker    ticker       = apiGDAX.GetTicker(symbol);
                ExchangeOrderBook orders       = apiGDAX.GetOrderBook(symbol);
                decimal           askAmountSum = orders.Asks.Sum(o => o.Amount);
                decimal           askPriceSum  = orders.Asks.Sum(o => o.Price);
                decimal           bidAmountSum = orders.Bids.Sum(o => o.Amount);
                decimal           bidPriceSum  = orders.Bids.Sum(o => o.Price);

                ExchangeTicker    ticker2       = apiGemini.GetTicker(symbol);
                ExchangeOrderBook orders2       = apiGemini.GetOrderBook(symbol);
                decimal           askAmountSum2 = orders2.Asks.Sum(o => o.Amount);
                decimal           askPriceSum2  = orders2.Asks.Sum(o => o.Price);
                decimal           bidAmountSum2 = orders2.Bids.Sum(o => o.Amount);
                decimal           bidPriceSum2  = orders2.Bids.Sum(o => o.Price);

                ExchangeTicker    ticker3       = apiKraken.GetTicker(symbol2);
                ExchangeOrderBook orders3       = apiKraken.GetOrderBook(symbol2);
                decimal           askAmountSum3 = orders3.Asks.Sum(o => o.Amount);
                decimal           askPriceSum3  = orders3.Asks.Sum(o => o.Price);
                decimal           bidAmountSum3 = orders3.Bids.Sum(o => o.Amount);
                decimal           bidPriceSum3  = orders3.Bids.Sum(o => o.Price);

                ExchangeTicker    ticker4       = apiBitfinex.GetTicker(symbol);
                ExchangeOrderBook orders4       = apiBitfinex.GetOrderBook(symbol);
                decimal           askAmountSum4 = orders4.Asks.Sum(o => o.Amount);
                decimal           askPriceSum4  = orders4.Asks.Sum(o => o.Price);
                decimal           bidAmountSum4 = orders4.Bids.Sum(o => o.Amount);
                decimal           bidPriceSum4  = orders4.Bids.Sum(o => o.Price);

                Console.Clear();
                Console.WriteLine("GDAX: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker.Last, ticker.Volume.PriceAmount, askAmountSum, askPriceSum, bidAmountSum, bidPriceSum);
                Console.WriteLine("GEMI: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker2.Last, ticker2.Volume.PriceAmount, askAmountSum2, askPriceSum2, bidAmountSum2, bidPriceSum2);
                Console.WriteLine("KRAK: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker3.Last, ticker3.Volume.PriceAmount, askAmountSum3, askPriceSum3, bidAmountSum3, bidPriceSum3);
                Console.WriteLine("BITF: {0:0.00}, {1:0.00}, {2:0.00}, {3:0.00}, {4:0.00}, {5:0.00}", ticker4.Last, ticker4.Volume.PriceAmount, askAmountSum4, askPriceSum4, bidAmountSum4, bidPriceSum4);
                Thread.Sleep(5000);
            }
        }
Ejemplo n.º 11
0
        public void AsksSorted_Ascending()
        {
            var exchangeOrderBook = new ExchangeOrderBook();

            exchangeOrderBook.Asks.Add(1.123m, new ExchangeOrderPrice {
                Price = 1.123m
            });
            exchangeOrderBook.Asks.Add(0.24m, new ExchangeOrderPrice {
                Price = 0.24m
            });
            exchangeOrderBook.Asks.Add(2.85m, new ExchangeOrderPrice {
                Price = 2.85m
            });

            exchangeOrderBook.Asks.First().Key.Should().Be(0.24m);
            exchangeOrderBook.Asks.Last().Key.Should().Be(2.85m);
        }
Ejemplo n.º 12
0
        private ExchangeOrderBook ParseOrderBook(JToken token)
        {
            ExchangeOrderBook book = new ExchangeOrderBook();

            foreach (JArray array in token["bids"])
            {
                book.Bids.Add(new ExchangeOrderPrice {
                    Price = (decimal)array[0], Amount = (decimal)array[1]
                });
            }
            foreach (JArray array in token["asks"])
            {
                book.Asks.Add(new ExchangeOrderPrice {
                    Price = (decimal)array[0], Amount = (decimal)array[1]
                });
            }
            return(book);
        }
Ejemplo n.º 13
0
        private ExchangeOrderBook ParseOrderBook(JToken data)
        {
            ExchangeOrderBook book = new ExchangeOrderBook();

            foreach (JToken token in data["bids"])
            {
                book.Bids.Add(new ExchangeOrderPrice {
                    Amount = (decimal)token["quantity"], Price = (decimal)token["price"]
                });
            }
            foreach (JToken token in data["asks"])
            {
                book.Asks.Add(new ExchangeOrderPrice {
                    Amount = (decimal)token["quantity"], Price = (decimal)token["price"]
                });
            }
            return(book);
        }
Ejemplo n.º 14
0
        public async Task <ExchangeOrderResult> Sell(Bot bot, decimal price)
        {
            _exchangeApi = GetExchange(bot);

            if (bot.CurrentPosition == null || bot.CurrentPosition.Status != Enumerations.PositionStatusEnum.Bought)
            {
                throw new Exception("No open current position on bot");
            }

            decimal quantity = (decimal)Math.Round(bot.CurrentPosition.Quantity, bot.Coin.OrderRoundingExponent, MidpointRounding.AwayFromZero);

            switch (bot.OrderType)
            {
            case Enumerations.OrderTypeEnum.Market:
                return(Sell(bot.BaseCoin, bot.Coin, quantity, null, Enumerations.OrderTypeEnum.Market));

            case Enumerations.OrderTypeEnum.Limit:

                // get the best bid
                ExchangeOrderBook orderBook = null;

                if (_exchangeApi.Simulated)
                {
                    orderBook = SimulateExchangeOrderBook(price);
                }
                else
                {
                    orderBook = _exchangeApi.GetOrderBook(bot.BaseCoin, bot.Coin, 1);
                }

                if (orderBook != null)
                {
                    ExchangeOrderPrice bestBid = orderBook.Bids.First();

                    return(Sell(bot.BaseCoin, bot.Coin, quantity, bestBid.Price, Enumerations.OrderTypeEnum.Market));
                }
                break;

            case Enumerations.OrderTypeEnum.Stop:     // to do
                throw new NotImplementedException();
            }
            return(null);
        }
Ejemplo n.º 15
0
        public async Task <ExchangeOrderResult> Buy(Bot bot, decimal price)
        {
            _exchangeApi = GetExchange(bot);


            switch (bot.OrderType)
            {
            case Enumerations.OrderTypeEnum.Market:
                return(Buy(bot.BaseCoin, bot.Coin, bot.Amount, null, Enumerations.OrderTypeEnum.Market));

            case Enumerations.OrderTypeEnum.Limit:


                // get the best ask
                ExchangeOrderBook orderBook = null;

                if (_exchangeApi.Simulated)
                {
                    orderBook = SimulateExchangeOrderBook(price);
                }
                else
                {
                    orderBook = _exchangeApi.GetOrderBook(bot.BaseCoin, bot.Coin, 1);
                }

                if (orderBook != null)
                {
                    ExchangeOrderPrice bestAsk = orderBook.Asks.First();

                    decimal quantity = Math.Round(bot.Amount / bestAsk.Price, bot.Coin.OrderRoundingExponent);

                    return(Buy(bot.BaseCoin, bot.Coin, quantity, bestAsk.Price, Enumerations.OrderTypeEnum.Market));
                }

                throw new Exception("Couldn't place a buy order");

            case Enumerations.OrderTypeEnum.Stop:     // to do
                throw new NotImplementedException();
            }

            return(null);
        }
Ejemplo n.º 16
0
        protected void PrintOrderBook(ExchangeOrderBook orderBook)
        {
            Console.WriteLine($"{"BID",-22} | {"ASK",22}");

            Console.WriteLine("---");

            var length = orderBook.Asks.Count;

            if (orderBook.Bids.Count > length)
            {
                length = orderBook.Bids.Count;
            }

            for (var i = 0; i < length; i++)
            {
                var(_, ask) = orderBook.Asks.ElementAtOrDefault(i);
                var(_, bid) = orderBook.Bids.ElementAtOrDefault(i);
                Console.WriteLine($"{bid.Price,10} ({bid.Amount,9:N2}) | "
                                  + $"{ask.Price,10} ({ask.Amount,9:N})");
            }
        }
Ejemplo n.º 17
0
        public override ExchangeOrderBook GetOrderBook(Coin baseCoin, Coin coin, int maxCount = 100)
        {
            string symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}");

            symbol = NormalizeSymbol(symbol);
            JToken            token = MakeBitstampRequest("/order_book/" + symbol);
            ExchangeOrderBook book  = new ExchangeOrderBook();

            foreach (JArray ask in token["asks"])
            {
                book.Asks.Add(new ExchangeOrderPrice {
                    Amount = (decimal)ask[1], Price = (decimal)ask[0]
                });
            }
            foreach (JArray bid in token["bids"])
            {
                book.Bids.Add(new ExchangeOrderPrice {
                    Amount = (decimal)bid[1], Price = (decimal)bid[0]
                });
            }
            return(book);
        }
Ejemplo n.º 18
0
        // call by StartTradePackage()
        public void SetArbitrageSymbolsDate()
        {
            ExchangeOrderBook book = api.GetOrderBook(arbitrageSymbol, StaticVariables.maxCount);

            FindingSymbolsTrading.GetPrice(book, arbitrageSymbolsDate, true);
            FindingSymbolsTrading.GetPrice(book, arbitrageSymbolsDate, false);
            arbitrageSymbolsDate.ItsBuy = itsBuyArbitrage;
            arbitrageSymbolsDate.orderTrade.request.api = StaticVariables.api;
            arbitrageSymbolsDate.orderTrade.request.ShouldRoundAmount = true;

            if (itsBuyArbitrage)
            {
                arbitrageSymbolsDate.orderTrade.request.Amount = AmountTrade * buySymbolsDate.orderTrade.request.Price;
            }
            else
            {
                arbitrageSymbolsDate.orderTrade.request.Amount = AmountTrade * sellSymbolsDate.orderTrade.request.Price;
            }

            if (arbitrageSymbolsDate.orderTrade.request.Amount < arbitrageSymbolsDate.MinAmount)
            {
                arbitrageSymbolsDate.orderTrade.request.Amount = arbitrageSymbolsDate.MinAmount;
            }
        }
Ejemplo n.º 19
0
        public override ExchangeOrderBook GetOrderBook(Coin baseCoin, Coin coin, int maxCount = 100)
        {
            string symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}");

            // {"asks":[["0.01021997",22.83117932],["0.01022000",82.3204],["0.01022480",140],["0.01023054",241.06436945],["0.01023057",140]],"bids":[["0.01020233",164.195],["0.01020232",66.22565096],["0.01020200",5],["0.01020010",66.79296968],["0.01020000",490.19563761]],"isFrozen":"0","seq":147171861}
            symbol = NormalizeSymbol(symbol);
            ExchangeOrderBook book = new ExchangeOrderBook();
            JObject           obj  = MakeJsonRequest <JObject>("/public?command=returnOrderBook&currencyPair=" + symbol + "&depth=" + maxCount);

            CheckError(obj);
            foreach (JArray array in obj["asks"])
            {
                book.Asks.Add(new ExchangeOrderPrice {
                    Amount = (decimal)array[1], Price = (decimal)array[0]
                });
            }
            foreach (JArray array in obj["bids"])
            {
                book.Bids.Add(new ExchangeOrderPrice {
                    Amount = (decimal)array[1], Price = (decimal)array[0]
                });
            }
            return(book);
        }
        public static OrderBook ToOrderBook(this ExchangeOrderBook source, string baseCurrency, string quoteCurrency)
        {
            var asksList = new List <Ask>();
            var bidsList = new List <Bid>();


            foreach (var order in source.Asks)
            {
                asksList.Add(
                    new Ask(
                        order.Value.Amount,
                        order.Value.Price));
            }

            foreach (var order in source.Bids)
            {
                bidsList.Add(
                    new Bid(
                        order.Value.Amount,
                        order.Value.Price));
            }

            return(new OrderBook(baseCurrency, quoteCurrency, asksList, bidsList));
        }
Ejemplo n.º 21
0
        public static decimal GetPrice(ExchangeOrderBook book, SymbolsDate item, bool buy)
        {
            decimal price  = 0;
            decimal amaunt = 0;
            int     j      = 0;

            do
            {
                if (buy)
                {
                    if (book.Asks.Count <= j)
                    {
                        return(0);
                    }

                    price  = book.Asks[j].Price;
                    amaunt = book.Asks[j].Amount;
                }
                else
                {
                    if (book.Bids.Count <= j)
                    {
                        return(0);
                    }

                    price  = book.Bids[j].Price;
                    amaunt = book.Bids[j].Amount;
                }

                j++;

                if (j == StaticVariables.maxCount) //  In case the first 5 orders in the bookOrder are below the minimum required quantity
                {
                    StaticVariables.maxCount = 10;
                    return(0);
                }

                if (!buy)
                {
                    item.MinAmount = price;
                }
            } while (amaunt < item.MinAmount);

            ExchangeOrderRequest request = new ExchangeOrderRequest();

            request.Amount    = amaunt;
            request.IsBuy     = buy;
            request.OrderType = StaticVariables.orderType;
            request.Price     = price;
            request.Symbol    = item.symbole;

            OrderTrade orderTrade = new OrderTrade(request);

            if (buy)
            {
                item.buyOrderTrade = orderTrade;
            }
            else
            {
                item.sellOrderTrade = orderTrade;
            }

            price = WalletFunc.ConversionPrice(price, item.payment);

#if DEBUG
            FindDebug += String.Format("{0}\tSymbol - {1}\n", (request.IsBuy ? "Buy" : "Sell"), request.Symbol);
            FindDebug += String.Format("while (amaunt < item.MinAmount) count - {0}\n", j);
            FindDebug += String.Format("MinAmount - {0}\n", item.MinAmount);
            FindDebug += String.Format("request - {0}\n", request.Print());
            FindDebug += String.Format("price - {0}\n\n", price);
#endif

            return(price);
        }