Exemplo n.º 1
0
        public override bool PlaceSellOrder(TradingData trade, bool closePosition = false)
        {
            using (var client = new BinanceFuturesClient())
            {
                var sellOrder = client.PlaceOrder(
                    trade.CoinPair.ToString(),
                    OrderSide.Sell,
                    OrderType.Limit,
                    quantity: Math.Round(trade.CoinQuantityToTrade, 3),
                    reduceOnly: closePosition,
                    price: Math.Round(trade.Price, 2),
                    timeInForce: TimeInForce.GoodTillCancel);

                if (sellOrder.Success)
                {
                    trade.SellOrderID = sellOrder.Data.OrderId;
                }
                else
                {
                    Console.WriteLine(sellOrder.Error.Message.ToString());
                }

                return(sellOrder.Success);
            }
        }
        public void SetUp()
        {
            BinanceFuturesClient client = new BinanceFuturesClient(Config.PublicKey, Config.PrivateKey);

            client.UseTestnet(true);
            trade = client.Trade;
        }
Exemplo n.º 3
0
        public void SetUp()
        {
            BinanceFuturesClient client = new BinanceFuturesClient(Config.PublicKey, Config.PrivateKey);

            client.UseTestnet(true);
            market = client.Market;
        }
Exemplo n.º 4
0
 /// <summary>
 /// Create a new instance
 /// </summary>
 /// <param name="symbol">The symbol of the order book</param>
 /// <param name="options">The options for the order book</param>
 public BinanceFuturesSymbolOrderBook(string symbol, BinanceOrderBookOptions?options = null) : base(symbol, options ?? new BinanceOrderBookOptions())
 {
     symbol.ValidateBinanceSymbol();
     limit          = options?.Limit;
     updateInterval = options?.UpdateInterval;
     restClient     = new BinanceFuturesClient();
     socketClient   = new BinanceFuturesSocketClient();
 }
Exemplo n.º 5
0
 public BinanceFuturesExchangeClient(string apiKey, string secretKey) : base(apiKey, secretKey)
 {
     BinanceFuturesClient.SetDefaultOptions(new BinanceFuturesClientOptions()
     {
         ApiCredentials = new ApiCredentials(apiKey, secretKey),
         LogVerbosity   = LogVerbosity.Error,
         LogWriters     = new List <TextWriter> {
             Console.Out
         }
     });
 }
        public void GetAccountTransactionHistoryListTest()
        {
            GBinanceFuturesClient.Trade trade = new BinanceFuturesClient(Config.PublicKey, Config.PrivateKey).Trade;

            try
            {
                trade.GetAccountTransactionHistory("USDT", 1588362716945);
            }
            catch (ErrorMessageException e)
            {
                StringAssert.AreNotEqualIgnoringCase("", e.Message);   // Invalide api key (test api key on public api, not testnet, unavailable in testnet).
                StringAssert.AreEqualIgnoringCase("Invalid Api-Key ID.", e.Message);
            }
        }
        public void NewFundsTransferTest()
        {
            GBinanceFuturesClient.Trade trade = new BinanceFuturesClient(Config.PublicKey, Config.PrivateKey).Trade;

            try
            {
                trade.NewFundsTransfer("USDT", 10, 1);
            }
            catch (ErrorMessageException e)
            {
                StringAssert.AreNotEqualIgnoringCase("", e.Message);   // Invalide api key (test api key on public api, not testnet).
                StringAssert.AreEqualIgnoringCase("Invalid Api-Key ID.", e.Message);
            }
        }
Exemplo n.º 8
0
 public override decimal GetPrice(CoinPair coinPair)
 {
     using (var client = new BinanceFuturesClient())
     {
         try
         {
             decimal marketPrice = Math.Round(client.GetPrice(coinPair.ToString()).Data.Price, 2);
             Portfolio.UpdateCoinMarketPrice(coinPair.Pair1, marketPrice);
             return(marketPrice);
         }
         catch (Exception)
         {
             return(0);
         }
     }
 }
Exemplo n.º 9
0
 public override decimal GetBalance(string coinName)
 {
     using (var client = new BinanceFuturesClient())
     {
         try
         {
             decimal balance = client.GetAccountInfo().Data.TotalWalletBalance;
             Portfolio.UpdateCoinBalance(coinName, balance);
             return(balance);
         }
         catch (Exception)
         {
             return(0);
         }
     }
 }
        public void UnautorizeUserTest()
        {
            GBinanceFuturesClient.Trade trade = new BinanceFuturesClient().Trade;

            try
            {
                string id = trade.NewFundsTransfer("USDT", 10, 1);
                Assert.Fail();
            }
            catch (ErrorMessageException e) {
                Assert.Fail(e.Message);
            }
            catch (Exception)
            {
                Assert.IsTrue(true);
            }
        }
Exemplo n.º 11
0
        public override void Trade()
        {
            using (var tempClient = new BinanceFuturesClient())
            {
                var openOrders = tempClient.GetOpenOrders().Data;

                TradingData trade = new TradingData(new CoinPair("BTC", "USDT", 3));
                var         pos   = tempClient.GetOpenPositions().Data.Single(s => s.Symbol == trade.CoinPair.ToString());
                trade.UpdateMarketPrice(pos.MarkPrice);

                Console.WriteLine($"{DateTime.Now} Entry Price: {pos.EntryPrice} Unrealised PnL: {pos.UnrealizedPnL}");

                var dataLast24hr = tempClient.Get24HPrice(trade.CoinPair.ToString()).Data;

                decimal priceDiff = dataLast24hr.WeightedAveragePrice - dataLast24hr.LowPrice;

                if (_settings.IsAutoAdjustShortAboveAndLongBelow)
                {
                    trade.PriceLongBelow = Math.Round(dataLast24hr.WeightedAveragePrice - priceDiff * 0.618m, 2);
                    decimal entryPrice = pos.EntryPrice == 0 ? dataLast24hr.WeightedAveragePrice : pos.EntryPrice;
                    trade.PriceShortAbove = Math.Round(priceDiff * 0.618m + entryPrice, 2);
                }
                else
                {
                    trade.PriceLongBelow  = _settings.LongBelow;
                    trade.PriceShortAbove = _settings.ShortAbove;
                }

                if (_settings.IsAutoAdjustTargetProfit)
                {
                    trade.ProfitTarget = Math.Round(Math.Abs(pos.Quantity) / pos.Leverage * pos.EntryPrice * 0.618m, 2);
                }
                else
                {
                    trade.ProfitTarget = _settings.FuturesProfitTarget;
                }

                // If zero positions
                if (pos.EntryPrice == 0 && openOrders.Count() == 0)
                {
                    decimal investment = _client.GetBalance(trade.CoinPair.Pair2) / _settings.FuturesSafetyFactor; // 11 is to have the liquidation very low or high
                    trade.CoinQuantity = investment / trade.Price * pos.Leverage;                                  // 20x leverage

                    // Short above or Long below
                    if (trade.Price < trade.PriceLongBelow)
                    {
                        _client.PlaceBuyOrder(trade);
                    }
                    else if (trade.Price > trade.PriceShortAbove)
                    {
                        _client.PlaceSellOrder(trade);
                    }
                }

                // When there is an existing position
                else if (pos.EntryPrice > 0)
                {
                    if (pos.LiquidationPrice < pos.EntryPrice) // Long position
                    {
                        trade.LastAction = Binance.Net.Enums.OrderSide.Buy;
                    }
                    else
                    {
                        trade.LastAction = Binance.Net.Enums.OrderSide.Sell;
                    }

                    if (pos.UnrealizedPnL > 0)
                    {
                        trade.CoinQuantity = pos.Quantity;

                        bool success;
                        bool targetProfitMet = trade.ProfitTarget > 0 && pos.UnrealizedPnL > trade.ProfitTarget;

                        if (trade.LastAction == Binance.Net.Enums.OrderSide.Buy && (targetProfitMet || pos.MarkPrice > trade.PriceShortAbove)) // i.e. Long position
                        {
                            success = _client.PlaceSellOrder(trade, closePosition: true);
                        }
                        else if (trade.LastAction == Binance.Net.Enums.OrderSide.Sell && (targetProfitMet || pos.MarkPrice < trade.PriceLongBelow))
                        {
                            success = _client.PlaceBuyOrder(trade, closePosition: true);
                        }
                        else
                        {
                            success = false;
                        }

                        if (success)
                        {
                            _settings.TotalProfit += pos.UnrealizedPnL;
                        }
                    }
                }

                // Below is for statistics and to keep UI up-to-date
                trade.SetQuantity(pos.Quantity);
                trade.SellPriceAfterFees = trade.BuyPriceAfterFees = pos.EntryPrice;
                trade.SetPriceChangePercentage(pos.MarkPrice, isFutures: true);
                OnTradeListItemHandled(trade);
            }
        }