Files
StockSharp/Tests/MarketDataStorageCacheTests.cs
mika@stocksharp.com 661fad5eb6 A backtest replays whatever history it has, and says why it ends
A run whose market data was all refused for lack of history waited for
its first subscription forever. It ends now when it starts with all the
market data asked for refused. Whether any is left is decided when the
run starts, never at a refusal: a strategy asks for one series after
another, so the refusal of a pair's first leg comes before its second
is asked for, and stopping there ended a run that had the second leg's
history. A run with nothing asked for yet keeps waiting, as a host may
start the strategy after the run, as the Studio runner does.

Such a run ends with an error rather than as a finished one: Connector.
Error says the market data is missing, StopError keeps it for a host
that looks once the run has stopped, and the progress does not reach
100. A run stopped on a failed subscription (StopOnSubscriptionError)
ends the same way. A strategy that asks for no market data, or whose
market data was all refused, is stopped with that error by
StrategyHelper.StopIfNoMarketDataAsync once it has started, which
ExecAsync and the optimizer use: ExecAsync reported such a run as
completed or waited for it forever, and the optimizer's check ran
before the connector was connected and left the iteration waiting.

Partial history, which the tests never fed a run, had more of the same:
- a refused subscription kept the strategy offline for the whole run,
  so a run that went on with the data it had sent no order. Only a
  subscription refused before it got going is left out; one that fails
  after it went online still takes the strategy offline, its data gone;
- ticks only a generator made never started the replay;
- a series stored only outside the run's dates stood in for the run's
  own data, so five-minute candles were not built from the run's
  one-minute candles and none arrived;
- a subscription added during the run made the replay send again what
  it had already sent at that moment, and with the cache of days it got
  nothing until the next day, the cache knowing a day by its date alone;
- history that ended before the run's stop left its progress at a
  fifth. A run that runs out of history reports the whole way now; one
  disconnected halfway still reports where it stopped, which the
  optimizer goes by to stop the strategy of an iteration it cancels;
- an instrument whose history ended before the run's kept its last bid
  and ask, so orders on it filled in any volume at a day-old price. Once
  its last bar is handed over its market closes: a market order finds
  no price, a limit waits, a position keeps the value of the quotes the
  market closed with, and more history opens the market again;
- a day without history moved the strategy's clock twice, just after
  midnight, and the clock reached the stop only after the run had
  stopped. The replay walks such a day at the pace of the time-frame
  candles and generators it still replays, the emulator hands the clock
  on with every bar it releases, and the run's last moment is its stop
  date, so timers and time rules fire through the gaps. Ticks, quotes
  and the order log keep no pace, and the days after every history has
  ended are marked only where they begin, so a long stop after the
  history costs no more than it did.
2026-10-24 22:31:07 +03:00

154 lines
4.3 KiB
C#

namespace StockSharp.Tests;
using System.Runtime.CompilerServices;
[TestClass]
public class MarketDataStorageCacheTests : BaseTestClass
{
private static SecurityId CreateSecurityId(string code = "TEST") => Helper.CreateSecurityId(code, BoardCodes.Test);
private static ExecutionMessage CreateTick(SecurityId securityId, DateTime serverTime) => new()
{
SecurityId = securityId,
DataTypeEx = DataType.Ticks,
ServerTime = serverTime,
TradePrice = 1,
TradeVolume = 1,
};
[TestMethod]
public async Task GetMessagesAsync_CachesPerKey()
{
var token = CancellationToken;
var cache = new MarketDataStorageCache();
var secId = CreateSecurityId();
var date = new DateTime(2025, 1, 1);
var messages = new Message[]
{
CreateTick(secId, date.AddHours(1)),
CreateTick(secId, date.AddHours(2)),
};
var loadCalls = 0;
async IAsyncEnumerable<Message> Loader(DateTime _)
{
loadCalls++;
foreach (var message in messages)
{
yield return message;
await Task.Yield();
}
}
var first = await cache.GetMessagesAsync(secId, DataType.Ticks, date, Loader).ToArrayAsync(token);
var second = await cache.GetMessagesAsync(secId, DataType.Ticks, date, Loader).ToArrayAsync(token);
loadCalls.AssertEqual(1);
first.SequenceEqual(messages).AssertTrue();
second.SequenceEqual(first).AssertTrue();
}
[TestMethod]
public Task GetMessagesAsync_Cancellation_ThrowsOperationCanceledException()
{
var cache = new MarketDataStorageCache();
var secId = CreateSecurityId();
var date = new DateTime(2025, 1, 1);
async IAsyncEnumerable<Message> Loader(DateTime _)
{
yield return CreateTick(secId, date.AddHours(1));
await Task.Yield();
}
var cts = new CancellationTokenSource();
cts.Cancel();
return ThrowsExactlyAsync<OperationCanceledException>(async () =>
{
await cache.GetMessagesAsync(secId, DataType.Ticks, date, Loader).ToArrayAsync(cts.Token);
});
}
[TestMethod]
public async Task GetMessagesAsync_OverLimit_EvictsCachedEntries()
{
var token = CancellationToken;
var cache = new MarketDataStorageCache { Limit = 1 };
var secId = CreateSecurityId();
var loadCalls = 0;
async IAsyncEnumerable<Message> Loader(DateTime date)
{
loadCalls++;
yield return CreateTick(secId, date.AddHours(1));
await Task.Yield();
}
await cache.GetMessagesAsync(secId, DataType.Ticks, new DateTime(2025, 1, 1), Loader).ToArrayAsync(token);
await cache.GetMessagesAsync(secId, DataType.Ticks, new DateTime(2025, 1, 2), Loader).ToArrayAsync(token);
await cache.GetMessagesAsync(secId, DataType.Ticks, new DateTime(2025, 1, 3), Loader).ToArrayAsync(token);
loadCalls.AssertEqual(3);
await cache.GetMessagesAsync(secId, DataType.Ticks, new DateTime(2025, 1, 1), Loader).ToArrayAsync(token);
loadCalls.AssertEqual(4);
}
[TestMethod]
public void Limit_Invalid_ThrowsArgumentOutOfRangeException()
{
var cache = new MarketDataStorageCache();
ThrowsExactly<ArgumentOutOfRangeException>(() => cache.Limit = 0);
}
/// <summary>
/// A day of several series is cached by what it is made of: the same day of other series is loaded on its own, and
/// the day of the same series again comes from the cache.
/// </summary>
[TestMethod]
public async Task GetMessagesAsync_TheSameDayOfOtherSeries_IsLoadedApart()
{
var token = CancellationToken;
var cache = new MarketDataStorageCache();
var first = CreateSecurityId("FIRST");
var second = CreateSecurityId("SECOND");
var date = new DateTime(2025, 1, 1);
var loadCalls = 0;
IAsyncEnumerable<Message> LoaderOf(params SecurityId[] securities)
{
return Load();
async IAsyncEnumerable<Message> Load()
{
loadCalls++;
foreach (var securityId in securities)
{
yield return CreateTick(securityId, date.AddHours(1));
await Task.Yield();
}
}
}
var alone = await cache.GetMessagesAsync("first", date, _ => LoaderOf(first)).ToArrayAsync(token);
var both = await cache.GetMessagesAsync("first|second", date, _ => LoaderOf(first, second)).ToArrayAsync(token);
var again = await cache.GetMessagesAsync("first", date, _ => LoaderOf(first)).ToArrayAsync(token);
loadCalls.AssertEqual(2);
alone.Length.AssertEqual(1);
both.Cast<ExecutionMessage>().Select(m => m.SecurityId).SequenceEqual([first, second]).AssertTrue();
again.SequenceEqual(alone).AssertTrue();
}
}