Exemple #1
0
        private decimal GetPriceToPlace(string pair, OrderSide side, BinanceOrderBook orderBook, decimal alfa,
                                        int tickUp)
        {
            var symbol        = symbols.Single(x => x.Name == pair);
            var orderbookSide = side == OrderSide.Buy ? orderBook.Bids.ToList() : orderBook.Asks.ToList();

            decimal sum = 0;
            var     i   = 0;

            while (sum < alfa)
            {
                sum += (orderbookSide[i].Quantity);
                i++;
            }
            i = i == 0 ? 0 : i - 1;
            var price    = orderbookSide[i].Price;
            var ticksize = symbol.PriceFilter.TickSize;

            var     tickToIncrease = ticksize * tickUp;
            decimal priceToPlace;

            if (side == OrderSide.Buy)
            {
                priceToPlace = price + tickToIncrease;
            }
            else
            {
                priceToPlace = price - tickToIncrease;
            }
            var round = Math.Round(priceToPlace, symbol.BaseAssetPrecision);

            return(round);
        }
Exemple #2
0
        private int GetAvailableTick(string pair, decimal price, BinanceOrderBook orderbook, OrderSide side)
        {
            var orderbookSide = side == OrderSide.Buy ? orderbook.Asks.ToList() : orderbook.Bids.ToList();
            var symbol        = symbols.Single(x => x.Name == pair);
            var availableTick = int.Parse((Math.Abs(orderbookSide[0].Price - price) / symbol.PriceFilter.TickSize).ToString("F0"));

            return(availableTick);
        }
Exemple #3
0
        public ExchangePricesEventArgs(BinanceOrderBook orderBook) : this()
        {
            var pair   = orderBook.Stream.Split('@')[0];
            var symbol = OrderBookEventArgs.ParseSymbol(pair);

            Instrument1 = symbol[0];
            Instrument2 = symbol[1];
            Exchange    = ExchangeName.Binance;
            OrderBook   = new OrderBookEventArgs(orderBook).OrderBook;
        }
Exemple #4
0
 private void HandleUpdate(BinanceOrderBook data)
 {
     if (Levels == null)
     {
         UpdateOrderBook(data.LastUpdateId, data.Bids, data.Asks);
     }
     else
     {
         SetInitialOrderBook(data.LastUpdateId, data.Bids, data.Asks);
     }
 }
 private void HandleUpdate(BinanceOrderBook data)
 {
     if (limit == null)
     {
         UpdateOrderBook(data.FirstUpdateId ?? 0, data.LastUpdateId, data.Bids, data.Asks);
     }
     else
     {
         SetInitialOrderBook(data.LastUpdateId, data.Asks, data.Bids);
     }
 }
Exemple #6
0
        public void OnSymbolBuyOrderBookReceived(BinanceOrderBook data, Trades pair)
        {
            try {
                if (data != null)
                {
                    //var isAlreadySubscribed = binanceHelper.GetSubscriptionByKey(pair.Symbol) != null;
                    //if (!isAlreadySubscribed) { //buy cycle..
                    var bestAsked = data.Asks.Where(d => d.Price <= pair.BuyPrice).ToList();
                    if (bestAsked.Count() > 0)
                    {
                        Application.Current.Dispatcher.Invoke(() => {
                            decimal buyPrice    = bestAsked.First().Price;
                            decimal buyQuantity = binanceHelper.GetFilteredBuyQuantity(client, pair.Symbol, buyPrice);
                            SafelyWriteToTradeLog("BUY: " + pair.Symbol + " Qty: " + buyQuantity + " at price: " + buyPrice);
                            if (buyPrice > 0 && buyQuantity > 0)
                            {
                                var buyResult = client.PlaceOrder(pair.Symbol, OrderSide.Buy, OrderType.Limit, buyQuantity, price: buyPrice, timeInForce: TimeInForce.GoodTillCancel);
                                if (buyResult.Success)
                                {
                                    SafelyWriteToTradeLog($"{ buyResult.Data.Side } ::> Pair: { buyResult.Data.Symbol }, Price: { buyResult.Data.Price}, Quantity: { buyResult.Data.OriginalQuantity }, Status: {buyResult.Data.Fills}");
                                    _logger.LogInfoMessage(JsonConvert.SerializeObject(buyResult.Data));

                                    //Unsubscribe from pair's stream and save to database..
                                    binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                                    SaveBuyTradeData(pair.Symbol, buyQuantity, buyPrice);

                                    //Immediately process sell after buy..
                                    ProcessSell(client, socketClient, tokenSource.Token);
                                }
                                else if (buyResult.Error != null)
                                {
                                    binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                                    _logger.LogError(buyResult.Error.Message);
                                }

                                ////Unsubscribe from pair's stream and save to database..
                                //binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                                //SaveBuyTradeData(pair.Symbol, buyQuantity, buyPrice);

                                //Immediately process sell after buy..
                                //ProcessSell(client, socketClient, tokenSource.Token);
                            }
                            else
                            {
                                binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                            }
                        });
                    }
                    //}
                }
            } catch (Exception ex) {
                _logger.LogException(ex);
            }
        }
Exemple #7
0
        private bool CheckBetaTick(string pair, BinanceOrderBook orderbook, decimal price, decimal beta, OrderSide side)
        {
            var availableTick = GetAvailableTick(pair, price, orderbook, side);

            if (availableTick >= beta)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #8
0
        private void insertRow(BinanceOrderBook data)
        {
            if (lastRecord == null)
            {
                lastRecord = data;
                return;
            }
            DateTime currTime   = data.EventTime.Value.ToUniversalTime();
            DateTime prevTime   = lastRecord.EventTime.Value.ToUniversalTime();
            DateTime currSecond = truncateToSecond(currTime);
            DateTime prevSecond = truncateToSecond(prevTime);

            if (lastRecord.EventTime.Value > data.EventTime.Value)
            {
                return;
            }
            else if (prevSecond == currSecond)
            {
                lastRecord = data;
                return;
            }
            else if (prevTime.Day == currTime.Day)
            {
                for (DateTime s = prevSecond; s < currSecond; s = addOneSecond(s))
                {
                    try
                    {
                        insertToBigQuery(s, lastRecord);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
                Console.WriteLine("Prev Day: " + prevTime + ", Curr Day: " + currTime);
                lastRecord = data;
                return;
            }
            else
            {
                setupTable(currTime);
                for (DateTime s = prevSecond; s < currSecond; s = addOneSecond(s))
                {
                    insertToBigQuery(s, lastRecord);
                }
                lastRecord = data;
                return;
            }
        }
Exemple #9
0
 private void HandleUpdate(BinanceOrderBook data)
 {
     if (limit == null)
     {
         var updates = new List <ProcessEntry>();
         updates.AddRange(data.Asks.Select(a => new ProcessEntry(OrderBookEntryType.Ask, a)));
         updates.AddRange(data.Bids.Select(b => new ProcessEntry(OrderBookEntryType.Bid, b)));
         UpdateOrderBook(data.FirstUpdateId ?? data.LastUpdateId, data.LastUpdateId, updates);
     }
     else
     {
         initialUpdateReceived = true;
         SetInitialOrderBook(data.LastUpdateId, data.Asks, data.Bids);
     }
 }
Exemple #10
0
        public void SubscribingToPartialBookDepthStream_Should_TriggerWhenPartialBookStreamMessageIsReceived()
        {
            // arrange
            var socket = new Mock <IWebsocket>();

            socket.Setup(s => s.Close());
            socket.Setup(s => s.Connect()).Returns(Task.FromResult(true));
            socket.Setup(s => s.SetEnabledSslProtocols(It.IsAny <System.Security.Authentication.SslProtocols>()));

            var factory = new Mock <IWebsocketFactory>();

            factory.Setup(s => s.CreateWebsocket(It.IsAny <string>())).Returns(socket.Object);

            BinanceOrderBook result = null;
            var client = new BinanceSocketClient {
                SocketFactory = factory.Object
            };

            client.SubscribeToPartialBookDepthStream("test", 10, (test) => result = test);

            var data = new BinanceOrderBook()
            {
                Asks = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.1m,
                        Quantity = 0.2m
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.3m,
                        Quantity = 0.4m
                    }
                },
                LastUpdateId = 1,
                Bids         = new List <BinanceOrderBookEntry>()
            };

            // act
            socket.Raise(r => r.OnMessage += null, JsonConvert.SerializeObject(data));

            // assert
            Assert.IsNotNull(result);
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(data, result, "Asks", "Bids"));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(data.Asks[0], result.Asks[0]));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(data.Asks[1], result.Asks[1]));
        }
Exemple #11
0
        public void GetOrderBook_Should_RespondWithOrderBook()
        {
            // arrange
            var orderBook = new BinanceOrderBook()
            {
                LastUpdateId = 123,
                Asks         = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.1m,
                        Quantity = 1.1m
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.2m,
                        Quantity = 2.2m
                    }
                },
                Bids = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.3m,
                        Quantity = 3.3m
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.4m,
                        Quantity = 4.4m
                    }
                }
            };

            var objects = TestHelpers.PrepareClient(() => Construct(), "{\"lastUpdateId\":123,\"asks\": [[0.1, 1.1], [0.2, 2.2]], \"bids\": [[0.3,3.3], [0.4,4.4]]}");

            // act
            var result = objects.Client.GetOrderBook("BNBBTC");

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(orderBook, result.Data, "Asks", "Bids"));
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(orderBook.Asks[0], result.Data.Asks[0]));
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(orderBook.Asks[1], result.Data.Asks[1]));
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(orderBook.Bids[0], result.Data.Bids[0]));
            Assert.IsTrue(TestHelpers.PublicInstancePropertiesEqual(orderBook.Bids[1], result.Data.Bids[1]));
        }
        public void GetOrderBook_Should_RespondWithOrderBook()
        {
            // arrange
            var orderBook = new BinanceOrderBook()
            {
                LastUpdateId = 123,
                Asks         = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.1,
                        Quantity = 1.1
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.2,
                        Quantity = 2.2
                    }
                },
                Bids = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.3,
                        Quantity = 3.3
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.4,
                        Quantity = 4.4
                    }
                }
            };

            var client = PrepareClient(JsonConvert.SerializeObject(orderBook));

            // act
            var result = client.GetOrderBook("BNBBTC");

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(orderBook, result.Data, "Asks", "Bids"));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(orderBook.Asks[0], result.Data.Asks[0]));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(orderBook.Asks[1], result.Data.Asks[1]));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(orderBook.Bids[0], result.Data.Bids[0]));
            Assert.IsTrue(Compare.PublicInstancePropertiesEqual(orderBook.Bids[1], result.Data.Bids[1]));
        }
        public void GetOrderBook_Should_RespondWithOrderBook()
        {
            // arrange
            var orderBook = new BinanceOrderBook()
            {
                LastUpdateId = 123,
                Symbol       = "BNBBTC",
                Asks         = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.1m,
                        Quantity = 1.1m
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.2m,
                        Quantity = 2.2m
                    }
                },
                Bids = new List <BinanceOrderBookEntry>()
                {
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.3m,
                        Quantity = 3.3m
                    },
                    new BinanceOrderBookEntry()
                    {
                        Price    = 0.4m,
                        Quantity = 4.4m
                    }
                }
            };
            var client = TestHelpers.CreateResponseClient("{\"lastUpdateId\":123,\"asks\": [[0.1, 1.1], [0.2, 2.2]], \"bids\": [[0.3,3.3], [0.4,4.4]]}");

            // act
            var result = client.GetOrderBook("BNBBTC");

            // assert
            Assert.IsTrue(result.Success);
            Assert.IsTrue(TestHelpers.AreEqual(orderBook, result.Data, "Asks", "Bids", "AsksStream", "BidsStream", "LastUpdateIdStream"));
            Assert.IsTrue(TestHelpers.AreEqual(orderBook.Asks.ToList()[0], result.Data.Asks.ToList()[0]));
            Assert.IsTrue(TestHelpers.AreEqual(orderBook.Asks.ToList()[1], result.Data.Asks.ToList()[1]));
            Assert.IsTrue(TestHelpers.AreEqual(orderBook.Bids.ToList()[0], result.Data.Bids.ToList()[0]));
            Assert.IsTrue(TestHelpers.AreEqual(orderBook.Bids.ToList()[1], result.Data.Bids.ToList()[1]));
        }
        /// <summary>
        /// Build <see cref="MarketDepth"/>
        /// </summary>
        /// <param name="marketDepth">Market depth</param>
        /// <param name="limit">Limit of returned orders count</param>
        public async Task BuildAsync(MarketDepth marketDepth, short limit = 10)
        {
            if (marketDepth == null)
            {
                throw new ArgumentNullException(nameof(marketDepth));
            }
            if (limit <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(limit));
            }

            WebCallResult <BinanceOrderBook> response = await _restClient.Spot.Market.GetOrderBookAsync(marketDepth.Symbol, limit);

            BinanceOrderBook orderBook = response.Data;

            marketDepth.UpdateDepth(orderBook.Asks, orderBook.Bids, orderBook.LastUpdateId);
        }
Exemple #15
0
        public void OnSymbolSellOrderBookReceived(BinanceOrderBook data, Trades pair)
        {
            try {
                if (data != null)
                {
                    var bestBid = data.Bids.Where(d => d.Price >= pair.ExpectedSellPrice).ToList();
                    SafelyWriteToTradeLog("Symbol: " + pair.Symbol + "  Price: " + data.Bids.First().Price);
                    if (bestBid.Count() > 0)
                    {
                        Application.Current.Dispatcher.Invoke(() => {
                            decimal sellPrice    = bestBid.First().Price;
                            decimal sellQuantity = binanceHelper.GetBaseCurrencyBalance(client, pair.Symbol.Replace(binanceHelper.GetBaseCurrencySymbol(), ""));
                            sellQuantity         = binanceHelper.GetFilteredSellQuantity(client, pair.Symbol, sellQuantity);
                            SafelyWriteToTradeLog("SELL: " + pair.Symbol + " Qty: " + sellQuantity + " at price: " + sellPrice);
                            if (sellPrice > 0 && sellQuantity > 0)
                            {
                                var sellResult = client.PlaceOrder(pair.Symbol, OrderSide.Sell, OrderType.Limit, sellQuantity, price: sellPrice, timeInForce: TimeInForce.GoodTillCancel);
                                if (sellResult.Success)
                                {
                                    SafelyWriteToTradeLog($"{ sellResult.Data.Side } ::> Pair: { sellResult.Data.Symbol }, Price: { sellResult.Data.Price}, Quantity: { sellResult.Data.OriginalQuantity }, Status: {sellResult.Data.Fills}");
                                    _logger.LogInfoMessage(JsonConvert.SerializeObject(sellResult.Data));

                                    //Unsubscribe from pair's stream and update to database..
                                    binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                                    SaveSellTradeData(pair, sellPrice);
                                }
                                else if (sellResult.Error != null)
                                {
                                    _logger.LogError(sellResult.Error.Message);
                                }
                            }

                            ////Unsubscribe from pair's stream and update to database..
                            //binanceHelper.UnsubscribeFromStream(pair.Symbol, socketClient);
                            //SaveSellTradeData(pair, sellPrice);
                        });
                    }

                    ////process buy again..
                    //ProcessBuy(client, socketClient, tokenSource.Token);
                }
            } catch (Exception ex) {
                _logger.LogException(ex);
            }
        }
        public TradeEventArgs(BinanceOrderBook orderBook) : this()
        {
            var data   = orderBook.Data;
            var pair   = orderBook.Stream.Split('@')[0];
            var symbol = OrderBookEventArgs.ParseSymbol(pair);

            Quantity           = data.Amount;
            Price              = data.Price;
            Instrument1        = symbol[0];
            Instrument2        = symbol[1];
            BuyerOrderId       = data.BuyerOrderId;
            SellerOrderId      = data.SellerOrderId;
            CreatedAt          = StartTime.AddMilliseconds(data.EventTime);
            Timestamp          = StartTime.AddMilliseconds(data.TradeTime);
            Exchange           = ExchangeName.Binance;
            TradeId            = data.TradeId;
            IsBuyerMarketMaker = data.IsBuyerMarketMaker;
        }
Exemple #17
0
        private void insertToBigQuery(DateTime currSecond, BinanceOrderBook record)
        {
            string baseCurrency   = SYMBOL_MAP[symbol].baseCurrency;
            string targetCurrency = SYMBOL_MAP[symbol].targetCurrency;

            BigQueryInsertRow row = new BigQueryInsertRow(insertId: currSecond.ToString())
            {
                { "t", addOneSecond(currSecond) },
                { "bid", BigQueryNumeric.Parse(record.Bids.ToArray()[0].Price.ToString()) },
                { "ask", BigQueryNumeric.Parse(record.Asks.ToArray()[0].Price.ToString()) },
                { "base", baseCurrency },
                { "target", targetCurrency },
                { "s", symbol },
                { "localTime", DateTime.UtcNow }
            };

            bqClient.InsertRow("firebase-lispace", "binance_orderbooks", getTableName(addOneSecond(currSecond)), row);
        }
Exemple #18
0
    public decimal getLowestAskAmount(string pair, decimal price)
    {
        try
        {
            decimal[] arrayValue = new decimal[2];
            arrayValue[0] = arrayValue[1] = 0;
            decimal priceBook = 0;
            decimal priceAux  = 0;
            int     lines     = 0;
            decimal total     = 0;

            BinanceOrderBook book = null;


            foreach (var item in Program.array)
            {
                if ((item as Program.ClassDetailOrder).symbol == pair.ToLower())
                {
                    book = (item as Program.ClassDetailOrder).book; break;
                }
            }


            foreach (var item in book.Asks)
            {
                lines++;
                priceBook += item.Price;

                if ((item.Quantity * item.Price) >= price)
                {
                    return(price / item.Price);
                }
            }
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.Message + ex.StackTrace);
        }
        throw new Exception("Erro askamount");
    }
Exemple #19
0
        private BinanceOrderBook RemoveMyOrderFromOrderbook(decimal price, decimal quantity, OrderSide orderSide,
                                                            BinanceOrderBook orderbook)
        {
            var orderbookSide = orderSide == OrderSide.Sell ? orderbook.Asks.ToList() : orderbook.Bids.ToList();

            var indexOfMyOrder = orderbookSide.FindIndex(x => x.Price == price);

            if (indexOfMyOrder == -1)
            {
                Console.WriteLine("My order not found in orderbook");
                return(orderbook);
            }

            var amountDifference = orderbookSide[indexOfMyOrder].Quantity - quantity;

            if (amountDifference == 0)
            {
                orderbookSide.Splice(indexOfMyOrder, 1);
            }
            else if (amountDifference > 0)
            {
                orderbookSide[indexOfMyOrder].Quantity = amountDifference;
            }
            else
            {
                Console.WriteLine("amount less than my order????");
            }

            if (orderSide == OrderSide.Sell)
            {
                orderbook.Asks = orderbookSide;
            }
            else
            {
                orderbook.Bids = orderbookSide;
            }

            return(orderbook);
        }
Exemple #20
0
        private void TT6(BinanceOrderBook obj)
        {
            var BestAsk = (List <BinanceOrderBookEntry>)obj.Asks;
            var BestBid = (List <BinanceOrderBookEntry>)obj.Bids;

            BookEntry Entry = new BookEntry(BestAsk[0].Price, BestBid[0].Price, obj.LastUpdateId);


            Logger.Info(string.Format("Spread : {0}", Entry.PriceSpread));
            Logger.Info(string.Format("MediumPrice : {0}", Entry.MediumPrice));
            Logger.Info(string.Format("Ask : {0}", Entry.Ask));
            Logger.Info(string.Format("Bid : {0}", Entry.Bid));

            if (Entry.PriceSpread > 1)
            {
                this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Sell);
                this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Buy, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Bid, 2));
            }
            if (Entry.NegativeSpread < -1)
            {
                this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Buy);
                this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Sell, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Ask, 2));
            }
        }
 public BinanceInstrumentsEventArgs(BinanceOrderBook orders)
 {
     OrderBook = orders;
 }
        public async Task <DataTable> GetVolumes()
        {
            await SetupCoinData();

            using (var client = new BinanceClient())
            {
                while (true)
                {
                    foreach (DataRow pricer in CoinData.Rows)
                    {
                        IEnumerable <BinanceKline>        eighthourcandles = client.GetKlines(pricer[0].ToString(), KlineInterval.FiveMinutes, startTime: DateTime.UtcNow.AddHours(-8), endTime: DateTime.UtcNow, limit: 100).Data.ToList();
                        IOrderedEnumerable <BinanceKline> candlearray      = eighthourcandles.OrderByDescending(e => e.CloseTime);
                        decimal averagevolumeeighthours = candlearray.Average(candlestick => candlestick.Volume);
                        decimal fifteenminavg           = (candlearray.ElementAt(1).Volume + candlearray.ElementAt(2).Volume +
                                                           candlearray.ElementAt(0).Volume) / 3;
                        BinanceOrderBook orderBook = client.GetOrderBook(pricer[0].ToString(), 10).Data;
                        IOrderedEnumerable <BinanceOrderBookEntry> orderAsks = orderBook.Asks.OrderByDescending(e => e.Quantity);
                        IOrderedEnumerable <BinanceOrderBookEntry> orderBids = orderBook.Bids.OrderByDescending(e => e.Quantity);
                        decimal maxAsk = orderAsks.First().Price;
                        decimal maxBid = orderBids.First().Price;
                        IEnumerable <BinanceAggregatedTrades> aggTrades = client.GetAggregatedTrades(pricer[0].ToString(), startTime: DateTime.UtcNow.AddMinutes(-2), endTime: DateTime.UtcNow, limit: 10).Data.ToList();
                        DataRow row = CoinData.Rows.Cast <DataRow>().First(o => o[0].ToString() == pricer[0].ToString());
                        row[1] = DateTime.UtcNow;
                        row[2] = eighthourcandles.Last().Close;
                        row[3] = Decimal.Round(averagevolumeeighthours, MidpointRounding.AwayFromZero);
                        row[4] = PercentGive(candlearray.First().Volume, averagevolumeeighthours);
                        row[5] = PercentGive(fifteenminavg, averagevolumeeighthours);
                        int i = 0;
                        while (i != 20)
                        {
                            if (candlearray.ElementAt(i).Close < candlearray.ElementAt(i + 1).Close)
                            {
                                break;
                            }
                            i++;
                        }
                        row[6] = i;
                        //if (enableTrading)
                        {
                            IEnumerable <Candle> candls = candlearray.Select(p => new Candle(p.CloseTime, p.Open, p.High, p.Low, p.Close, p.Volume));
                            Trady.Analysis.Indicator.AverageDirectionalIndexRating avgDirIdx = new Trady.Analysis.Indicator.AverageDirectionalIndexRating(candls, 12, 12);
                            Trady.Analysis.Indicator.ModifiedMovingAverage         mavgFast  = new Trady.Analysis.Indicator.ModifiedMovingAverage(candls, 9);
                            Trady.Analysis.Indicator.ModifiedMovingAverage         mavgSlow  = new Trady.Analysis.Indicator.ModifiedMovingAverage(candls, 50);
                            Trady.Analysis.Indicator.IchimokuCloud ich = new Trady.Analysis.Indicator.IchimokuCloud(candls, 3, 9, 50);

                            /*if (ich.ShortPeriodCount > ich.MiddlePeriodCount)
                             * {
                             *  Binance.Account.Orders.LimitOrder lmtOrder = new Binance.Account.Orders.LimitOrder(iuser);
                             *  lmtOrder.Symbol = pricer[0].ToString();
                             *  lmtOrder.Id = "1230";
                             *  lmtOrder.Price = candlearray.First().Close;
                             *  lmtOrder.Quantity = 100000;
                             *  lmtOrder.IcebergQuantity = 12;
                             *  api.PlaceAsync(lmtOrder, 0, CancellationToken.None);
                             * }*/
                        }
                        sql = "INSERT INTO ORDERS (Symbol, Scanned, Price, Volume, TakerBuyBaseAssetVolume, TakerBuyQuoteAssetVolume, NumberOfTrades, Hr8Av, NowPercent, Min15Percent, GreenCandles) VALUES ('" + pricer[0].ToString() + "','" + row[1].ToString() + "', '" + row[2].ToString() + "', '" + candlearray.First().Volume.ToString() + "', '" + candlearray.First().TakerBuyBaseAssetVolume.ToString() + "', '" + candlearray.First().TakerBuyQuoteAssetVolume.ToString() + "', '" + candlearray.First().Trades.ToString() + "', '" + row[3].ToString() + "', '" + row[4].ToString() + "', '" + row[5].ToString() + "', '" + row[6].ToString() + "');";
                        SQLiteCommand command = new SQLiteCommand(sql, _conn);
                        command.ExecuteNonQuery();
                        if (chkShowNowPercent.Checked)
                        {
                            CoinData.DefaultView.RowFilter = "NowPercent > 0";
                        }
                        //var filtered = CoinData.Select().Where(o => Convert.ToDecimal(o[3].ToString()) > Convert.ToDecimal(o[4].ToString()));
                        if (this.WindowState != FormWindowState.Minimized)
                        {
                            DataViewColours();
                            coindatagridview.DataSource = CoinData;
                            //coindatagridview.Sort(coindatagridview.Columns[3], ListSortDirection.Descending);
                        }
                    }
                }
            }

            return(CoinData);
        }
Exemple #23
0
    public decimal getBook(string pair, decimal amount, string type, string operation, bool division = true)
    {
        try
        {
            BinanceOrderBook book = null;

            foreach (var item in Program.array)
            {
                if ((item as Program.ClassDetailOrder).symbol == pair.ToLower())
                {
                    book = (item as Program.ClassDetailOrder).book; break;
                }
            }



            List <BinanceOrderBookEntry> lst = null;
            if (type == "asks")
            {
                lst = book.Asks;
            }
            if (type == "bids")
            {
                lst = book.Bids;
            }

            decimal[] arrayValue = new decimal[2];
            arrayValue[0] = arrayValue[1] = 0;
            decimal orderPrice  = 0;
            decimal orderAmount = 0;
            decimal totalCost   = 0;
            decimal totalAmount = 0;
            decimal remaining   = amount;
            decimal cost        = 0;

            foreach (var item in lst)
            {
                orderPrice  = item.Price;
                orderAmount = item.Quantity;
                cost        = orderPrice * orderAmount;
                if (cost < remaining)
                {
                    remaining   -= cost;
                    totalCost   += cost;
                    totalAmount += orderAmount;
                }
                else
                {
                    //finished
                    remaining   -= amount;
                    totalCost   += amount * orderPrice;
                    totalAmount += amount;
                    if (division)
                    {
                        arrayValue[0] = Math.Round(amount / (totalCost / totalAmount), 8);
                        arrayValue[1] = Math.Round(amount / orderPrice, 8);
                    }
                    else
                    {
                        arrayValue[0] = Math.Round((totalCost / totalAmount) * amount, 8);
                        arrayValue[1] = Math.Round(orderPrice * amount, 8);
                    }
                    return(arrayValue[0]);
                }
            }
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.Message + ex.StackTrace);
            //System.Threading.Thread.Sleep(1000);
        }
        //System.Threading.Thread.Sleep(1000);
        throw new Exception("Error Asks");
    }
Exemple #24
0
        /// <summary>
        /// Receive Orderbook Update coming for the subscription
        /// </summary>
        /// <param name="OrderbookLevel"></param>
        private void OrderBookHandler(BinanceOrderBook OrderbookLevel)
        {
            try
            {
                var BestAsk = (List <BinanceOrderBookEntry>)OrderbookLevel.Asks;
                var BestBid = (List <BinanceOrderBookEntry>)OrderbookLevel.Bids;
                var Capture = BestAsk.ConvertToBook(BestBid);
                Capture.Compute();
                BookSnapshot.AddBook(Capture);

                var RounderAsk    = BestAsk.Select(y => Math.Round(y.Price, 0)).ToList().ToList();
                var RounderAskVol = BestAsk.Select(y => Math.Round(y.Quantity, 5)).ToList().ToList();

                var RounderBid    = BestBid.Select(y => Math.Round(y.Price, 0)).ToList().ToList();
                var RounderBidVol = BestBid.Select(y => Math.Round(y.Quantity, 5)).ToList().ToList();

                for (int i = 0; i < RounderAsk.Count; i++)
                {
                    Map.AddPrice(new PriceLayer(RounderAsk[i], RounderAskVol[i], PriceDirection.Ask));
                }
                for (int i = 0; i < RounderBid.Count; i++)
                {
                    Map.AddPrice(new PriceLayer(RounderBid[i], RounderBidVol[i], PriceDirection.Bid));
                }
                //Logger.Info(string.Format("Price : {0}", Map.Map.Last().Price));
                //Logger.Info(string.Format("Ask Quantity Price : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Ask).Last().PriceLayerRef));
                //Logger.Info(string.Format("Ask Quantity Before : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Ask).Last().QuantityBefore));
                //Logger.Info(string.Format("Ask Quantity After : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Ask).Last().QuantityAfter));
                //Logger.Info(string.Format("Bid Quantity Price : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Bid).Last().PriceLayerRef));
                //Logger.Info(string.Format("Bid Quantity Before : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Bid).Last().QuantityBefore));
                //Logger.Info(string.Format("Bid Quantity After : {0}", Map.Update.Where(y => y.TheChoice == PriceDirection.Bid).Last().QuantityAfter));
                //Logger.Info(string.Format("RounderAskVol : {0}", RounderAskVol.First()));
                //Logger.Info(string.Format("RounderBidVol : {0}", RounderBidVol.First()));


                //Extract Average volume Per Price;



                //BookEntry Entry = new BookEntry(BestAsk[0].Price, BestBid[0].Price, obj.LastUpdateId);


                //Logger.Info(string.Format("Spread : {0}", Entry.PriceSpread));
                //Logger.Info(string.Format("MediumPrice : {0}", Entry.MediumPrice));
                //Logger.Info(string.Format("Ask : {0}", Entry.Ask));
                //Logger.Info(string.Format("CumuluatedBuyerOnHotRange : {0}", CumuluatedBuyerOnHotRange));
                //Logger.Info(string.Format("BestLiquidAsk : {0}", BestLiquidAsk));

                //Logger.Info(string.Format("Bid : {0}", Entry.Bid));
                //Logger.Info(string.Format("CumuluatedSellerOnHotRange : {0}", CumuluatedSellerOnHotRange));
                //Logger.Info(string.Format("BestLiquidBid : {0}", BestLiquidBid));
            }

            catch (Exception ex)
            {
                MamaBot.GlobalShared.Vars.Logger.LogError("Exception occured in the OrderBookHandler : " + ex.Message);
            }



            //if (WANTTOBUY)
            //{
            //    Task.Run(() =>
            //    {
            //        this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Buy);
            //        //this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Sell);

            //        this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Buy, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Bid, 3));
            //        //this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Sell, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Ask, 2));

            //    });
            //}
        }
Exemple #25
0
        private Task Process(Order order)
        {
            return(Task.Run(async() =>
            {
                try
                {
                    order.Processing = true;
                    var orderBookRequest = (await binanceClient.GetOrderBookAsync(order.Pair, 50));
                    if (!orderBookRequest.Success)
                    {
                        order.Status = Status.Error;
                        order.ErrorMessage = orderBookRequest.Error.Message;
                        return;
                    }

                    BinanceOrderBook orderbook = orderBookRequest.Data;

                    order.Bid = orderbook.Bids.First().Price;
                    order.Ask = orderbook.Asks.First().Price;

                    if (order.Status == Status.WaitBuy)
                    {
                        var priceToPlace = GetPriceToPlace(order.Pair,
                                                           OrderSide.Buy,
                                                           orderbook,
                                                           order.BAlfa,
                                                           order.TickUp);

                        var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                        if (checkBetaTick)
                        {
                            order.BuyOrder = await PlaceOrder(order.Pair, order.Amount, OrderSide.Buy, priceToPlace);
                            order.Status = Status.Buy;
                            order.BuyPrice = priceToPlace;
                        }
                    }
                    else if (order.Status == Status.WaitSell)
                    {
                        var priceToPlace = GetPriceToPlace(order.Pair,
                                                           OrderSide.Sell,
                                                           orderbook,
                                                           order.SAlfa,
                                                           order.TickUp);

                        var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                          OrderSide.Sell);

                        if (checkBetaTick)
                        {
                            order.SellOrder = await PlaceOrder(order.Pair, order.Amount, OrderSide.Sell, priceToPlace);
                            order.Status = Status.Sell;
                            order.SellPrice = priceToPlace;
                        }
                    }
                    else if (order.Status == Status.Buy)
                    {
                        var statusOrderRequest = await binanceClient.GetOrderAsync(order.Pair, order.BuyOrder.OrderId);

                        if (!statusOrderRequest.Success)
                        {
                            if (statusOrderRequest.Error.Code == -2013)
                            {
                                return;
                            }
                            order.Status = Status.Error;
                            order.ErrorMessage = statusOrderRequest.Error.Message;
                        }

                        var statusOrder = statusOrderRequest.Data;

                        if (statusOrder.Status == OrderStatus.Filled)
                        {
                            order.BuyOrderCompletedDatetime = DateTime.Now;
                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Sell, orderbook, order.SAlfa,
                                                               order.TickUp);

                            var checkBeta = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                          OrderSide.Sell);

                            if (checkBeta)
                            {
                                order.SellOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                   OrderSide.Sell, priceToPlace);
                                order.Status = Status.Sell;
                                order.SellPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitSell;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.New)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.BuyOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Buy, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Buy, orderBookClear, order.BAlfa,
                                                               order.TickUp);
                            var checkBeta = CheckBetaTick(order.Pair, orderBookClear, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                            if (checkBeta)
                            {
                                if (priceToPlace != order.BuyOrder.Price)
                                {
                                    BinanceCanceledOrder orderCancelled;
                                    try
                                    {
                                        orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                                    }
                                    catch (UnknowOrderException)
                                    {
                                        return;
                                    }
                                    if (orderCancelled.ExecutedQuantity > 0)
                                    {
                                        ManagePartiallyFilledBuy(order, orderCancelled);
                                    }
                                    // Controllare
                                    order.BuyOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                      OrderSide.Buy, priceToPlace);
                                    order.BuyPrice = priceToPlace;
                                }
                            }
                            else
                            {
                                BinanceCanceledOrder orderCancelled;
                                try
                                {
                                    orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                                }
                                catch (UnknowOrderException)
                                {
                                    return;
                                }
                                if (orderCancelled.ExecutedQuantity > 0)
                                {
                                    ManagePartiallyFilledBuy(order, orderCancelled);
                                }

                                order.Status = Status.WaitBuy;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.Canceled)
                        {
                            var priceToPlace = GetPriceToPlace(order.Pair, OrderSide.Buy, orderbook, order.BAlfa,
                                                               order.TickUp);
                            var checkBeta = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.BBeta,
                                                          OrderSide.Buy);

                            if (checkBeta)
                            {
                                // Controllare
                                order.BuyOrder = await PlaceOrder(order.Pair, order.BuyOrder.OriginalQuantity,
                                                                  OrderSide.Buy, priceToPlace);
                                order.BuyPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitBuy;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.PartiallyFilled)
                        {
                            BinanceCanceledOrder orderCancelled;
                            try
                            {
                                orderCancelled = await CancelBinanceOrder(order.Pair, order.BuyOrder.OrderId);
                            }
                            catch (UnknowOrderException)
                            {
                                return;
                            }
                            ManagePartiallyFilledBuy(order, orderCancelled);
                            context.Send(x => Orders.Remove(order), null);
                        }
                    }
                    else if (order.Status == Status.Sell)
                    {
                        var orderStatusRequest = await binanceClient.GetOrderAsync(order.Pair, order.SellOrder.OrderId);

                        if (!orderStatusRequest.Success)
                        {
                            order.Status = Status.Error;
                            order.ErrorMessage = orderStatusRequest.Error.Message;
                            return;
                        }

                        BinanceOrder statusOrder = orderStatusRequest.Data;

                        if (statusOrder.Status == OrderStatus.Filled)
                        {
                            order.SellOrderCompletedDatetime = DateTime.Now;
                            CompleteOrder(order);
                        }
                        else if (statusOrder.Status == OrderStatus.New)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.SellOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Sell, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair,
                                                               OrderSide.Sell,
                                                               orderBookClear,
                                                               order.SAlfa,
                                                               order.TickUp);

                            var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                              OrderSide.Sell);
                            if (checkBetaTick)
                            {
                                if (priceToPlace != order.SellOrder.Price)
                                {
                                    BinanceCanceledOrder orderCancelled;
                                    try
                                    {
                                        orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                                    }
                                    catch (UnknowOrderException)
                                    {
                                        return;
                                    }

                                    if (orderCancelled.ExecutedQuantity > 0)
                                    {
                                        ManagePartiallyFilledSell(order, orderCancelled);
                                        return;
                                    }

                                    order.SellOrder = await PlaceOrder(order.Pair, order.SellOrder.OriginalQuantity,
                                                                       OrderSide.Sell, priceToPlace);
                                    order.SellPrice = priceToPlace;
                                }
                            }
                            else
                            {
                                BinanceCanceledOrder orderCancelled;
                                try
                                {
                                    orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                                }
                                catch (UnknowOrderException)
                                {
                                    return;
                                }
                                if (orderCancelled.ExecutedQuantity > 0)
                                {
                                    ManagePartiallyFilledSell(order, orderCancelled);
                                    return;
                                }

                                order.Status = Status.WaitSell;
                            }
                        }
                        else if (statusOrder.Status == OrderStatus.Canceled)
                        {
                            var orderBookClear = RemoveMyOrderFromOrderbook(order.SellOrder.Price,
                                                                            order.BuyOrder.OriginalQuantity, OrderSide.Sell, orderbook);

                            var priceToPlace = GetPriceToPlace(order.Pair,
                                                               OrderSide.Sell,
                                                               orderBookClear,
                                                               order.SAlfa,
                                                               order.TickUp);

                            var checkBetaTick = CheckBetaTick(order.Pair, orderbook, priceToPlace, order.SBeta,
                                                              OrderSide.Sell);
                            if (checkBetaTick)
                            {
                                order.SellOrder = await PlaceOrder(order.Pair, order.SellOrder.OriginalQuantity,
                                                                   OrderSide.Sell, priceToPlace);
                                order.SellPrice = priceToPlace;
                            }
                            else
                            {
                                order.Status = Status.WaitSell;
                            }
                        }

                        else if (statusOrder.Status == OrderStatus.PartiallyFilled)
                        {
                            BinanceCanceledOrder orderCancelled;
                            try
                            {
                                orderCancelled = await CancelBinanceOrder(order.Pair, order.SellOrder.OrderId);
                            }
                            catch (UnknowOrderException)
                            {
                                return;
                            }
                            ManagePartiallyFilledSell(order, orderCancelled);
                        }
                    }
                }
                catch (Exception ex)
                {
                    order.Status = Status.Error;
                    order.ErrorMessage = ex.Message;
                }
                finally
                {
                    order.Processing = false;
                }
            }));
        }