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.
339 lines
9.6 KiB
C#
339 lines
9.6 KiB
C#
namespace StockSharp.Algo;
|
|
|
|
/// <summary>
|
|
/// Security ALL subscription counter adapter.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Initializes a new instance of the <see cref="SubscriptionSecurityAllMessageAdapter"/>.
|
|
/// </remarks>
|
|
/// <param name="innerAdapter">Inner message adapter.</param>
|
|
public class SubscriptionSecurityAllMessageAdapter(IMessageAdapter innerAdapter) : MessageAdapterWrapper(innerAdapter)
|
|
{
|
|
private class ParentSubscription(MarketDataMessage origin)
|
|
{
|
|
public MarketDataMessage Origin { get; } = origin ?? throw new ArgumentNullException(nameof(origin));
|
|
public CachedSynchronizedPairSet<long, MarketDataMessage> Alls = [];
|
|
public SynchronizedDictionary<SecurityId, CachedSynchronizedSet<long>> NonAlls = [];
|
|
public SynchronizedDictionary<SecurityId, Message> Snapshots = [];
|
|
}
|
|
|
|
private readonly AsyncLock _sync = new();
|
|
|
|
private readonly Dictionary<long, ParentSubscription> _parents = [];
|
|
private readonly Dictionary<long, ParentSubscription> _unsubscribes = [];
|
|
private readonly Dictionary<long, (ParentSubscription parent, MarketDataMessage request)> _requests = [];
|
|
|
|
private async ValueTask ClearState(CancellationToken cancellationToken)
|
|
{
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
_parents.Clear();
|
|
_unsubscribes.Clear();
|
|
_requests.Clear();
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override async ValueTask OnSendInMessageAsync(Message message, CancellationToken cancellationToken)
|
|
{
|
|
switch (message.Type)
|
|
{
|
|
case MessageTypes.Reset:
|
|
await ClearState(cancellationToken);
|
|
break;
|
|
|
|
case MessageTypes.MarketData:
|
|
{
|
|
var mdMsg = (MarketDataMessage)message;
|
|
|
|
if (mdMsg.IsSubscribe)
|
|
{
|
|
var transId = mdMsg.TransactionId;
|
|
Message outMsg = null;
|
|
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
if (!IsSecurityRequired(mdMsg.DataType2) || mdMsg.SecurityId == default)
|
|
{
|
|
mdMsg = mdMsg.TypedClone();
|
|
|
|
var parent = _parents.FirstOrDefault(p => p.Value.Origin.DataType2 == mdMsg.DataType2).Value;
|
|
|
|
void AddSubscription()
|
|
{
|
|
if (mdMsg.SecurityId == default)
|
|
{
|
|
// first ALL is initiator
|
|
parent.Alls.Add(transId, mdMsg);
|
|
}
|
|
else
|
|
{
|
|
parent.NonAlls.SafeAdd(mdMsg.SecurityId).Add(transId);
|
|
}
|
|
|
|
_requests.Add(transId, (parent, mdMsg));
|
|
}
|
|
|
|
if (parent == null)
|
|
{
|
|
parent = new ParentSubscription(mdMsg);
|
|
_parents.Add(transId, parent);
|
|
|
|
AddSubscription();
|
|
|
|
if (mdMsg.DataType2 != DataType.News)
|
|
{
|
|
mdMsg = mdMsg.TypedClone();
|
|
// do not specify security cause adapter doesn't require it
|
|
Extensions.AllSecurity.CopyEx(mdMsg, false);
|
|
message = mdMsg;
|
|
}
|
|
|
|
LogInfo("Sec ALL {0} subscribing.", transId);
|
|
}
|
|
else
|
|
{
|
|
AddSubscription();
|
|
|
|
// for child subscriptions make online (or finished) immediatelly
|
|
outMsg = mdMsg.CreateResponse();
|
|
}
|
|
}
|
|
}
|
|
|
|
if (outMsg != null)
|
|
{
|
|
Message snapshot = null;
|
|
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
if (mdMsg.SecurityId != default)
|
|
{
|
|
var parent2 = _parents.FirstOrDefault(p => p.Value.Origin.DataType2 == mdMsg.DataType2).Value;
|
|
parent2?.Snapshots.TryGetValue(mdMsg.SecurityId, out snapshot);
|
|
}
|
|
}
|
|
|
|
await RaiseNewOutMessageAsync(outMsg, cancellationToken);
|
|
await RaiseNewOutMessageAsync(new SubscriptionOnlineMessage { OriginalTransactionId = mdMsg.TransactionId }, cancellationToken);
|
|
|
|
if (snapshot != null)
|
|
{
|
|
snapshot = snapshot.TypedClone();
|
|
|
|
if (snapshot is ISubscriptionIdMessage subscrIdMsg)
|
|
{
|
|
subscrIdMsg.OriginalTransactionId = mdMsg.TransactionId;
|
|
subscrIdMsg.SetSubscriptionIds(subscriptionId: mdMsg.TransactionId);
|
|
}
|
|
|
|
await RaiseNewOutMessageAsync(snapshot, cancellationToken);
|
|
}
|
|
|
|
return;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
var originId = mdMsg.OriginalTransactionId;
|
|
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
var found = false;
|
|
|
|
if (!_requests.TryGetAndRemove(originId, out var tuple))
|
|
break;
|
|
|
|
//LogDebug("Sec ALL child {0} unsubscribe.", originId);
|
|
|
|
var parent = tuple.parent;
|
|
var request = tuple.request;
|
|
var secId = request.SecurityId;
|
|
var transId = request.TransactionId;
|
|
|
|
if (parent.Alls.RemoveByValue(request))
|
|
found = true;
|
|
else if (parent.NonAlls.TryGetValue(secId, out var set) && set.Remove(transId))
|
|
{
|
|
if (set.Count == 0)
|
|
parent.NonAlls.Remove(secId);
|
|
|
|
found = true;
|
|
}
|
|
|
|
if (found)
|
|
{
|
|
if (parent.Alls.Count == 0 && parent.NonAlls.Count == 0)
|
|
{
|
|
// last unsubscribe is not initial subscription
|
|
if (parent.Origin.TransactionId != originId)
|
|
{
|
|
mdMsg = mdMsg.TypedClone();
|
|
mdMsg.OriginalTransactionId = parent.Origin.TransactionId;
|
|
|
|
message = mdMsg;
|
|
}
|
|
|
|
_unsubscribes.Add(mdMsg.TransactionId, parent);
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
await RaiseNewOutMessageAsync(mdMsg.CreateResponse(found ? null : new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId))), cancellationToken);
|
|
return;
|
|
}
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
await base.OnSendInMessageAsync(message, cancellationToken);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override async ValueTask OnInnerAdapterNewOutMessageAsync(Message message, CancellationToken cancellationToken)
|
|
{
|
|
switch (message.Type)
|
|
{
|
|
case MessageTypes.Disconnect:
|
|
case MessageTypes.ConnectionRestored:
|
|
{
|
|
if (message is ConnectionRestoredMessage restoredMsg && !restoredMsg.IsResetState)
|
|
break;
|
|
|
|
await ClearState(cancellationToken);
|
|
break;
|
|
}
|
|
case MessageTypes.SubscriptionResponse:
|
|
{
|
|
var responseMsg = (SubscriptionResponseMessage)message;
|
|
var originId = responseMsg.OriginalTransactionId;
|
|
|
|
if (!responseMsg.IsOk())
|
|
{
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
if (_parents.TryGetAndRemove(originId, out _))
|
|
{
|
|
LogError("Sec ALL {0} error.", originId);
|
|
}
|
|
else if (_unsubscribes.TryGetAndRemove(originId, out var parent))
|
|
{
|
|
LogError("Sec ALL {0} unsubscribe error.", parent.Origin.TransactionId);
|
|
_parents.Remove(parent.Origin.TransactionId);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (_unsubscribes.TryGetAndRemove(originId, out var parent))
|
|
{
|
|
LogInfo("Sec ALL {0} unsubscribed.", parent.Origin.TransactionId);
|
|
_parents.Remove(parent.Origin.TransactionId);
|
|
}
|
|
}
|
|
|
|
break;
|
|
}
|
|
case MessageTypes.SubscriptionFinished:
|
|
{
|
|
var finishMsg = (SubscriptionFinishedMessage)message;
|
|
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
_parents.Remove(finishMsg.OriginalTransactionId);
|
|
|
|
break;
|
|
}
|
|
default:
|
|
{
|
|
if (_parents.Count > 0 && message is ISubscriptionIdMessage subscrMsg and ISecurityIdMessage secIdMsg)
|
|
{
|
|
var drop = false;
|
|
|
|
using (await _sync.LockAsync(cancellationToken))
|
|
{
|
|
foreach (var parentId in subscrMsg.GetSubscriptionIds())
|
|
{
|
|
if (_parents.TryGetValue(parentId, out var parent))
|
|
{
|
|
// cache latest snapshot per security for late subscribers
|
|
if (secIdMsg.SecurityId != default && message is IServerTimeMessage)
|
|
{
|
|
if (CanOpenLateSubscriber(message))
|
|
parent.Snapshots[secIdMsg.SecurityId] = message.TypedClone();
|
|
else
|
|
parent.Snapshots.Remove(secIdMsg.SecurityId);
|
|
}
|
|
|
|
if (!ApplySubscriptionIds(subscrMsg, parent, secIdMsg.SecurityId))
|
|
drop = true;
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// no subscribers for this security — drop the message
|
|
if (drop)
|
|
return;
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
await base.OnInnerAdapterNewOutMessageAsync(message, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A subscriber that arrives after the ALL subscription is already running is opened with the last
|
|
/// message cached for its security, so that message has to state where the market is. A trade is an
|
|
/// event that already happened, and a book increment is a difference against a book the subscriber
|
|
/// has never seen - an increment also makes whatever was cached before it stale.
|
|
/// </summary>
|
|
private static bool CanOpenLateSubscriber(Message message)
|
|
=> message switch
|
|
{
|
|
ExecutionMessage => false,
|
|
QuoteChangeMessage book => book.State is null or QuoteChangeStates.SnapshotComplete,
|
|
_ => true,
|
|
};
|
|
|
|
private static bool ApplySubscriptionIds(ISubscriptionIdMessage subscrMsg, ParentSubscription parent, SecurityId secId)
|
|
{
|
|
var ids = subscrMsg.GetSubscriptionIds();
|
|
var initialId = parent.Origin.TransactionId;
|
|
long[] newIds = parent.Alls.CachedKeys;
|
|
|
|
if (parent.NonAlls.TryGetValue(secId, out var set))
|
|
newIds = newIds.Concat(set.Cache);
|
|
|
|
if (newIds.Length == 0)
|
|
{
|
|
// no ALL subscribers and no per-security subscribers for this secId
|
|
var otherIds = ids.Where(id => id != initialId).ToArray();
|
|
if (otherIds.Length == 0)
|
|
return false;
|
|
|
|
subscrMsg.SetSubscriptionIds(otherIds);
|
|
}
|
|
else if (ids.Length == 1 && ids[0] == initialId)
|
|
subscrMsg.SetSubscriptionIds(newIds);
|
|
else
|
|
subscrMsg.SetSubscriptionIds([.. ids.Where(id => id != initialId), .. newIds]);
|
|
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a copy of <see cref="SubscriptionSecurityAllMessageAdapter"/>.
|
|
/// </summary>
|
|
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
|
|
/// <returns>Copy.</returns>
|
|
public override async ValueTask<IMessageAdapter> CloneAsync(CancellationToken cancellationToken)
|
|
{
|
|
return new SubscriptionSecurityAllMessageAdapter(await InnerAdapter.CloneAsync(cancellationToken));
|
|
}
|
|
} |