示例#1
0
        public void CancelOrder(UserTradeOrder aOrder, bool aUseProxy = true)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            if (aOrder == null)
            {
                throw new ArgumentNullException(nameof(aOrder), "Invalid argument: " + nameof(aOrder));
            }

            BitfinexClientOptions lBittrexClientOptions = new BitfinexClientOptions()
            {
                Proxy          = PandoraProxy.GetApiProxy(),
                ApiCredentials = new ApiCredentials(FUserCredentials.Item1, FUserCredentials.Item2)
            };

            using (BitfinexClient lClient = aUseProxy ? new BitfinexClient(lBittrexClientOptions) : new BitfinexClient())
            {
                var lResponse = lClient.CancelOrderAsync(Convert.ToInt64(aOrder.ID)).Result;
                if (!lResponse.Success)
                {
                    throw new Exception("Failed to cancel order in exchange. Message: " + lResponse.Error.Message);
                }
            }
        }
示例#2
0
        private void DoUpdateMarketPrices(object aState)
        {
            try
            {
                var lChanged = new ConcurrentBag <string>();
                using (var lClient = new BitfinexClient())

                {
                    var lMarketsData = lClient.GetTickerAsync(symbols: "ALL").Result;
                    if (!lMarketsData.Success)
                    {
                        throw new Exception("Unable to get updated market prices info");
                    }
                    Parallel.ForEach(lMarketsData.Data, (lMarketData) =>
                    {
                        string lMarketPairID = lMarketData.Symbol.Remove(0, 1).ToLowerInvariant();
                        MarketPriceInfo lRemoteMarketPrice = new MarketPriceInfo
                        {
                            Last = lMarketData.LastPrice,
                            Bid  = lMarketData.Bid,
                            Ask  = lMarketData.Ask
                        };

                        if ((FMarketPrices.TryGetValue(lMarketPairID, out MarketPriceInfo lPrice) && lPrice != lRemoteMarketPrice) || lPrice == null)
                        {
                            FMarketPrices.AddOrUpdate(lMarketPairID, lRemoteMarketPrice, (key, oldValue) => lRemoteMarketPrice);
                            lChanged.Add(lMarketPairID);
                        }
                    });
                }
示例#3
0
        private BitfinexClient PrepareClient(string responseData, bool credentials = true)
        {
            var expectedBytes  = Encoding.UTF8.GetBytes(responseData);
            var responseStream = new MemoryStream();

            responseStream.Write(expectedBytes, 0, expectedBytes.Length);
            responseStream.Seek(0, SeekOrigin.Begin);

            var response = new Mock <IResponse>();

            response.Setup(c => c.GetResponseStream()).Returns(responseStream);

            var request = new Mock <IRequest>();

            request.Setup(c => c.Headers).Returns(new WebHeaderCollection());
            request.Setup(c => c.GetResponse()).Returns(Task.FromResult(response.Object));
            request.Setup(c => c.GetRequestStream()).Returns(Task.FromResult((Stream) new MemoryStream()));

            var factory = new Mock <IRequestFactory>();

            factory.Setup(c => c.Create(It.IsAny <string>()))
            .Returns(request.Object);

            BitfinexClient client = credentials ? new BitfinexClient(new BitfinexClientOptions()
            {
                ApiCredentials = new ApiCredentials("test", "test")
            }) : new BitfinexClient();

            client.RequestFactory = factory.Object;
            return(client);
        }
示例#4
0
        //static Task<int> CreateTask(string name)
        //{
        //    return new Task<int>(() => TaskMethod(name));
        //}

        public string start()
        {
            string         info = "";
            BitfinexClient bit  = new BitfinexClient();

            bit.SetApiKey("cndYoNyd8Tp2g1rAslKFPCcuxYklO3PEprVrlTYMT5l");
            bit.SetApiSecret("ms0cM9Hd1FgEkR6p9TZYVWfw9yDiO3OXg7o2mMhvvx8");
            BitfinexApiResult <BitfinexAccountInfo> result = bit.GetAccountInfo();

            if (result.Error == null)
            {
                info += "MakerFees:" + result.Result.MakerFees;
                info += "TakerFees:" + result.Result.TakerFees;
                int i = 1;
                foreach (BitfinexFee bf in result.Result.Fees)
                {
                    info += "BitfinexFee:" + i.ToString();
                    info += "MakerFees:" + bf.MakerFees;
                    info += "Pairs:" + bf.Pairs;
                    info += "TakerFees:" + bf.TakerFees;
                    info += "\r\n";
                    i++;
                }
            }
            else
            {
                info = "error:" + result.Error.ErrorCode.ToString() + result.Error.ErrorMessage;
            }
            return(info);
        }
示例#5
0
        public bool RefundOrder(UserTradeOrder aOrder, string aAddress, bool aUseProxy = true)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            if (aOrder.Status == OrderStatus.Withdrawn)
            {
                return(false);
            }

            BitfinexClientOptions lBittrexClientOptions = new BitfinexClientOptions()
            {
                Proxy          = PandoraProxy.GetApiProxy(),
                ApiCredentials = new ApiCredentials(FUserCredentials.Item1, FUserCredentials.Item2)
            };

            using (BitfinexClient lClient = aUseProxy ? new BitfinexClient(lBittrexClientOptions) : new BitfinexClient())
            {
                var lResponse = lClient.WithdrawAsync(aOrder.Market.SellingCurrencyInfo.Name.ToLowerInvariant(), WithdrawWallet.Exchange, aOrder.SentQuantity, aAddress).Result;
                if (!lResponse.Success)
                {
                    throw new Exception("Failed to withdraw. Error message:" + lResponse.Error.Message);
                }
            }

            return(true);
        }
示例#6
0
        public BitfinexRestApi(string apiKey, string apiSecret)
        {
            BitfinexClientOptions options = new BitfinexClientOptions();

            options.ApiCredentials = new CryptoExchange.Net.Authentication.ApiCredentials(apiKey, apiSecret);
            m_client = new BitfinexClient(options);
        }
示例#7
0
        static async Task DemoBitfinexSimple(BitfinexClient exch)
        {
            var exchName   = "BITFINEX";
            var resSymbols = await exch.GetSymbolsAsync();

            var symbols = resSymbols.Data;

            Console.WriteLine($"[{exchName}]   {symbols.Count()} symbols");
        }
示例#8
0
        public void Clear()
        {
            var lClientOptions = new BitfinexClientOptions {
                ApiCredentials = null
            };

            BitfinexClient.SetDefaultOptions(lClientOptions);
            IsCredentialsSet = false;
        }
示例#9
0
        static async Task BitfinexWriteSymbolsCsv(BitfinexClient exch)
        {
            string exchName   = "BITFINEX";
            var    resSymbols = await exch.GetSymbolsAsync();

            var symbols = resSymbols.Data;

            WriteStringsToCsv(symbols, SymbolFilepath(exchName), "Symbol");
        }
示例#10
0
 public DataClient()
 {
     Binance  = new BinanceClient();
     Bitfinex = new BitfinexClient();
     Poloniex = new PoloniexClient();
     Bitstamp = new BitstampClient();
     Gdax     = new GdaxClient();
     Gemini   = new GeminiClient();
     Kraken   = new KrakenClient();
     Okex     = new OkexClient();
 }
        internal BitfinexClientGeneralApi(Log log, BitfinexClient baseClient, BitfinexClientOptions options) :
            base(options, options.SpotApiOptions)
        {
            _baseClient = baseClient;
            _log        = log;
            _options    = options;

            Funding = new BitfinexClientGeneralApiFunding(this);

            AffiliateCode = options.AffiliateCode;
        }
示例#12
0
        public BitfinexClient GetBitfinexClient()
        {
            var exchange  = "BITFINEX";
            var apiKey    = m_creds[exchange].Key;
            var apiSecret = m_creds[exchange].Secret;
            var options   = new BitfinexClientOptions();

            options.ApiCredentials = new CryptoExchange.Net.Authentication.ApiCredentials(apiKey, apiSecret);
            var client = new BitfinexClient(options);

            return(client);
        }
示例#13
0
        internal BitfinexClientSpotApi(Log log, BitfinexClient baseClient, BitfinexClientOptions options) :
            base(options, options.SpotApiOptions)
        {
            _baseClient = baseClient;
            _log        = log;
            _options    = options;

            Account      = new BitfinexClientSpotApiAccount(this);
            ExchangeData = new BitfinexClientSpotApiExchangeData(this);
            Trading      = new BitfinexClientSpotApiTrading(this);

            AffiliateCode = options.AffiliateCode;
        }
示例#14
0
        public BlocktraderService(ILog log, ExchangeProxySettings settings)
        {
            binance  = new BinanceClient(log);
            bitfinex = new BitfinexClient(log);
            bitstamp = new BitstampClient(log, settings);

            exchangeClients = new Dictionary <ExchangeTitle, IExchangeClient>
            {
                [ExchangeTitle.Binance]  = binance,
                [ExchangeTitle.Bitfinex] = bitfinex,
                [ExchangeTitle.Bitstamp] = bitstamp
            };
        }
示例#15
0
        public BitfinexManager(string accessKey, string accessSecret)
        {
            _accessKey    = accessKey;
            _accessSecret = accessSecret;

            _client = new BitfinexClient(
                new BitfinexClientOptions()
            {
                ApiCredentials = new ApiCredentials(
                    key: _accessKey,
                    secret: _accessSecret)
            });
        }
示例#16
0
        public TickerService(Dictionary <CurrencyName, Instrument> restInstruments,
                             //Dictionary<CurrencyName, Instrument> wsInstruments,
                             ExchangeSettingsData[] settings,
                             ServiceEventLogger log)
        {
            _bitfinex = new BitfinexClient(settings.Where(s => s.Exchange == ExchangeName.Bitfinex).Single().RestUrl);
            _timer    = new Timer(60 * 60000);
            _log      = log;

            _restInstruments = restInstruments;
            //_wsInstruments = wsInstruments;

            _timer.Elapsed += OnTimerElapsed;
        }
示例#17
0
        public bool PlaceOrder(UserTradeOrder aOrder, bool aUseProxy = true)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            if (aOrder == null || aOrder.Market == null)
            {
                throw new ArgumentNullException(aOrder == null ? nameof(aOrder) : nameof(aOrder.Market), "Invalid argument: " + aOrder == null ? nameof(aOrder) : nameof(aOrder.Market));
            }

            if (aOrder.Status != OrderStatus.Waiting)
            {
                return(false);
            }

            BitfinexClientOptions lBitfinexClientOptions = new BitfinexClientOptions()
            {
                Proxy          = PandoraProxy.GetApiProxy(),
                ApiCredentials = new ApiCredentials(FUserCredentials.Item1, FUserCredentials.Item2)
            };

            using (BitfinexClient lClient = aUseProxy ? new BitfinexClient(lBitfinexClientOptions) : new BitfinexClient())
            {
                if (!aOrder.Market.TryCastToLocalMarket(out ExchangeMarket lExchangeMarket))
                {
                    throw new ArgumentException(nameof(aOrder.Market), "Invalid Market");
                }
                var lResponse = lClient.PlaceOrderAsync(lExchangeMarket.MarketPairID, lExchangeMarket.MarketDirection == MarketDirection.Sell ? OrderSide.Sell : OrderSide.Buy, OrderType.ExchangeLimit, lExchangeMarket.MarketDirection == MarketDirection.Sell ? aOrder.SentQuantity : aOrder.SentQuantity / aOrder.Rate, aOrder.Rate).Result;
                if (!lResponse.Success)
                {
                    throw new Exception($"Bitfinex Error. Message: {lResponse.Error.Message}");
                }
                long lUuid = lResponse.Data.Id;

                var lVerifyResponse = lClient.GetOrderAsync(lUuid).Result;
                if (!lResponse.Success)
                {
                    throw new Exception("Failed to verify order with exchange server");
                }
                aOrder.ID        = lUuid.ToString();
                aOrder.OpenTime  = lVerifyResponse.Data.Timestamp;
                aOrder.Cancelled = lVerifyResponse.Data.Canceled;
                aOrder.Completed = lVerifyResponse.Data.RemainingAmount == 0;
            }

            return(true);
        }
示例#18
0
        static void CreateBitfinexExchange(out BitfinexClient exch, out BitfinexSocketClient sock)
        {
            var evKeys = Environment.GetEnvironmentVariable("BITFINEX_KEY", EnvironmentVariableTarget.User);
            var keys   = evKeys.Split('|');

            var clientOptions = new BitfinexClientOptions();

            clientOptions.ApiCredentials = new ApiCredentials(keys[0], keys[1]);
            exch = new BitfinexClient(clientOptions);
            //----------
            var socketOptions = new BitfinexSocketClientOptions();

            socketOptions.ApiCredentials = clientOptions.ApiCredentials;
            sock = new BitfinexSocketClient(socketOptions);
        }
示例#19
0
        /// <summary>Initializes a new instance of the <see cref="BitfinexService" /> class.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="loggerService">The logger service.</param>
        /// <param name="dbOrderService">The database order service.</param>
        public BitfinexService(IConfiguration configuration, ILoggerService loggerService, IDbOrderService dbOrderService)
        {
            _configuration  = configuration;
            _loggerService  = loggerService;
            _dbOrderService = dbOrderService;

            BitfinexClient.SetDefaultOptions(new BitfinexClientOptions
            {
                ApiCredentials =
                    new ApiCredentials(
                        _configuration["BitfinexClient:Key"],
                        _configuration["BitfinexClient:Secret"]),
            });

            _bitfinexClient = new BitfinexClient();
        }
        //public BitfinexExchange(KafkaProducer p)
        public BitfinexExchange(string bootstrapServers, string topic)
        {
            var evKeys = Environment.GetEnvironmentVariable(ApiKeyEnvVar, EnvironmentVariableTarget.User);
            var keys = evKeys.Split('|');

            var clientOptions = new BitfinexClientOptions();
            clientOptions.ApiCredentials = new ApiCredentials(keys[0], keys[1]);
            this.exch = new BitfinexClient(clientOptions);
            //----------
            var socketOptions = new BitfinexSocketClientOptions();
            socketOptions.ApiCredentials = clientOptions.ApiCredentials;
            this.sock = new BitfinexSocketClient(socketOptions);

            //_p = p;
            _p = new KafkaProducer(bootstrapServers, topic);
        }
示例#21
0
        public string GetDepositAddress(IExchangeMarket aMarket)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            using (var lClient = new BitfinexClient())
            {
                var lAddressResponse = lClient.GetDepositAddressAsync(aMarket.SellingCurrencyInfo.Name.ToLowerInvariant(), WithdrawWallet.Exchange).Result;
                if (!lAddressResponse.Success)
                {
                    throw new Exception($"Failed to get deposit address for bitfinex. Details: {lAddressResponse.Error}");
                }
                return(lAddressResponse.Data.Address);
            }
        }
示例#22
0
        public decimal GetTransactionsFee(ICurrencyIdentity aCurrency)
        {
            decimal?lResult = null;

            if (FLastFeesDataRetrieval == DateTime.MinValue || FLastFeesDataRetrieval < DateTime.UtcNow.AddDays(-1))
            {
                using (var lClient = new BitfinexClient())
                {
                    var lResponse = lClient.GetWithdrawalFeesAsync().Result;
                    if (!lResponse.Success)
                    {
                        throw new Exception($"Failed to get withdrawn fees from exchange server. {lResponse.Error}");
                    }
                    var lFees = lResponse.Data.Withdraw;
                    FWithdrawnFeesCache.Clear();
                    foreach (var lFee in lFees)
                    {
                        FWithdrawnFeesCache.TryAdd(lFee.Key, lFee.Value);
                    }
                }
                FLastFeesDataRetrieval = DateTime.UtcNow;
            }

            if (FWithdrawnFeesCache.TryGetValue(aCurrency.Ticker, out decimal lTxFee))
            {
                lResult = lTxFee;
            }
            else
            {
                using (var lClient = new BitfinexClient())
                {
                    var lResponse = lClient.GetCurrenciesAsync().Result;
                    if (lResponse.Success)
                    {
                        var lExchangeTicker = lResponse.Data.Where(lCurrency => string.Equals(lCurrency.FullName, aCurrency.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()?.Name;
                        if (lExchangeTicker != null && FWithdrawnFeesCache.TryGetValue(lExchangeTicker, out lTxFee))
                        {
                            lResult = lTxFee;
                        }
                    }
                }
            }

            return(lResult ?? throw new Exception($"Transaction fee for currency with ticker '{aCurrency.Ticker}' not found"));
        }
示例#23
0
        public void SetCredentials(string aApiKey, string aApiSecret)
        {
            var lCredentials = new ApiCredentials(aApiKey, aApiSecret);

            var lClientOptions = new BitfinexClientOptions {
                ApiCredentials = lCredentials
            };

            BitfinexClient.SetDefaultOptions(lClientOptions);
            using (BitfinexClient lClient = new BitfinexClient())
            {
                var lResponse = lClient.GetBalancesAsync().Result;
                if (!lResponse.Success)
                {
                    throw new PandoraExchangeExceptions.InvalidExchangeCredentials("Incorrect Key Pair for selected exchange");
                }
            }
            FUserCredentials = new Tuple <string, string>(aApiKey, aApiSecret);
            IsCredentialsSet = true;
        }
示例#24
0
        public decimal GetBalance(IExchangeMarket aMarket)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            using (var lClient = new BitfinexClient())
            {
                var lResponse = lClient.GetBalancesAsync().Result;
                if (!lResponse.Success)
                {
                    throw new Exception($"Failed to retrieve balance. Details: {lResponse.Error}");
                }
                var lBalances       = lResponse.Data;
                var lDecimalBalance = lBalances.Where(lBalance => lBalance.Currency == aMarket.SellingCurrencyInfo.Ticker).FirstOrDefault();
                if (lDecimalBalance == null)
                {
                    throw new Exception($"Failed to get balance for currency {aMarket.SellingCurrencyInfo.Name}");
                }
                return(lDecimalBalance.Balance);
            }
        }
示例#25
0
        private async Task DoUpdatemarketCoins()
        {
            if (FLastMarketCoinsRetrieval == DateTime.MinValue || FLastMarketCoinsRetrieval < DateTime.UtcNow.AddHours(-1))
            {
                using (var lClient = new BitfinexClient())
                {
                    var lCurrenciesResponse = await lClient.GetCurrenciesAsync();

                    var lMarketsResponse = await lClient.GetTickerAsync(symbols : "ALL");

                    var lSymbolDetails = await lClient.GetSymbolDetailsAsync();

                    if (!lCurrenciesResponse.Success || !lMarketsResponse.Success || !lSymbolDetails.Success)
                    {
                        throw new Exception("Failed to retrieve Bitfinex Markets");
                    }
                    BitfinexPair.ExchangeCurrencies = lCurrenciesResponse.Data;
                    FMarkets = lMarketsResponse.Data.Select(lMarket => new BitfinexPair(lMarket.Symbol, lSymbolDetails.Data.Where(lSymbol => string.Equals(lSymbol.Pair, lMarket.Symbol.Remove(0, 1), StringComparison.OrdinalIgnoreCase)).FirstOrDefault())).ToArray();
                }
                FLastMarketCoinsRetrieval = DateTime.UtcNow;
                FLocalCacheOfMarkets.Clear();
            }
        }
示例#26
0
        public TradeOrderStatusInfo GetOrderStatus(string lUuid)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            using (var lClient = new BitfinexClient())
            {
                var lResponse = lClient.GetOrderAsync(Convert.ToInt64(lUuid)).Result;
                if (!lResponse.Success)
                {
                    throw new Exception($"Failed to retrieve order status. Id: {lUuid}");
                }
                return(new TradeOrderStatusInfo
                {
                    ID = lUuid,
                    Completed = lResponse.Data.RemainingAmount == 0,
                    Cancelled = lResponse.Data.Canceled,
                    Rate = lResponse.Data.Price
                });
            }
        }
 public BitfinexRestExchange(ExchangeSettingsData setting) : base(setting)
 {
     _client = new BitfinexClient(setting);
 }
示例#28
0
        static void Main(string[] args)
        {
            Console.WriteLine("Started ...");

            TradingMarket market;

            Console.WriteLine("Choose traiding market (0-bitfinex): ");
            var marketNum = Convert.ToInt32(Console.ReadLine());

            market = (TradingMarket)marketNum;

            IMarketClient marketClient;

            switch (market)
            {
            case TradingMarket.Bitfinex:
                marketClient = new BitfinexClient();
                break;

            default:
                marketClient = new BitfinexClient();
                break;
            }
            Console.WriteLine("You chose next market: {0}", marketClient.Name);

            TradingPair pair;

            do
            {
                Console.WriteLine("Choose currency pair (e.g. 'btcusd'): ");
                var name = Console.ReadLine();
                pair = marketClient.GetPairByName(name);
            }while (pair == null);
            Console.WriteLine("Info for {0}/{1} :", pair.Title, pair.Name);


            Console.WriteLine("Enter boundary (or 'no' if you don't want): ");
            var boundary = Console.ReadLine();

            decimal parsedBoundary;

            if (boundary != "no" && decimal.TryParse(boundary, out parsedBoundary))
            {
                var rule = new TradingRule();
                rule.Pair     = pair;
                rule.Boundary = parsedBoundary;
                rule.Callback = () => Console.WriteLine("We broke boundary, sending smth to telegram or viber!");

                marketClient.SetUpAlert(rule, false);
            }

            var previous = default(decimal);

            using (marketClient)
            {
                var subscriptionResult = marketClient.SubscribeToTraidingPair(pair, (data) =>
                {
                    var current = data.Price;

                    ConsoleColor color;
                    if (previous > current)
                    {
                        color = ConsoleColor.Red;
                    }
                    else if (previous < current)
                    {
                        color = ConsoleColor.Green;
                    }
                    else
                    {
                        color = ConsoleColor.Yellow;
                    }

                    Console.ForegroundColor = color;

                    previous = current;
                    Console.WriteLine(current);
                });
                Console.ReadLine();
                marketClient.UnsubscribeTraidingPair(subscriptionResult.Data);
            }

            Console.WriteLine("Finished ...");
        }