Files
mika@stocksharp.com 6e7a7dae22 Move instrument lookups and persistence to async
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.
2026-10-04 11:28:17 +03:00

286 lines
8.0 KiB
C#

namespace StockSharp.Samples.Testing.Optimization;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Collections.Generic;
using System.Threading;
using Ecng.Xaml;
using Ecng.Common;
using Ecng.Serialization;
using Ecng.Compilation;
using Ecng.Configuration;
using Ecng.Compilation.Roslyn;
using Ecng.ComponentModel;
using Ecng.Collections;
using Ecng.Logging;
using Ecng.IO;
using StockSharp.Algo;
using StockSharp.Algo.Storages;
using StockSharp.Algo.Strategies;
using StockSharp.Algo.Strategies.Optimization;
using StockSharp.Algo.Commissions;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
using StockSharp.Configuration;
using StockSharp.Xaml;
public partial class MainWindow
{
private DateTime _startEmulationTime;
private CancellationTokenSource _cts;
private BaseOptimizer _optimizer;
// strategies already shown in the stat panel (keyed by Strategy.Id);
// the first progress event adds the strategy, the rest only update progress
private readonly HashSet<Guid> _shownStrategies = [];
public MainWindow()
{
InitializeComponent();
ConfigManager.RegisterService<ICompiler>(new CSharpCompiler());
HistoryPath.Folder = Paths.HistoryDataPath;
GeneticSettings.SelectedObject = new GeneticSettings();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
ThemeExtensions.ApplyDefaultTheme();
}
private async void StartBtnClick(object sender, RoutedEventArgs e)
{
if (_cts != null)
return;
OptimizeTypeGrid.IsEnabled = false;
var folder = HistoryPath.Folder;
if (folder.IsEmpty() || !Directory.Exists(folder))
{
MessageBox.Show(this, LocalizedStrings.WrongPath);
return;
}
TestingProcess.Value = 0;
TestingProcessText.Text = string.Empty;
_shownStrategies.Clear();
Stat.Clear();
Stat.ClearColumns();
Stat.CreateColumns(new History.SmaStrategy());
var logManager = new LogManager();
var fileLogListener = new FileLogListener("sample.log");
logManager.Listeners.Add(fileLogListener);
// storage to historical data
var storageRegistry = new StorageRegistry
{
// set historical path
DefaultDrive = new LocalMarketDataDrive(Paths.FileSystem, folder)
};
// create test security
var security = new Security
{
Id = Paths.HistoryDefaultSecurity, // sec id has the same name as folder with historical data
PriceStep = 0.01m,
};
var startTime = Paths.HistoryBeginDate;
var stopTime = Paths.HistoryEndDate;
// test portfolio
var portfolio = Portfolio.CreateSimulator();
var secProvider = new CollectionSecurityProvider([security]);
var pfProvider = new CollectionPortfolioProvider([portfolio]);
BaseOptimizer optimizer;
if (BruteForce.IsChecked == true)
optimizer = new BruteForceOptimizer(secProvider, pfProvider, storageRegistry);
else
optimizer = new GeneticOptimizer(secProvider, pfProvider, storageRegistry, Paths.FileSystem);
_optimizer = optimizer;
var settings = optimizer.EmulationSettings;
// set max possible iteration to 100
settings.MaxIterations = 100;
// 1 cent commission for trade
settings.CommissionRules =
[
new CommissionTradeRule { Value = 0.01m },
];
// count of parallel testing strategies
// if not set, then CPU count * 2
//optimizer.EmulationSettings.BatchSize = 1;
// settings caching mode non security optimized param
optimizer.AdapterCache = new();
// handle single iteration progress
optimizer.SingleProgressChanged += (s, a, p) =>
{
this.GuiAsync(() =>
{
// add the strategy on its first progress event: AddStrategy registers
// it in the panel and subscribes to PnL (so the equity chart gets filled
// while the backtest runs); only then does UpdateProgress have a target.
if (_shownStrategies.Add(s.Id))
Stat.AddStrategy(s);
else
Stat.UpdateProgress(s, p);
});
};
PauseBtn.Content = LocalizedStrings.Pause;
SetIsEnabled(false, true, true, false);
_startEmulationTime = DateTime.UtcNow;
_cts = new CancellationTokenSource();
// Create base strategy with optimization ranges configured
var strategy = new History.SmaStrategy
{
Volume = 1,
Security = security,
Portfolio = portfolio,
// by default interval is 1 min,
// it is excessively for time range with several months
UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>(),
};
// Configure optimization ranges on parameters
var longParam = (StrategyParam<int>)strategy.Parameters[nameof(strategy.LongSma)];
var shortParam = (StrategyParam<int>)strategy.Parameters[nameof(strategy.ShortSma)];
var tfParam = (StrategyParam<TimeSpan?>)strategy.Parameters[nameof(strategy.CandleTimeFrame)];
longParam.SetOptimize(50, 100, 5);
shortParam.SetOptimize(20, 40, 1);
tfParam.SetOptimize(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15), TimeSpan.FromMinutes(5));
var optimizeParams = new IStrategyParam[] { longParam, shortParam, tfParam };
var cancelled = false;
var count = 0;
try
{
if (optimizer is BruteForceOptimizer btOptimizer)
{
var isRandomMode = RandomMode.IsChecked == true;
var randomCount = isRandomMode ? RandomCount.Text.To<int>() : 0;
IAsyncEnumerable<(Strategy strategy, IStrategyParam[] parameters)> strategies;
if (isRandomMode)
strategies = strategy.ToBruteForceRandomAsync(optimizeParams, randomCount, out _, out _);
else
strategies = strategy.ToBruteForceAsync(optimizeParams, out _, out _);
await foreach (var (s, _) in btOptimizer.RunAsync(startTime, stopTime, strategies, _cts.Token))
{
count++;
this.GuiAsync(() => UpdateProgressText(count));
}
}
else
{
var go = (GeneticOptimizer)optimizer;
await go.Settings.ApplyAsync((GeneticSettings)GeneticSettings.SelectedObject);
var geneticParams = strategy.ToGeneticParameters([
(tfParam, new[] { TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(15) }),
(longParam, null),
(shortParam, null),
]);
await foreach (var (s, _) in go.RunAsync(startTime, stopTime, strategy, geneticParams, cancellationToken: _cts.Token))
{
count++;
this.GuiAsync(() => UpdateProgressText(count));
}
}
}
catch (OperationCanceledException)
{
cancelled = true;
}
finally
{
_cts.Dispose();
_cts = null;
_optimizer = null;
optimizer.Dispose();
}
SetIsEnabled(true, false, false, true);
if (!cancelled)
{
TestingProcess.Value = TestingProcess.Maximum;
MessageBox.Show(this, LocalizedStrings.CompletedIn.Put(DateTime.UtcNow - _startEmulationTime));
}
else
MessageBox.Show(this, LocalizedStrings.Cancelled);
}
private void UpdateProgressText(int count)
{
TestingProcess.Value = count;
// Pausing now halts the in-flight backtests immediately (the optimizer suspends their replay),
// so reflect the suspended state in the text - otherwise a paused run just looks frozen.
var suffix = _optimizer?.IsPaused == true ? $" ({LocalizedStrings.Suspended})" : string.Empty;
TestingProcessText.Text = $"{count} iterations | {(int)(DateTime.UtcNow - _startEmulationTime).TotalSeconds} sec{suffix}";
}
private void SetIsEnabled(bool canStart, bool canSuspend, bool canStop, bool canType)
{
this.GuiAsync(() =>
{
StopBtn.IsEnabled = canStop;
StartBtn.IsEnabled = canStart;
PauseBtn.IsEnabled = canSuspend;
OptimizeTypeGrid.IsEnabled = canType;
});
}
private void StopBtnClick(object sender, RoutedEventArgs e)
{
_cts?.Cancel();
}
private async void PauseBtnClick(object sender, RoutedEventArgs e)
{
var optimizer = _optimizer;
if (optimizer is null)
return;
if (optimizer.IsPaused)
await optimizer.Resume();
else
await optimizer.Pause();
// The button is a toggle. Without updating its caption it always reads "Pause", so pressing
// it repeatedly silently flips pause/resume and looks like nothing happens. Show what the
// next click will do (Pause <-> Continue) and refresh the suspended marker in the text.
PauseBtn.Content = optimizer.IsPaused ? LocalizedStrings.Continue : LocalizedStrings.Pause;
UpdateProgressText((int)TestingProcess.Value);
}
}