private static void UpdateDataTable(HistDataResponse data, SQLiteCommand cmd)
        {
            if (data != null)
            {
                //look for market. if !exist then CreateNewDataTable()
                cmd.CommandText = string.Format("SELECT CASE WHEN tbl_name = '{0}' THEN 1 ELSE 0 END FROM sqlite_master "
                                                + "WHERE tbl_name = '{0}' AND type = 'table'", data.MarketDelta);

                if (!Convert.ToBoolean(cmd.ExecuteScalar()))
                {
                    CreateNewDataTable(data, cmd);
                    return;
                }

                cmd.CommandText = string.Format("SELECT * FROM {0} ORDER BY datetime(DateTime) DESC Limit 1", data.MarketDelta);
                DateTime dateTime = Convert.ToDateTime(cmd.ExecuteScalar());

                foreach (HistDataLine line in data.result)
                {
                    if (line.T <= dateTime)
                    {
                        continue;
                    }
                    else
                    {
                        EnterSQLiteRow(line, cmd, data.MarketDelta);
                    }
                }
            }
            saved++;
            Console.Write("\rDownloading Candle Data: {0}/{1}", saved, totalCount);
        }
        private static async Task EnqueueData(string delta)
        {
            HistDataResponse histData = await BtrexREST.GetMarketHistoryV2(delta, "fiveMin");

            if (histData.success != true)
            {
                Console.WriteLine("    !!!!ERR GET-HISTORY>>> " + histData.message);
                return;
            }
            //downloaded++;

            DataQueue.Enqueue(histData);
        }
        private static void CreateNewDataTable(HistDataResponse data, SQLiteCommand cmd)
        {
            if (data != null)
            {
                cmd.CommandText = string.Format("CREATE TABLE IF NOT EXISTS {0} (DateTime TEXT, Open TEXT, Close TEXT, Low TEXT, High TEXT, Volume TEXT, BaseVolume TEXT)", data.MarketDelta);
                cmd.ExecuteNonQuery();

                foreach (HistDataLine line in data.result)
                {
                    EnterSQLiteRow(line, cmd, data.MarketDelta);
                }
            }
            saved++;
            Console.Write("\rDownloading Candle Data: {0}/{1}", saved, totalCount);
        }
        //public static async Task<MarketHistoryResponse> GetMarketHistory(string delta)
        //{
        //    MarketHistoryResponse marketHistory = null;
        //    HttpResponseMessage response = await client.GetAsync("");
        //    if (response.IsSuccessStatusCode)
        //        marketHistory = await response.Content.ReadAsAsync<MarketHistoryResponse>();

        //    return marketHistory;
        //}

        public static async Task <HistDataResponse> GetMarketHistoryV2(string delta, string period)
        {
            HistDataResponse history = new HistDataResponse();

            while (true)
            {
                try
                {
                    var mesg = new HttpRequestMessage()
                    {
                        RequestUri = new Uri("https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + delta + "&tickInterval=" + period + "", UriKind.Absolute),
                        Method     = HttpMethod.Get
                    };
                    HttpResponseMessage response = await client.SendAsync(mesg);

                    if (response.IsSuccessStatusCode)
                    {
                        history = await response.Content.ReadAsAsync <HistDataResponse>();
                    }
                    else if (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable || history.result == null)
                    {
                        do
                        {
                            Thread.Sleep(500);
                            HttpRequestMessage mesgClone = new HttpRequestMessage()
                            {
                                RequestUri = new Uri("https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=" + delta + "&tickInterval=" + period + "", UriKind.Absolute),
                                Method     = HttpMethod.Get
                            };

                            response = await client.SendAsync(mesgClone);

                            history = await response.Content.ReadAsAsync <HistDataResponse>();
                        } while (response.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable || history.result == null);
                    }
                    else
                    {
                        Trace.WriteLine("FAIL:  " + response.ReasonPhrase);
                    }


                    history.MarketDelta = string.Empty;

                    if (history.result == null || history.MarketDelta == null || delta.Replace('-', '_') == null)
                    {
                        Trace.WriteLine("\r\nHIST NULL " + delta + " RESPONSE CODE: " + response.StatusCode + "\r\n\r\n");
                    }


                    history.MarketDelta = delta.Replace('-', '_');
                    if (period.ToUpper() != "ONEMIN" && history.result.Count > 0)
                    {
                        history.result.Remove(history.result.Last());
                    }
                    break;
                }
                catch (Exception e)
                {
                    //Trace.WriteLine("\r\n222HIST NULL " + delta + " RESPONSE CODE: " + response.StatusCode + "\r\n\r\n");
                }
            }
            return(history);
        }
Ejemplo n.º 5
0
        public async Task <bool> Resolve5mCandles(bool retryOnFail = true)
        {
            DateTime NextCandleTime     = LastStoredCandle.AddMinutes(5);
            DateTime NextCandleCurrTime = LastStoredCandle.AddMinutes(10);

            if (CandlesResolved)
            {
                Trace.WriteLine(string.Format("\r[{1}] CANDLES RESOLVED - LastCandleStart: {0}", LastStoredCandle, MarketDelta));
                return(true);
            }

            while (!CandlesResolved)
            {
                HistDataResponse response = await BtrexREST.GetMarketHistoryV2(MarketDelta, "oneMin");

                if (!response.success)
                {
                    Trace.WriteLine("    !!!!ERR GET-1m-CANDLES: [{0}]", MarketDelta);
                    return(false);
                }

                DateTime last1mCandleCurrTime = response.result.Last().T.AddMinutes(1);
                DateTime firstFillTime        = RecentFills.First().TimeStamp;

                if (last1mCandleCurrTime >= firstFillTime)
                {
                    //Build latest 5m candle with 1m data and RecentFills:
                    List <HistDataLine> Candles1m = new List <HistDataLine>();
                    foreach (HistDataLine line in response.result)
                    {
                        if (line.T >= LastStoredCandle.AddMinutes(5))
                        {
                            Candles1m.Add(line);
                        }
                    }

                    //Grab O:H:L:V (noC) from 1mCandles
                    //simulate 2 mdFills (H&L:V) and add to beginning of RecentFills
                    Decimal O = Candles1m.First().O,
                            H = Candles1m.Max(x => x.H),
                            L = Candles1m.Min(x => x.L),
                            V = Candles1m.Sum(x => x.V),
                            C = Candles1m.Last().C;

                    List <mdFill> RevisedFills = new List <mdFill>();
                    RevisedFills.Add(new mdFill(LastStoredCandle.AddMinutes(5), O, (V / 4M), "BUY"));
                    RevisedFills.Add(new mdFill(LastStoredCandle.AddSeconds(300.5), H, (V / 4M), "SELL"));
                    RevisedFills.Add(new mdFill(LastStoredCandle.AddSeconds(300.5), L, (V / 4M), "BUY"));
                    RevisedFills.Add(new mdFill(LastStoredCandle.AddSeconds(301), C, (V / 4M), "SELL"));

                    if (last1mCandleCurrTime >= NextCandleCurrTime)
                    {
                        RecentFills = new List <mdFill>(RevisedFills);
                    }
                    else
                    {
                        foreach (mdFill fill in RecentFills)
                        {
                            if (fill.TimeStamp >= last1mCandleCurrTime && last1mCandleCurrTime < NextCandleCurrTime)
                            {
                                RevisedFills.Add(fill);
                            }
                        }

                        RecentFills = new List <mdFill>(RevisedFills);
                    }



                    BuildCandleFromRecentFills(NextCandleTime);

                    CandlesResolved = true;
                    Trace.WriteLine(string.Format("\r[{1}] CANDLES RESOLVED - LastCandleStart: {0}", LastStoredCandle, MarketDelta));
                }
                else
                {
                    //Trace.WriteLine("    !!!!ERR RESOLVE_CANDLES>>Current: {0} < LastFill: {1} :: [{2}]", last1mCandleCurrTime, firstFillTime, MarketDelta);
                    if (!retryOnFail)
                    {
                        return(false);
                    }

                    for (int s = 15; s > 0; s--)
                    {
                        Trace.Write(string.Format("\r    Resolving [{0}] TradeHist->Candles time gap. Retry in {1} seconds...", MarketDelta, s));
                        Thread.Sleep(1000);
                    }
                    Trace.Write("\r                                                                                  \r");
                }
            }

            return(true);
        }