public void DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough() { var algorithm = new AlgorithmStub(equities: new List <string> { "SPY" }); var referenceTime = DateTime.UtcNow; algorithm.SetDateTime(referenceTime); var localReferencTime = referenceTime.ConvertFromUtc(TimeZones.NewYork); var open = localReferencTime.AddSeconds(1).TimeOfDay; var closed = TimeSpan.FromDays(1); var marketHours = new MarketHoursSegment(MarketHoursState.Market, open, closed); algorithm.Securities[Symbols.SPY].Exchange.SetMarketHours(new [] { marketHours }, localReferencTime.DayOfWeek); var job = new LiveNodePacket(); var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet))); var api = new Api.Api(); var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(.25)); Assert.IsNull(algorithm.RunTimeError); handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!")); Thread.Sleep(100); handler.Handle(BrokerageMessageEvent.Reconnected("Reconnected!")); Thread.Sleep(500); Assert.IsNull(algorithm.RunTimeError); results.Exit(); }
/// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { if (IsConnected) { return; } Log.Trace("FxcmBrokerage.Connect()"); _cancellationTokenSource = new CancellationTokenSource(); // create new thread to fire order events in queue if (!EnableOnlyHistoryRequests) { _orderEventThread = new Thread(() => { while (!_cancellationTokenSource.IsCancellationRequested) { try { OrderEvent orderEvent; if (!_orderEventQueue.TryDequeue(out orderEvent)) { Thread.Sleep(1); continue; } OnOrderEvent(orderEvent); } catch (Exception exception) { Log.Error(exception); } } }) { IsBackground = true }; _orderEventThread.Start(); while (!_orderEventThread.IsAlive) { Thread.Sleep(1); } } // create the gateway _gateway = GatewayFactory.createGateway(); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // create local login properties var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server); loginProperties.addProperty(IConnectionManager.APP_INFO, "QuantConnect"); // log in try { _gateway.login(loginProperties); } catch (Exception err) { var message = err.Message.Contains("ORA-20101") ? "Incorrect login credentials" : err.Message.Contains("ORA-20003") ? "API connections are not available on Mini accounts. If you have a standard account contact [email protected] to enable API access" : err.Message; _cancellationTokenSource.Cancel(); throw new BrokerageException(message, err.InnerException); } // create new thread to manage disconnections and reconnections if (!EnableOnlyHistoryRequests) { _connectionMonitorThread = new Thread(() => { _lastReadyMessageTime = DateTime.UtcNow; try { while (!_cancellationTokenSource.IsCancellationRequested) { TimeSpan elapsed; lock (_lockerConnectionMonitor) { elapsed = DateTime.UtcNow - _lastReadyMessageTime; } if (!_connectionLost && elapsed > TimeSpan.FromSeconds(10)) { _connectionLost = true; OnMessage(BrokerageMessageEvent.Disconnected("Connection with FXCM server lost. " + "This could be because of internet connectivity issues. ")); } else if (_connectionLost && IsWithinTradingHours()) { Log.Trace("FxcmBrokerage.ConnectionMonitorThread(): Attempting reconnection..."); try { // log out try { _gateway.logout(); } catch (Exception) { // ignored } // remove the message listeners _gateway.removeGenericMessageListener(this); _gateway.removeStatusMessageListener(this); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // log in _gateway.login(loginProperties); // load instruments, accounts, orders, positions LoadInstruments(); if (!EnableOnlyHistoryRequests) { LoadAccounts(); LoadOpenOrders(); LoadOpenPositions(); } _connectionLost = false; OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored.")); } catch (Exception exception) { Log.Trace("FxcmBrokerage.ConnectionMonitorThread(): reconnect failed."); Log.Error(exception); } } Thread.Sleep(5000); } } catch (Exception exception) { Log.Error(exception); } }) { IsBackground = true }; _connectionMonitorThread.Start(); while (!_connectionMonitorThread.IsAlive) { Thread.Sleep(1); } } // load instruments, accounts, orders, positions LoadInstruments(); if (!EnableOnlyHistoryRequests) { LoadAccounts(); LoadOpenOrders(); LoadOpenPositions(); } }
/// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { // Register to the event session to receive events. StartTransactionStream(); _isConnected = true; // create new thread to manage disconnections and reconnections _cancellationTokenSource = new CancellationTokenSource(); _connectionMonitorThread = new Thread(() => { var nextReconnectionAttemptUtcTime = DateTime.UtcNow; double nextReconnectionAttemptSeconds = 1; lock (LockerConnectionMonitor) { LastHeartbeatUtcTime = DateTime.UtcNow; } try { while (!_cancellationTokenSource.IsCancellationRequested) { TimeSpan elapsed; lock (LockerConnectionMonitor) { elapsed = DateTime.UtcNow - LastHeartbeatUtcTime; } if (!_connectionLost && elapsed > TimeSpan.FromSeconds(20)) { _connectionLost = true; nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds); OnMessage(BrokerageMessageEvent.Disconnected("Connection with Oanda server lost. " + "This could be because of internet connectivity issues. ")); } else if (_connectionLost) { try { if (elapsed <= TimeSpan.FromSeconds(20)) { _connectionLost = false; nextReconnectionAttemptSeconds = 1; OnMessage(BrokerageMessageEvent.Reconnected("Connection with Oanda server restored.")); } else { if (DateTime.UtcNow > nextReconnectionAttemptUtcTime) { try { // check if we have a connection GetInstrumentList(); // restore events session StopTransactionStream(); StartTransactionStream(); // restore rates session List <Symbol> symbolsToSubscribe; lock (LockerSubscriptions) { symbolsToSubscribe = SubscribedSymbols.ToList(); } SubscribeSymbols(symbolsToSubscribe); } catch (Exception) { // double the interval between attempts (capped to 1 minute) nextReconnectionAttemptSeconds = Math.Min(nextReconnectionAttemptSeconds * 2, 60); nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds); } } } } catch (Exception exception) { Log.Error(exception); } } Thread.Sleep(1000); } } catch (Exception exception) { Log.Error(exception); } }) { IsBackground = true }; _connectionMonitorThread.Start(); while (!_connectionMonitorThread.IsAlive) { Thread.Sleep(1); } }
/// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { if (IsConnected) { return; } _sockClient.ConnectAsync().SynchronouslyAwaitTask(); _natsClient.Open(); _isConnected = true; // create new thread to manage disconnections and reconnections var connectionMonitorStartedEvent = new AutoResetEvent(false); _cancellationTokenSource = new CancellationTokenSource(); _connectionMonitorThread = new Thread(() => { connectionMonitorStartedEvent.Set(); var nextReconnectionAttemptSeconds = 1; try { while (!_cancellationTokenSource.IsCancellationRequested) { var isAlive = true; try { isAlive = _sockClient.IsAlive; } catch (Exception) { // ignored } if (isAlive && _connectionLost) { _connectionLost = false; nextReconnectionAttemptSeconds = 1; OnMessage(BrokerageMessageEvent.Reconnected("Connection with Alpaca server restored.")); } else if (!isAlive) { if (_connectionLost) { try { Thread.Sleep(TimeSpan.FromSeconds(nextReconnectionAttemptSeconds)); _sockClient.ConnectAsync().SynchronouslyAwaitTask(); } catch (Exception exception) { // double the interval between attempts (capped to 1 minute) nextReconnectionAttemptSeconds = Math.Min(nextReconnectionAttemptSeconds * 2, 60); Log.Error(exception); } } else { _connectionLost = true; OnMessage( BrokerageMessageEvent.Disconnected( "Connection with Alpaca server lost. " + "This could be because of internet connectivity issues. ")); } } Thread.Sleep(1000); } } catch (Exception exception) { Log.Error(exception); } }) { IsBackground = true }; _connectionMonitorThread.Start(); connectionMonitorStartedEvent.WaitOne(); }
/// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { if (IsConnected) { return; } Log.Trace("FxcmBrokerage.Connect()"); _cancellationTokenSource = new CancellationTokenSource(); // create new thread to fire order events in queue _orderEventThread = new Thread(() => { while (!_cancellationTokenSource.IsCancellationRequested) { OrderEvent orderEvent; if (!_orderEventQueue.TryDequeue(out orderEvent)) { Thread.Sleep(1); continue; } OnOrderEvent(orderEvent); } }); _orderEventThread.Start(); while (!_orderEventThread.IsAlive) { Thread.Sleep(1); } // create the gateway _gateway = GatewayFactory.createGateway(); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // create local login properties var loginProperties = new FXCMLoginProperties(_userName, _password, _terminal, _server); // log in _gateway.login(loginProperties); // create new thread to manage disconnections and reconnections _connectionMonitorThread = new Thread(() => { _lastReadyMessageTime = DateTime.UtcNow; try { while (!_cancellationTokenSource.IsCancellationRequested) { TimeSpan elapsed; lock (_lockerConnectionMonitor) { elapsed = DateTime.UtcNow - _lastReadyMessageTime; } if (!_connectionLost && elapsed > TimeSpan.FromSeconds(5)) { _connectionLost = true; OnMessage(BrokerageMessageEvent.Disconnected("Connection with FXCM server lost. " + "This could be because of internet connectivity issues. ")); } else if (_connectionLost && elapsed <= TimeSpan.FromSeconds(5)) { try { _gateway.relogin(); _connectionLost = false; OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored.")); } catch (Exception exception) { Log.Error(exception); } } else if (_connectionError) { try { // log out _gateway.logout(); // remove the message listeners _gateway.removeGenericMessageListener(this); _gateway.removeStatusMessageListener(this); // register the message listeners with the gateway _gateway.registerGenericMessageListener(this); _gateway.registerStatusMessageListener(this); // log in _gateway.login(loginProperties); // load instruments, accounts, orders, positions LoadInstruments(); LoadAccounts(); LoadOpenOrders(); LoadOpenPositions(); _connectionError = false; _connectionLost = false; OnMessage(BrokerageMessageEvent.Reconnected("Connection with FXCM server restored.")); } catch (Exception exception) { Log.Error(exception); } } Thread.Sleep(5000); } } catch (Exception exception) { Log.Error(exception); } }); _connectionMonitorThread.Start(); while (!_connectionMonitorThread.IsAlive) { Thread.Sleep(1); } // load instruments, accounts, orders, positions LoadInstruments(); LoadAccounts(); LoadOpenOrders(); LoadOpenPositions(); }
private void OnTransactionsConnectionRestored(object sender, EventArgs e) { Log.Trace("OnTransactionsConnectionRestored(): transactions connection restored"); OnMessage(BrokerageMessageEvent.Reconnected("Transactions connection with Oanda server restored.")); }
private void OnPricingConnectionRestored(object sender, EventArgs e) { Log.Trace("OnPricingConnectionRestored(): pricing connection restored"); OnMessage(BrokerageMessageEvent.Reconnected("Pricing connection with Oanda server restored.")); }
/// <summary> /// Connects the client to the broker's remote servers /// </summary> public override void Connect() { if (IsConnected) { return; } // Load the list of instruments _oandaInstruments = GetInstruments().ToDictionary(x => x.instrument); // Register to the event session to receive events. _eventsSession = new EventsSession(this, _accountId); _eventsSession.DataReceived += OnEventReceived; _eventsSession.StartSession(); _isConnected = true; // create new thread to manage disconnections and reconnections _cancellationTokenSource = new CancellationTokenSource(); _connectionMonitorThread = new Thread(() => { var nextReconnectionAttemptUtcTime = DateTime.UtcNow; double nextReconnectionAttemptSeconds = 1; lock (_lockerConnectionMonitor) { _lastHeartbeatUtcTime = DateTime.UtcNow; } try { while (!_cancellationTokenSource.IsCancellationRequested) { TimeSpan elapsed; lock (_lockerConnectionMonitor) { elapsed = DateTime.UtcNow - _lastHeartbeatUtcTime; } if (!_connectionLost && elapsed > TimeSpan.FromSeconds(20)) { _connectionLost = true; nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds); OnMessage(BrokerageMessageEvent.Disconnected("Connection with Oanda server lost. " + "This could be because of internet connectivity issues. ")); } else if (_connectionLost) { try { if (elapsed <= TimeSpan.FromSeconds(20)) { _connectionLost = false; nextReconnectionAttemptSeconds = 1; OnMessage(BrokerageMessageEvent.Reconnected("Connection with Oanda server restored.")); } else { if (DateTime.UtcNow > nextReconnectionAttemptUtcTime) { try { // check if we have a connection GetInstruments(); // restore events session if (_eventsSession != null) { _eventsSession.DataReceived -= OnEventReceived; _eventsSession.StopSession(); } _eventsSession = new EventsSession(this, _accountId); _eventsSession.DataReceived += OnEventReceived; _eventsSession.StartSession(); // restore rates session List <Symbol> symbolsToSubscribe; lock (_lockerSubscriptions) { symbolsToSubscribe = _subscribedSymbols.ToList(); } SubscribeSymbols(symbolsToSubscribe); } catch (Exception) { // double the interval between attempts (capped to 1 minute) nextReconnectionAttemptSeconds = Math.Min(nextReconnectionAttemptSeconds * 2, 60); nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds); } } } } catch (Exception exception) { Log.Error(exception); } } Thread.Sleep(1000); } } catch (Exception exception) { Log.Error(exception); } }); _connectionMonitorThread.Start(); while (!_connectionMonitorThread.IsAlive) { Thread.Sleep(1); } }