mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 08:32:23 +00:00
Instrument lookups, configuration, credentials, CSV entities, snapshots and the alert processing service are read and written asynchronously; the blocking synchronous forms are obsolete wrappers. IAsyncPersistable replaces IPersistable: every type that saves and loads its settings has LoadAsync and SaveAsync only, and nested objects are read with GetValueAsync, LoadEntireAsync and LoadAllAsync. The synchronous Load and Save are the obsolete Ecng extensions. The MultiConnect sample keeps IPersistable for two settings classes, because the settings window of the published StockSharp.Xaml package takes it. Copies that were made by saving and loading are made asynchronously. IMessageAdapter, IIndicator, the risk, commission, PnL, latency, slippage and position managers, IStorageBuffer, Strategy, DiagramElement, ICompositionModel and its nodes get CloneAsync and no longer implement ICloneable; Clone is an obsolete blocking wrapper. A strategy copy keeps every security and portfolio parameter the original holds. Messages, FieldMapping, BankDetails and WithdrawInfo are copied in memory. A CommissionRuleMessage shares its rule and the emulator takes a copy of it. Envelope gets a constructor that takes all three lines and CreateAsync. ToBruteForce and ToBruteForceRandom become ToBruteForceAsync and ToBruteForceRandomAsync and return IAsyncEnumerable; BruteForceOptimizer runs over it and takes the next strategy through an asynchronous delegate. Diagram elements keep their own state in SaveState, OnLoading and LoadState. Undo restores an in-memory snapshot; a chart element holds its series and axes in it by reference. An alert rule keeps its value in the form a message carries it. A diagram strategy applies composition settings that were loaded before the composition was set in SetCompositionAsync or at the start, and saves them while they wait. Strategies get an OnStartedAsync hook; diagram strategies resolve securities, underlyings and strikes before the start so value processing never looks up instruments. Paths.Serialize, SerializeInvariant, AppStartSettings.TrySave, ICredentialsProvider.Save, ISnapshotSerializer.Serialize and the composition registry gain async forms. ICredentialsProvider.Delete becomes DeleteAsync, so loading, saving and deleting the credentials wait for one another. Paths.InstalledVersion and AppNameWithVersion are obsolete in favour of GetInstalledVersionAsync and GetAppNameWithVersionAsync. A file is opened for writing only after the last cancellation check, because opening it empties it; a cancelled read reports the cancellation instead of an empty result. A snapshot flush that failed leaves what it took due for the next one. The indicator templates for C#, F# and Python override LoadAsync and SaveAsync.
244 lines
7.3 KiB
C#
244 lines
7.3 KiB
C#
namespace StockSharp.Algo;
|
|
|
|
/// <summary>
|
|
/// The messages adapter build order book and tick data from order log flow.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Initializes a new instance of the <see cref="OrderLogMessageAdapter"/>.
|
|
/// </remarks>
|
|
/// <param name="innerAdapter">Underlying adapter.</param>
|
|
public class OrderLogMessageAdapter(IMessageAdapter innerAdapter) : MessageAdapterWrapper(innerAdapter)
|
|
{
|
|
private class SubscriptionInfo
|
|
{
|
|
public readonly AsyncLock Lock = new();
|
|
|
|
public SubscriptionInfo(MarketDataMessage origin)
|
|
{
|
|
Origin = origin ?? throw new ArgumentNullException(nameof(origin));
|
|
IsTicks = Origin.DataType2 == DataType.Ticks;
|
|
}
|
|
|
|
public MarketDataMessage Origin { get; }
|
|
|
|
public readonly bool IsTicks;
|
|
|
|
public IOrderLogMarketDepthBuilder Builder { get; set; }
|
|
public SubscriptionStates State { get; set; }
|
|
}
|
|
|
|
private readonly SynchronizedDictionary<long, SubscriptionInfo> _subscriptionIds = [];
|
|
|
|
/// <inheritdoc />
|
|
protected override async ValueTask OnSendInMessageAsync(Message message, CancellationToken cancellationToken)
|
|
{
|
|
switch (message.Type)
|
|
{
|
|
case MessageTypes.Reset:
|
|
_subscriptionIds.Clear();
|
|
break;
|
|
|
|
case MessageTypes.MarketData:
|
|
message = await ProcessMarketDataRequest((MarketDataMessage)message, cancellationToken);
|
|
break;
|
|
}
|
|
|
|
await base.OnSendInMessageAsync(message, cancellationToken);
|
|
}
|
|
|
|
private async ValueTask<MarketDataMessage> ProcessMarketDataRequest(MarketDataMessage message, CancellationToken cancellationToken)
|
|
{
|
|
if (message.IsSubscribe)
|
|
{
|
|
if (message.SecurityId == default || !await InnerAdapter.IsMarketDataTypeSupportedAsync(DataType.OrderLog, cancellationToken))
|
|
return message;
|
|
|
|
var isBuild = message.BuildMode == MarketDataBuildModes.Build && message.BuildFrom == DataType.OrderLog;
|
|
|
|
if (message.DataType2 == DataType.MarketDepth)
|
|
{
|
|
if (isBuild || !await InnerAdapter.IsMarketDataTypeSupportedAsync(message.DataType2, cancellationToken))
|
|
{
|
|
var builder = message.DepthBuilder ?? InnerAdapter.CreateOrderLogMarketDepthBuilder(message.SecurityId);
|
|
|
|
_subscriptionIds.Add(message.TransactionId, new SubscriptionInfo(message.TypedClone()) { Builder = builder });
|
|
|
|
message = message.TypedClone();
|
|
message.DataType2 = DataType.OrderLog;
|
|
|
|
LogInfo("OL->MD subscribed {0}/{1}.", message.SecurityId, message.TransactionId);
|
|
}
|
|
}
|
|
else if (message.DataType2 == DataType.Ticks)
|
|
{
|
|
if (isBuild || !await InnerAdapter.IsMarketDataTypeSupportedAsync(message.DataType2, cancellationToken))
|
|
{
|
|
_subscriptionIds.Add(message.TransactionId, new SubscriptionInfo(message.TypedClone()));
|
|
|
|
message = message.TypedClone();
|
|
message.DataType2 = DataType.OrderLog;
|
|
|
|
LogInfo("OL->TICK subscribed {0}/{1}.", message.SecurityId, message.TransactionId);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
TryRemoveSubscription(message.OriginalTransactionId, out _);
|
|
|
|
return message;
|
|
}
|
|
|
|
private bool TryRemoveSubscription(long id, out SubscriptionInfo info)
|
|
{
|
|
if (!_subscriptionIds.TryGetAndRemove(id, out info))
|
|
return false;
|
|
|
|
LogInfo("OL->{0} unsubscribed {1}/{2}.", info.IsTicks ? "MD" : "TICK", info.Origin.SecurityId, info.Origin.TransactionId);
|
|
return true;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override async ValueTask OnInnerAdapterNewOutMessageAsync(Message message, CancellationToken cancellationToken)
|
|
{
|
|
switch (message.Type)
|
|
{
|
|
case MessageTypes.SubscriptionResponse:
|
|
{
|
|
var responseMsg = (SubscriptionResponseMessage)message;
|
|
var id = responseMsg.OriginalTransactionId;
|
|
|
|
if (!responseMsg.IsOk())
|
|
{
|
|
if (TryRemoveSubscription(id, out var info))
|
|
{
|
|
using (await info.Lock.LockAsync(cancellationToken))
|
|
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Error, id, this);
|
|
}
|
|
}
|
|
else if (_subscriptionIds.TryGetValue(id, out var info) && info.State != SubscriptionStates.Online)
|
|
{
|
|
QuoteChangeMessage snapshot = null;
|
|
|
|
using (await info.Lock.LockAsync(cancellationToken))
|
|
{
|
|
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Online, id, this);
|
|
|
|
if (!info.IsTicks)
|
|
{
|
|
snapshot = info.Builder.GetSnapshot(responseMsg.LocalTime)
|
|
?? throw new InvalidOperationException(LocalizedStrings.MarketDepthIsEmpty);
|
|
}
|
|
|
|
if (snapshot != null)
|
|
snapshot.SetSubscriptionIds(subscriptionId: id);
|
|
}
|
|
|
|
if (snapshot != null)
|
|
await base.OnInnerAdapterNewOutMessageAsync(snapshot, cancellationToken);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case MessageTypes.SubscriptionFinished:
|
|
{
|
|
var id = ((SubscriptionFinishedMessage)message).OriginalTransactionId;
|
|
|
|
if (TryRemoveSubscription(id, out var info))
|
|
{
|
|
using (await info.Lock.LockAsync(cancellationToken))
|
|
info.State = info.State.ChangeSubscriptionState(SubscriptionStates.Finished, id, this);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case MessageTypes.Execution:
|
|
{
|
|
if (_subscriptionIds.Count == 0)
|
|
break;
|
|
|
|
var execMsg = (ExecutionMessage)message;
|
|
|
|
if (execMsg.DataType == DataType.OrderLog && execMsg.IsSystem != false)
|
|
message = await ProcessBuildersAsync(execMsg, cancellationToken);
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (message != null)
|
|
await base.OnInnerAdapterNewOutMessageAsync(message, cancellationToken);
|
|
}
|
|
|
|
private async ValueTask<Message> ProcessBuildersAsync(ExecutionMessage execMsg, CancellationToken cancellationToken)
|
|
{
|
|
List<long> nonBuilderIds = null;
|
|
|
|
foreach (var subscriptionId in execMsg.GetSubscriptionIds())
|
|
{
|
|
if (!_subscriptionIds.TryGetValue(subscriptionId, out var info))
|
|
{
|
|
nonBuilderIds ??= [];
|
|
|
|
nonBuilderIds.Add(subscriptionId);
|
|
|
|
// can be non OL->MB subscription
|
|
//LogDebug("OL processing {0}/{1} not found.", execMsg.SecurityId, subscriptionId);
|
|
continue;
|
|
}
|
|
|
|
if (!info.IsTicks)
|
|
{
|
|
try
|
|
{
|
|
QuoteChangeMessage depth;
|
|
|
|
using (await info.Lock.LockAsync(cancellationToken))
|
|
{
|
|
depth = info.Builder.Update(execMsg);
|
|
|
|
if (info.State != SubscriptionStates.Online)
|
|
depth = null;
|
|
else
|
|
depth = depth?.TypedClone();
|
|
}
|
|
|
|
LogDebug("OL->MD processing {0}={1}.", execMsg.SecurityId, depth != null);
|
|
|
|
if (depth != null)
|
|
{
|
|
depth.SetSubscriptionIds(subscriptionId: subscriptionId);
|
|
await base.OnInnerAdapterNewOutMessageAsync(depth, cancellationToken);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// если ОЛ поврежден, то не нарушаем весь цикл обработки сообщения
|
|
// а только выводим сообщение в лог
|
|
await base.OnInnerAdapterNewOutMessageAsync(ex.ToErrorMessage(), cancellationToken);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
LogDebug("OL->TICK processing {0}.", execMsg.SecurityId);
|
|
var tick = execMsg.ToTick();
|
|
tick.SetSubscriptionIds(subscriptionId: subscriptionId);
|
|
await base.OnInnerAdapterNewOutMessageAsync(tick, cancellationToken);
|
|
}
|
|
}
|
|
|
|
if (nonBuilderIds is null)
|
|
return null;
|
|
|
|
execMsg.SetSubscriptionIds([.. nonBuilderIds]);
|
|
return execMsg;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a copy of <see cref="OrderLogMessageAdapter"/>.
|
|
/// </summary>
|
|
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
|
|
/// <returns>Copy.</returns>
|
|
public override async ValueTask<IMessageAdapter> CloneAsync(CancellationToken cancellationToken)
|
|
=> new OrderLogMessageAdapter(await InnerAdapter.CloneAsync(cancellationToken));
|
|
}
|