/// <summary> /// Calculate number of candles in a time range /// </summary> /// <param name="granularity">Granularity of the candles</param> /// <param name="from">The from date</param> /// <param name="to">The to date</param> /// <returns></returns> public static double GetNumberOfCandlesForTimeRange(this CandlestickGranularity granularity, DateTime from, DateTime to) { // Always convert dates to UTC when working with Oanda from = from.ToUniversalTime(); to = to.ToUniversalTime(); // Check not to enter endless loops if (from > to) { throw new ArgumentException("The 'to' time cannot be before the 'to' time."); } // Return the number of candles return((to - from).TotalSeconds / granularity.GetInSeconds()); }
/// <summary> /// Explode a datetime range to multiple to fit in to Oanda API limitation /// </summary> /// <param name="granularity"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public static IEnumerable <DateTimeRange> ExplodeToMultipleCandleRanges(this CandlestickGranularity granularity, DateTime from, DateTime to) { // Always convert dates to UTC when working with Oanda from = from.ToUniversalTime(); to = to.ToUniversalTime(); // Make the timerange calulation var numberOfCandles = granularity.GetNumberOfCandlesForTimeRange(from, to); var numberOfQueries = Math.Ceiling(numberOfCandles / OANDA_MAX_CANDLES); var candleRanges = new List <DateTimeRange>(); for (var i = 0; i <= (numberOfQueries - 1); i++) { candleRanges.Add(new DateTimeRange() { From = from.AddSeconds(i * OANDA_MAX_CANDLES * granularity.GetInSeconds()), To = (i == (numberOfQueries - 1)) ? to : from.AddSeconds(((i + 1) * OANDA_MAX_CANDLES * granularity.GetInSeconds()) - 1) }); } // Return the tim ranges created return(candleRanges); }