Example #1
0
        public void GetTicker(BitFinexTicker info) {
            string address = string.Format("https://bittrex.com/api/v1.1/public/getticker?market={0}", Uri.EscapeDataString(info.MarketName));
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch(Exception) {
                return;
            }
            if(bytes == null)
                return;

            int startIndex = 1;
            if(!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
                return;

            string[] res = JSonHelper.Default.DeserializeObject(bytes, ref startIndex, new string[] { "Bid", "Ask", "Last" });
            if(res == null)
                return;
            info.HighestBid = FastValueConverter.Convert(res[0]);
            info.LowestAsk = FastValueConverter.Convert(res[1]);
            info.Last = FastValueConverter.Convert(res[2]);
            info.Time = DateTime.UtcNow;
            info.UpdateHistoryItem();
        }
Example #2
0
        public override bool UpdateCurrencies() {
            string address = "https://bittrex.com/api/v1.1/public/getcurrencies";
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch(Exception) {
                return false;
            }
            if(bytes == null)
                return false;

            int startIndex = 1;
            if(!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
                return false;

            List<string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Currency", "CurrencyLong", "MinConfirmation", "TxFee", "IsActive", "CoinType", "BaseAddress", "Notice" });
            for(int i = 0; i < res.Count; i++) {
                string[] item = res[i];
                string currency = item[0];
                BitFinexCurrencyInfo c = (BitFinexCurrencyInfo)Currencies.FirstOrDefault(curr => curr.Currency == currency);
                if(c == null) {
                    c = new BitFinexCurrencyInfo();
                    c.Currency = item[0];
                    c.CurrencyLong = item[1];
                    c.MinConfirmation = int.Parse(item[2]);
                    c.TxFee = FastValueConverter.Convert(item[3]);
                    c.CoinType = item[5];
                    c.BaseAddress = item[6];
                    Currencies.Add(c);
                }
                c.IsActive = item[4].Length == 4;
            }
            return true;
        }
Example #3
0
        public override bool UpdateTicker(Ticker tickerBase) {
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(string.Format("https://api.bitfinex.com/v2/ticker/{0}", ((BitFinexTicker)tickerBase).MarketName));
            }
            catch(Exception e) {
                Debug.WriteLine(e.ToString());
                return false;
            }
            if(bytes == null)
                return false;

            int startIndex = 0;
            string[] item = JSonHelper.Default.DeserializeArray(bytes, ref startIndex, 9);

            BitFinexTicker ticker = (BitFinexTicker)tickerBase;
            ticker.HighestBid = FastValueConverter.Convert(item[0]);
            ticker.LowestAsk = FastValueConverter.Convert(item[2]);
            ticker.Change = FastValueConverter.Convert(item[4]);
            ticker.Last = FastValueConverter.Convert(item[5]);
            ticker.Volume = FastValueConverter.Convert(item[6]);
            ticker.Hr24High = FastValueConverter.Convert(item[7]);
            ticker.Hr24Low = FastValueConverter.Convert(item[8]);
            ticker.Time = DateTime.Now;
            ticker.UpdateHistoryItem();

            return true;
        }
Example #4
0
        public override bool UpdateTickersInfo() {
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(TickersUpdateAddress);
            }
            catch(Exception e) {
                Debug.WriteLine(e.ToString());
                return false;
            }
            if(bytes == null)
                return false;

            int startIndex = 0;
            List<string[]> list = JSonHelper.Default.DeserializeArrayOfArrays(bytes, ref startIndex, 11);
            for(int i = 0; i < list.Count; i++) {
                string[] item = list[i];
                BitFinexTicker ticker = (BitFinexTicker)Tickers.FirstOrDefault(t => t.CurrencyPair == item[0]);
                ticker.HighestBid = FastValueConverter.Convert(item[1]);
                ticker.LowestAsk = FastValueConverter.Convert(item[3]);
                ticker.Change = FastValueConverter.Convert(item[6]);
                ticker.Last = FastValueConverter.Convert(item[7]);
                ticker.Volume = FastValueConverter.Convert(item[8]);
                ticker.Hr24High = FastValueConverter.Convert(item[9]);
                ticker.Hr24Low = FastValueConverter.Convert(item[10]);
            }
            return true;
        }
 public TradingResult OnTradingResult(AccountInfo account, Ticker ticker, string text)
 {
     try {
         JObject obj   = JsonConvert.DeserializeObject <JObject>(text);
         JObject error = obj.Value <JObject>("error");
         if (error != null)
         {
             LogManager.Default.Error(this, "trade", error.Value <string>("message"));
             return(null);
         }
         TradingResult res = new TradingResult();
         res.OrderId     = obj.Value <string>("orderID");
         res.Date        = Convert.ToDateTime(obj.Value <string>("transactTime"));
         res.Amount      = FastValueConverter.Convert(obj.Value <string>("orderQty"));
         res.Type        = obj.Value <string>("side")[0] == 'B' ? OrderType.Buy : OrderType.Sell;
         res.Value       = FastValueConverter.Convert(obj.Value <string>("price"));
         res.OrderStatus = obj.Value <string>("ordStatus");
         res.Filled      = res.OrderStatus == "Filled";
         res.Total       = res.Amount;
         return(res);
     }
     catch (Exception e) {
         Telemetry.Default.TrackException(e);
         return(null);
     }
 }
        protected void On24HourTickerRecv(string[] item)
        {
            string symbolName = item[2];
            Ticker first      = null;

            for (int i = 0; i < Tickers.Count; i++)
            {
                Ticker tt = Tickers[i];
                if (tt.Name == symbolName)
                {
                    first = tt;
                    break;
                }
            }
            BinanceTicker t = (BinanceTicker)first;

            if (t == null)
            {
                throw new DllNotFoundException("binance symbol not found " + symbolName);
            }
            t.Change     = FastValueConverter.Convert(item[4]);
            t.HighestBid = FastValueConverter.Convert(item[9]);
            t.LowestAsk  = FastValueConverter.Convert(item[11]);
            t.Hr24High   = FastValueConverter.Convert(item[14]);
            t.Hr24Low    = FastValueConverter.Convert(item[15]);
            t.BaseVolume = FastValueConverter.Convert(item[16]);
            t.Volume     = FastValueConverter.Convert(item[17]);

            t.UpdateTrailings();

            lock (t) {
                RaiseTickerChanged(t);
            }
        }
        protected virtual void OnKlineItemRecv(Ticker ticker, string[] item)
        {
            long     dt   = FastValueConverter.ConvertPositiveLong(item[0]);
            DateTime time = FromUnixTime(dt);
            CandleStickIntervalInfo info = null;

            for (int ci = 0; ci < AllowedCandleStickIntervals.Count; ci++)
            {
                CandleStickIntervalInfo i = AllowedCandleStickIntervals[ci];
                if (i.Command == item[3])
                {
                    info = i;
                    break;
                }
            }
            if (ticker.CandleStickPeriodMin != info.Interval.TotalMinutes)
            {
                return;
            }
            //Debug.WriteLine(item[6] + " " + item[7] + " " + item[8] + " " + item[9]);
            lock (ticker.CandleStickData) {
                CandleStickData data = new CandleStickData();
                data.Time        = time;
                data.Open        = FastValueConverter.Convert(item[6]);
                data.Close       = FastValueConverter.Convert(item[7]);
                data.High        = FastValueConverter.Convert(item[8]);
                data.Low         = FastValueConverter.Convert(item[9]);
                data.Volume      = FastValueConverter.Convert(item[10]);
                data.QuoteVolume = FastValueConverter.Convert(item[13]);
                ticker.UpdateCandleStickData(data);
            }
        }
Example #8
0
        public override bool UpdateBalances(AccountInfo account)
        {
            if (Currencies.Count == 0)
            {
                if (!GetCurrenciesInfo())
                {
                    return(false);
                }
            }
            string    address = string.Format("https://bittrex.com/api/v1.1/account/getbalances?apikey={0}&nonce={1}", Uri.EscapeDataString(account.ApiKey), GetNonce());
            WebClient client  = GetWebClient();

            client.Headers.Clear();
            client.Headers.Add("apisign", account.GetSign(address));
            try {
                byte[] bytes = client.DownloadData(address);


                if (bytes == null)
                {
                    return(false);
                }

                int startIndex = 1;
                if (!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
                {
                    return(false);
                }

                List <string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] {
                    "Currency",
                    "Balance",
                    "Available",
                    "Pending",
                    "CryptoAddress"
                });

                foreach (string[] item in res)
                {
                    BitFinexAccountBalanceInfo binfo = (BitFinexAccountBalanceInfo)account.Balances.FirstOrDefault(b => b.Currency == item[0]);
                    if (binfo == null)
                    {
                        binfo          = new BitFinexAccountBalanceInfo(account);
                        binfo.Currency = item[0];
                        account.Balances.Add(binfo);
                    }
                    //info.Balance = FastDoubleConverter.Convert(item[1]);
                    binfo.Available = FastValueConverter.Convert(item[2]);
                    //info.Pending = FastDoubleConverter.Convert(item[3]);
                    binfo.DepositAddress = item[4];
                }
            }
            catch (Exception) {
                return(false);
            }
            return(true);
        }
Example #9
0
        public override bool UpdateTrades(Ticker info)
        {
            string address = string.Format("https://bittrex.com/api/v1.1/public/getmarkethistory?market={0}", Uri.EscapeDataString(info.MarketName));

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(false);
            }
            if (bytes == null)
            {
                return(false);
            }

            int startIndex = 1;

            if (!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
            {
                return(false);
            }

            long            lastId       = info.TradeHistory.Count > 0 ? info.TradeHistory.First().Id : -1;
            string          lastIdString = lastId.ToString();
            List <string[]> res          = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Id", "TimeStamp", "Quantity", "Price", "Total", "FillType", "OrderType" },
                                                                                        (itemIndex, paramIndex, value) => {
                return(paramIndex != 0 || lastIdString != value);
            });

            if (res == null || res.Count == 0)
            {
                return(true);
            }

            int index = 0;

            lock (info) {
                foreach (string[] obj in res)
                {
                    TradeInfoItem item = new TradeInfoItem(null, info);
                    item.Id           = Convert.ToInt64(obj[0]);
                    item.Time         = Convert.ToDateTime(obj[1]);
                    item.AmountString = obj[2];
                    item.RateString   = obj[3];
                    item.Total        = FastValueConverter.Convert(obj[4]);
                    item.Type         = obj[6].Length == 3 ? TradeType.Buy : TradeType.Sell;
                    item.Fill         = obj[5].Length == 4 ? TradeFillType.Fill : TradeFillType.PartialFill;
                    info.TradeHistory.Insert(index, item);
                    index++;
                }
            }
            info.RaiseTradeHistoryAdd();
            return(true);
        }
Example #10
0
        public override List <TradeInfoItem> GetTrades(Ticker info, DateTime starTime)
        {
            string address = string.Format("https://bittrex.com/api/v1.1/public/getmarkethistory?market={0}", Uri.EscapeDataString(info.MarketName));

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(null);
            }
            if (bytes == null)
            {
                return(null);
            }

            int startIndex = 1;

            if (!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
            {
                return(null);
            }

            List <string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Id", "TimeStamp", "Quantity", "Price", "Total", "FillType", "OrderType" },
                                                                               (itemIndex, paramIndex, value) => {
                return(paramIndex != 1 || Convert.ToDateTime(value) >= starTime);
            });

            if (res == null)
            {
                return(null);
            }
            List <TradeInfoItem> list = new List <TradeInfoItem>();

            int index = 0;

            foreach (string[] obj in res)
            {
                TradeInfoItem item = new TradeInfoItem(null, info);
                item.Id           = Convert.ToInt64(obj[0]);
                item.Time         = Convert.ToDateTime(obj[1]);
                item.AmountString = obj[2];
                item.RateString   = obj[3];
                item.Total        = FastValueConverter.Convert(obj[4]);
                item.Type         = obj[6].Length == 3 ? TradeType.Buy : TradeType.Sell;
                item.Fill         = obj[5].Length == 4 ? TradeFillType.Fill : TradeFillType.PartialFill;
                list.Insert(index, item);
                index++;
            }
            return(list);
        }
        public override BindingList <CandleStickData> GetCandleStickData(Ticker ticker, int candleStickPeriodMin, DateTime startUtc, long periodInSeconds)
        {
            long startSec = (long)(startUtc.Subtract(epoch)).TotalSeconds;
            long end      = startSec + periodInSeconds;
            CandleStickIntervalInfo info = AllowedCandleStickIntervals.FirstOrDefault(i => i.Interval.TotalMinutes == candleStickPeriodMin);

            string address = string.Format("https://api.binance.com/api/v1/klines?symbol={0}&interval={1}&startTime={2}&endTime={3}&limit=10000",
                                           Uri.EscapeDataString(ticker.CurrencyPair), info.Command, startSec * 1000, end * 1000);

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(null);
            }
            if (bytes == null || bytes.Length == 0)
            {
                return(null);
            }

            DateTime startTime = epoch;

            BindingList <CandleStickData> list = new BindingList <CandleStickData>();
            int             startIndex         = 0;
            List <string[]> res = JSonHelper.Default.DeserializeArrayOfArrays(bytes, ref startIndex, 12);

            if (res == null)
            {
                return(list);
            }
            foreach (string[] item in res)
            {
                CandleStickData data = new CandleStickData();
                data.Time          = startTime.AddMilliseconds(FastValueConverter.ConvertPositiveLong(item[0])).ToLocalTime();
                data.Open          = FastValueConverter.Convert(item[1]);
                data.High          = FastValueConverter.Convert(item[2]);
                data.Low           = FastValueConverter.Convert(item[3]);
                data.Close         = FastValueConverter.Convert(item[4]);
                data.Volume        = FastValueConverter.Convert(item[5]);
                data.QuoteVolume   = FastValueConverter.Convert(item[7]);
                data.BuyVolume     = FastValueConverter.Convert(item[9]);
                data.SellVolume    = data.Volume - data.BuyVolume;
                data.BuySellVolume = data.BuyVolume - data.SellVolume;
                list.Add(data);
            }

            //List<TradeInfoItem> trades = GetTradeVolumesForCandleStick(ticker, startSec * 1000, end * 1000);
            //CandleStickChartHelper.InitializeVolumes(list, trades, ticker.CandleStickPeriodMin);
            return(list);
        }
Example #12
0
        public override BindingList <CandleStickData> GetCandleStickData(Ticker ticker, int candleStickPeriodMin, DateTime start, long periodInSeconds)
        {
            long startSec = (long)(start.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            long end      = startSec + periodInSeconds;

            string address = string.Format("https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName={0}&tickInterval={1}&_={2}",
                                           Uri.EscapeDataString(ticker.CurrencyPair), GetInvervalCommand(candleStickPeriodMin), GetNonce());

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(null);
            }
            if (bytes == null || bytes.Length == 0)
            {
                return(null);
            }

            BindingList <CandleStickData> list = new BindingList <CandleStickData>();

            int startIndex = 1;

            if (!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
            {
                return(list);
            }

            List <string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "O", "H", "L", "C", "V", "T", "BV" });

            if (res == null)
            {
                return(list);
            }
            foreach (string[] item in res)
            {
                CandleStickData data = new CandleStickData();
                data.Time            = Convert.ToDateTime(item[5]);
                data.High            = FastValueConverter.Convert(item[1]);
                data.Low             = FastValueConverter.Convert(item[2]);
                data.Open            = FastValueConverter.Convert(item[0]);
                data.Close           = FastValueConverter.Convert(item[3]);
                data.Volume          = FastValueConverter.Convert(item[6]);
                data.QuoteVolume     = FastValueConverter.Convert(item[4]);
                data.WeightedAverage = 0;
                list.Add(data);
            }
            return(list);
        }
Example #13
0
 protected override void On24HourTickerRecvCore(BinanceTicker t, string[] item)
 {
     if (t == null)
     {
         throw new DllNotFoundException("binance symbol not found " + item[2]);
     }
     t.Change     = FastValueConverter.Convert(item[4]);
     t.HighestBid = 0;
     t.LowestAsk  = 0;
     t.Last       = FastValueConverter.Convert(item[6]);
     t.Hr24High   = FastValueConverter.Convert(item[9]);
     t.Hr24Low    = FastValueConverter.Convert(item[10]);
     t.BaseVolume = FastValueConverter.Convert(item[11]);
     t.Volume     = FastValueConverter.Convert(item[12]);
 }
Example #14
0
        bool OnGetAccountTrades(AccountInfo account, Ticker ticker, byte[] bytes) {
            if(bytes == null)
                return false;

            int startIndex = 1;
            if(!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
                return false;

            string tradeUuid = ticker.MyTradeHistory.Count == 0 ? null : ticker.MyTradeHistory.First().IdString;
            List<string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] {
                "OrderUuid", // 0
                "Exchange",  // 1
                "TimeStamp",  // 2
                "OrderType", // 3
                "Limit",     // 4
                "Quantity",  // 5
                "QuantityRemaining", // 6
                "Commission", // 7
                "Price",  // 8
                "PricePerUnit",  // 9
                "IsConditional",
                "Condition",
                "ConditionTarget",
                "ImmediateOrCancel",
            },
            (itemIndex, paramIndex, value) => {
                return paramIndex != 0 || value != tradeUuid;
            });
            if(res == null)
                return false;
            if(res.Count == 0)
                return true;
            int index = 0;
            for(int i = 0; i < res.Count; i++) {
                string[] obj = res[i];
                TradeInfoItem item = new TradeInfoItem(account, ticker);
                item.IdString = obj[0];
                item.Type = obj[3] == "LIMIT_BUY" ? TradeType.Buy : TradeType.Sell;
                item.AmountString = obj[5];
                item.RateString = obj[9];
                item.Fee = FastValueConverter.Convert(obj[7]);
                item.Total = FastValueConverter.Convert(obj[8]);
                item.TimeString = obj[2];
                ticker.MyTradeHistory.Insert(index, item);
                index++;
            }
            return true;
        }
Example #15
0
        public bool GetTrades(BitFinexTicker info)
        {
            string address = string.Format("https://bittrex.com/api/v1.1/public/getmarkethistory?market={0}", Uri.EscapeDataString(info.MarketName));

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(false);
            }
            if (bytes == null)
            {
                return(false);
            }

            int startIndex = 1;

            if (!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
            {
                return(false);
            }

            List <string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Id", "TimeStamp", "Quantity", "Price", "Total", "FillType", "OrderType" });

            if (res == null)
            {
                return(false);
            }
            lock (info) {
                info.TradeHistory.Clear();
                foreach (string[] obj in res)
                {
                    TradeInfoItem item = new TradeInfoItem(null, info);
                    item.Id           = Convert.ToInt64(obj[0]);;
                    item.Time         = Convert.ToDateTime(obj[1]);
                    item.AmountString = obj[2];
                    item.RateString   = obj[3];
                    item.Total        = FastValueConverter.Convert(obj[4]);
                    item.Type         = obj[6].Length == 3 ? TradeType.Buy : TradeType.Sell;
                    item.Fill         = obj[5].Length == 4 ? TradeFillType.Fill : TradeFillType.PartialFill;
                    info.TradeHistory.Add(item);
                }
            }
            info.RaiseTradeHistoryAdd();
            return(true);
        }
Example #16
0
        public bool UpdateOrderBook(Ticker ticker, byte[] bytes, bool raiseChanged, int depth)
        {
            if (bytes == null)
            {
                return(false);
            }

            int startIndex = 0;

            List <string[]> items = JSonHelper.Default.DeserializeArrayOfArrays(bytes, ref startIndex, 3);

            ticker.OrderBook.GetNewBidAsks();
            int bidIndex = 0, askIndex = 0;
            List <OrderBookEntry> bids = ticker.OrderBook.Bids;
            List <OrderBookEntry> asks = ticker.OrderBook.Asks;

            foreach (string[] item in items)
            {
                OrderBookEntry entry = null;
                if (item[2][0] == '-')
                {
                    entry        = asks[askIndex];
                    entry.Amount = -FastValueConverter.Convert(item[2]);
                    askIndex++;
                }
                else
                {
                    entry = bids[bidIndex];
                    entry.AmountString = item[2];
                    bidIndex++;
                }
                entry.ValueString = item[0];

                if (bidIndex >= bids.Count || askIndex >= asks.Count)
                {
                    break;
                }
            }
            ticker.OrderBook.UpdateEntries();
            return(true);
        }
        protected virtual void OnKlineItemRecv(Ticker ticker, string[] item)
        {
            long     dt   = FastValueConverter.ConvertPositiveLong(item[0]);
            DateTime time = FromUnixTime(dt);
            CandleStickIntervalInfo info = AllowedCandleStickIntervals.FirstOrDefault(i => i.Command == item[3]);

            if (ticker.CandleStickPeriodMin != info.Interval.TotalMinutes)
            {
                return;
            }
            Debug.WriteLine(item[6] + " " + item[7] + " " + item[8] + " " + item[9]);
            lock (ticker.CandleStickData) {
                CandleStickData data = ticker.GetOrCreateCandleStickData(time);
                data.Open        = FastValueConverter.Convert(item[6]);
                data.Close       = FastValueConverter.Convert(item[7]);
                data.High        = FastValueConverter.Convert(item[8]);
                data.Low         = FastValueConverter.Convert(item[9]);
                data.Volume      = FastValueConverter.Convert(item[10]);
                data.QuoteVolume = FastValueConverter.Convert(item[13]);
                ticker.RaiseCandleStickChanged();
            }
        }
Example #18
0
        public bool OnUpdateOrderBook(Ticker ticker, byte[] bytes, bool raiseChanged, int depth) {
            if(bytes == null)
                return false;

            int startIndex = 0;

            List<string[]> items = JSonHelper.Default.DeserializeArrayOfArrays(bytes, ref startIndex, 3);

            ticker.OrderBook.BeginUpdate();
            try {
                ticker.OrderBook.GetNewBidAsks();
                int bidIndex = 0, askIndex = 0;
                List<OrderBookEntry> bids = ticker.OrderBook.Bids;
                List<OrderBookEntry> asks = ticker.OrderBook.Asks;
                for(int i = 0; i < items.Count; i++) {
                    string[] item = items[i];
                    OrderBookEntry entry = null;
                    if(item[2][0] == '-') {
                        entry = asks[askIndex];
                        entry.Amount = -FastValueConverter.Convert(item[2]);
                        askIndex++;
                    }
                    else {
                        entry = bids[bidIndex];
                        entry.AmountString = item[2];
                        bidIndex++;
                    }
                    entry.ValueString = item[0];
                    if(bidIndex >= bids.Count || askIndex >= asks.Count)
                        break;
                }
            }
            finally {
                ticker.OrderBook.IsDirty = false;
                ticker.OrderBook.EndUpdate();
            }
            return true;
        }
        protected void On24HourTickerRecv(string[] item)
        {
            string        symbolName = item[2];
            BinanceTicker t          = (BinanceTicker)Tickers.FirstOrDefault(tt => tt.Name == symbolName);

            if (t == null)
            {
                throw new DllNotFoundException("binance symbol not found " + symbolName);
            }
            t.Change     = FastValueConverter.Convert(item[4]);
            t.HighestBid = FastValueConverter.Convert(item[9]);
            t.LowestAsk  = FastValueConverter.Convert(item[11]);
            t.Hr24High   = FastValueConverter.Convert(item[14]);
            t.Hr24Low    = FastValueConverter.Convert(item[15]);
            t.BaseVolume = FastValueConverter.Convert(item[16]);
            t.Volume     = FastValueConverter.Convert(item[17]);

            t.UpdateTrailings();

            lock (t) {
                RaiseTickerUpdate(t);
            }
        }
        protected void OnTickersInfoRecv(JObject jObject)
        {
            JArray items = jObject.Value <JArray>("data");

            if (items == null)
            {
                return;
            }
            for (int i = 0; i < items.Count; i++)
            {
                JObject item       = (JObject)items[i];
                string  tickerName = item.Value <string>("symbol");
                Ticker  first      = null;
                for (int index = 0; index < Tickers.Count; index++)
                {
                    Ticker tt = Tickers[index];
                    if (tt.CurrencyPair == tickerName)
                    {
                        first = tt;
                        break;
                    }
                }
                BitmexTicker t = (BitmexTicker)first;
                if (t == null)
                {
                    continue;
                }
                JEnumerable <JToken> props = item.Children();
                foreach (JProperty prop in props)
                {
                    string name  = prop.Name;
                    string value = prop.Value == null ? null : prop.Value.ToString();
                    switch (name)
                    {
                    case "lastPrice":
                        t.Last = FastValueConverter.Convert(value);
                        break;

                    case "highPrice":
                        t.Hr24High = FastValueConverter.Convert(value);
                        break;

                    case "lowPrice":
                        t.Hr24Low = FastValueConverter.Convert(value);
                        break;

                    case "bidPrice":
                        t.HighestBid = FastValueConverter.Convert(value);
                        break;

                    case "askPrice":
                        t.LowestAsk = FastValueConverter.Convert(value);
                        break;

                    case "timestamp":
                        t.Timestamp = t.Time = Convert.ToDateTime(value);
                        break;

                    case "lastChangePcnt":
                        t.Change = FastValueConverter.Convert(value);
                        break;

                    case "volume24h":
                        t.Volume = FastValueConverter.Convert(value);
                        break;
                    }
                }
                t.UpdateTrailings();
                lock (t) {
                    RaiseTickerChanged(t);
                }
            }
        }
Example #21
0
        public bool UpdateTradesStatistic(BitFinexTicker info, int depth) {
            string address = string.Format("https://bittrex.com/api/v1.1/public/getmarkethistory?market={0}", Uri.EscapeDataString(info.MarketName));
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch(Exception) {
                return false;
            }
            if(bytes == null)
                return false;

            int startIndex = 1;
            if(!JSonHelper.Default.SkipSymbol(bytes, ':', 3, ref startIndex))
                return false;

            string lastIdString = info.LastTradeId.ToString();
            List<string[]> res = JSonHelper.Default.DeserializeArrayOfObjects(bytes, ref startIndex, new string[] { "Id", "TimeStamp", "Quantity", "Price", "Total", "FillType", "OrderType" },
                (itemIndex, paramIndex, value) => {
                    return paramIndex != 0 || lastIdString != value;
                });
            if(res == null)
                return false;

            int lastTradeId = Convert.ToInt32(res[0][0]);
            if(lastTradeId == info.LastTradeId) {
                info.TradeStatistic.Add(new TradeStatisticsItem() { Time = DateTime.UtcNow });
                if(info.TradeStatistic.Count > 5000) {
                    for(int i = 0; i < 100; i++)
                        info.TradeStatistic.RemoveAt(0);
                }
                return true;
            }

            TradeStatisticsItem st = new TradeStatisticsItem();
            st.MinBuyPrice = double.MaxValue;
            st.MinSellPrice = double.MaxValue;
            lock(info) {
                for(int i = 0; i < res.Count; i++) {
                    string[] obj = res[i];
                    bool isBuy = obj[6].Length == 3;
                    double price = FastValueConverter.Convert(obj[3]);
                    double amount = FastValueConverter.Convert(obj[2]);
                    if(isBuy) {
                        st.BuyAmount += amount;
                        st.MinBuyPrice = Math.Min(st.MinBuyPrice, price);
                        st.MaxBuyPrice = Math.Max(st.MaxBuyPrice, price);
                        st.BuyVolume += amount * price;
                    }
                    else {
                        st.SellAmount += amount;
                        st.MinSellPrice = Math.Min(st.MinSellPrice, price);
                        st.MaxSellPrice = Math.Max(st.MaxSellPrice, price);
                        st.SellVolume += amount * price;
                    }
                }
            }
            if(st.MinSellPrice == double.MaxValue)
                st.MinSellPrice = 0;
            if(st.MinBuyPrice == double.MaxValue)
                st.MinBuyPrice = 0;
            info.LastTradeId = lastTradeId;
            info.TradeStatistic.Add(st);
            if(info.TradeStatistic.Count > 5000) {
                for(int i = 0; i < 100; i++)
                    info.TradeStatistic.RemoveAt(0);
            }
            return true;
        }
        public void Test1()
        {
            double val = FastValueConverter.Convert("4085187338");

            Assert.AreEqual(Convert.ToDouble("4085187338"), val);
        }