Files
StockSharp/Tests/SecurityNativeIdMessageAdapterTests.cs

655 lines
22 KiB
C#

namespace StockSharp.Tests;
[TestClass]
public class SecurityNativeIdMessageAdapterTests : BaseTestClass
{
private sealed class TestPassThroughAdapter : PassThroughMessageAdapter
{
private readonly string _storageName;
// Default constructor required for cloning
public TestPassThroughAdapter()
: base(new IncrementalIdGenerator())
{
_storageName = "TestAdapter";
}
public TestPassThroughAdapter(string storageName)
: base(new IncrementalIdGenerator())
{
_storageName = storageName;
}
public override string StorageName => _storageName;
public List<Message> InMessages { get; } = [];
public override ValueTask SendInMessageAsync(Message message, CancellationToken cancellationToken)
{
// Snapshot the message on receipt: the pass-through echo runs it back through the wrapping
// adapter's out-resolution, which mutates the same instance (native id -> friendly id).
InMessages.Add(message.Clone());
return base.SendInMessageAsync(message, cancellationToken);
}
}
private sealed class MockNativeIdStorage : INativeIdStorage
{
private readonly SynchronizedDictionary<SecurityId, object> _bySecurityId = [];
private readonly SynchronizedDictionary<object, SecurityId> _byNativeId = new(new ObjectComparer());
public event Func<SecurityId, object, CancellationToken, ValueTask> Added;
public ValueTask<(SecurityId secId, object nativeId)[]> GetAsync(CancellationToken cancellationToken = default)
{
return new([.. _bySecurityId.Select(p => (p.Key, p.Value))]);
}
public async ValueTask<bool> TryAddAsync(SecurityId securityId, object nativeId, bool isPersistable = true, CancellationToken cancellationToken = default)
{
if (_bySecurityId.ContainsKey(securityId) || _byNativeId.ContainsKey(nativeId))
return false;
_bySecurityId[securityId] = nativeId;
_byNativeId[nativeId] = securityId;
await Added.InvokeAsync(securityId, nativeId, cancellationToken);
return true;
}
public ValueTask<SecurityId?> TryGetByNativeIdAsync(object nativeId, CancellationToken cancellationToken = default)
{
return new(_byNativeId.TryGetValue(nativeId, out var secId) ? secId : null);
}
public ValueTask<object> TryGetBySecurityIdAsync(SecurityId securityId, CancellationToken cancellationToken = default)
{
return new(_bySecurityId.TryGetValue(securityId));
}
public ValueTask ClearAsync(CancellationToken cancellationToken = default)
{
_bySecurityId.Clear();
_byNativeId.Clear();
return default;
}
public ValueTask<bool> RemoveBySecurityIdAsync(SecurityId securityId, bool isPersistable = true, CancellationToken cancellationToken = default)
{
if (!_bySecurityId.TryGetAndRemove(securityId, out var nativeId))
return new(false);
_byNativeId.Remove(nativeId);
return new(true);
}
public ValueTask<bool> RemoveByNativeIdAsync(object nativeId, bool isPersistable = true, CancellationToken cancellationToken = default)
{
if (!_byNativeId.TryGetAndRemove(nativeId, out var secId))
return new(false);
_bySecurityId.Remove(secId);
return new(true);
}
private sealed class ObjectComparer : IEqualityComparer<object>
{
public new bool Equals(object x, object y) => Equals2(x, y);
private static bool Equals2(object x, object y)
{
if (ReferenceEquals(x, y))
return true;
if (x is null || y is null)
return false;
if (x is byte[] xBytes && y is byte[] yBytes)
return xBytes.SequenceEqual(yBytes);
return x.Equals(y);
}
public int GetHashCode(object obj)
{
if (obj is byte[] bytes)
return bytes.Length > 0 ? bytes[0].GetHashCode() : 0;
return obj?.GetHashCode() ?? 0;
}
}
}
private sealed class MockNativeIdStorageProvider : INativeIdStorageProvider
{
private readonly SynchronizedDictionary<string, INativeIdStorage> _storages = [];
public INativeIdStorage GetStorage(string storageName)
{
return _storages.SafeAdd(storageName, _ => new MockNativeIdStorage());
}
public ValueTask<Dictionary<string, Exception>> InitAsync(CancellationToken cancellationToken)
{
return new([]);
}
public ValueTask DisposeAsync() => default;
}
[TestMethod]
public async Task Connect_LoadsExistingNativeIds_AndTranslatesOutMessages()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "AAPL", BoardCode = "NASDAQ" };
var nativeId = 12345L;
var storageProvider = new MockNativeIdStorageProvider();
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId, nativeId, cancellationToken: token);
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
output.OfType<ConnectMessage>().Count().AssertEqual(1);
// After connect, outgoing messages with native id should be translated to security id
var level1Msg = new Level1ChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
ServerTime = DateTime.UtcNow
};
level1Msg.Add(Level1Fields.LastTradePrice, 150m);
await inner.SendOutMessageAsync(level1Msg, CancellationToken);
// The message should be translated and forwarded
var level1s = output.OfType<Level1ChangeMessage>().ToArray();
level1s.Length.AssertEqual(1);
level1s[0].SecurityId.SecurityCode.AssertEqual("AAPL");
level1s[0].SecurityId.BoardCode.AssertEqual("NASDAQ");
level1s[0].SecurityId.Native.AssertNull(); // Native should be stripped
}
[TestMethod]
public async Task SecurityMessage_WithNativeId_StoresMapping()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "MSFT", BoardCode = "NYSE", Native = "native_msft" };
var storageProvider = new MockNativeIdStorageProvider();
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
await inner.SendOutMessageAsync(new SecurityMessage { SecurityId = secId }, CancellationToken);
var secMsgs = output.OfType<SecurityMessage>().ToArray();
secMsgs.Length.AssertEqual(1);
secMsgs[0].SecurityId.Native.AssertNull();
secMsgs[0].SecurityId.SecurityCode.AssertEqual("MSFT");
secMsgs[0].SecurityId.BoardCode.AssertEqual("NYSE");
var storage = storageProvider.GetStorage("TestAdapter");
var storedNative = await storage.TryGetBySecurityIdAsync(new SecurityId { SecurityCode = "MSFT", BoardCode = "NYSE" }, token);
storedNative.AssertEqual("native_msft");
}
[TestMethod]
public async Task InMessage_WithoutKnownNativeId_IsSuspended()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "UNKNOWN", BoardCode = "TEST" };
var storageProvider = new MockNativeIdStorageProvider();
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var orderMsg = new OrderRegisterMessage
{
SecurityId = secId,
TransactionId = 1,
Side = Sides.Buy,
Price = 100,
Volume = 10
};
await adapter.SendInMessageAsync(orderMsg, token);
// Should NOT be forwarded since native id is unknown
inner.InMessages.OfType<OrderRegisterMessage>().Count().AssertEqual(0);
var nativeId = "native_unknown";
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId, nativeId, cancellationToken: token);
var releaseId = secId;
releaseId.Native = nativeId;
await adapter.SendInMessageAsync(new ProcessSuspendedMessage(adapter, releaseId), token);
var released = inner.InMessages.OfType<OrderRegisterMessage>().Single();
released.SecurityId.SecurityCode.AssertEqual(secId.SecurityCode);
released.SecurityId.BoardCode.AssertEqual(secId.BoardCode);
released.SecurityId.Native.AssertEqual(nativeId);
}
[TestMethod]
public async Task OutMessage_WithNativeId_IsTranslatedToSecurityId()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "GOOG", BoardCode = "NASDAQ" };
var nativeId = 12345L;
var storageProvider = new MockNativeIdStorageProvider();
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId, nativeId, cancellationToken: token);
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var execMsg = new ExecutionMessage
{
SecurityId = new SecurityId { Native = nativeId },
DataTypeEx = DataType.Ticks,
TradePrice = 100,
TradeVolume = 10,
ServerTime = DateTime.UtcNow
};
await inner.SendOutMessageAsync(execMsg, CancellationToken);
var execs = output.OfType<ExecutionMessage>().ToArray();
execs.Length.AssertEqual(1);
execs[0].SecurityId.SecurityCode.AssertEqual("GOOG");
execs[0].SecurityId.BoardCode.AssertEqual("NASDAQ");
execs[0].SecurityId.Native.AssertNull();
}
[TestMethod]
public async Task OutMessage_WithUnknownNativeId_IsSuspended_ThenReleased()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "TSLA", BoardCode = "NASDAQ" };
var nativeId = "native_tsla";
var storageProvider = new MockNativeIdStorageProvider();
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var level1Msg = new Level1ChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
ServerTime = DateTime.UtcNow
};
level1Msg.Add(Level1Fields.LastTradePrice, 100m);
await inner.SendOutMessageAsync(level1Msg, CancellationToken);
// Should be suspended since native id is not yet known
output.OfType<Level1ChangeMessage>().Count().AssertEqual(0);
// Now send security message that maps the native id
await inner.SendOutMessageAsync(new SecurityMessage
{
SecurityId = new SecurityId { SecurityCode = "TSLA", BoardCode = "NASDAQ", Native = nativeId }
}, CancellationToken);
// Suspended message should now be released
var level1s = output.OfType<Level1ChangeMessage>().ToArray();
level1s.Length.AssertEqual(1);
level1s[0].SecurityId.SecurityCode.AssertEqual("TSLA");
level1s[0].SecurityId.BoardCode.AssertEqual("NASDAQ");
level1s[0].SecurityId.Native.AssertNull();
}
[TestMethod]
public async Task Reset_ClearsAllState()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "FB", BoardCode = "NASDAQ" };
var nativeId = "native_fb";
var storageProvider = new MockNativeIdStorageProvider();
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new OrderRegisterMessage
{
SecurityId = secId,
TransactionId = 1,
Side = Sides.Buy,
Price = 100,
Volume = 10,
}, token);
await inner.SendOutMessageAsync(new Level1ChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
ServerTime = DateTime.UtcNow,
}, token);
await adapter.SendInMessageAsync(new ResetMessage(), token);
await inner.SendOutMessageAsync(new SecurityMessage
{
SecurityId = new SecurityId { SecurityCode = secId.SecurityCode, BoardCode = secId.BoardCode, Native = nativeId },
}, token);
var releaseId = secId;
releaseId.Native = nativeId;
await adapter.SendInMessageAsync(new ProcessSuspendedMessage(adapter, releaseId), token);
inner.InMessages.OfType<OrderRegisterMessage>().Count().AssertEqual(0);
output.OfType<Level1ChangeMessage>().Count().AssertEqual(0);
}
// Note: Clone test removed because nested test adapter classes don't work well with reflection-based cloning
[TestMethod]
public async Task DuplicateNativeId_UpdatesMappingAndTranslationCache()
{
var token = CancellationToken;
var secId1 = new SecurityId { SecurityCode = "SYM1", BoardCode = "BOARD" };
var secId2 = new SecurityId { SecurityCode = "SYM2", BoardCode = "BOARD" };
var nativeId = "shared_native";
var storageProvider = new MockNativeIdStorageProvider();
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId1, nativeId, cancellationToken: token);
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
// Send security with same native id but different security code
await inner.SendOutMessageAsync(new SecurityMessage
{
SecurityId = new SecurityId { SecurityCode = "SYM2", BoardCode = "BOARD", Native = nativeId }
}, CancellationToken);
// Verify the new mapping is stored
var storedSecId = await storage.TryGetByNativeIdAsync(nativeId, token);
storedSecId.AssertNotNull();
storedSecId.Value.SecurityCode.AssertEqual("SYM2");
await inner.SendOutMessageAsync(new Level1ChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
ServerTime = DateTime.UtcNow,
}, token);
var translated = output.OfType<Level1ChangeMessage>().Single();
translated.SecurityId.AssertEqual(secId2);
}
[TestMethod]
public async Task ExecutionMessage_WithTransactionId_TracksSecurityId()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "AMZN", BoardCode = "NASDAQ" };
var nativeId = "native_amzn";
var storageProvider = new MockNativeIdStorageProvider();
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var tracked = new ExecutionMessage
{
SecurityId = new SecurityId { Native = nativeId },
DataTypeEx = DataType.Transactions,
TransactionId = 100,
ServerTime = DateTime.UtcNow,
HasOrderInfo = true,
OrderState = OrderStates.Active
};
await inner.SendOutMessageAsync(tracked, CancellationToken);
output.OfType<ExecutionMessage>().Count().AssertEqual(0);
await inner.SendOutMessageAsync(new ExecutionMessage
{
DataTypeEx = DataType.Transactions,
OriginalTransactionId = tracked.TransactionId,
ServerTime = DateTime.UtcNow,
TradePrice = 101,
TradeVolume = 1,
}, CancellationToken);
output.OfType<ExecutionMessage>().Count().AssertEqual(0);
await inner.SendOutMessageAsync(new SecurityMessage
{
SecurityId = new SecurityId { SecurityCode = secId.SecurityCode, BoardCode = secId.BoardCode, Native = nativeId },
}, CancellationToken);
var execs = output.OfType<ExecutionMessage>().ToArray();
execs.Length.AssertEqual(2);
execs.All(m => m.SecurityId == secId).AssertTrue();
execs.Single(m => m.TradePrice != null).OriginalTransactionId.AssertEqual(tracked.TransactionId);
}
[TestMethod]
public async Task QuoteChangeMessage_WithNativeId_IsTranslated()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "NVDA", BoardCode = "NASDAQ" };
var nativeId = 99999L;
var storageProvider = new MockNativeIdStorageProvider();
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId, nativeId, cancellationToken: token);
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var quotesMsg = new QuoteChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
ServerTime = DateTime.UtcNow,
Bids = [new QuoteChange(100, 10)],
Asks = [new QuoteChange(101, 10)]
};
await inner.SendOutMessageAsync(quotesMsg, CancellationToken);
var quotes = output.OfType<QuoteChangeMessage>().ToArray();
quotes.Length.AssertEqual(1);
quotes[0].SecurityId.SecurityCode.AssertEqual("NVDA");
quotes[0].SecurityId.BoardCode.AssertEqual("NASDAQ");
}
[TestMethod]
public async Task PositionChangeMessage_WithNativeId_IsTranslated()
{
var token = CancellationToken;
var secId = new SecurityId { SecurityCode = "AMD", BoardCode = "NASDAQ" };
var nativeId = "native_amd";
var storageProvider = new MockNativeIdStorageProvider();
var storage = storageProvider.GetStorage("TestAdapter");
await storage.TryAddAsync(secId, nativeId, cancellationToken: token);
var inner = new TestPassThroughAdapter("TestAdapter");
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ConnectMessage(), token);
var posMsg = new PositionChangeMessage
{
SecurityId = new SecurityId { Native = nativeId },
PortfolioName = "TestPortfolio",
ServerTime = DateTime.UtcNow
};
posMsg.Add(PositionChangeTypes.CurrentValue, 100m);
await inner.SendOutMessageAsync(posMsg, CancellationToken);
var positions = output.OfType<PositionChangeMessage>().ToArray();
positions.Length.AssertEqual(1);
positions[0].SecurityId.SecurityCode.AssertEqual("AMD");
positions[0].SecurityId.BoardCode.AssertEqual("NASDAQ");
}
[TestMethod]
public async Task SendInMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<ISecurityNativeIdManager>();
var storageProvider = new MockNativeIdStorageProvider();
var toInner = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 1,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
};
var toOut = new SubscriptionResponseMessage { OriginalTransactionId = 1 };
manager
.Setup(m => m.ProcessInMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((toInner: (Message[])[toInner], toOut: (Message[])[toOut]));
manager
.Setup(m => m.ProcessOutMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((forward: (Message)null, extraOut: [], loopbackIn: []));
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await adapter.SendInMessageAsync(new ResetMessage(), CancellationToken);
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertSame(toInner);
output.Count.AssertEqual(1);
output[0].AssertSame(toOut);
manager.Verify(m => m.ProcessInMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()), Times.Once);
}
[TestMethod]
public async Task InnerMessage_DelegatesToManager_AndRoutesMessages()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<ISecurityNativeIdManager>();
var storageProvider = new MockNativeIdStorageProvider();
var forward = new ConnectMessage();
var extra = new SubscriptionResponseMessage { OriginalTransactionId = 2 };
var loopback = new MarketDataMessage
{
IsSubscribe = true,
TransactionId = 3,
SecurityId = Helper.CreateSecurityId(),
DataType2 = DataType.Ticks,
};
manager
.Setup(m => m.ProcessOutMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((forward: (Message)forward, extraOut: (Message[])[extra], loopbackIn: (Message[])[loopback]));
manager
.Setup(m => m.InitializeAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(ValueTask.CompletedTask);
using var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider, manager.Object);
var output = new List<Message>();
adapter.NewOutMessageAsync += (m, ct) => { output.Add(m); return default; };
await inner.SendOutMessageAsync(new ConnectMessage(), CancellationToken);
// Should have forwarded + extra
output.Count.AssertEqual(2);
output[0].AssertSame(forward);
output[1].AssertSame(extra);
// Loopback should have been sent to inner
inner.InMessages.Count.AssertEqual(1);
inner.InMessages[0].AssertSame(loopback);
manager.Verify(m => m.ProcessOutMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()), Times.Once);
}
[TestMethod]
public async Task Dispose_UnsubscribesFromManager()
{
var inner = new RecordingMessageAdapter();
var manager = new Mock<ISecurityNativeIdManager>();
var storageProvider = new MockNativeIdStorageProvider();
manager
.Setup(m => m.ProcessInMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((toInner: [], toOut: []));
var adapter = new SecurityNativeIdMessageAdapter(inner, storageProvider, manager.Object);
adapter.Dispose();
manager.VerifyRemove(
m => m.ProcessSuspendedRequested -= It.IsAny<Func<SecurityId, CancellationToken, ValueTask>>(),
Times.Once);
manager.Verify(m => m.Dispose(), Times.Never);
}
}