mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-06 01:22:11 +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.
213 lines
5.5 KiB
C#
213 lines
5.5 KiB
C#
namespace StockSharp.Alerts;
|
|
|
|
using System.Threading.Channels;
|
|
|
|
/// <summary>
|
|
/// Alert processing service.
|
|
/// </summary>
|
|
public class AlertProcessingService : BaseLogReceiver, IAlertProcessingService
|
|
{
|
|
private readonly CachedSynchronizedDictionary<Type, CachedSynchronizedSet<AlertSchema>> _schemas = [];
|
|
private readonly Channel<Message> _channel;
|
|
private readonly CancellationTokenSource _cts = new();
|
|
private long _droppedMessages;
|
|
|
|
// Schemas whose alert reached the user, and which therefore stop matching.
|
|
private readonly SynchronizedSet<AlertSchema> _delivered = [];
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="AlertProcessingService"/>.
|
|
/// </summary>
|
|
/// <param name="maxQueue">Max queue for process.</param>
|
|
public AlertProcessingService(int maxQueue)
|
|
{
|
|
_channel = Channel.CreateBounded<Message>(new BoundedChannelOptions(maxQueue)
|
|
{
|
|
FullMode = BoundedChannelFullMode.Wait,
|
|
SingleReader = true,
|
|
});
|
|
|
|
var messages = _channel.Reader;
|
|
var token = _cts.Token;
|
|
|
|
Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
await foreach (var message in messages.ReadAllAsync(token))
|
|
{
|
|
if (!_schemas.TryGetValue(message.GetType(), out var schemas))
|
|
continue;
|
|
|
|
foreach (var schema in schemas.Cache)
|
|
{
|
|
if (!schema.IsEnabled || schema.AlertType is null || _delivered.Contains(schema))
|
|
continue;
|
|
|
|
bool isMatch;
|
|
|
|
try
|
|
{
|
|
isMatch = IsMatch(schema, message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// a schema that cannot be evaluated says nothing about the ones next to it.
|
|
LogError(ex);
|
|
continue;
|
|
}
|
|
|
|
if (!isMatch)
|
|
continue;
|
|
|
|
try
|
|
{
|
|
await AlertServicesRegistry.NotificationService.NotifyAsync(schema.AlertType.Value,
|
|
schema.ExternalId, schema.LogLevel, schema.Caption, schema.Message, message.LocalTime, token);
|
|
_delivered.Add(schema);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (token.IsCancellationRequested)
|
|
break;
|
|
|
|
// A refused delivery leaves the schema eligible for the next matching message.
|
|
LogError(ex);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
if (!token.IsCancellationRequested)
|
|
LogError(ex);
|
|
}
|
|
}, token);
|
|
}
|
|
|
|
private static bool IsMatch(AlertSchema schema, Message message)
|
|
{
|
|
return schema.Rules.All(rule =>
|
|
{
|
|
var field = rule.Field;
|
|
|
|
var value = field.Invoke(message);
|
|
|
|
if (value == null)
|
|
return false;
|
|
|
|
var expected = rule.Value;
|
|
|
|
int Compare() => field.ValueType.GetOperator().Compare(value, expected);
|
|
|
|
return rule.Operator switch
|
|
{
|
|
ComparisonOperator.Equal => expected.Equals(value),
|
|
ComparisonOperator.NotEqual => !expected.Equals(value),
|
|
|
|
ComparisonOperator.Greater => Compare() > 0,
|
|
ComparisonOperator.GreaterOrEqual => Compare() >= 0,
|
|
ComparisonOperator.Less => Compare() < 0,
|
|
ComparisonOperator.LessOrEqual => Compare() <= 0,
|
|
|
|
ComparisonOperator.Any => true,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(rule), rule.Operator.ToString()),
|
|
};
|
|
});
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public event Action<AlertSchema> Registered;
|
|
|
|
/// <inheritdoc />
|
|
public event Action<AlertSchema> UnRegistered;
|
|
|
|
/// <summary>
|
|
/// Number of messages dropped because the processing queue was full.
|
|
/// </summary>
|
|
public long DroppedMessages => Interlocked.Read(ref _droppedMessages);
|
|
|
|
/// <inheritdoc />
|
|
public void Register(AlertSchema schema)
|
|
{
|
|
if (schema == null)
|
|
throw new ArgumentNullException(nameof(schema));
|
|
|
|
var schemas = _schemas.SafeAdd(schema.MessageType);
|
|
|
|
if (schemas.TryAdd(schema))
|
|
Registered?.Invoke(schema);
|
|
}
|
|
|
|
void IAlertProcessingService.UnRegister(AlertSchema schema)
|
|
{
|
|
if (schema == null)
|
|
throw new ArgumentNullException(nameof(schema));
|
|
|
|
if (_schemas.TryGetValue(schema.MessageType, out var schemas) && schemas.Remove(schema))
|
|
UnRegistered?.Invoke(schema);
|
|
|
|
_delivered.Remove(schema);
|
|
}
|
|
|
|
void IAlertProcessingService.Process(Message message)
|
|
{
|
|
if (message == null)
|
|
throw new ArgumentNullException(nameof(message));
|
|
|
|
if (_channel.Writer.TryWrite(message) || _cts.IsCancellationRequested)
|
|
return;
|
|
|
|
if (Interlocked.Increment(ref _droppedMessages) == 1)
|
|
LogWarning("Alert processing queue is full. Messages are being dropped.");
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public IEnumerable<AlertSchema> Schemas
|
|
=> _schemas.CachedValues.SelectMany(v => v.Cache);
|
|
|
|
AlertSchema IAlertProcessingService.FindSchema(Guid id)
|
|
=> _schemas
|
|
.CachedValues
|
|
.SelectMany(v => v.Cache)
|
|
.FirstOrDefault(v => v.Id == id);
|
|
|
|
/// <inheritdoc />
|
|
public override async Task LoadAsync(SettingsStorage storage, CancellationToken cancellationToken)
|
|
{
|
|
var schemas = new List<AlertSchema>();
|
|
|
|
foreach (var schemaSettings in storage.GetValue<IEnumerable<SettingsStorage>>(nameof(Schemas)))
|
|
schemas.Add(await schemaSettings.LoadAsync<AlertSchema>(cancellationToken));
|
|
|
|
// Replaced only once everything has been read, so settings that cannot be read leave what was
|
|
// registered as it was.
|
|
_schemas.Clear();
|
|
_delivered.Clear();
|
|
|
|
foreach (var schema in schemas)
|
|
Register(schema);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override async Task SaveAsync(SettingsStorage storage, CancellationToken cancellationToken)
|
|
{
|
|
var schemas = new List<SettingsStorage>();
|
|
|
|
foreach (var schema in Schemas)
|
|
schemas.Add(await schema.SaveAsync(cancellationToken));
|
|
|
|
storage.SetValue(nameof(Schemas), schemas.ToArray());
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
protected override void DisposeManaged()
|
|
{
|
|
_cts.Cancel();
|
|
|
|
_channel.Writer.TryComplete();
|
|
|
|
base.DisposeManaged();
|
|
}
|
|
}
|