PineForge HPO 1.11.0
Native hyperparameter optimization for PineForge strategies
Loading...
Searching...
No Matches
trial_executor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <pineforge/pineforge.h>
4
5#include <array>
6#include <cstdint>
7#include <limits>
8#include <map>
9#include <memory>
10#include <optional>
11#include <string>
12#include <string_view>
13#include <vector>
14
18
19namespace pineforge {
20namespace hpo {
21
23using ParameterValues = std::map<std::string, std::string>;
24
28 std::string input_timeframe;
30 std::string script_timeframe;
32 std::string chart_timezone;
34 bool bar_magnifier = false;
38 pf_magnifier_distribution_t magnifier_distribution = PF_MAGNIFIER_ENDPOINTS;
39
46 bool capture_trades = false;
50 bool return_stats_bar = false;
63 std::uint32_t pbo_blocks = 0;
65 std::optional<SymbolInfo> symbol_info;
67 std::shared_ptr<const SymbolFeeds> symbol_feeds;
68};
69
80
88 bool computed = false;
90 std::array<double, 9> values{{
91 std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(),
92 std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(),
93 std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(),
94 std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(),
95 std::numeric_limits<double>::quiet_NaN()}};
96};
97
105 std::int32_t total_trades = 0;
107 double net_profit = 0.0;
108
110 std::int64_t input_bars_processed = 0;
112 std::int64_t script_bars_processed = 0;
114 std::int64_t security_feeds_total = 0;
116 std::int64_t security_complete_total = 0;
118 std::int64_t security_partial_total = 0;
120 std::int64_t magnifier_sub_bars_total = 0;
123
125 std::int32_t input_tf_seconds = 0;
127 std::int32_t script_tf_seconds = 0;
129 std::int32_t script_tf_ratio = 0;
131 bool needs_aggregation = false;
134
136 pf_metrics_t metrics{};
138 std::vector<pf_equity_point_t> equity_curve;
140 std::vector<pf_trade_t> trades;
151
162 std::optional<double> metric(std::string_view path) const noexcept;
163};
164
165namespace detail {
166
169class TrialResources final {
170public:
172 TrialResources(const StrategyPlugin& plugin, pf_strategy_t strategy)
173 : plugin_(plugin), strategy_(strategy) {}
175 ~TrialResources() {
176 plugin_.free_report(&report);
177 plugin_.free_strategy(strategy_);
178 }
180 TrialResources(const TrialResources&) = delete;
182 TrialResources& operator=(const TrialResources&) = delete;
184 pf_strategy_t strategy() const noexcept { return strategy_; }
186 pf_report_t report{};
187
188private:
189 const StrategyPlugin& plugin_;
190 pf_strategy_t strategy_;
191};
192
194void apply_trial_settings(const StrategyPlugin& plugin, pf_strategy_t strategy,
195 const ParameterValues& inputs, const ParameterValues& overrides,
196 const BacktestConfiguration& configuration);
198ReportSnapshot copy_report(const pf_report_t& report, const BacktestConfiguration& configuration,
199 bool reduce_blocks);
200
201} // namespace detail
202
204enum class TrialExecutionStatus : std::uint8_t {
205 kSucceeded = 0,
206 kEngineError = 1,
207};
208
214 std::string error;
216 std::optional<std::string> error_code;
218 std::optional<std::string> error_args;
221
223 bool succeeded() const noexcept { return status == TrialExecutionStatus::kSucceeded; }
224};
225
231class TrialExecutor final {
232public:
237 TrialExecutor(std::shared_ptr<const StrategyPlugin> plugin,
240
243 TrialExecutor(std::shared_ptr<const StrategyPlugin> plugin,
244 std::shared_ptr<const Dataset> dataset,
246
252 const ParameterValues& strategy_overrides = {}) const;
253
257 const ParameterValues& strategy_overrides,
258 std::size_t bar_count) const;
259
261 const BacktestConfiguration& configuration() const noexcept { return configuration_; }
263 const Dataset& dataset() const noexcept { return *view_.owner; }
265 const DatasetView& view() const noexcept { return view_; }
267 const StrategyPlugin& plugin() const noexcept { return *plugin_; }
268
269private:
270 std::shared_ptr<const StrategyPlugin> plugin_;
271 DatasetView view_;
272 BacktestConfiguration configuration_;
273};
274
275} // namespace hpo
276} // namespace pineforge
Immutable owned or file-mapped OHLCV input shared by independent trial executions.
Definition dataset.hpp:44
RAII wrapper around one compiled PineForge strategy plugin.
Deterministic one-shot adapter from serialized parameters to a detached report.
TrialExecutor(std::shared_ptr< const StrategyPlugin > plugin, DatasetView view, BacktestConfiguration configuration={})
Binds a validated plugin, immutable dataset view, and execution configuration.
TrialExecutionResult execute_prefix(const ParameterValues &inputs, const ParameterValues &strategy_overrides, std::size_t bar_count) const
Runs the exact full-backtest engine path on an immutable bar prefix.
const StrategyPlugin & plugin() const noexcept
Returns the loaded strategy plugin.
const DatasetView & view() const noexcept
Returns the immutable execution range.
const BacktestConfiguration & configuration() const noexcept
Returns the immutable per-execution configuration.
TrialExecutionResult execute(const ParameterValues &inputs, const ParameterValues &strategy_overrides={}) const
Runs one fresh strategy instance with overrides applied before ordinary inputs.
const Dataset & dataset() const noexcept
Returns the shared immutable owner; its size may exceed the execution view.
TrialExecutor(std::shared_ptr< const StrategyPlugin > plugin, std::shared_ptr< const Dataset > dataset, BacktestConfiguration configuration={})
Binds the whole dataset as a view, preserving existing callers' pointer and length.
void require_return_stats_identity()
Refuses return statistics in a build whose identity is unbound.
std::map< std::string, std::string > ParameterValues
Serialized Pine input or runtime-override values keyed by strategy parameter name.
TrialExecutionStatus
Terminal status of one native strategy execution.
@ kSucceeded
Backtest completed and a detached snapshot is available.
@ kEngineError
Strategy reported an error; no comparable snapshot is available.
Immutable engine settings applied to every execution owned by a TrialExecutor.
bool return_stats_monthly
Computes the returns.monthly statistics; the chart timezone above selects the calendar (only UTC is d...
bool capture_trades
Whether ReportSnapshot owns the complete C-ABI trade records (off in the HPO hot loop).
bool return_stats_bar
Computes the returns.bar statistics from the report's equity curve (see docs/return-stats....
std::string chart_timezone
Optional chart timezone applied through the strategy plugin.
bool bar_magnifier
Enables PineForge bar-magnifier sampling.
std::optional< SymbolInfo > symbol_info
Optional instrument metadata, applied after inputs and overrides.
std::shared_ptr< const SymbolFeeds > symbol_feeds
Fixed other-symbol bars loaded once, validated before trials, and shared read-only.
std::string script_timeframe
Pine strategy execution timeframe; may differ from the input timeframe.
pf_magnifier_distribution_t magnifier_distribution
Distribution used to place magnifier samples.
std::string input_timeframe
Timeframe represented by the input Dataset bars.
bool capture_equity_curve
Whether ReportSnapshot owns a copy of the report equity curve.
int magnifier_samples
Positive number of magnifier samples per sub-bar.
std::uint32_t pbo_blocks
Number of blocks S of the bar series to reduce per completed trial, and 0, the default,...
Immutable, non-copying range of bars retaining its Dataset owner.
Definition dataset.hpp:127
const std::shared_ptr< const Dataset > owner
Keeps owned bars or the mapping and its descriptor alive.
Definition dataset.hpp:138
Owning report snapshot detached from strategy and C-ABI report lifetimes.
bool needs_aggregation
Whether the engine aggregated input bars for script execution.
std::int64_t security_complete_total
Number of complete secondary-feed observations.
std::int64_t security_partial_total
Number of partial secondary-feed observations.
std::int64_t security_feeds_total
Number of requested secondary security feeds.
double net_profit
Report-level net profit in account currency.
ReturnStatsFields return_monthly
Monthly-return statistics, computed before the report was released when requested.
std::int32_t input_tf_seconds
Input timeframe duration in seconds.
ReturnStatsFields return_bar
Bar-return statistics, computed before the report was released when requested.
std::int64_t script_bars_processed
Number of script-timeframe bars processed by the strategy.
std::int32_t script_tf_seconds
Script timeframe duration in seconds.
bool bar_magnifier_enabled
Whether bar magnification was active.
std::int32_t total_trades
Number of completed trades.
pf_metrics_t metrics
Complete detached PineForge metrics structure.
std::int64_t input_bars_processed
Number of input-timeframe bars processed by the engine.
std::vector< pf_equity_point_t > equity_curve
Optional owned copy controlled by BacktestConfiguration::capture_equity_curve.
std::vector< pf_trade_t > trades
Optional owned trade records controlled by BacktestConfiguration::capture_trades.
std::int64_t magnifier_sample_ticks_total
Total synthetic magnifier ticks sampled.
std::int64_t magnifier_sub_bars_total
Total magnifier sub-bars processed.
std::int32_t script_tf_ratio
Integer aggregation ratio reported by the engine.
ReturnBlockMoments return_blocks
Per-block moments of the full-window equity curve; status NotRequested when blocks were not requested...
std::optional< double > metric(std::string_view path) const noexcept
Resolves a canonical objective path without allocating a string map.
ReturnBlockLayout return_block_layout
Block layout of the full-window equity curve, computed before the report was released when blocks wer...
Block layout of one bar-return series: how many intervals each block holds and which curve point open...
Moments of every block of one bar-return series, ascending block.
Published fields of one return-statistics series, in wire order: count, skipped, periods_per_year,...
bool computed
True when the series was requested and computed from a report's equity curve.
std::array< double, 9 > values
Field values in wire order; NaN stands for null.
Result envelope returned by TrialExecutor::execute().
bool succeeded() const noexcept
Returns whether status is TrialExecutionStatus::kSucceeded.
std::string error
Strategy error text when status is TrialExecutionStatus::kEngineError.
std::optional< std::string > error_code
Engine-owned failure code; absent for plugins without the optional getter.
std::optional< std::string > error_args
Raw engine argument JSON; consumers must validate it before serialization.
ReportSnapshot report
Detached report populated when execution succeeds.
TrialExecutionStatus status
Machine-readable terminal status.