mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-05 09:02:09 +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.
5.7 KiB
5.7 KiB
StockSharp.Configuration
StockSharp.Configuration is a .NET Standard library that centralizes various configuration facilities used by the StockSharp trading platform. It provides classes for storing application paths, loading settings, managing user credentials, and constructing message adapters.
The assembly is titled S#.Configuration and described as "Configuration components."
Features
- System paths – the
Pathsclass defines all important directories and files used by StockSharp. Paths are initialized fromPathsHolderand configuration files, as shown below:【F:Configuration/Paths.cs†L14-L26】var companyPath = PathsHolder.CompanyPath ?? ConfigManager.TryGet<string>("companyPath"); CompanyPath = companyPath.IsEmpty() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StockSharp") : companyPath.ToFullPathIfNeed(); CredentialsFile = Path.Combine(CompanyPath, $"credentials{DefaultSettingsExt}"); PlatformConfigurationFile = Path.Combine(AppDataPath, $"platform_config{DefaultSettingsExt}"); - Start‑up settings –
AppStartSettingsstores language preference and online/offline mode and can be loaded or saved from the platform configuration file:【F:Configuration/AppStartSettings.cs†L4-L41】public class AppStartSettings : IAsyncPersistable { public string Language { get; set; } = LocalizedStrings.ActiveLanguage; public bool Online { get; set; } = true; public static async ValueTask<AppStartSettings> TryLoadAsync(IFileSystem fileSystem, CancellationToken cancellationToken) { var configFile = Paths.PlatformConfigurationFile; if (configFile.IsEmptyOrWhiteSpace() || !configFile.IsConfigExists(fileSystem)) return null; var storage = await configFile.DeserializeAsync<SettingsStorage>(fileSystem, cancellationToken); return storage is null ? null : await storage.LoadAsync<AppStartSettings>(cancellationToken); } } - Credentials management – the
ICredentialsProviderinterface allows loading, saving and deleting ofServerCredentials. The default implementation persists credentials inPaths.CredentialsFile:【F:Configuration/ICredentialsProvider.cs†L4-L25】public interface ICredentialsProvider { bool TryLoad(out ServerCredentials credentials); void Save(ServerCredentials credentials, bool keepSecret); void Delete(); }class DefaultCredentialsProvider : ICredentialsProvider { -
}
private readonly Lock _lock = new(); private ServerCredentials _credentials; bool ICredentialsProvider.TryLoad(out ServerCredentials credentials) { using (_lock.EnterScope()) { if(_credentials != null) { credentials = _credentials.Clone(); return credentials.CanAutoLogin(); } var file = Paths.CredentialsFile; credentials = null; if (file.IsConfigExists()) { credentials = new ServerCredentials(); credentials.LoadIfNotNull(file.Deserialize<SettingsStorage>()); _credentials = credentials.Clone(); } return credentials?.CanAutoLogin() == true; } }【F:Configuration/DefaultCredentialsProvider.cs†L3-L38】 - Invariant serialization –
InvariantCultureSerializersaves configuration files using the invariant culture and UTF‑8 encoding, enabling culture‑independent settings:【F:Configuration/InvariantCultureSerializer.cs†L3-L23】public static class InvariantCultureSerializer { public static void SerializeInvariant(this SettingsStorage settings, string fileName, bool bom = true) { if (settings is null) throw new ArgumentNullException(nameof(settings)); Do.Invariant(() => settings.Serialize(fileName, bom)); } } - Message adapter discovery –
InMemoryMessageAdapterProviderscans all local assemblies forIMessageAdapterimplementations and can create adapters on demand:【F:Configuration/InMemoryMessageAdapterProvider.cs†L5-L51】public class InMemoryMessageAdapterProvider : IMessageAdapterProvider { public InMemoryMessageAdapterProvider(IEnumerable<IMessageAdapter> currentAdapters, Type transportAdapter = null) { CurrentAdapters = currentAdapters ?? throw new ArgumentNullException(nameof(currentAdapters)); var idGenerator = new IncrementalIdGenerator(); PossibleAdapters = [.. GetAdapters().Select(t => { try { return t.CreateAdapter(idGenerator); } catch (Exception ex) { ex.LogError(); return null; } }).WhereNotNull()]; } } - Utility helpers – the
Pathsclass also exposes methods for serialization, backup management and building links to StockSharp documentation and store pages.
Usage
- Configure global paths before accessing
Pathsby settingPathsHolder.CompanyPathandPathsHolder.AppDataPathif your application uses custom directories. - Load or create application start settings with
AppStartSettings.TryLoadand save them usingTrySave. - Implement
ICredentialsProvideror useDefaultCredentialsProviderto persist server credentials securely. - Use
InvariantCultureSerializerwhen you need stable serialization irrespective of system locale. - Create an instance of
InMemoryMessageAdapterProviderto dynamically discover available message adapters.