Пример #1
0
        public override IEnumerable <Candle> GetCandles(Coin baseCoin, Coin coin, int periodSeconds, DateTime?startDate = null, DateTime?endDate = null)
        {
            // https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400
            // [{"date":1405699200,"high":0.0045388,"low":0.00403001,"open":0.00404545,"close":0.00435873,"volume":44.34555992,"quoteVolume":10311.88079097,"weightedAverage":0.00430043}]
            string symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}");
            string url    = "/public?command=returnChartData&currencyPair=" + symbol;

            if (startDate != null)
            {
                url += "&start=" + (long)startDate.Value.UnixTimestampFromDateTimeSeconds();
            }
            url += "&end=" + (endDate == null ? long.MaxValue : (long)endDate.Value.UnixTimestampFromDateTimeSeconds());
            url += "&period=" + periodSeconds;
            JToken token = MakeJsonRequest <JToken>(url);

            CheckError(token);
            foreach (JToken candle in token)
            {
                yield return(new Candle
                {
                    ClosePrice = (decimal)candle["close"],
                    ExchangeName = Name,
                    HighPrice = (decimal)candle["high"],
                    LowPrice = (decimal)candle["low"],
                    OpenPrice = (decimal)candle["open"],
                    Name = symbol,
                    PeriodSeconds = periodSeconds,
                    Timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)candle["date"]),
                    VolumePrice = (double)candle["volume"],
                    VolumeQuantity = (double)candle["quoteVolume"],
                    WeightedAverage = (decimal)candle["weightedAverage"]
                });
            }
        }
Пример #2
0
        public override IEnumerable <Trade> GetHistoricalTrades(Coin baseCoin, Coin coin, DateTime?sinceDateTime = null)
        {
            string       symbol  = $"{baseCoin.Code}-{coin.Code}";
            string       baseUrl = "/0/public/Trades?pair=" + symbol;
            string       url;
            DateTime     timestamp;
            List <Trade> trades = new List <Trade>();

            while (true)
            {
                url = baseUrl;
                if (sinceDateTime != null)
                {
                    url += "&since=" + (long)(CryptoUtility.UnixTimestampFromDateTimeMilliseconds(sinceDateTime.Value) * 1000000.0);
                }
                JObject obj = MakeJsonRequest <JObject>(url);
                if (obj == null)
                {
                    break;
                }
                JToken result     = CheckError(obj);
                JArray outerArray = result[symbol] as JArray;
                if (outerArray == null || outerArray.Count == 0)
                {
                    break;
                }
                if (sinceDateTime != null)
                {
                    sinceDateTime = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(result["last"].Value <double>() / 1000000.0d);
                }
                foreach (JArray array in outerArray.Children <JArray>())
                {
                    timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds(array[2].Value <double>());
                    trades.Add(new Trade
                    {
                        Amount    = array[1].Value <decimal>(),
                        Price     = array[0].Value <decimal>(),
                        Timestamp = timestamp,
                        Id        = timestamp.Ticks,
                        IsBuy     = array[3].Value <char>() == 'b'
                    });
                }
                trades.Sort((t1, t2) => t1.Timestamp.CompareTo(t2.Timestamp));
                foreach (Trade t in trades)
                {
                    yield return(t);
                }
                trades.Clear();
                if (sinceDateTime == null)
                {
                    break;
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
Пример #3
0
        public override IEnumerable <Trade> GetHistoricalTrades(Coin baseCoin, Coin coin, DateTime?sinceDateTime = null)
        {
            string symbol  = $"{coin.Code}-{baseCoin.Code}";
            string baseUrl = "/products/" + symbol.ToUpperInvariant() + "/candles?granularity=" +
                             (sinceDateTime == null ? "30.0" : "1.0");
            string       url;
            List <Trade> trades = new List <Trade>();

            decimal[][] tradeChunk;
            while (true)
            {
                url = baseUrl;
                if (sinceDateTime != null)
                {
                    url += "&start=" +
                           HttpUtility.UrlEncode(sinceDateTime.Value.ToString("s",
                                                                              System.Globalization.CultureInfo.InvariantCulture));
                    url += "&end=" +
                           HttpUtility.UrlEncode(sinceDateTime.Value.AddMinutes(5.0)
                                                 .ToString("s", System.Globalization.CultureInfo.InvariantCulture));
                }
                tradeChunk = MakeJsonRequest <decimal[][]>(url);
                if (tradeChunk == null || tradeChunk.Length == 0)
                {
                    break;
                }
                if (sinceDateTime != null)
                {
                    sinceDateTime = CryptoUtility.UnixTimeStampToDateTimeSeconds((double)tradeChunk[0][0]);
                }
                foreach (decimal[] tradeChunkPiece in tradeChunk)
                {
                    trades.Add(new Trade
                    {
                        Amount    = tradeChunkPiece[5],
                        IsBuy     = true,
                        Price     = tradeChunkPiece[3],
                        Timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds((double)tradeChunkPiece[0]),
                        Id        = 0
                    });
                }
                trades.Sort((t1, t2) => t1.Timestamp.CompareTo(t2.Timestamp));
                foreach (Trade t in trades)
                {
                    yield return(t);
                }
                trades.Clear();
                if (sinceDateTime == null)
                {
                    break;
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
Пример #4
0
        public override ExchangeOrderResult GetOrderDetails(string orderId)
        {
            if (string.IsNullOrWhiteSpace(orderId))
            {
                return(null);
            }

            Dictionary <string, object> payload = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase)
            {
                { "txid", orderId },
                { "nonce", DateTime.UtcNow.Ticks }
            };
            JObject             obj         = MakeJsonRequest <JObject>("/0/private/QueryOrders", null, payload);
            JToken              result      = CheckError(obj);
            ExchangeOrderResult orderResult = new ExchangeOrderResult {
                OrderId = orderId
            };

            if (result == null || result[orderId] == null)
            {
                orderResult.Message = "Unknown Error";
                return(orderResult);
            }
            result = result[orderId];
            switch (result["status"].Value <string>())
            {
            case "pending": orderResult.Result = ExchangeAPIOrderResult.Pending; break;

            case "open": orderResult.Result = ExchangeAPIOrderResult.FilledPartially; break;

            case "closed": orderResult.Result = ExchangeAPIOrderResult.Filled; break;

            case "canceled":
            case "expired": orderResult.Result = ExchangeAPIOrderResult.Canceled; break;

            default: orderResult.Result = ExchangeAPIOrderResult.Error; break;
            }
            orderResult.Message      = (orderResult.Message ?? result["reason"].Value <string>());
            orderResult.OrderDate    = CryptoUtility.UnixTimeStampToDateTimeSeconds(result["opentm"].Value <double>());
            orderResult.Symbol       = result["descr"]["pair"].Value <string>();
            orderResult.IsBuy        = (result["descr"]["type"].Value <string>() == "buy");
            orderResult.Amount       = result["vol"].Value <decimal>();
            orderResult.AmountFilled = result["vol_exec"].Value <decimal>();
            orderResult.AveragePrice = result["price"].Value <decimal>();
            return(orderResult);
        }
Пример #5
0
        private ExchangeOrderResult ParseOrder(JToken order)
        {
            decimal amount       = order["original_amount"].Value <decimal>();
            decimal amountFilled = order["executed_amount"].Value <decimal>();

            return(new ExchangeOrderResult
            {
                Amount = amount,
                AmountFilled = amountFilled,
                AveragePrice = order["price"].Value <decimal>(),
                Message = string.Empty,
                OrderId = order["id"].Value <string>(),
                Result = (amountFilled == amount ? ExchangeAPIOrderResult.Filled : (amountFilled == 0 ? ExchangeAPIOrderResult.Pending : ExchangeAPIOrderResult.FilledPartially)),
                OrderDate = CryptoUtility.UnixTimeStampToDateTimeSeconds(order["timestamp"].Value <double>()),
                Symbol = order["symbol"].Value <string>(),
                IsBuy = order["side"].Value <string>() == "buy"
            });
        }
Пример #6
0
        public override IEnumerable <Trade> GetHistoricalTrades(Coin baseCoin, Coin coin, DateTime?sinceDateTime = null)
        {
            string symbol = $"{baseCoin.Code}-{coin.Code}";

            // [{"date": "1513387997", "tid": "33734815", "price": "0.01724547", "type": "1", "amount": "5.56481714"}]
            symbol = NormalizeSymbol(symbol);
            JToken token = MakeBitstampRequest("/transactions/" + symbol);

            foreach (JToken trade in token)
            {
                yield return(new Trade
                {
                    Amount = (decimal)trade["amount"],
                    Id = (long)trade["tid"],
                    IsBuy = (string)trade["type"] == "0",
                    Price = (decimal)trade["price"],
                    Timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)trade["date"])
                });
            }
        }
Пример #7
0
        public override IEnumerable <Candle> GetCandles(Coin baseCoin, Coin coin, int periodSeconds, DateTime?startDate = null, DateTime?endDate = null)
        {
            string symbol = NormalizeSymbol($"{baseCoin.Code}-{coin.Code}");

            // https://api.kraken.com/0/public/OHLC
            // pair = asset pair to get OHLC data for, interval = time frame interval in minutes(optional):, 1(default), 5, 15, 30, 60, 240, 1440, 10080, 21600, since = return committed OHLC data since given id(optional.exclusive)
            // array of array entries(<time>, <open>, <high>, <low>, <close>, <vwap>, <volume>, <count>)
            symbol    = NormalizeSymbol(symbol);
            startDate = startDate ?? DateTime.UtcNow.Subtract(TimeSpan.FromDays(1.0));
            endDate   = endDate ?? DateTime.UtcNow;
            JObject json = MakeJsonRequest <JObject>("/0/public/OHLC?pair=" + symbol + "&interval=" + periodSeconds / 60 + "&since=" + startDate);

            CheckError(json);
            if (json["result"].Children().Count() != 0)
            {
                JProperty prop = json["result"].Children().First() as JProperty;
                foreach (JArray jsonCandle in prop.Value)
                {
                    Candle candle = new Candle
                    {
                        ClosePrice      = (decimal)jsonCandle[4],
                        ExchangeName    = Name,
                        HighPrice       = (decimal)jsonCandle[2],
                        LowPrice        = (decimal)jsonCandle[3],
                        Name            = symbol,
                        OpenPrice       = (decimal)jsonCandle[1],
                        PeriodSeconds   = periodSeconds,
                        Timestamp       = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)jsonCandle[0]),
                        VolumePrice     = (double)jsonCandle[6],
                        VolumeQuantity  = (double)jsonCandle[6] * (double)jsonCandle[4],
                        WeightedAverage = (decimal)jsonCandle[5]
                    };
                    if (candle.Timestamp >= startDate.Value && candle.Timestamp <= endDate.Value)
                    {
                        yield return(candle);
                    }
                }
            }
        }
Пример #8
0
        public override Ticker GetTicker(Coin baseCoin, Coin coin)
        {
            string symbol = $"{baseCoin.Code}-{coin.Code}";

            // {"high": "0.10948945", "last": "0.10121817", "timestamp": "1513387486", "bid": "0.10112165", "vwap": "0.09958913", "volume": "9954.37332614", "low": "0.09100000", "ask": "0.10198408", "open": "0.10250028"}
            symbol = NormalizeSymbol(symbol);
            JToken token = MakeBitstampRequest("/ticker/" + symbol);

            return(new Ticker
            {
                Ask = (decimal)token["ask"],
                Bid = (decimal)token["bid"],
                Last = (decimal)token["last"],
                Volume = new ExchangeVolume
                {
                    PriceAmount = (decimal)token["volume"],
                    PriceSymbol = symbol,
                    QuantityAmount = (decimal)token["volume"] * (decimal)token["last"],
                    QuantitySymbol = symbol,
                    Timestamp = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)token["timestamp"])
                }
            });
        }
Пример #9
0
        public override IEnumerable <Candle> GetCandles(Coin baseCoin, Coin coin, int periodSeconds, DateTime?startDate = null, DateTime?endDate = null)
        {
            // /products/<product-id>/candles
            // https://api.gdax.com/products/LTC-BTC/candles?granularity=86400&start=2017-12-04T18:15:33&end=2017-12-11T18:15:33
            List <Candle> candles = new List <Candle>();
            string        symbol  = NormalizeSymbol($"{coin.Code}-{baseCoin.Code}");

            if (startDate == null)
            {
                startDate = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1.0));
            }

            if (endDate == null)
            {
                endDate = DateTime.UtcNow;
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("/products/");
            sb.Append(symbol);
            sb.Append("/candles?granularity=" + periodSeconds);
            sb.Append("&start=" +
                      HttpUtility.UrlEncode(startDate.Value.ToString("s",
                                                                     System.Globalization.CultureInfo.InvariantCulture)).ToUpper());
            sb.Append("&end=" +
                      HttpUtility.UrlEncode(endDate.Value.ToString("s",
                                                                   System.Globalization.CultureInfo.InvariantCulture)).ToUpper());

            // nightmare here with GDAX, they ignore the date in the url and return 350+ records
            // howvwer, if you hover over the sb.ToString() it will acknowledge the dates, wtf? I kid you not

            // time, low, high, open, close, volume
            try
            {
                JToken token = MakeJsonRequest <JToken>(sb.ToString());

                foreach (JArray candle in token)
                {
                    candles.Add(new Candle
                    {
                        ClosePrice     = (decimal)candle[4],
                        ExchangeName   = Name,
                        HighPrice      = (decimal)candle[2],
                        LowPrice       = (decimal)candle[1],
                        Name           = symbol,
                        OpenPrice      = (decimal)candle[3],
                        PeriodSeconds  = periodSeconds,
                        Timestamp      = CryptoUtility.UnixTimeStampToDateTimeSeconds((long)candle[0]),
                        VolumePrice    = (double)candle[5],
                        VolumeQuantity = (double)candle[5] * (double)candle[4]
                    });
                }
                // re-sort in ascending order
                candles.Sort((c1, c2) => c1.Timestamp.CompareTo(c2.Timestamp));
            }
            catch (Exception e)
            {
                throw e;
            }


            return(candles);
        }