public void InitializeBrokerage() { InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"), Config.Get("ib-tws-dir"), Config.Get("ib-user-name"), Config.Get("ib-password"), Config.Get("ib-trading-mode"), Config.GetBool("ib-use-tws") ); // grabs account info from configuration var securityProvider = new SecurityProvider(); securityProvider[Symbols.USDJPY] = new Security( SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), new SubscriptionDataConfig( typeof(TradeBar), Symbols.USDJPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, false, false, false ), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance ); _interactiveBrokersBrokerage = new InteractiveBrokersBrokerage(new QCAlgorithm(), new OrderProvider(_orders), securityProvider); _interactiveBrokersBrokerage.Connect(); }
public void GetsTickData() { InteractiveBrokersGatewayRunner.StartFromConfiguration(); var ib = new InteractiveBrokersBrokerage(new OrderProvider()); ib.Connect(); ib.Subscribe(null, new Dictionary <SecurityType, List <string> > { { SecurityType.Forex, new List <string> { "USDJPY", "EURGBP" } } }); Thread.Sleep(1000); for (int i = 0; i < 10; i++) { foreach (var tick in ib.GetNextTicks()) { Console.WriteLine("{0}: {1} - {2} @ {3}", tick.Time, tick.Symbol, tick.Price, ((Tick)tick).Quantity); } } InteractiveBrokersGatewayRunner.Stop(); }
public void GetsTickData() { InteractiveBrokersGatewayRunner.StartFromConfiguration(); var ib = new InteractiveBrokersBrokerage(new QCAlgorithm(), new OrderProvider(), new SecurityProvider()); ib.Connect(); ib.Subscribe(null, new List <Symbol> { Symbols.USDJPY, Symbols.EURGBP }); Thread.Sleep(1000); var gotUsdData = false; var gotEurData = false; for (int i = 0; i < 20; i++) { foreach (var tick in ib.GetNextTicks()) { Console.WriteLine("{0}: {1} - {2} @ {3}", tick.Time, tick.Symbol, tick.Price, ((Tick)tick).Quantity); gotUsdData |= tick.Symbol == Symbols.USDJPY; gotEurData |= tick.Symbol == Symbols.EURGBP; } } Assert.IsTrue(gotUsdData); Assert.IsTrue(gotEurData); InteractiveBrokersGatewayRunner.Stop(); }
public void StressTestGetUsdConversion() { var brokerage = GetBrokerage(); Assert.IsTrue(brokerage.IsConnected); // private method testing hack :) var method = brokerage.GetType().GetMethod("GetUsdConversion", BindingFlags.NonPublic | BindingFlags.Instance); const string currency = "SEK"; const int count = 20; for (var i = 1; i <= count; i++) { var value = (decimal)method.Invoke(brokerage, new object[] { currency }); Console.WriteLine(i + " - GetUsdConversion({0}) = {1}", currency, value); Assert.IsTrue(value > 0); } brokerage.Disconnect(); brokerage.Dispose(); InteractiveBrokersGatewayRunner.Stop(); }
public void TestRateLimiting() { using (var brokerage = GetBrokerage()) { Assert.IsTrue(brokerage.IsConnected); var method = brokerage.GetType().GetMethod("GetContractDetails", BindingFlags.NonPublic | BindingFlags.Instance); var contract = new Contract { Symbol = "EUR", Exchange = "IDEALPRO", SecType = "CASH", Currency = Currencies.USD }; var parameters = new object[] { contract }; var result = Parallel.For(1, 100, x => { var stopwatch = Stopwatch.StartNew(); var value = (ContractDetails)method.Invoke(brokerage, parameters); stopwatch.Stop(); Console.WriteLine($"{DateTime.UtcNow:O} Response time: {stopwatch.Elapsed}"); }); while (!result.IsCompleted) { Thread.Sleep(1000); } } InteractiveBrokersGatewayRunner.Stop(); }
public void InitializeBrokerage() { InteractiveBrokersGatewayRunner.Start(Config.Get("ib-account")); // grabs account info from configuration _interactiveBrokersBrokerage = new InteractiveBrokersBrokerage(new OrderMapping(_orders)); _interactiveBrokersBrokerage.Connect(); }
public void IsConnectedAfterReset() { var ib = _interactiveBrokersBrokerage; Assert.IsTrue(ib.IsConnected); ib.ResetGatewayConnection(); Assert.IsTrue(InteractiveBrokersGatewayRunner.IsRunning()); Assert.IsTrue(ib.IsConnected); ib.CheckIbGateway(); Assert.IsTrue(ib.IsConnected); }
public void InitializeBrokerage() { InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"), Config.Get("ib-tws-dir"), Config.Get("ib-user-name"), Config.Get("ib-password"), Config.GetBool("ib-use-tws") ); // grabs account info from configuration _interactiveBrokersBrokerage = new InteractiveBrokersBrokerage(new OrderProvider(_orders)); _interactiveBrokersBrokerage.Connect(); }
protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider) { if (!_manualGatewayControl && !_gatewayLaunched) { _gatewayLaunched = true; InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"), Config.Get("ib-tws-dir"), Config.Get("ib-user-name"), Config.Get("ib-password"), Config.GetBool("ib-use-tws") ); } return(new InteractiveBrokersBrokerage(orderProvider, securityProvider)); }
protected override IBrokerage CreateBrokerage(IOrderMapping orderMapping, IHoldingsProvider holdingsProvider) { if (!_gatewayLaunched) { _gatewayLaunched = true; InteractiveBrokersGatewayRunner.Start(Config.Get("ib-controller-dir"), Config.Get("ib-tws-dir"), Config.Get("ib-user-name"), Config.Get("ib-password"), Config.GetBool("ib-use-tws") ); } return(new InteractiveBrokersBrokerage(orderMapping)); }
public void InitializesInstanceFromComposer() { var composer = Composer.Instance; var factory = composer.Single <IBrokerageFactory>(instance => instance.BrokerageType == typeof(InteractiveBrokersBrokerage)); Assert.IsNotNull(factory); var job = new LiveNodePacket { Brokerage = "Interactive Brokers" }; var brokerage = factory.CreateBrokerage(job, null); // IB factory doesn't use IAlgorithm instance Assert.IsNotNull(brokerage); Assert.IsInstanceOf <InteractiveBrokersBrokerage>(brokerage); brokerage.Connect(); Assert.IsTrue(brokerage.IsConnected); // this was launched by the factory InteractiveBrokersGatewayRunner.Stop(); }
public void GetsHistoryWithMultipleApiCalls() { using (var brokerage = GetBrokerage()) { Assert.IsTrue(brokerage.IsConnected); // request a week of historical data (including a weekend) var request = new HistoryRequest( new DateTime(2018, 2, 1, 9, 30, 0).ConvertToUtc(TimeZones.NewYork), new DateTime(2018, 2, 7, 16, 0, 0).ConvertToUtc(TimeZones.NewYork), typeof(TradeBar), Symbols.SPY, Resolution.Minute, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), TimeZones.NewYork, null, false, false, DataNormalizationMode.Raw, TickType.Trade); var history = brokerage.GetHistory(request).ToList(); // check if data points are in chronological order var previousEndTime = DateTime.MinValue; foreach (var bar in history) { Assert.IsTrue(bar.EndTime > previousEndTime); previousEndTime = bar.EndTime; } // should return 5 days of data (Thu-Fri-Mon-Tue-Wed) // each day has 390 minute bars for equities Assert.AreEqual(5 * 390, history.Count); } InteractiveBrokersGatewayRunner.Stop(); }
public void KillGateway() { InteractiveBrokersGatewayRunner.Stop(); Thread.Sleep(250); }
public void InitializeGateway() { InteractiveBrokersGatewayRunner.Start(Config.Get("ib-account")); }
/// <summary> /// Primary entry point to the program. This program only supports FOREX for now. /// </summary> static void Main(string[] args) { if (args.Length != 5) { Console.WriteLine("Usage: QuantConnect.ToolBox SYMBOLS RESOLUTION FROMDATE TODATE"); Console.WriteLine("SYMBOLS = eg EURUSD,USDJPY"); Console.WriteLine("RESOLUTION = Second/Minute/Hour/Daily/All"); Console.WriteLine("FROMDATE = yyyymmdd"); Console.WriteLine("TODATE = yyyymmdd"); Environment.Exit(1); } try { // Load settings from command line var tickers = args[1].Split(','); var allResolutions = args[2].ToLower() == "all"; var resolution = allResolutions ? Resolution.Second : (Resolution)Enum.Parse(typeof(Resolution), args[2]); var startDate = DateTime.ParseExact(args[3], "yyyyMMdd", CultureInfo.InvariantCulture).ConvertToUtc(TimeZones.NewYork); var endDate = DateTime.ParseExact(args[4], "yyyyMMdd", CultureInfo.InvariantCulture).ConvertToUtc(TimeZones.NewYork); // fix end date endDate = new DateTime(Math.Min(endDate.Ticks, DateTime.Now.AddDays(-1).Ticks)); // Max number of histoy days int maxDays = 1; if (!allResolutions) { switch (resolution) { case Resolution.Daily: maxDays = 365; break; case Resolution.Hour: maxDays = 30; break; case Resolution.Minute: maxDays = 10; break; } } // Load settings from config.json var dataDirectory = Config.Get("data-folder", "../../../Data"); // Create IB Broker Gateway Runner InteractiveBrokersGatewayRunner.StartFromConfiguration(); // Only FOREX for now SecurityType securityType = SecurityType.Forex; string market = Market.FXCM; using (var downloader = new IBDataDownloader()) { foreach (var ticker in tickers) { // Download the data var symbol = Symbol.Create(ticker, securityType, market); var auxEndDate = startDate.AddDays(maxDays); auxEndDate = new DateTime(Math.Min(auxEndDate.Ticks, endDate.Ticks)); while (startDate < auxEndDate) { var data = downloader.Get(symbol, resolution, startDate, auxEndDate); var bars = data.Cast <QuoteBar>().ToList(); if (allResolutions) { // Save the data (second resolution) var writer = new LeanDataWriter(resolution, symbol, dataDirectory); writer.Write(bars); // Save the data (other resolutions) foreach (var res in new[] { Resolution.Minute, Resolution.Hour, Resolution.Daily }) { var resData = downloader.AggregateBars(symbol, bars, res.ToTimeSpan()); writer = new LeanDataWriter(res, symbol, dataDirectory); writer.Write(resData); } } else { // Save the data (single resolution) var writer = new LeanDataWriter(resolution, symbol, dataDirectory); writer.Write(data); } startDate = auxEndDate; auxEndDate = auxEndDate.AddDays(maxDays); auxEndDate = new DateTime(Math.Min(auxEndDate.Ticks, endDate.Ticks)); } } } } catch (Exception err) { Log.Error(err); } finally { if (InteractiveBrokersGatewayRunner.IsRunning()) { InteractiveBrokersGatewayRunner.Stop(); } } }
public void Teardown() { try { // give the tear down a header so we can easily find it in the logs Log.Trace("-----"); Log.Trace("InteractiveBrokersBrokerageTests.Teardown(): Starting teardown..."); Log.Trace("-----"); var canceledResetEvent = new ManualResetEvent(false); var filledResetEvent = new ManualResetEvent(false); _interactiveBrokersBrokerage.OrderStatusChanged += (sender, orderEvent) => { if (orderEvent.Status == OrderStatus.Filled) { filledResetEvent.Set(); } if (orderEvent.Status == OrderStatus.Canceled) { canceledResetEvent.Set(); } }; // cancel all open orders Log.Trace("InteractiveBrokersBrokerageTests.Teardown(): Canceling open orders..."); var orders = _interactiveBrokersBrokerage.GetOpenOrders(); foreach (var order in orders) { _interactiveBrokersBrokerage.CancelOrder(order); canceledResetEvent.WaitOne(3000); canceledResetEvent.Reset(); } Log.Trace("InteractiveBrokersBrokerageTests.Teardown(): Liquidating open positions..."); // liquidate all positions var holdings = _interactiveBrokersBrokerage.GetAccountHoldings(); foreach (var holding in holdings.Where(x => x.Quantity != 0)) { //var liquidate = new MarketOrder(holding.Symbol, (int) -holding.Quantity, DateTime.UtcNow, type: holding.Type); //_interactiveBrokersBrokerage.PlaceOrder(liquidate); //filledResetEvent.WaitOne(3000); //filledResetEvent.Reset(); } var openOrdersText = _interactiveBrokersBrokerage.GetOpenOrders().Select(x => x.Symbol.ToString() + " " + x.Quantity); Log.Trace("InteractiveBrokersBrokerageTests.Teardown(): Open orders: " + string.Join(", ", openOrdersText)); //Assert.AreEqual(0, actualOpenOrderCount, "Failed to verify that there are zero open orders."); var holdingsText = _interactiveBrokersBrokerage.GetAccountHoldings().Where(x => x.Quantity != 0).Select(x => x.Symbol.ToString() + " " + x.Quantity); Log.Trace("InteractiveBrokersBrokerageTests.Teardown(): Account holdings: " + string.Join(", ", holdingsText)); //Assert.AreEqual(0, holdingsCount, "Failed to verify that there are zero account holdings."); _interactiveBrokersBrokerage.Dispose(); _interactiveBrokersBrokerage = null; _orders.Clear(); } finally { InteractiveBrokersGatewayRunner.Stop(); } }
public void DisposeBrokerage() { InteractiveBrokersGatewayRunner.Stop(); }
/// <summary> /// Primary entry point to the program. This program only supports FOREX for now. /// </summary> public static void IBDownloader(IList <string> tickers, string resolution, DateTime fromDate, DateTime toDate) { if (resolution.IsNullOrEmpty() || tickers.IsNullOrEmpty()) { Console.WriteLine("IBDownloader ERROR: '--tickers=' or '--resolution=' parameter is missing"); Console.WriteLine("--tickers=eg EURUSD,USDJPY"); Console.WriteLine("--resolution=Second/Minute/Hour/Daily/All"); Environment.Exit(1); } try { var allResolutions = resolution.ToLower() == "all"; var castResolution = allResolutions ? Resolution.Second : (Resolution)Enum.Parse(typeof(Resolution), resolution); var startDate = fromDate.ConvertToUtc(TimeZones.NewYork); var endDate = toDate.ConvertToUtc(TimeZones.NewYork); // fix end date endDate = new DateTime(Math.Min(endDate.Ticks, DateTime.Now.AddDays(-1).Ticks)); // Max number of histoy days int maxDays = 1; if (!allResolutions) { switch (castResolution) { case Resolution.Daily: maxDays = 365; break; case Resolution.Hour: maxDays = 30; break; case Resolution.Minute: maxDays = 10; break; } } // Load settings from config.json var dataDirectory = Config.Get("data-folder", "../../../Data"); // Create IB Broker Gateway Runner InteractiveBrokersGatewayRunner.StartFromConfiguration(); // Only FOREX for now SecurityType securityType = SecurityType.Forex; string market = Market.FXCM; using (var downloader = new IBDataDownloader()) { foreach (var ticker in tickers) { // Download the data var symbol = Symbol.Create(ticker, securityType, market); var auxEndDate = startDate.AddDays(maxDays); auxEndDate = new DateTime(Math.Min(auxEndDate.Ticks, endDate.Ticks)); while (startDate < auxEndDate) { var data = downloader.Get(symbol, castResolution, startDate, auxEndDate); var bars = data.Cast <QuoteBar>().ToList(); if (allResolutions) { // Save the data (second resolution) var writer = new LeanDataWriter(castResolution, symbol, dataDirectory); writer.Write(bars); // Save the data (other resolutions) foreach (var res in new[] { Resolution.Minute, Resolution.Hour, Resolution.Daily }) { var resData = downloader.AggregateBars(symbol, bars, res.ToTimeSpan()); writer = new LeanDataWriter(res, symbol, dataDirectory); writer.Write(resData); } } else { // Save the data (single resolution) var writer = new LeanDataWriter(castResolution, symbol, dataDirectory); writer.Write(data); } startDate = auxEndDate; auxEndDate = auxEndDate.AddDays(maxDays); auxEndDate = new DateTime(Math.Min(auxEndDate.Ticks, endDate.Ticks)); } } } } catch (Exception err) { Log.Error(err); } finally { if (InteractiveBrokersGatewayRunner.IsRunning()) { InteractiveBrokersGatewayRunner.Stop(); } } }