Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions Common/Brokerages/DefaultBrokerageMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,15 @@ public void HandleMessage(BrokerageMessageEvent message)
_connected = false;
Log.Trace(Messages.DefaultBrokerageMessageHandler.Disconnected);

// the check below waits in wall time, the algorithm time can lag behind it, during warm up by far
var utcNow = DateTime.UtcNow;

// check to see if any non-custom security exchanges are open within the next x minutes
var open = (from kvp in _algorithm.Securities
let security = kvp.Value
where security.Type != SecurityType.Base
let exchange = security.Exchange
let localTime = _algorithm.UtcTime.ConvertFromUtc(exchange.TimeZone)
let localTime = utcNow.ConvertFromUtc(exchange.TimeZone)
where exchange.IsOpenDuringBar(
localTime,
localTime + _openThreshold,
Expand Down Expand Up @@ -133,7 +136,7 @@ where exchange.IsOpenDuringBar(
let security = kvp.Value
where security.Type != SecurityType.Base
let exchange = security.Exchange
let localTime = _algorithm.UtcTime.ConvertFromUtc(exchange.TimeZone)
let localTime = utcNow.ConvertFromUtc(exchange.TimeZone)
let marketOpen = exchange.Hours.GetNextMarketOpen(localTime,
_algorithm.SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(security.Symbol)
Expand All @@ -144,10 +147,11 @@ where exchange.IsOpenDuringBar(
else
{
// if we have no securities just make next market open an hour from now
nextMarketOpenUtc = DateTime.UtcNow.AddHours(1);
nextMarketOpenUtc = utcNow.AddHours(1);
}

var timeUntilNextMarketOpen = nextMarketOpenUtc - DateTime.UtcNow - _openThreshold;
// a negative delay throws, a due check still runs
var timeUntilNextMarketOpen = Time.Max(nextMarketOpenUtc - utcNow - _openThreshold, TimeSpan.Zero);
Log.Trace(Messages.DefaultBrokerageMessageHandler.TimeUntilNextMarketOpen(timeUntilNextMarketOpen));

// wake up 5 minutes before market open and check if we've reconnected
Expand Down Expand Up @@ -201,7 +205,7 @@ private void StartCheckReconnected(TimeSpan delay, BrokerageMessageEvent message

CheckReconnected(message);

}, _cancellationTokenSource.Token);
});
}

private void CheckReconnected(BrokerageMessageEvent message)
Expand Down
45 changes: 45 additions & 0 deletions Tests/Engine/DefaultBrokerageMessageHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,50 @@ public void DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough()

results.Exit();
}

[Test]
public void DoesNotThrowOnDisconnectDuringWarmUpWhenAlgorithmTimeIsInThePast()
{
// during a live warm up the algorithm time lags the wall time by the warm up period
var algorithm = new AlgorithmStub();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.AddSecurities(equities: new List<string> { "SPY" });
algorithm.SetWarmUp(TimeSpan.FromDays(400));
var referenceTime = DateTime.UtcNow.AddDays(-400);
algorithm.SetDateTime(referenceTime);
algorithm.Securities[Symbols.SPY].Exchange.SetMarketHours(Enumerable.Empty<MarketHoursSegment>(), referenceTime.ConvertFromUtc(TimeZones.NewYork).DayOfWeek);
using var api = new Api.Api();
var handler = new DefaultBrokerageMessageHandler(algorithm, new LiveNodePacket(), api, TimeSpan.FromSeconds(2));

Assert.IsTrue(algorithm.IsWarmingUp);
Assert.DoesNotThrow(() => handler.HandleMessage(BrokerageMessageEvent.Disconnected("Disconnection!")));
Assert.IsNull(algorithm.RunTimeError);

handler.HandleMessage(BrokerageMessageEvent.Reconnected("Reconnected!"));
}

[Test]
public void DoesNotThrowOnDisconnectWhenTheAlgorithmTimeLagsBehindThePreOpenCutoff()
{
// the algorithm time is two seconds before the pre open cutoff, the wall time is two seconds after it
var openThreshold = TimeSpan.FromMinutes(5);
var wallTime = DateTime.UtcNow;
var algorithm = new AlgorithmStub();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
algorithm.AddSecurities(equities: new List<string> { "SPY" });
algorithm.SetDateTime(wallTime.AddSeconds(-4));
var localWallTime = wallTime.ConvertFromUtc(TimeZones.NewYork);
var open = (localWallTime + openThreshold).AddSeconds(-2);
Assume.That(open.Date, Is.EqualTo(localWallTime.Date), "The test needs the market open on the same day");
var marketHours = new MarketHoursSegment(MarketHoursState.Market, open.TimeOfDay, TimeSpan.FromDays(1));
algorithm.Securities[Symbols.SPY].Exchange.SetMarketHours(new[] { marketHours }, localWallTime.DayOfWeek);
using var api = new Api.Api();
var handler = new DefaultBrokerageMessageHandler(algorithm, new LiveNodePacket(), api, TimeSpan.FromSeconds(2), openThreshold);

Assert.DoesNotThrow(() => handler.HandleMessage(BrokerageMessageEvent.Disconnected("Disconnection!")));
Assert.IsNull(algorithm.RunTimeError);

handler.HandleMessage(BrokerageMessageEvent.Reconnected("Reconnected!"));
}
}
}
Loading