mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 08:32:23 +00:00
Strategy.Start/Stop are obsolete in favour of StartAsync/StopAsync. Where the caller was already async it now awaits. Where it is a click handler or a void-returning event delegate it cannot await, so the call follows the pattern BaseOptimizer already uses for the same situation: launch the task and report only its failure, rather than blocking the caller or turning it into async void. SmaServerStopStrategy declared a private OnOrderChanged that hid the virtual hook of the same name, then subscribed to OrderReceived by hand to reach it - so the framework hook sat dead. It is an override now and the manual subscription is gone. The Designer template copy had the same defect. MarketQuotingStrategy is obsolete in favour of QuotingProcessor, which is not a Strategy and so cannot be handed to the sample's strategy editor. The terminal sample gets a small strategy of its own that drives the processor.
233 lines
6.1 KiB
C#
233 lines
6.1 KiB
C#
namespace StockSharp.Samples.Testing.HistoryConsole;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
using Ecng.Common;
|
|
using Ecng.Excel;
|
|
using Ecng.Logging;
|
|
using Ecng.Interop;
|
|
|
|
using StockSharp.Algo;
|
|
using StockSharp.Algo.Commissions;
|
|
using StockSharp.Algo.Storages;
|
|
using StockSharp.Algo.Testing;
|
|
using StockSharp.BusinessEntities;
|
|
using StockSharp.Messages;
|
|
using StockSharp.Configuration;
|
|
using StockSharp.Reporting;
|
|
using StockSharp.Samples.Testing.History;
|
|
|
|
class Program
|
|
{
|
|
static async Task Main()
|
|
{
|
|
// check history data path
|
|
if (Paths.HistoryDataPath == null)
|
|
{
|
|
Console.WriteLine("History data path not found. Install StockSharp.Samples.HistoryData package.");
|
|
return;
|
|
}
|
|
|
|
Console.WriteLine($"History data path: {Paths.HistoryDataPath}");
|
|
Console.WriteLine($"Security: {Paths.HistoryDefaultSecurity}");
|
|
Console.WriteLine($"Period: {Paths.HistoryBeginDate:d} - {Paths.HistoryEndDate:d}");
|
|
Console.WriteLine();
|
|
|
|
// create log manager with console and file output
|
|
var logManager = new LogManager();
|
|
logManager.Listeners.Add(new ConsoleLogListener());
|
|
logManager.Listeners.Add(new FileLogListener("backtest.log"));
|
|
|
|
var token = CancellationToken.None;
|
|
|
|
var exchangeInfoProvider = new InMemoryExchangeInfoProvider();
|
|
|
|
var id = Paths.HistoryDefaultSecurity.ToSecurityId();
|
|
var board = exchangeInfoProvider.GetOrCreateBoard(id.BoardCode);
|
|
|
|
// create test security
|
|
var security = new Security
|
|
{
|
|
Id = Paths.HistoryDefaultSecurity,
|
|
Code = id.SecurityCode,
|
|
Board = board,
|
|
};
|
|
|
|
// storage for historical data
|
|
var storageRegistry = new StorageRegistry
|
|
{
|
|
DefaultDrive = new LocalMarketDataDrive(Paths.FileSystem, Paths.HistoryDataPath)
|
|
};
|
|
|
|
var startTime = Paths.HistoryBeginDate.UtcKind();
|
|
var stopTime = Paths.HistoryEndDate.UtcKind();
|
|
|
|
var secId = security.ToSecurityId();
|
|
|
|
var level1Info = new Level1ChangeMessage
|
|
{
|
|
SecurityId = secId,
|
|
ServerTime = startTime,
|
|
}
|
|
.TryAdd(Level1Fields.MinPrice, 0.01m)
|
|
.TryAdd(Level1Fields.MaxPrice, 1000000m)
|
|
.TryAdd(Level1Fields.MarginBuy, 10000m)
|
|
.TryAdd(Level1Fields.MarginSell, 10000m);
|
|
|
|
var secProvider = (ISecurityProvider)new CollectionSecurityProvider(new[] { security });
|
|
var pf = Portfolio.CreateSimulator();
|
|
pf.CurrentValue = 1000;
|
|
|
|
// create backtesting connector
|
|
var connector = new HistoryEmulationConnector(secProvider, new[] { pf })
|
|
{
|
|
EmulationAdapter =
|
|
{
|
|
Settings =
|
|
{
|
|
MatchOnTouch = false,
|
|
CommissionRules = new ICommissionRule[]
|
|
{
|
|
new CommissionTradeRule { Value = 0.01m },
|
|
},
|
|
}
|
|
},
|
|
|
|
HistoryMessageAdapter =
|
|
{
|
|
StorageRegistry = storageRegistry,
|
|
},
|
|
};
|
|
|
|
((ILogSource)connector).LogLevel = LogLevels.Info;
|
|
logManager.Sources.Add(connector);
|
|
|
|
// create strategy based on 80 and 10 SMA
|
|
var strategy = new SmaStrategy
|
|
{
|
|
LongSma = 80,
|
|
ShortSma = 10,
|
|
Volume = 1,
|
|
Portfolio = connector.Portfolios.First(),
|
|
Security = security,
|
|
Connector = connector,
|
|
LogLevel = LogLevels.Info,
|
|
|
|
// candle type for subscription
|
|
CandleType = TimeSpan.FromMinutes(1).TimeFrame(),
|
|
|
|
UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>(),
|
|
};
|
|
|
|
logManager.Sources.Add(strategy);
|
|
|
|
// set history range
|
|
connector.HistoryMessageAdapter.StartDate = startTime;
|
|
connector.HistoryMessageAdapter.StopDate = stopTime;
|
|
|
|
var finishedEvent = new ManualResetEvent(false);
|
|
|
|
connector.SecurityReceived += (subscr, s) =>
|
|
{
|
|
if (s != security)
|
|
return;
|
|
|
|
// fill level1 values
|
|
_ = connector.EmulationAdapter.SendInMessageAsync(level1Info, default);
|
|
};
|
|
|
|
var lastProgress = 0;
|
|
connector.ProgressChanged += steps =>
|
|
{
|
|
var progress = (int)steps;
|
|
if (progress > lastProgress && progress % 10 == 0)
|
|
{
|
|
Console.WriteLine($"Progress: {progress}%");
|
|
lastProgress = progress;
|
|
}
|
|
};
|
|
|
|
connector.StateChanged2 += async state =>
|
|
{
|
|
if (state == ChannelStates.Stopped)
|
|
{
|
|
await strategy.StopAsync();
|
|
|
|
Console.WriteLine();
|
|
Console.WriteLine();
|
|
Console.WriteLine("=== Backtest completed ===");
|
|
Console.WriteLine();
|
|
Console.WriteLine($"Total trades: {strategy.StatisticManager.Parameters.FirstOrDefault(p => p.Name == "TradeCount")?.Value}");
|
|
Console.WriteLine($"Net profit: {strategy.StatisticManager.Parameters.FirstOrDefault(p => p.Name == "NetProfit")?.Value}");
|
|
Console.WriteLine($"Max drawdown: {strategy.StatisticManager.Parameters.FirstOrDefault(p => p.Name == "MaxDrawdown")?.Value}");
|
|
Console.WriteLine();
|
|
|
|
Console.WriteLine("Statistics:");
|
|
foreach (var param in strategy.StatisticManager.Parameters)
|
|
{
|
|
Console.WriteLine($" {param.Name}: {param.Value}");
|
|
}
|
|
|
|
finishedEvent.Set();
|
|
}
|
|
};
|
|
|
|
Console.WriteLine("Starting backtest on candles...");
|
|
Console.WriteLine();
|
|
|
|
// start strategy before emulation started
|
|
await strategy.StartAsync();
|
|
|
|
// start connector
|
|
connector.Connect();
|
|
await connector.StartAsync();
|
|
|
|
// wait for completion
|
|
finishedEvent.WaitOne();
|
|
|
|
logManager.Dispose();
|
|
|
|
// Generate report - choose format
|
|
Console.WriteLine();
|
|
Console.WriteLine("Select report format:");
|
|
Console.WriteLine(" 1. JSON (default)");
|
|
Console.WriteLine(" 2. XML");
|
|
Console.WriteLine(" 3. CSV");
|
|
Console.WriteLine(" 4. Excel");
|
|
Console.Write("Enter choice (1-4): ");
|
|
|
|
var choice = Console.ReadLine()?.Trim();
|
|
|
|
IReportGenerator generator = choice switch
|
|
{
|
|
"1" => new JsonReportGenerator(),
|
|
"2" => new XmlReportGenerator(),
|
|
"3" => new CsvReportGenerator(),
|
|
"4" => new ExcelReportGenerator(new OpenXmlExcelWorkerProvider()),
|
|
_ => null,
|
|
};
|
|
|
|
if (generator is not null)
|
|
await GenerateReport(strategy, generator, token);
|
|
}
|
|
|
|
private static async Task GenerateReport(SmaStrategy strategy, IReportGenerator generator, CancellationToken token)
|
|
{
|
|
var reportPath = $"backtest_report.{generator.Extension}";
|
|
|
|
Console.WriteLine();
|
|
Console.WriteLine($"Generating {generator.Name} report to {reportPath}...");
|
|
|
|
await using var stream = File.OpenWrite(reportPath);
|
|
await generator.Generate(strategy, stream, token);
|
|
|
|
Console.WriteLine($"Report saved: {reportPath}");
|
|
reportPath.OpenLink(false);
|
|
}
|
|
}
|