public void GetsHistory(Symbol symbol, Resolution resolution, TimeSpan period, bool throwsException)
        {
            TestDelegate test = () =>
            {
                var environment = Config.Get("oanda-environment").ConvertTo <Environment>();
                var accessToken = Config.Get("oanda-access-token");
                var accountId   = Config.Get("oanda-account-id");

                var brokerage = new OandaBrokerage(null, null, environment, accessToken, accountId);

                var historyProvider = new BrokerageHistoryProvider();
                historyProvider.SetBrokerage(brokerage);
                historyProvider.Initialize(null, null, null, null, null, null);

                var now = DateTime.UtcNow;

                var requests = new[]
                {
                    new HistoryRequest
                    {
                        Symbol       = symbol,
                        Resolution   = resolution,
                        StartTimeUtc = now.Add(-period),
                        EndTimeUtc   = now
                    }
                };

                var history = historyProvider.GetHistory(requests, TimeZones.Utc);

                foreach (var slice in history)
                {
                    if (resolution == Resolution.Tick)
                    {
                        foreach (var tick in slice.Ticks[symbol])
                        {
                            Log.Trace("{0}: {1} - {2} / {3}", tick.Time, tick.Symbol, tick.BidPrice, tick.AskPrice);
                        }
                    }
                    else
                    {
                        var bar = slice.QuoteBars[symbol];

                        Log.Trace("{0}: {1} - O={2}, H={3}, L={4}, C={5}", bar.Time, bar.Symbol, bar.Open, bar.High, bar.Low, bar.Close);
                    }
                }

                Log.Trace("Data points retrieved: " + historyProvider.DataPointCount);
            };

            if (throwsException)
            {
                Assert.Throws <ArgumentException>(test);
            }
            else
            {
                Assert.DoesNotThrow(test);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OandaDataDownloader"/> class
 /// </summary>
 public OandaDataDownloader(string accessToken, string accountId)
 {
     // Set Oanda account credentials
     _brokerage = new OandaBrokerage(null,
                                     null,
                                     Environment.Practice,
                                     accessToken,
                                     accountId);
 }
示例#3
0
 /// <summary>
 /// Aggregates a list of 5-second bars at the requested resolution
 /// </summary>
 /// <param name="symbol"></param>
 /// <param name="bars"></param>
 /// <param name="resolution"></param>
 /// <returns></returns>
 private static IEnumerable <TradeBar> AggregateBars(Symbol symbol, List <Candle> bars, TimeSpan resolution)
 {
     return
         (from b in bars
          group b by OandaBrokerage.GetDateTimeFromString(b.time).RoundDown(resolution)
          into g
          select new TradeBar
     {
         Symbol = symbol,
         Time = g.Key,
         Open = Convert.ToDecimal(g.First().openMid),
         High = Convert.ToDecimal(g.Max(b => b.highMid)),
         Low = Convert.ToDecimal(g.Min(b => b.lowMid)),
         Close = Convert.ToDecimal(g.Last().closeMid)
     });
 }
示例#4
0
        /// <summary>
        /// Groups a list of bars into a dictionary keyed by date
        /// </summary>
        /// <param name="bars"></param>
        /// <returns></returns>
        private static SortedDictionary <DateTime, List <Candle> > GroupBarsByDate(List <Candle> bars)
        {
            var groupedBars = new SortedDictionary <DateTime, List <Candle> >();

            foreach (var bar in bars)
            {
                var date = OandaBrokerage.GetDateTimeFromString(bar.time).Date;

                if (!groupedBars.ContainsKey(date))
                {
                    groupedBars[date] = new List <Candle>();
                }

                groupedBars[date].Add(bar);
            }

            return(groupedBars);
        }
示例#5
0
        /// <summary>
        ///     Creates the brokerage under test and connects it
        /// </summary>
        /// <returns>A connected brokerage instance</returns>
        protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, IHoldingsProvider holdingsProvider)
        {
            var oandaBrokerage = new OandaBrokerage(orderProvider, 0);
            var tokens         = OandaBrokerageFactory.GetTokens();
            var environment    = Config.Get("oanda-environment");

            if (environment == "sandbox")
            {
                var requestString   = EndpointResolver.ResolveEndpoint(Environment.Sandbox, Server.Account) + "accounts";
                var accountResponse = oandaBrokerage.MakeRequest <AccountResponse>(requestString, "POST");
                oandaBrokerage.SetAccountId(accountResponse.accountId);
                oandaBrokerage.SetEnvironment("sandbox");
                oandaBrokerage.SetUserName(accountResponse.username);
            }
            else
            {
                oandaBrokerage.SetAccountId(Convert.ToInt32(Config.Get("oanda-account-id")));
                oandaBrokerage.SetEnvironment(Config.Get("oanda-environment"));
            }

            var qcUserId = OandaBrokerageFactory.Configuration.QuantConnectUserId;

            oandaBrokerage.SetTokens(qcUserId, tokens.AccessToken, tokens.IssuedAt,
                                     TimeSpan.FromSeconds(tokens.ExpiresIn));

            oandaBrokerage.InitializeInstrumentSecurityTypeMap();

            // keep the tokens up to date in the event of a refresh
            oandaBrokerage.SessionRefreshed +=
                (sender, args) =>
            {
                File.WriteAllText(OandaBrokerageFactory.TokensFile,
                                  JsonConvert.SerializeObject(args, Formatting.Indented));
            };

            return(oandaBrokerage);
        }
        public void GetsHistory(Symbol symbol, Resolution resolution, TimeSpan period, bool throwsException)
        {
            TestDelegate test = () =>
            {
                var environment = Config.Get("oanda-environment").ConvertTo <Environment>();
                var accessToken = Config.Get("oanda-access-token");
                var accountId   = Config.Get("oanda-account-id");

                var brokerage = new OandaBrokerage(null, null, null, environment, accessToken, accountId);

                var historyProvider = new BrokerageHistoryProvider();
                historyProvider.SetBrokerage(brokerage);
                historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, null, null, null, null, null, false, null));

                var now = DateTime.UtcNow;

                var requests = new[]
                {
                    new HistoryRequest(now.Add(-period),
                                       now,
                                       typeof(QuoteBar),
                                       symbol,
                                       resolution,
                                       SecurityExchangeHours.AlwaysOpen(TimeZones.EasternStandard),
                                       DateTimeZone.Utc,
                                       Resolution.Minute,
                                       false,
                                       false,
                                       DataNormalizationMode.Adjusted,
                                       TickType.Quote)
                };

                var history = historyProvider.GetHistory(requests, TimeZones.Utc);

                foreach (var slice in history)
                {
                    if (resolution == Resolution.Tick)
                    {
                        foreach (var tick in slice.Ticks[symbol])
                        {
                            Log.Trace("{0}: {1} - {2} / {3}", tick.Time, tick.Symbol, tick.BidPrice, tick.AskPrice);
                        }
                    }
                    else
                    {
                        var bar = slice.QuoteBars[symbol];

                        Log.Trace("{0}: {1} - O={2}, H={3}, L={4}, C={5}", bar.Time, bar.Symbol, bar.Open, bar.High, bar.Low, bar.Close);
                    }
                }

                Log.Trace("Data points retrieved: " + historyProvider.DataPointCount);
            };

            if (throwsException)
            {
                Assert.Throws <ArgumentException>(test);
            }
            else
            {
                Assert.DoesNotThrow(test);
            }
        }
示例#7
0
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (!_symbolMapper.IsKnownLeanSymbol(symbol))
            {
                throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
            }

            if (resolution == Resolution.Tick)
            {
                throw new NotSupportedException("Resolution not available: " + resolution);
            }

            if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
            {
                throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
            }

            if (endUtc < startUtc)
            {
                throw new ArgumentException("The end date must be greater or equal than the start date.");
            }

            var barsTotalInPeriod = new List <Candle>();
            var barsToSave        = new List <Candle>();

            // set the starting date/time
            DateTime date          = startUtc;
            DateTime startDateTime = date;

            // loop until last date
            while (startDateTime <= endUtc.AddDays(1))
            {
                string start = startDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ");

                // request blocks of 5-second bars with a starting date/time
                var oandaSymbol = _symbolMapper.GetBrokerageSymbol(symbol);
                var bars        = _brokerage.DownloadBars(oandaSymbol, start, OandaBrokerage.MaxBarsPerRequest, EGranularity.S5);
                if (bars.Count == 0)
                {
                    break;
                }

                var groupedBars = GroupBarsByDate(bars);

                if (groupedBars.Count > 1)
                {
                    // we received more than one day, so we save the completed days and continue
                    while (groupedBars.Count > 1)
                    {
                        var currentDate = groupedBars.Keys.First();
                        if (currentDate > endUtc)
                        {
                            break;
                        }

                        barsToSave.AddRange(groupedBars[currentDate]);

                        barsTotalInPeriod.AddRange(barsToSave);

                        barsToSave.Clear();

                        // remove the completed date
                        groupedBars.Remove(currentDate);
                    }

                    // update the current date
                    date = groupedBars.Keys.First();

                    if (date <= endUtc)
                    {
                        barsToSave.AddRange(groupedBars[date]);
                    }
                }
                else
                {
                    var currentDate = groupedBars.Keys.First();
                    if (currentDate > endUtc)
                    {
                        break;
                    }

                    // update the current date
                    date = currentDate;

                    barsToSave.AddRange(groupedBars[date]);
                }

                // calculate the next request datetime (next 5-sec bar time)
                startDateTime = OandaBrokerage.GetDateTimeFromString(bars[bars.Count - 1].time).AddSeconds(5);
            }

            if (barsToSave.Count > 0)
            {
                barsTotalInPeriod.AddRange(barsToSave);
            }

            switch (resolution)
            {
            case Resolution.Second:
            case Resolution.Minute:
            case Resolution.Hour:
            case Resolution.Daily:
                foreach (var bar in AggregateBars(symbol, barsTotalInPeriod, resolution.ToTimeSpan()))
                {
                    yield return(bar);
                }
                break;
            }
        }
示例#8
0
 public EventsSession(OandaBrokerage brokerage, int accountId)
     : base(accountId)
 {
     _brokerage = brokerage;
 }
示例#9
0
 protected override async Task <WebResponse> GetSession()
 {
     return(await OandaBrokerage.StartEventsSession(new List <int> {
         _accountId
     }));
 }
示例#10
0
 public RatesSession(OandaBrokerage brokerage, int accountId, List <Instrument> instruments)
     : base(accountId)
 {
     _brokerage   = brokerage;
     _instruments = instruments;
 }