Esempio n. 1
0
        public static Equity Transform(this Equity sourceEquity, PeriodOption targetPeriod)
        {
            if (sourceEquity.Period == targetPeriod)
            {
                return(sourceEquity);
            }

            if (!IsTransformationValid(sourceEquity.Period, targetPeriod))
            {
                throw new InvalidTransformationException(sourceEquity.Period, targetPeriod);
            }

            var candles        = new List <Candle>();
            var periodInstance = targetPeriod.CreateInstance();

            DateTime startTime = sourceEquity.First().DateTime;

            while (startTime <= sourceEquity.Last().DateTime)
            {
                var nextStartTime = periodInstance.NextTimestamp(startTime);
                if (periodInstance.IsTimestamp(startTime))
                {
                    var candle = ComputeCandle(sourceEquity, startTime, nextStartTime);
                    if (candle != null)
                    {
                        candles.Add(candle);
                    }
                }
                startTime = nextStartTime;
            }

            return(new Equity(sourceEquity.Name, candles, targetPeriod));
        }
Esempio n. 2
0
        private static bool IsTransformationValid(PeriodOption inputPeriod, PeriodOption outputPeriod)
        {
            var inputInstance  = inputPeriod.CreateInstance();
            var outputInstance = outputPeriod.CreateInstance();

            if (inputInstance is IIntradayPeriod input)
            {
                return(!(outputInstance is IIntradayPeriod output) || (input.NumberOfSecond < output.NumberOfSecond));
            }

            var input2 = inputInstance as IInterdayPeriod;

            if (outputInstance is IIntradayPeriod output2)
            {
                return(false);
            }

            var output3 = outputInstance as IInterdayPeriod;

            if (input2.OrderOfTransformation >= output3.OrderOfTransformation)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(
            string symbol,
            DateTime?startTime      = null,
            DateTime?endTime        = null,
            PeriodOption period     = PeriodOption.Daily,
            CancellationToken token = default(CancellationToken))
        => await Task.Factory.StartNew(() =>
        {
            using (var fs = File.OpenRead(_path))
                using (var sr = new StreamReader(fs))
                    using (var csvReader = new CsvReader(sr, new CsvConfiguration(_culture)
                    {
                        Delimiter = string.IsNullOrWhiteSpace(_delimiter) ? "," : _delimiter, HasHeaderRecord = _hasHeader
                    }))
                    {
                        var candles           = new List <IOhlcv>();
                        bool isHeaderBypassed = false;
                        while (csvReader.Read())
                        {
                            // HasHeaderRecord is not working for CsvReader 6.0.2
                            if (_hasHeader && !isHeaderBypassed)
                            {
                                isHeaderBypassed = true;
                                continue;
                            }

                            var date = string.IsNullOrWhiteSpace(_format) ? csvReader.GetField <DateTime>(0) : DateTime.ParseExact(csvReader.GetField <string>(0), _format, _culture);
                            if ((!startTime.HasValue || date >= startTime) && (!endTime.HasValue || date <= endTime))
                            {
                                candles.Add(GetRecord(csvReader));
                            }
                        }
                        return(candles.OrderBy(c => c.Time).ToList());
                    }
        }, token);
        public static SelectList GetPeriodOptionsList(PeriodOption?defaultPeriodOption = null)
        {
            PeriodOption defaultOption        = defaultPeriodOption ?? PeriodOption.None;
            string       selectedPeriodOption = ConvertPeriodOptionToString(defaultOption);
            SelectList   periodOptionsList    = new SelectList(_optionsList, selectedPeriodOption);

            return(periodOptionsList);
        }
Esempio n. 5
0
        public TimeSeries(string name, IEnumerable <TTick> ticks, PeriodOption period)
        {
            Name   = name;
            Ticks  = (ticks ?? new List <TTick>()).OrderBy(t => t.DateTime).ToList();
            Period = period;

            if (!IsTimeSeriesValid(out var errorTick))
            {
                throw new InvalidTimeFrameException(errorTick.DateTime);
            }
        }
Esempio n. 6
0
        public PeriodViewModel(PeriodBindingModel periodBinging, int?periodId)
        {
            Period   = periodBinging;
            PeriodId = periodId;

            PeriodNumber number = PeriodNumbersHelper.ConvertStringToPeriodNumber(Period.Number);
            PeriodOption option = PeriodOptionsHelper.ConvertStringToPeriodOption(Period.Option);

            NumbersList = PeriodNumbersHelper.GetPeriodNumbersList(number);
            OptionsList = PeriodOptionsHelper.GetPeriodOptionsList(option);
        }
Esempio n. 7
0
        public static IPeriod CreateInstance(this PeriodOption period, Country?country = null)
        {
            string periodName = Enum.GetName(typeof(PeriodOption), period);
            var    periodType = Type.GetType($"Trady.Core.Period.{periodName}");

            if (!country.HasValue || periodType is IIntradayPeriod)
            {
                return((IPeriod)Activator.CreateInstance(periodType));
            }
            else
            {
                return((IPeriod)Activator.CreateInstance(periodType, new object[] { country.Value }));
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Imports the async. endTime stock history inclusive
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="symbol">Symbol.</param>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time.</param>
        /// <param name="period">Period.</param>
        /// <param name="token">Token.</param>
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(
            string symbol,
            DateTime?startTime      = default(DateTime?),
            DateTime?endTime        = default(DateTime?),
            PeriodOption period     = PeriodOption.Daily,
            CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Monthly && period != PeriodOption.Weekly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var candles = await StooqApi.Stooq.GetHistoricalAsync(symbol, PeriodMap[period], startTime, endTime, SkipOption.None, false, token);

            return(candles.Select(c => new ES.Domain.Models.CandleTrade(c.DateTime, c.Open, c.High, c.Low, c.Close, c.Volume)).OrderBy(c => c.Time).ToList());
        }
Esempio n. 9
0
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(
            string symbol,
            DateTime?startTime      = null,
            DateTime?endTime        = null,
            PeriodOption period     = PeriodOption.Daily,
            CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var response = await _client.Timeseries.GetDataAsync(_databaseCode, symbol, startDate : startTime, endDate : endTime, token : token, collapse : PeriodMap[period]).ConfigureAwait(false);

            return(response.DatasetData.Data.Where(r => !r.IsNullOrWhitespace()).Select(r => r.CreateIOhlcvData()).OrderBy(c => c.Time).ToList());
        }
Esempio n. 10
0
        private static DateTime AddPeriod(DateTime dateTime, PeriodOption period)
        {
            switch (period)
            {
            case PeriodOption.Daily:
                return(dateTime.AddDays(1));

            case PeriodOption.Weekly:
                return(dateTime.AddDays(7));

            case PeriodOption.Monthly:
                return(dateTime.AddMonths(1));

            default:
                return(dateTime);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Imports the async. Endtime stock history exclusive
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="symbol">Symbol.</param>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time.</param>
        /// <param name="period">Period.</param>
        /// <param name="token">Token.</param>
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(string symbol,
                                                                DateTime?startTime      = default(DateTime?),
                                                                DateTime?endTime        = default(DateTime?),
                                                                PeriodOption period     = PeriodOption.Daily,
                                                                CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var corrStartTime = (startTime < UnixMinDateTime ? UnixMinDateTime : startTime) ?? UnixMinDateTime;
            var corrEndTime   = (endTime > UnixMaxDateTime ? UnixMaxDateTime : endTime) ?? UnixMaxDateTime;
            var candles       = await YahooFinanceApi.Yahoo.GetHistoricalAsync(symbol, corrStartTime, corrEndTime, PeriodMap[period], token);

            return(candles.Select(c => new ES.Domain.Models.CandleTrade(c.DateTime, c.Open, c.High, c.Low, c.Close, c.Volume)).OrderBy(c => c.Time).ToList());
        }
Esempio n. 12
0
        public static string ConvertPeriodOptionToString(PeriodOption periodOption)
        {
            switch (periodOption)
            {
            case PeriodOption.None:
                return(None);

            case PeriodOption.Once:
                return(Once);

            case PeriodOption.Since:
                return(Since);

            case PeriodOption.Until:
                return(Until);

            case PeriodOption.OnceDifferentCabinet:
                return(OnceDifferentCabinet);

            default:
                throw new InvalidEnumArgumentException(nameof(periodOption), (int)periodOption,
                                                       typeof(PeriodOption));
            }
        }
Esempio n. 13
0
        public async Task <IReadOnlyList <Candle> > ImportAsync(string symbol, DateTime?startTime = null, DateTime?endTime = null, PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            List <Candle> cndls = new List <Candle>();

            //Import Candles from Data.Candle5m, get more data from sqlite if needed:
            if (endTime == null)
            {
                endTime = DateTime.UtcNow;
            }

            bool histLinesReady = BtrexData.Markets[symbol].TradeHistory.Candles5m != null && BtrexData.Markets[symbol].TradeHistory.Candles5m.Any();

            if (histLinesReady)
            {
                List <HistDataLine> HistLines = new List <HistDataLine>();
                HistLines.AddRange(BtrexData.Markets[symbol].TradeHistory.Candles5m);

                if (startTime <= HistLines.First().T)
                {
                    histLinesReady = false;
                }

                foreach (HistDataLine histLine in HistLines)
                {
                    if (histLine.T >= startTime || histLine.T <= endTime)
                    {
                        cndls.Add(new Candle(histLine.T, histLine.O, histLine.H, histLine.L, histLine.C, histLine.V));
                    }
                }
            }


            if (!histLinesReady)
            {
                //Call lines from SQLite and set cndls in correct order:
                List <Candle> sqlCndls = new List <Candle>();
                using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + HistoricalData.dbName + ";Version=3;"))
                {
                    conn.Open();
                    string startTimeString = startTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                           endTimeString   = endTime.Value.ToString("yyyy-MM-dd HH:mm:ss");

                    DataTable dt            = new DataTable();
                    string    commandString = "SELECT * FROM " + symbol.Replace('-', '_') +
                                              " WHERE DateTime >= '" + startTimeString + "'" +
                                              " AND DateTime <= '" + endTimeString + "'";

                    using (var sqlAdapter = new SQLiteDataAdapter(commandString, conn))
                        sqlAdapter.Fill(dt);

                    foreach (DataRow line in dt.Rows)
                    {
                        sqlCndls.Add(new Candle(Convert.ToDateTime(line["DateTime"]), Convert.ToDecimal(line["Open"]), Convert.ToDecimal(line["High"]), Convert.ToDecimal(line["Low"]), Convert.ToDecimal(line["Close"]), Convert.ToDecimal(line["Volume"])));
                    }

                    conn.Close();
                }
                cndls.InsertRange(0, sqlCndls);
            }

            return(cndls);
        }
Esempio n. 14
0
        /// <summary>
        /// Imports the async. endTime stock history inclusive
        /// </summary>
        /// <returns>The async.</returns>
        /// <param name="symbol">Symbol.</param>
        /// <param name="startTime">Start time.</param>
        /// <param name="endTime">End time.</param>
        /// <param name="period">Period.</param>
        /// <param name="token">Token.</param>
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(string symbol, DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (period == PeriodOption.PerSecond || period == PeriodOption.Per10Minute || period == PeriodOption.BiHourly)
            {
                throw new ArgumentException($"This importer does not support {period.ToString()}");
            }

            Client.BaseAddress = new Uri("https://www.alphavantage.co");
            string query    = string.Empty;
            string function = "TIME_SERIES_DAILY";
            string format   = "yyyy-MM-dd";

            switch (period)
            {
            case PeriodOption.PerMinute:
                format   = "yyyy-MM-dd HH:mm:ss";
                function = "function=TIME_SERIES_INTRADAY&interval=1min";
                break;

            case PeriodOption.Per5Minute:
                format   = "yyyy-MM-dd HH:mm:ss";
                function = "function=TIME_SERIES_INTRADAY&interval=5min";
                break;

            case PeriodOption.Per15Minute:
                format   = "yyyy-MM-dd HH:mm:ss";
                function = "function=TIME_SERIES_INTRADAY&interval=15min";
                break;

            case PeriodOption.Per30Minute:
                format   = "yyyy-MM-dd HH:mm:ss";
                function = "function=TIME_SERIES_INTRADAY&interval=30min";
                break;

            case PeriodOption.Hourly:
                format   = "yyyy-MM-dd HH:mm:ss";
                function = "function=TIME_SERIES_INTRADAY&interval=60min";
                break;

            case PeriodOption.Daily:
                function = "function=TIME_SERIES_DAILY";
                break;

            case PeriodOption.Weekly:
                function = "function=TIME_SERIES_WEEKLY";
                break;

            case PeriodOption.Monthly:
                function = "function=TIME_SERIES_MONTHLY";
                break;

            default:
                break;
            }
            query = $"/query?{function}&symbol={symbol}&apikey={ApiKey}&outputsize={OutputSize.ToString()}&datatype=csv";
            var csvStream = await client.GetStreamAsync(query);

            TextReader textReader  = new StreamReader(csvStream);
            var        culture     = "en-US";
            var        cultureInfo = new CultureInfo(culture);
            var        candles     = new List <IOhlcv>();

            using (var csvReader = new CsvReader(textReader, new Configuration()
            {
                CultureInfo = cultureInfo, Delimiter = ",", HasHeaderRecord = true
            }))
            {
                bool isHeaderBypassed = false;
                while (csvReader.Read())
                {
                    // HasHeaderRecord is not working for CsvReader 6.0.2
                    if (!isHeaderBypassed)
                    {
                        isHeaderBypassed = true;
                        continue;
                    }

                    var date = string.IsNullOrWhiteSpace(format) ? csvReader.GetField <DateTime>(0) : DateTime.ParseExact(csvReader.GetField <string>(0), format, cultureInfo);
                    if ((!startTime.HasValue || date >= startTime) && (!endTime.HasValue || date <= endTime))
                    {
                        candles.Add(GetRecord(csvReader, format, cultureInfo));
                    }
                }
            }

            return(candles.OrderBy(c => c.DateTime).ToList());
        }
Esempio n. 15
0
 public Equity(string name, IEnumerable <Candle> candles, PeriodOption period)
     : base(name, candles, period)
 {
 }
Esempio n. 16
0
 public static Equity ToEquity(this IEnumerable <Candle> candles, string name, PeriodOption period)
 => new Equity(name, candles, period);
Esempio n. 17
0
        public async Task <IReadOnlyList <Core.Candle> > ImportAsync(string symbol, DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (!PeriodMap.TryGetValue(period, out int frequency))
            {
                throw new ArgumentException("This importer only supports second, minute, hourly & daily data");
            }

            if (!symbol.Contains(SymbolSeparator.ToString()))
            {
                throw new ArgumentException("The input symbol should be in the form of \'{Market}/{Symbol}\'");
            }

            string[] syms    = symbol.Split(SymbolSeparator);
            var      candles = await Task.Run(() => _lqs.GetValues(syms[0].ToUpper(), syms[1], PeriodMap[period], startTime, endTime));

            return(candles.Select(c => new Core.Candle(c.Date, c.Open, c.High, c.Low, c.Close, c.Volume)).OrderBy(c => c.DateTime).ToList());
        }
Esempio n. 18
0
        public async Task <IReadOnlyList <IOhlcv> > ImportAsync(string symbol, DateTime?startTime = null,
                                                                DateTime?endTime        = null, PeriodOption period = PeriodOption.Daily,
                                                                CancellationToken token = default(CancellationToken))
        => await Task.Factory.StartNew(() =>
        {
            using (var stream = File.Open(_path, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var candles = new List <IOhlcv>();

                    var result = reader.AsDataSet();

                    for (int i = 1; i < result.Tables[0].Rows.Count; i++)
                    {
                        var row  = result.Tables[0].Rows[i];
                        var date = GetDate(row.Field <double>(2));
                        if ((!startTime.HasValue || date >= startTime) && (!endTime.HasValue || date <= endTime))
                        {
                            candles.Add(GetRecord(row));
                        }
                    }

                    return(candles.OrderBy(c => c.DateTime).ToList());
                }
            }
        }, token);
Esempio n. 19
0
 public async Task <IReadOnlyList <IOhlcv> > ImportAsync(string symbol, DateTime?startTime = null, DateTime?endTime = null, PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
 => await Task.Factory.StartNew(() =>
 {
     using (var fs = File.OpenRead(_path))
         using (var sr = new StreamReader(fs))
             using (var csvReader = new CsvReader(sr, new CsvConfiguration()
             {
                 CultureInfo = _culture
             }))
             {
                 var candles = new List <IOhlcv>();
                 while (csvReader.Read())
                 {
                     var date = csvReader.GetField <DateTime>(0);
                     if ((!startTime.HasValue || date >= startTime) && (!endTime.HasValue || date <= endTime))
                     {
                         candles.Add(GetRecord(csvReader));
                     }
                 }
                 return(candles.OrderBy(c => c.DateTime).ToList());
             }
 });
Esempio n. 20
0
        public async Task <Equity> ImportAsync(string symbol, DateTime?startTime = default(DateTime?), DateTime?endTime = default(DateTime?), PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var yahooCandles = await Yahoo.GetHistoricalAsync(symbol, startTime, endTime, _periodMap[period], false, token);

            var output = new List <Core.Candle>();

            foreach (var yahooCandle in yahooCandles)
            {
                output.Add(new Core.Candle(yahooCandle.DateTime, yahooCandle.Open, yahooCandle.High, yahooCandle.Low, yahooCandle.Close, yahooCandle.Volume));
            }

            return(output.ToEquity(symbol, period));
        }
Esempio n. 21
0
        public async Task <Equity> ImportAsync(string symbol, DateTime?startTime = null, DateTime?endTime = null, PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
        {
            if (period != PeriodOption.Daily && period != PeriodOption.Weekly && period != PeriodOption.Monthly)
            {
                throw new ArgumentException("This importer only supports daily, weekly & monthly data");
            }

            var response = await _client.Dataset.GetAsync(_databaseCode, symbol, startDate : startTime, endDate : endTime, token : token, collapse : _periodMap[period]).ConfigureAwait(false);

            var candles = response.DatasetData.Data.Where(r => !r.IsNullOrWhitespace()).Select(r => r.CreateCandle()).ToList();

            return(candles.ToEquity(symbol, period));
        }
Esempio n. 22
0
 public async Task <Equity> ImportAsync(string symbol, DateTime?startTime = null, DateTime?endTime = null, PeriodOption period = PeriodOption.Daily, CancellationToken token = default(CancellationToken))
 {
     return(await Task.Factory.StartNew(() =>
     {
         using (var fs = File.OpenRead(_path))
             using (var sr = new StreamReader(fs))
                 using (var csvReader = new CsvReader(sr))
                 {
                     var candles = new List <Candle>();
                     while (csvReader.Read())
                     {
                         var record = csvReader.CurrentRecord;
                         var recordDatetime = Convert.ToDateTime(record[0]);
                         if (startTime.HasValue && recordDatetime < startTime.Value || endTime.HasValue && recordDatetime >= endTime.Value)
                         {
                             continue;
                         }
                         candles.Add(record.CreateCandle());
                     }
                     return candles.ToEquity(symbol, period);
                 }
     }));
 }
 public InvalidTransformationException(PeriodOption sourcePeriod, PeriodOption targetPeriod)
 {
     _sourcePeriod = sourcePeriod;
     _targetPeriod = targetPeriod;
 }