Files
StockSharp/Tests/OrderLogMessageAdapterTests.cs
mika@stocksharp.com d36df908af Tests: convert audit-flagged tests into TDD bug reproducers and strengthen oracles
Audit follow-up pass over the test suite, squashed from four commits. No engine
or production code is touched: red tests reproduce real defects and stay
failing until the engine is fixed; the rest of the strengthened tests pin the
contract where the engine is already correct.

- Rewrite the masking tests in the 12 masks-bug classes to assert the correct,
  domain-expected behavior instead of pinning the engine's broken output:
  AlertProcessingService inverted Greater/Less operators; degenerate Renko
  bricks and the Heikin-Ashi Open outside [Low, High]; the candle leak after
  SubscriptionFinished when Count is exhausted; VolumeProfile Value Area
  boundary defects; Level1DepthBuilderManager leaking the managed depth
  subscription id; invalid MarketDepth.Sparse books; OfflineMessageAdapter
  addressing the replaced order Done to the wrong transaction id;
  OrderLogMessageAdapter dropping the subscription id on built ticks;
  OrderMatcher FOK destructive book consumption and empty ghost levels;
  SecurityProvider dropping Skip in the lookup-all paging branch; Statistics
  double-counting cumulative commission; SubscriptionOnlineManager misrouting
  hist+live history and unsubscribe errors.

- Strengthen the audit's suspicious classes (vacuous, tautological, inert and
  weak oracles) into load-bearing tests and reproduce the residual core bugs:
  the FillGaps wrapper missing OwnInnerAdapter so Dispose does not cascade;
  BasketRoutingManager duplicating the parent subscription id and dropping data
  for pinned-adapter subscriptions; continuous-contract volume not reset on
  rollover; Import losing sub-second precision and the missing board ExpiryTime
  mapping; MarketOrderAlgo.IsFinished stuck after Cancel; ClearDatesCacheAsync
  not invalidating the cached dates; string condition parameters dropped from
  snapshot serialization; StorageBuffer buffering PositionChange with
  EnabledPositions off; StrategyParamHelper distorted float/double optimization
  ranges, off-by-one iteration count and bool GetRandom; the Renko volume
  profile counting tick volume once per brick; hist+live children never
  receiving their own subscription error; InMemorySecurityStorage ignoring the
  forced flag and never matching code-only ids; DecomposedStrategy.CanAttach
  claiming foreign orders.

- Unify Absolute protective units as an offset from the protected entry price
  (the same entry +/- level formula the engine already applies to Percent) and
  pin that contract consistently across the protection tests; the offset tests
  fail against the current raw-price-level engine behavior. Add real activation
  oracles for MarketOrderFlag and the limit close-by-timeout path.

- Reproduce the remaining audit bugs that need test doubles and add the first
  ServerProtectiveBehaviour coverage via a mock adapter: the self-created
  RemoteMarketDataDrive transport adapter never disposed; BasketMessageAdapter
  dropping out-data for known pinned-adapter subscriptions; the
  CandleBuilderManager Count leak for candles built from ticks; the
  ServerProtectiveBehaviour isTake flag hard-coded to the condition interface
  so stop-only registrations are mislabeled as takes. Absolute protective
  levels are verified as offsets from entry, each side on its own registration.
2026-06-12 18:58:01 +03:00

305 lines
9.3 KiB
C#

namespace StockSharp.Tests;
[TestClass]
public class OrderLogMessageAdapterTests : BaseTestClass
{
private sealed class TestDepthBuilder : IOrderLogMarketDepthBuilder
{
public QuoteChangeMessage Snapshot { get; set; }
public Func<ExecutionMessage, QuoteChangeMessage> UpdateFunc { get; set; }
public int SnapshotCalls { get; private set; }
public int UpdateCalls { get; private set; }
public DateTime? LastSnapshotTime { get; private set; }
public QuoteChangeMessage LastUpdateResult { get; private set; }
public QuoteChangeMessage GetSnapshot(DateTime serverTime)
{
SnapshotCalls++;
LastSnapshotTime = serverTime;
var snapshot = Snapshot?.TypedClone() ?? throw new InvalidOperationException("Snapshot is not set.");
snapshot.ServerTime = serverTime;
snapshot.LocalTime = serverTime;
return snapshot;
}
public QuoteChangeMessage Update(ExecutionMessage item)
{
UpdateCalls++;
LastUpdateResult = UpdateFunc?.Invoke(item);
return LastUpdateResult;
}
}
private static SubscriptionResponseMessage OkResponse(long originalTransactionId, DateTime localTime)
=> new() { OriginalTransactionId = originalTransactionId, LocalTime = localTime };
private static ExecutionMessage CreateOrderLog(SecurityId securityId, DateTime time, long[] subscriptionIds, decimal orderVolume = 1m)
{
var msg = new ExecutionMessage
{
DataTypeEx = DataType.OrderLog,
SecurityId = securityId,
ServerTime = time,
LocalTime = time,
IsSystem = true,
TradeId = 123,
TradePrice = 100m,
OrderVolume = orderVolume,
};
msg.SetSubscriptionIds(subscriptionIds);
return msg;
}
[TestMethod]
public async Task MarketDepth_Subscribe_RewrittenToOrderLog_AndSnapshotSentOnResponse()
{
var token = CancellationToken;
var secId = Helper.CreateSecurityId();
var builder = new TestDepthBuilder
{
Snapshot = new QuoteChangeMessage
{
SecurityId = secId,
BuildFrom = DataType.OrderLog,
State = QuoteChangeStates.SnapshotComplete,
Bids = [new QuoteChange(100m, 1m)],
Asks = [new QuoteChange(101m, 2m)],
}
};
var inner = new RecordingPassThroughMessageAdapter(supportedMarketDataTypes: [DataType.OrderLog]);
using var adapter = new OrderLogMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = secId,
DataType2 = DataType.MarketDepth,
DepthBuilder = builder,
}, token);
inner.InMessages.Count.AssertEqual(1);
((MarketDataMessage)inner.InMessages[0]).DataType2.AssertEqual(DataType.OrderLog);
output.Clear();
var time = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
await inner.SendOutMessageAsync(OkResponse(1, time), CancellationToken);
builder.SnapshotCalls.AssertEqual(1);
builder.LastSnapshotTime.AssertEqual(time);
output.Count.AssertEqual(2);
output[0].AssertOfType<QuoteChangeMessage>();
((QuoteChangeMessage)output[0]).GetSubscriptionIds().SequenceEqual([1L]).AssertTrue();
output[1].AssertOfType<SubscriptionResponseMessage>();
((SubscriptionResponseMessage)output[1]).OriginalTransactionId.AssertEqual(1);
}
[TestMethod]
public async Task Execution_OrderLog_ForMarketDepth_EmitsDepthUpdate_AndSuppressesOriginal()
{
var token = CancellationToken;
var secId = Helper.CreateSecurityId();
var builder = new TestDepthBuilder
{
Snapshot = new QuoteChangeMessage
{
SecurityId = secId,
BuildFrom = DataType.OrderLog,
State = QuoteChangeStates.SnapshotComplete,
Bids = [],
Asks = [],
},
UpdateFunc = item => new QuoteChangeMessage
{
SecurityId = item.SecurityId,
ServerTime = item.ServerTime,
LocalTime = item.LocalTime,
BuildFrom = DataType.OrderLog,
State = QuoteChangeStates.Increment,
Bids = [new QuoteChange(100m, 10m)],
Asks = [],
}
};
var inner = new RecordingPassThroughMessageAdapter(supportedMarketDataTypes: [DataType.OrderLog]);
using var adapter = new OrderLogMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = secId,
DataType2 = DataType.MarketDepth,
DepthBuilder = builder,
}, token);
await inner.SendOutMessageAsync(OkResponse(1, DateTime.UtcNow), CancellationToken);
output.Clear();
await inner.SendOutMessageAsync(CreateOrderLog(secId, DateTime.UtcNow.AddSeconds(1), subscriptionIds: [1]), CancellationToken);
output.OfType<ExecutionMessage>().Count().AssertEqual(0);
var depth = output.OfType<QuoteChangeMessage>().Single();
depth.GetSubscriptionIds().SequenceEqual([1L]).AssertTrue();
depth.State.AssertEqual(QuoteChangeStates.Increment);
depth.Bids.Length.AssertEqual(1);
depth.Bids[0].Price.AssertEqual(100m);
depth.Bids[0].Volume.AssertEqual(10m);
}
[TestMethod]
public async Task Execution_OrderLog_WithUnknownSubscriptionId_IsForwardedWithRemainingIds()
{
var token = CancellationToken;
var secId = Helper.CreateSecurityId();
var builder = new TestDepthBuilder
{
Snapshot = new QuoteChangeMessage
{
SecurityId = secId,
BuildFrom = DataType.OrderLog,
State = QuoteChangeStates.SnapshotComplete,
Bids = [],
Asks = [],
},
UpdateFunc = _ => new QuoteChangeMessage
{
SecurityId = secId,
ServerTime = DateTime.UtcNow,
LocalTime = DateTime.UtcNow,
State = QuoteChangeStates.Increment,
Bids = [new QuoteChange(100m, 1m)],
Asks = [],
}
};
var inner = new RecordingPassThroughMessageAdapter(supportedMarketDataTypes: [DataType.OrderLog]);
using var adapter = new OrderLogMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = secId,
DataType2 = DataType.MarketDepth,
DepthBuilder = builder,
}, token);
await inner.SendOutMessageAsync(OkResponse(1, DateTime.UtcNow), CancellationToken);
output.Clear();
await inner.SendOutMessageAsync(CreateOrderLog(secId, DateTime.UtcNow.AddSeconds(1), subscriptionIds: [1, 99]), CancellationToken);
output.OfType<QuoteChangeMessage>().Single().GetSubscriptionIds().SequenceEqual([1L]).AssertTrue();
var forwarded = output.OfType<ExecutionMessage>().Single();
forwarded.GetSubscriptionIds().SequenceEqual([99L]).AssertTrue();
}
[TestMethod]
public async Task Ticks_Subscribe_RewrittenToOrderLog_AndExecutionConvertedToTick()
{
var token = CancellationToken;
var secId = Helper.CreateSecurityId();
var inner = new RecordingPassThroughMessageAdapter(supportedMarketDataTypes: [DataType.OrderLog]);
using var adapter = new OrderLogMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 2,
SecurityId = secId,
DataType2 = DataType.Ticks,
}, token);
inner.InMessages.Count.AssertEqual(1);
((MarketDataMessage)inner.InMessages[0]).DataType2.AssertEqual(DataType.OrderLog);
await inner.SendOutMessageAsync(OkResponse(2, DateTime.UtcNow), CancellationToken);
output.Clear();
await inner.SendOutMessageAsync(CreateOrderLog(secId, DateTime.UtcNow.AddSeconds(1), subscriptionIds: [2], orderVolume: 7m), CancellationToken);
output.OfType<ExecutionMessage>().Count().AssertEqual(1);
var tick = output.OfType<ExecutionMessage>().Single();
tick.DataType.AssertEqual(DataType.Ticks);
tick.BuildFrom.AssertEqual(DataType.OrderLog);
tick.TradePrice.AssertEqual(100m);
tick.TradeVolume.AssertEqual(7m);
// The tick built from order log must carry the originating subscription id,
// mirroring the depth branch (depth.SetSubscriptionIds), otherwise it is
// never routed to the subscriber downstream.
tick.GetSubscriptionIds().SequenceEqual([2L]).AssertTrue();
}
[TestMethod]
public async Task Execution_OrderLog_WhenBuilderThrows_SendsErrorMessage()
{
var token = CancellationToken;
var secId = Helper.CreateSecurityId();
var builder = new TestDepthBuilder
{
Snapshot = new QuoteChangeMessage
{
SecurityId = secId,
BuildFrom = DataType.OrderLog,
State = QuoteChangeStates.SnapshotComplete,
Bids = [],
Asks = [],
},
UpdateFunc = _ => throw new InvalidOperationException("broken order log"),
};
var inner = new RecordingPassThroughMessageAdapter(supportedMarketDataTypes: [DataType.OrderLog]);
using var adapter = new OrderLogMessageAdapter(inner);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = secId,
DataType2 = DataType.MarketDepth,
DepthBuilder = builder,
}, token);
await inner.SendOutMessageAsync(OkResponse(1, DateTime.UtcNow), CancellationToken);
output.Clear();
await inner.SendOutMessageAsync(CreateOrderLog(secId, DateTime.UtcNow.AddSeconds(1), subscriptionIds: [1]), CancellationToken);
output.OfType<ErrorMessage>().Single().Error.Message.AssertEqual("broken order log");
}
}