Exemple #1
0
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    try
                    {
                        CancelTimer();
                        if (semaphoreSlim != null)
                        {
                            semaphoreSlim.Dispose();
                        }
                    }
                    finally
                    {
                        updateTimer    = null;
                        semaphoreSlim  = null;
                        PoloniexClient = null;
                    }
                }

                disposedValue = true;
            }
        }
Exemple #2
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));
            }

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

            using (PoloniexClient lClient = aUseProxy ? new PoloniexClient(lPoloniexClientOptions) : new PoloniexClient())
            {
                var lResponse = lClient.CancelOrder(Convert.ToInt64(aOrder.ID));
                if (!lResponse.Success || !Convert.ToBoolean(lResponse.Data.success))
                {
                    throw new Exception($"Failed to cancel order in exchange. Message: {lResponse.Data?.message ?? lResponse.Error.Message}");
                }
            }
        }
Exemple #3
0
        private void Form1_LoadBot(object sender, EventArgs e)
        {
            PC = new PoloniexClient(publApi, privApi);
            PubpicApiKey.Text  = publApi;
            PrivateApiKey.Text = privApi;
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            markets = PC.Markets.GetSummaryAsync();

            pairsBase   = markets.Result.Keys.Select(i => i.BaseCurrency).Distinct().ToList();
            pairsQuota  = markets.Result.Keys.Select(i => i.QuoteCurrency).Distinct().OrderBy(s => s).ToList();
            pairsChange = markets.Result.Keys.Select(i => i.QuoteCurrency).Distinct().OrderBy(s => s).ToList();

            BaseCur.DataSource  = pairsBase;
            QuoteCur.DataSource = pairsQuota;

            startpair.DataSource   = pairsBase;
            startpairex.DataSource = pairsChange;

            sw.Stop();
            TimeControls.Text = "Time: " + sw.ElapsedMilliseconds / 100.0;
            if (tt)
            {
                makeTime.BackColor = Color.Red;
            }
            else
            {
                makeTime.BackColor = Color.Green;
            }
            MPeriod.SelectedIndex = 0;
        }
Exemple #4
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);
            }

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

            using (PoloniexClient lClient = aUseProxy ? new PoloniexClient(lPoloniexClientOptions) : new PoloniexClient())
            {
                var lResponse = lClient.Withdraw(aOrder.Market.SellingCurrencyInfo.Ticker, aOrder.SentQuantity, aAddress);
                if (!lResponse.Success)
                {
                    throw new Exception("Failed to refund order. Error message:" + lResponse.Error.Message);
                }
                if (!string.IsNullOrEmpty(lResponse.Data.error))
                {
                    throw new Exception($"Failed to refund order. Error message: {lResponse.Data.error}");
                }
            }

            return(true);
        }
Exemple #5
0
        private void DoUpdateMarketPrices(object aState)
        {
            try
            {
                var lChanged = new ConcurrentBag <string>();
                using (var lClient = new PoloniexClient())
                {
                    var lMarketsData = lClient.GetTickerMarkets();
                    if (!lMarketsData.Success)
                    {
                        throw new Exception("Unable to get updated market prices info");
                    }
                    Parallel.ForEach(lMarketsData.Data, (lMarketData) =>
                    {
                        string lMarketPairID = lMarketData.Key;
                        MarketPriceInfo lRemoteMarketPrice = new MarketPriceInfo
                        {
                            Last = lMarketData.Value.last,
                            Bid  = lMarketData.Value.highestBid,
                            Ask  = lMarketData.Value.lowestAsk
                        };

                        if ((FMarketPrices.TryGetValue(lMarketPairID, out MarketPriceInfo lPrice) && lPrice != lRemoteMarketPrice) || lPrice == null)
                        {
                            FMarketPrices.AddOrUpdate(lMarketPairID, lRemoteMarketPrice, (key, oldValue) => lRemoteMarketPrice);
                            lChanged.Add(lMarketPairID);
                        }
                    });
                }
Exemple #6
0
        private PoloniexCurrency GetPoloniexCurrency(string aTicker)
        {
            PoloniexCurrency lCurrency = null;

            if (!string.IsNullOrEmpty(aTicker) && !FCacheCurrencies.TryGetValue(aTicker, out lCurrency))
            {
                using (PoloniexClient lClient = new PoloniexClient())
                {
                    var lResponse = lClient.GetCurrencies();
                    if (!lResponse.Success)
                    {
                        throw new Exception($"Unable to retrieve Poloniex currency {aTicker}");
                    }
                    foreach (var lPoloniexCurrency in lResponse.Data)
                    {
                        FCacheCurrencies.AddOrUpdate(lPoloniexCurrency.Key, lPoloniexCurrency.Value, (x, y) => lPoloniexCurrency.Value);
                        if (lPoloniexCurrency.Key == aTicker)
                        {
                            lCurrency = lPoloniexCurrency.Value;
                        }
                    }
                }
            }
            return(lCurrency);
        }
Exemple #7
0
        public string GetDepositAddress(IExchangeMarket aMarket)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }
            string lResult;
            string lTicker = aMarket.SellingCurrencyInfo.Ticker;

            using (PoloniexClient lClient = new PoloniexClient())
            {
                var lResponse = lClient.GetDepositAddresses();
                if (!lResponse.Success)
                {
                    throw new Exception("Failed to retrieve Poloniex Address. " + lResponse.Error.Message);
                }
                if (lResponse.Data.TryGetValue(lTicker, out string lAddress))
                {
                    lResult = lAddress;
                }
                else
                {
                    var lNewAddressResponse = lClient.GenerateNewAddress(lTicker);
                    if (!lNewAddressResponse.Success || !Convert.ToBoolean(lNewAddressResponse.Data.success))
                    {
                        throw new Exception("Failed to retrieve Poloniex Address. " + lResponse.Error.Message);
                    }
                    lResult = lNewAddressResponse.Data.response;
                }
            }
            return(lResult);
        }
Exemple #8
0
        public static async Task <IList <Trade> > GetTradeHistory(this PoloniexClient client, DateTime?start = null, DateTime?end = null, Int32?limit = null)
        {
            Dictionary <String, Trade[]> CustomDeserializer(String value)
            {
                if (value == "[]")
                {
                    return(new Dictionary <String, Trade[]>());
                }

                return(JsonConvert.DeserializeObject <Dictionary <String, Trade[]> >(value));
            }

            var response = await client.SendRequestAsync <Dictionary <String, Trade[]> >(new PoloniexRequest
            {
                Api        = PoloniexApi.Trading,
                Command    = "returnTradeHistory",
                Parameters =
                {
                    { "currencyPair", "all"                               },
                    { "start",        start?.ToUnixTimestamp().ToString() },
                    { "end",          end?.ToUnixTimestamp().ToString()   },
                    { "limit",        limit?.ToString()                   }
                }
            }, CustomDeserializer);

            return(response.SelectMany(x =>
            {
                foreach (var value in x.Value)
                {
                    value.CurrencyPair = x.Key;
                }

                return x.Value;
            }).ToList());
        }
Exemple #9
0
        public async void TickerThread(ExchangeData Data)
        {
            InProgress = true;
            using (ApiClient = new PoloniexClient(ApiKey, ApiSecret))
            {
                ApiClient.OnError += (sender, error) =>
                {
                    Data.Status   = EnumData.ExchangeStatus.異常;
                    Data.ErrorMsg = error.Message;
                };

                ApiClient.OnClose += (sender, e) => { Data.Status = EnumData.ExchangeStatus.停止; };
                //USDT_BTC
                var SocketResult = ApiClient.SubscribeTicker(Data.ExchangeType, (data) =>
                {
                    Data.Ask        = data.Data.Ask;
                    Data.Bid        = data.Data.Bid;
                    Data.UpdateTime = DateTime.UtcNow;
                });

                if (!SocketResult.Status)
                {
                    throw new Exception(SocketResult.Message);
                }

                while (InProgress)
                {
                    Thread.Sleep(500);
                }

                ApiClient.UnsubscribeFromStream(SocketResult.Data);
            }
        }
Exemple #10
0
 private Poloniex(string apikey, string apisecret)
 {
     ApiKey     = apikey;
     ApiSecret  = apisecret;
     m_api      = new PoloniexClient(ApiKey, ApiSecret);
     m_instance = this;
 }
Exemple #11
0
 public static void Shutdown()
 {
     CLI.Manager.PrintLog("Global Shutdown Initiated");
     ThreadManager.KillNetwork();
     CLI.Manager.PrintLog("Clearing All Trade Data");
     Data.Store.ClearAllData();
     client = null;
 }
Exemple #12
0
        public void Clear()
        {
            var lClientOptions = new PoloniexClientOptions {
                ApiCredentials = null
            };

            PoloniexClient.SetDefaultOptions(lClientOptions);
            IsCredentialsSet = false;
        }
Exemple #13
0
        public MainWindow()
        {
            // Set icon from the assembly
            Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource();

            InitializeComponent();

            PoloniexClient = new PoloniexClient(ApiKeys.PublicKey, ApiKeys.PrivateKey);
            LoadMarketSummaryAsync();
        }
        public MainWindow()
        {
            // Set icon from the assembly
            Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource();
            
            InitializeComponent();

            PoloniexClient = new PoloniexClient(ApiKeys.PublicKey, ApiKeys.PrivateKey);
            LoadMarketSummaryAsync();
        }
Exemple #15
0
        public Form1()
        {
            InitializeComponent();
            PoloniexClient = new PoloniexClient("", "");

            Task t = Task.Run(() =>
            {
                GetValues();
            });
        }
 public MainViewModel(IDataService dataService)
 {
     myNotEmptyBalances = new Dictionary <string, Balance>();
     PoloniexClient     = new PoloniexClient(ApiKeys.PublicKey, ApiKeys.PrivateKey);
     LoadNotEmptyBalancesAsync();
     GetLastSysPrice();
     GetSysTrades();
     StartTimer();
     StartTime = DateTime.Now;
 }
Exemple #17
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();
 }
 public PoloniexService(
     PoloniexConfig poloniexConfig,
     ILogger <PoloniexService> log,
     DatabaseService databaseService,
     PriceService priceService)
 {
     _log             = log;
     _databaseService = databaseService;
     _priceService    = priceService;
     _poloniexClient  = new PoloniexClient(poloniexConfig.Key, poloniexConfig.Secret);
 }
 public PoloniexService(
     PoloniexConfig poloniexConfig,
     ILogger <PoloniexService> log,
     DatabaseService databaseService,
     GeneralConfig generalConfig)
 {
     _log             = log;
     _databaseService = databaseService;
     _generalConfig   = generalConfig;
     _poloniexClient  = new PoloniexClient(poloniexConfig.Key, poloniexConfig.Secret);
 }
Exemple #20
0
        public AccountPage() : base()
        {
            InitializeComponent();

            if (!int.TryParse(ConfigurationManager.AppSettings.Get("walletUpdateTimeMiliseconds"), out updateTimeMiliseconds))
            {
                MessageBox.Show("O parametro do App.Config walletUpdateTimeMiliseconds está setado com valor inválido, foi aplicado o valor padrão (" + updateTimeMiliseconds + ")!");
            }

            PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey);
        }
Exemple #21
0
        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    try
                    {
                        CancelTimer();

                        if (currencyItems != null)
                        {
                            currencyItems.Clear();
                        }


                        if (TradeHistoryWindow != null)
                        {
                            TradeHistoryWindow.Close();
                        }

                        if (chartWindow != null)
                        {
                            chartWindow.Close();
                        }

                        if (MarketService.Instance().TradesHistoryList != null)
                        {
                            MarketService.Instance().TradesHistoryList.Clear();
                        }

                        if (semaphoreSlim != null)
                        {
                            semaphoreSlim.Dispose();
                        }
                    }
                    finally
                    {
                        updateTimer        = null;
                        semaphoreSlim      = null;
                        PoloniexClient     = null;
                        currencyItems      = null;
                        TradeHistoryWindow = null;
                        chartWindow        = null;

                        MarketService.Instance().TradesHistoryList = null;

                        disposedValue = true;
                    }
                }
            }
        }
Exemple #22
0
        private async void btnBuy_Click(object sender, RoutedEventArgs e)
        {
            double amount = 0;
            double price  = 0;

            if (double.TryParse(txtAmount.Text, out amount))
            {
                if (double.TryParse(txtPrice.Text, out price))
                {
                    await PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey).Trading.PostOrderAsync(_currencyPair, OrderType.Buy, price, amount);
                }
            }
        }
Exemple #23
0
        public MainWindow()
        {
            InitializeComponent();

            //PoloniexClient = new PoloniexClient(ApiKeys.PublicKey, ApiKeys.PrivateKey);
            PoloniexClient = new PoloniexClient(Properties.Settings.Default.PublicKey, Properties.Settings.Default.PrivateKey);
            Application.Current.Properties.Add("PoloniexClient", PoloniexClient);
            //PoloniexClient = (PoloniexClient)Application.Current.Properties["PoloniexClient"];

            PoloniexClient.Live.Start();

            QuoteSymbolSelect.SelectionChanged += QuoteSymbolSelect_SelectionChanged;
            BaseSymbolSelect.SelectionChanged  += BaseSymbolSelect_SelectionChanged;
        }
Exemple #24
0
        public TradeHistory(CurrencyPair currencyPair, int _selectedIndex = 0)
        {
            InitializeComponent();

            // Set icon from the assembly
            this.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource();

            PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey);

            CurrencyPair = currencyPair;

            Title = string.Concat("Trade History", "(", CurrencyPair.ToString(), ")");
            tabControl.SelectedIndex = _selectedIndex;
        }
Exemple #25
0
        public Client()
        {
            PoloniexClient = new PoloniexClient(Properties.Settings.Default.PublicKey, Properties.Settings.Default.PrivateKey);

            if (!Application.Current.Properties.Contains("PoloniexClient"))
            {
                Application.Current.Properties.Add("PoloniexClient", PoloniexClient);
            }

            else
            {
                PoloniexClient = (PoloniexClient)Application.Current.Properties["PoloniexClient"];
            }
        }
Exemple #26
0
        public ChartLendingWindow(string currency)
        {
            InitializeComponent();

            // Set icon from the assembly
            Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource();

            PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey);

            Currency = currency;

            Title = string.Concat("Lending Candlestick ", "(", currency, ")");

            LoadChart();
        }
Exemple #27
0
        public ChartWindow(CurrencyPair currencyPair)
        {
            InitializeComponent();

            // Set icon from the assembly
            Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location).ToImageSource();

            PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey);

            CurrencyPair = currencyPair;

            Title = string.Concat("History ", "(", CurrencyPair.ToString(), ")");

            LoadChart();
        }
        public void Start()
        {
            //start live stream
            _api = new PoloniexClient(Url, PublicKey, PrivateKey);

            //get latest quotes to populate securities list
            List <Quote> quotes = null;

            Task.Run(async() => quotes = await _api.Markets.GetSummary()).Wait();
            if (quotes != null && quotes.Count > 0)
            {
                foreach (var q in quotes)
                {
                    if (Securities.All(i => i.Symbol != q.Symbol.ToString()))
                    {
                        var security = GetSecurityFromCurrencyPair(q.Symbol);
                        Securities.Add(security);
                        NewSecurity?.Invoke(security);
                        _securities[q.Symbol]        = security;
                        _securitiesById[q.Symbol.Id] = security;
                        Subscribe(security);
                    }
                }
            }
            else
            {
                throw new Exception($"No securities defined for {Name} data feed");
            }

            _api.Live.OnOrderBookUpdate += Api_OnOrderBookUpdate;
            _api.Live.OnTickerUpdate    += Api_OnTickerUpdate;
            _api.Live.OnSessionError    += Api_OnSessionError;
            _api.Live.Start();
            IsStarted = true;

            Task.Run(async() =>
            {
                var books = await _api.Markets.GetOrderBooks();
                lock (_orderBooks)
                {
                    _orderBooks.Clear();
                    foreach (var book in books)
                    {
                        _orderBooks.Add(book.Key, book.Value);
                    }
                }
            });
        }
Exemple #29
0
        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            if (!int.TryParse(ConfigurationManager.AppSettings.Get("exchangeUpdateTimeMiliseconds"), out updateTimeMiliseconds))
            {
                MessageBox.Show("O parametro do App.Config exchangeUpdateTimeMiliseconds está setado com valor inválido, foi aplicado o valor padrão (" + updateTimeMiliseconds + ")!");
            }

            switch (currentExchangeCoin)
            {
            case "XMR":
                selectedCurrency         = "XMR_LTC";
                exchangeBTCVolumeMinimun = 0;
                break;

            case "USDT":
                selectedCurrency         = "USDT_BTC";
                exchangeBTCVolumeMinimun = 0;
                break;

            case "ETH":
                selectedCurrency         = "ETH_LSK";
                exchangeBTCVolumeMinimun = 0;
                break;

            default:
                selectedCurrency = "BTC_ETH";
                if (!double.TryParse(ConfigurationManager.AppSettings.Get("exchangeBTCVolumeMinimun"), out exchangeBTCVolumeMinimun))
                {
                    MessageBox.Show("O parametro do App.Config exchangeBTCVolumeMinimun está setado com valor inválido, foi aplicado o valor padrão (3.1)!");
                    exchangeBTCVolumeMinimun = 3.1;
                }
                break;
            }
            PoloniexClient = PoloniexClient.Instance(ApiKeys.PublicKey, ApiKeys.PrivateKey);

            semaphoreSlim = new SemaphoreSlim(1);

            updateTimer = new Timer(UpdateGrid, null, 0, updateTimeMiliseconds);

            if (currencyItems == null)
            {
                currencyItems = new List <string>();
            }

            disposedValue = false;
        }
Exemple #30
0
        public decimal GetBalance(IExchangeMarket aMarket)
        {
            if (!IsCredentialsSet)
            {
                throw new Exception("No Credentials were set");
            }

            using (PoloniexClient lClient = new PoloniexClient())
            {
                var lResponse = lClient.GetBalances();
                if (!lResponse.Success || !lResponse.Data.TryGetValue(aMarket.SellingCurrencyInfo.Ticker, out decimal lBalance))
                {
                    throw new Exception("Failed to retrieve balance");
                }
                return(lBalance);
            }
        }
Exemple #31
0
        public async Task LoadLoanOffersAsync(PoloniexClient PoloniexClient)
        {
            await Task.Run(async() =>
            {
                PublicLoanOffersData lendings = null;
                LendingOffer firstLoanOffer   = null;

                try
                {
                    lendings       = await PoloniexClient.Lendings.GetLoanOffersAsync("BTC");
                    firstLoanOffer = lendings.offers.OrderBy(x => x.rate).First();

                    if (MarketService.Instance().MarketList != null)
                    {
                        if (MarketService.Instance().MarketList.Any())
                        {
                            double ethPriceLast = MarketService.Instance().MarketList.First(x => x.Key.ToString().ToUpper().Equals("BTC_ETH")).Value.PriceLast;
                            double btcPriceLast = MarketService.Instance().MarketList.First(x => x.Key.ToString().ToUpper().Equals("USDT_BTC")).Value.PriceLast;

                            firstLoanOffer.ethExchangeValue = ethPriceLast;
                            firstLoanOffer.btcExchangeValue = btcPriceLast;


                            string dolarValor = FachadaWSSGSService.Instance().getUltimoValorVOResponse.getUltimoValorVOReturn.ultimoValor.svalor;

                            string eth     = string.Concat("BTC/ETH: ", firstLoanOffer.ethExchangeValue.ToString("0.00000000"));
                            string btc     = string.Concat("USDT/BTC: ", firstLoanOffer.btcExchangeValue.ToString("0.000000"));
                            string loan    = string.Concat("BTC Loan Rate: ", firstLoanOffer.rate.ToString("0.00000%"));
                            string dolar   = string.Concat("USD: ", double.Parse(dolarValor.Replace(".", ",")).ToString("C2"));
                            string btcReal = string.Concat("BTC: ", (firstLoanOffer.btcExchangeValue * double.Parse(dolarValor.Replace(".", ","))).ToString("C2"));

                            txtDisplay.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart) delegate {
                                animation          = new DoubleAnimation((Application.Current.MainWindow.Width - 202), 0, TimeSpan.FromSeconds(10));
                                txtDisplay.Content = string.Concat(btc, "     ", eth, "     ", loan, "     ", dolar, "     ", btcReal);
                            });
                        }
                    }
                }
                finally
                {
                    lendings       = null;
                    firstLoanOffer = null;
                }
            });
        }