Пример #1
0
        public static T2 ChangeType <T, T2>(this Binance exchange, ICurrencyFactory currencyFactory, ISymbolFactory symbolFactory, NameValueCollection postData, T obj)
        {
            if (typeof(T) == typeof(ICollection <BinancePriceTicker>))
            {
                var ticks = new List <MarketTick>();

                var priceTicks = obj as ICollection <BinancePriceTicker>;

                foreach (var tick in priceTicks)
                {
                    var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == tick.Symbol).FirstOrDefault();

                    var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                    var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);
                    var symbol            = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                    ticks.Add(new MarketTick
                    {
                        Exchange   = exchange.Name,
                        SymbolCode = symbol.Code,
                        Epoch      = Epoch.Now,
                        LastPrice  = tick.Price,
                    });
                }

                return((T2)(object)ticks);
            }

            if (typeof(T) == typeof(ICollection <BinanceOrderBookTicker>))
            {
                var ticks = new List <MarketTick>();

                var bookTicks = (obj as ICollection <BinanceOrderBookTicker>);

                foreach (var tick in bookTicks)
                {
                    var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == tick.Symbol).FirstOrDefault();

                    var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                    var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);
                    var symbol            = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                    ticks.Add(new MarketTick
                    {
                        Exchange   = exchange.Name,
                        SymbolCode = symbol.Code,
                        Epoch      = Epoch.Now,
                        BuyPrice   = tick.AskPrice,
                        SellPrice  = tick.BidPrice
                    });
                }

                return((T2)(object)ticks);
            }

            if (typeof(T2) == typeof(TradeResult))
            {
                var trades = obj as ICollection <Dictionary <string, object> >;

                var filter = trades.Count > 0 ? trades.Last()["a"].ToString() : postData["fromId"];

                var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == postData["symbol"]).FirstOrDefault();

                var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);
                var symbol            = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                return((T2)(object)new TradeResult
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Trades = trades.Select(t => new MarketTrade
                    {
                        Exchange = exchange.Name,
                        SymbolCode = symbol.Code,
                        Epoch = Epoch.FromMilliseconds(Convert.ToInt64(t["T"])),
                        Price = Convert.ToDecimal(t["p"]),
                        Volume = Convert.ToDecimal(t["q"]),
                        Side = Convert.ToBoolean(t["m"]) ? OrderSideEnum.Sell : OrderSideEnum.Buy,
                        SourceTradeId = Convert.ToString(t["a"])
                    }).ToList(),
                    Filter = filter
                });
            }

            if (typeof(T) == typeof(ICollection <BinanceTradeItem>))
            {
                var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == postData["symbol"]).FirstOrDefault();

                var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);

                var symbol = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                var trades = obj as ICollection <BinanceTradeItem>;

                return((T2)(object)trades.Select(t => new TradeItem
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Created = Epoch.FromMilliseconds(t.Time),
                    Id = t.Id.ToString(),
                    OrderId = t.OrderId.ToString(),
                    Fee = t.Commission,
                    FeeCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, t.CommissionAsset),
                    Price = t.Price,
                    Volume = t.Quantity,
                    Side = t.IsBuyer ? OrderSideEnum.Buy : OrderSideEnum.Sell
                }).ToList());
            }

            if (typeof(T) == typeof(BinanceNewOrder))
            {
                var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == postData["symbol"]).FirstOrDefault();

                var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);

                var symbol = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                var newOrder = obj as BinanceNewOrder;

                var orderType = exchange.GetOrderType(newOrder.Type);

                var price = orderType == OrderTypeEnum.Limit ? newOrder.Price : newOrder.Fills.Average(f => f.Price);

                return((T2)(object)new CreateOrder
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Id = newOrder.OrderId,
                    Side = exchange.GetOrderSide(newOrder.Side),
                    Type = orderType,
                    State = exchange.GetOrderState(newOrder.Status),
                    OrderEpoch = Epoch.FromMilliseconds(newOrder.TransactTime),
                    Price = price,
                    Volume = newOrder.OriginalQuantity
                });
            }

            if (typeof(T) == typeof(ICollection <BinanceOpenOrder>))
            {
                var binanceSymbol = exchange.Info.Symbols.Where(x => x.Symbol == postData["symbol"]).FirstOrDefault();

                var baseCurrencyCode  = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.BaseAsset);
                var quoteCurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, binanceSymbol.QuoteAsset);

                var symbol = symbolFactory.Get(baseCurrencyCode, quoteCurrencyCode);

                var openOrders = obj as ICollection <BinanceOpenOrder>;

                return((T2)(object)openOrders.Select(o => new OrderItem
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Id = o.OrderId,
                    Side = exchange.GetOrderSide(o.Side),
                    Type = exchange.GetOrderType(o.Type),
                    State = exchange.GetOrderState(o.Status),
                    OrderEpoch = Epoch.FromMilliseconds(o.Time),
                    Price = o.Price,
                    AvgPrice = o.Price,
                    Volume = o.OriginalQuantity,
                    RemainingVolume = o.OriginalQuantity - o.ExecutedQuantity
                }).ToList());
            }

            if (typeof(T) == typeof(BinanceCancelOrder))
            {
                var cancelOrder = obj as BinanceCancelOrder;

                return((T2)(object)new CancelOrder
                {
                    Exchange = exchange.Name,
                    Id = cancelOrder.OrderId,
                    Epoch = Epoch.FromMilliseconds(cancelOrder.TransactTime),
                    State = exchange.GetOrderState(cancelOrder.Status)
                });
            }

            if (typeof(T) == typeof(T2))
            {
                return((T2)(object)obj);
            }

            throw new Exception("Invalid type provided - " + typeof(T2));
        }
Пример #2
0
        public static T2 ChangeType <T, T2>(this Bitfinex exchange, ISymbolFactory symbolFactory, T obj, NameValueCollection query, NameValueCollection additionalData)
        {
            if (typeof(T2) == typeof(ICollection <MarketTick>))
            {
                var ticks = obj as List <object[]>;

                return((T2)(object)ticks.Select(t => new MarketTick
                {
                    Exchange = exchange.Name,
                    Epoch = new Epoch(DateTime.UtcNow),
                    SymbolCode = symbolFactory.Get(exchange.DecodeSymbol(t[0].ToString())[0], exchange.DecodeSymbol(t[0].ToString())[1]).Code,
                    BuyPrice = Convert.ToDecimal(t[1]),
                    SellPrice = Convert.ToDecimal(t[3]),
                    LastPrice = Convert.ToDecimal(t[7])
                }).ToList());
            }

            if (typeof(T2) == typeof(MarketTick))
            {
                var tick = obj as object[];

                var symbolCode = (SymbolCodeEnum)Enum.Parse(typeof(SymbolCodeEnum), additionalData["SymbolCode"]);

                return((T2)(object)new MarketTick
                {
                    Exchange = exchange.Name,
                    Epoch = new Epoch(DateTime.UtcNow),
                    SymbolCode = symbolCode,
                    BuyPrice = Convert.ToDecimal(tick[0]),
                    SellPrice = Convert.ToDecimal(tick[2]),
                    LastPrice = Convert.ToDecimal(tick[6])
                });
            }

            if (typeof(T2) == typeof(TradeResult))
            {
                var trades = obj as JArray;

                var filter = trades.Count > 0 ? Convert.ToString(trades.Max(t => t[1])) : query["start"];

                var symbolCode = (SymbolCodeEnum)Enum.Parse(typeof(SymbolCodeEnum), additionalData["SymbolCode"]);

                return((T2)(object)new TradeResult
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbolCode,
                    Trades = trades.Select(t => new MarketTrade
                    {
                        Exchange = exchange.Name,
                        SymbolCode = symbolCode,
                        Epoch = Epoch.FromMilliseconds(Convert.ToInt64(t[1])),
                        Price = Convert.ToDecimal(t[3]),
                        Volume = Math.Abs(Convert.ToDecimal(t[2])),
                        Side = Convert.ToDecimal(t[2]) > 0 ? OrderSideEnum.Buy : OrderSideEnum.Sell,
                        SourceTradeId = Convert.ToString(t[0])
                    }).OrderBy(t => t.Epoch.TimestampMilliseconds).ThenBy(t => t.SourceTradeId).ToList(),
                    Filter = filter
                });
            }

            if (typeof(T2) == typeof(ICollection <ExchangeStats>))
            {
                var tradeStats = (obj as List <BitfinexMarketStats>);

                var statKey    = (ExchangeStatsKeyEnum)Enum.Parse(typeof(ExchangeStatsKeyEnum), additionalData["StatKey"]);
                var symbolCode = (SymbolCodeEnum)Enum.Parse(typeof(SymbolCodeEnum), additionalData["SymbolCode"]);

                return((T2)(object)tradeStats.Select(t => new ExchangeStats
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbolCode,
                    StatKey = statKey,
                    Epoch = Epoch.FromMilliseconds(Convert.ToInt64(t[0])),
                    Value = Convert.ToDecimal(t[1])
                }).ToList());
            }

            if (typeof(T) == typeof(T2))
            {
                return((T2)(object)obj);
            }

            throw new Exception("Invalid type provided - " + typeof(T2));
        }
Пример #3
0
        public static T2 ChangeType <T, T2>(this Kraken exchange, ICurrencyFactory currencyFactory, ISymbolFactory symbolFactory, NameValueCollection postData, T obj)
        {
            if (typeof(T) == typeof(KrakenCancelOrderResult))
            {
                var cancelOrder = obj as KrakenCancelOrderResult;

                return((T2)(object)new CancelOrder());
            }

            if (typeof(T) == typeof(KrakenOrderQuery))
            {
                var orders = obj as KrakenOrderQuery;

                return((T2)(object)orders.Select(kvp => new OrderItem
                {
                    SymbolCode = symbolFactory.Get(exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[0], exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[1]).Code,
                    Id = kvp.Key,
                    OrderEpoch = Epoch.FromSeconds((long)kvp.Value.OpenTm),
                    Side = exchange.GetOrderSide(kvp.Value.Descr.Type),
                    Type = exchange.GetOrderType(kvp.Value.Descr.OrderType),
                    State = exchange.GetOrderState(kvp.Value.Status),
                    Price = exchange.GetOrderType(kvp.Value.Descr.OrderType) == OrderTypeEnum.Limit ? kvp.Value.LimitPrice : kvp.Value.Price,
                    AvgPrice = kvp.Value.Price,
                    Fee = kvp.Value.Fee,
                    Volume = kvp.Value.Volume,
                    RemainingVolume = kvp.Value.Volume - kvp.Value.VolumeExec
                }));
            }

            if (typeof(T) == typeof(KrakenOpenOrders))
            {
                var orders = obj as KrakenOpenOrders;

                return((T2)(object)orders.Open.Where(o => o.Value.Descr.Pair == postData["pair"]).Select(kvp => new OrderItem
                {
                    SymbolCode = symbolFactory.Get(exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[0], exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[1]).Code,
                    Id = kvp.Key,
                    OrderEpoch = Epoch.FromSeconds((long)kvp.Value.OpenTm),
                    Side = exchange.GetOrderSide(kvp.Value.Descr.Type),
                    Type = exchange.GetOrderType(kvp.Value.Descr.OrderType),
                    State = exchange.GetOrderState(kvp.Value.Status),
                    Price = exchange.GetOrderType(kvp.Value.Descr.OrderType) == OrderTypeEnum.Limit ? kvp.Value.LimitPrice : kvp.Value.Price,
                    AvgPrice = kvp.Value.Price,
                    Fee = kvp.Value.Fee,
                    Volume = kvp.Value.Volume,
                    RemainingVolume = kvp.Value.Volume - kvp.Value.VolumeExec
                }).ToList());
            }

            if (typeof(T) == typeof(KrakenClosedOrders))
            {
                var orders = obj as KrakenClosedOrders;

                return((T2)(object)orders.Closed.Where(o => o.Value.Descr.Pair == postData["pair"]).Select(kvp => new OrderItem
                {
                    SymbolCode = symbolFactory.Get(exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[0], exchange.DecodeAssetPair(kvp.Value.Descr.Pair)[1]).Code,
                    Id = kvp.Key,
                    OrderEpoch = Epoch.FromSeconds((long)kvp.Value.OpenTm),
                    Side = exchange.GetOrderSide(kvp.Value.Descr.Type),
                    Type = exchange.GetOrderType(kvp.Value.Descr.OrderType),
                    State = exchange.GetOrderState(kvp.Value.Status),
                    Price = exchange.GetOrderType(kvp.Value.Descr.OrderType) == OrderTypeEnum.Limit ? kvp.Value.LimitPrice : kvp.Value.Price,
                    AvgPrice = kvp.Value.Price,
                    Fee = kvp.Value.Fee,
                    Volume = kvp.Value.Volume,
                    RemainingVolume = kvp.Value.Volume - kvp.Value.VolumeExec
                }).ToList());
            }

            if (typeof(T) == typeof(KrakenAddOrderResult))
            {
                var order = obj as KrakenAddOrderResult;

                return((T2)(object)new CreateOrder
                {
                    Id = order.TxId.First(),
                    OrderEpoch = Epoch.Now,
                    SymbolCode = symbolFactory.Get(exchange.DecodeAssetPair(postData["pair"])[0], exchange.DecodeAssetPair(postData["pair"])[1]).Code,
                    Side = exchange.GetOrderSide(postData["type"]),
                    Type = exchange.GetOrderType(postData["ordertype"]),
                    Price = Convert.ToDecimal(postData["price"]),
                    Volume = Convert.ToDecimal(postData["volume"]),
                    State = OrderStateEnum.Pending
                });
            }

            if (typeof(T) == typeof(KrakenAccount))
            {
                var balance = obj as KrakenAccount;

                var assets = exchange.Assets;

                return((T2)(object)balance.Select(kvp => new AccountBalance
                {
                    CurrencyCode = exchange.GetStandardisedCurrencyCode(currencyFactory, assets[kvp.Key].AltName),
                    Balance = kvp.Value
                }).ToList());
            }

            if (typeof(T) == typeof(KrakenTradeHistory))
            {
                var assets = exchange.Assets;

                var assetPairs = exchange.AssetPairs;

                var trades = obj as KrakenTradeHistory;

                return((T2)(object)trades.Trades
                       .Where(kvp => postData["pair"] == $"{exchange.GetCurrencyCode(exchange.DecodeQuotePair(kvp.Value.Pair)[0])}{exchange.GetCurrencyCode(exchange.DecodeQuotePair(kvp.Value.Pair)[1])}")
                       .Select(kvp => new TradeItem
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbolFactory.Get(exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[kvp.Value.Pair].Base].AltName), exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[kvp.Value.Pair].Quote].AltName)).Code,
                    Id = kvp.Key,
                    OrderId = kvp.Value.OrderTxId,
                    Created = Epoch.FromSeconds(kvp.Value.Time),
                    Side = exchange.GetOrderSide(kvp.Value.Type),
                    Price = kvp.Value.Price,
                    Fee = kvp.Value.Fee,
                    Volume = kvp.Value.Volume
                }).ToList());
            }

            if (typeof(T) == typeof(KrakenTick))
            {
                var assets = exchange.Assets;

                var assetPairs = exchange.AssetPairs;

                var tick = (obj as KrakenTick).First();

                return((T2)(object)new MarketTick
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbolFactory.Get(exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[tick.Key].Base].AltName), exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[tick.Key].Quote].AltName)).Code,
                    Epoch = Epoch.Now,
                    BuyPrice = tick.Value.Ask.First(),
                    SellPrice = tick.Value.Bid.First(),
                    LastPrice = tick.Value.Last.First()
                });
            }

            if (typeof(T) == typeof(KrakenTicks))
            {
                var assets = exchange.Assets;

                var assetPairs = exchange.AssetPairs;

                var ticks = obj as KrakenTicks;

                return((T2)(object)ticks.Select(kvp => new MarketTick
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbolFactory.Get(exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[kvp.Key].Base].AltName), exchange.GetStandardisedCurrencyCode(currencyFactory, assets[assetPairs[kvp.Key].Quote].AltName)).Code,
                    Epoch = Epoch.Now,
                    BuyPrice = kvp.Value.Ask.First(),
                    SellPrice = kvp.Value.Bid.First(),
                    LastPrice = kvp.Value.Last.First()
                }).ToList());
            }

            if (typeof(T) == typeof(KrakenOrderBook))
            {
                var book = (obj as KrakenOrderBook).First();

                var pair = exchange.DecodeAssetPair(postData["pair"]);

                var symbol = symbolFactory.Get(pair[0], pair[1]);

                return((T2)(object)new OrderBook
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Ask = book.Value.Asks.Select(a => new OrderBookItem
                    {
                        Price = a.ElementAt(0),
                        AvgPrice = a.ElementAt(0),
                        Volume = a.ElementAt(1),
                        OrderTime = Epoch.FromSeconds((long)a.ElementAt(2)).DateTime
                    }).ToList(),
                    Bid = book.Value.Bids.Select(a => new OrderBookItem
                    {
                        Price = a.ElementAt(0),
                        Volume = a.ElementAt(1),
                        OrderTime = Epoch.FromSeconds((long)a.ElementAt(2)).DateTime
                    }).ToList()
                });
            }

            if (typeof(T) == typeof(KrakenTradeVolume))
            {
                var tradeVol = (obj as KrakenTradeVolume);

                var takerFee = tradeVol.Fees.First().Value.Fee;

                return((T2)(object)new TradeFee
                {
                    CurrencyCode = CurrencyCodeEnum.USD,
                    Taker = takerFee / 100.0m,
                    Maker = (tradeVol.FeesMaker != null && tradeVol.FeesMaker.Count > 0 ? tradeVol.FeesMaker.First().Value.Fee : takerFee) / 100.0m
                });
            }

            if (typeof(T) == typeof(KrakenTrade <string, List <List <object> > >))
            {
                var tradeResult = (obj as KrakenTrade <string, List <List <object> > >);

                var pair = exchange.DecodeAssetPair(postData["pair"]);

                var symbol = symbolFactory.Get(pair[0], pair[1]);

                return((T2)(object)new TradeResult
                {
                    Exchange = exchange.Name,
                    SymbolCode = symbol.Code,
                    Filter = Convert.ToString(tradeResult.Last),
                    Trades = tradeResult.First().Value.Select(t => new MarketTrade
                    {
                        Exchange = exchange.Name,
                        SymbolCode = symbol.Code,
                        Epoch = Epoch.FromSeconds(Convert.ToDouble(t[2])),
                        Price = Convert.ToDecimal(t[0]),
                        Volume = Convert.ToDecimal(t[1]),
                        Side = Convert.ToString(t[3]) == "b" ? OrderSideEnum.Buy : OrderSideEnum.Sell
                    }).ToList()
                });
            }

            if (typeof(T) == typeof(T2))
            {
                return((T2)(object)obj);
            }

            throw new Exception("Invalid type provided - " + typeof(T2));
        }