Skip to content

Commit 1eab934

Browse files
authored
Merge #814 into the engine 1.11.1 train
Test strategy.risk.max_drawdown at closing fills, as TradingView does
2 parents 2605f22 + b26ce63 commit 1eab934

14 files changed

Lines changed: 736 additions & 44 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ version number follows semantic versioning over the surfaces the
77

88
## Unreleased
99

10+
- `strategy.risk.max_drawdown` is now tested at the order fills that close units, on the equity at that fill with open positions included, against the highest equity at such fills (the equity at an opening fill or at a bar close does not raise it), and a breach closes every open position at that fill's price (exit text "Close Position (Max Drawdown)"), cancels the pending orders and blocks later entries; before, it was measured once per bar close and only refused new entries (#804).
1011
- The internal native Store live-object policy defaults to 0 (unbounded).
1112
The former capped default of 1,048,576 is now 0. Native limits are kept
1213
exactly: every positive uint64, including UINT64_MAX, is finite;

‎include/pineforge/source/pine_adapter.hpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ inline constexpr char kSourceAdapterDomain[] = "pineforge-source-adapter/v4";
6464
// layer supplies the corresponding report labels.
6565
inline constexpr char kMarginCallLabel[] = "__margin_call__";
6666
inline constexpr char kIntradayLossComment[] = "Close Position (Max intraday Loss)";
67+
inline constexpr char kMaxDrawdownComment[] = "Close Position (Max Drawdown)";
6768
// The published C contract matched this PREFIX, not the whole comment, so the
6869
// classifier keeps matching the prefix.
6970
inline constexpr char kFillCapCommentPrefix[] =
@@ -1573,6 +1574,7 @@ struct PineRiskState {
15731574
// its latches.
15741575
double observed_peak_equity = std::numeric_limits<double>::quiet_NaN();
15751576
double observed_max_drawdown = 0.0;
1577+
double fill_peak_equity = std::numeric_limits<double>::quiet_NaN();
15761578
std::int64_t intraday_block_day = std::numeric_limits<std::int64_t>::min();
15771579
bool intraday_cancel_pending = false;
15781580
};

‎scripts/check_twin_parity.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@
2929
# executable code means a ledger/inventory rewrite cannot silently redefine
3030
# what the guard proves.
3131
BASE_MANIFEST_SHA256 = "a20f80eb29af455400fd2ab1bdef86e477af3d81891b1207623b4c890f6056db"
32-
INVENTORY_SHA256 = "04fd304bcc8f86a2abd4c121de88465307eaf069a8e5f1285307fdd45189b8b0"
33-
LEDGER_SHA256 = "c568999da8777ff967cdb3fcf007f382f88902bf78f9e02c2c5d7d15de22e9ba"
32+
INVENTORY_SHA256 = "a38305d7d402a6a236c53039ae4e4806caa88bbd6dfa3e554db01c26529e9a03"
33+
LEDGER_SHA256 = "5956795e5a65e80a79916e6ef0ced46dcc5474273fca1e5f166f09ed60e027d1"
3434

3535
APPENDIX_HEADING = "## Appendix 5 — CHECK-parity unobservable literal ledger"
3636
TABLE_HEADING = "| base file:line | CHECK text | reason unobservable | covering twin row |"

‎src/source/pine_adapter.cpp‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2718,6 +2718,7 @@ void PineExecutionAdapter::reset_for_run() {
27182718
day_ledger_ = {};
27192719
risk_.observed_peak_equity = kNaN;
27202720
risk_.observed_max_drawdown = 0.0;
2721+
risk_.fill_peak_equity = kNaN;
27212722
risk_.intraday_block_day = std::numeric_limits<std::int64_t>::min();
27222723
risk_.intraday_cancel_pending = false;
27232724
policy_script_bar_ = {};
@@ -18199,10 +18200,6 @@ void PineExecutionAdapter::update_risk_state(double mark_price) {
1819918200
engine_command_value_invalid_or_count("risk.threshold",
1820018201
EngineValueStage::risk, EngineValueReason::numeric_overflow);
1820118202
}
18202-
if (risk_.observed_max_drawdown >= threshold) {
18203-
risk_.halted = true;
18204-
return;
18205-
}
1820618203
}
1820718204
if (risk_.max_cons_loss_days > 0
1820818205
&& day_ledger_.consecutive_loss_days >= risk_.max_cons_loss_days) {
@@ -25197,6 +25194,36 @@ void PineExecutionAdapter::on_applied(const native_order::ExecutionAppliedEvent&
2519725194
pine_host->adapter_label_bracket_trades(event, from_bracket);
2519825195
}
2519925196
}
25197+
bool max_drawdown_breached = false;
25198+
if (risk_.max_drawdown > 0.0 && !risk_.halted) {
25199+
// A reversal has already closed the old position and opened the
25200+
// new one. Capture its equity before any further fills.
25201+
const double equity = require_host().native_marked_equity(event.resolved_price);
25202+
if (std::isfinite(equity)) {
25203+
// The peak is seeded at the first applied fill and afterwards
25204+
// follows the equity at fills that close units only: the equity
25205+
// at an opening fill never raises it.
25206+
if (!std::isfinite(risk_.fill_peak_equity)) {
25207+
risk_.fill_peak_equity = equity;
25208+
}
25209+
if (event.closed_units > 0.0) {
25210+
if (equity > risk_.fill_peak_equity) {
25211+
risk_.fill_peak_equity = equity;
25212+
}
25213+
const double threshold = risk_.max_drawdown_percent
25214+
? risk_.fill_peak_equity * risk_.max_drawdown / 100.0
25215+
: risk_.max_drawdown;
25216+
if (std::isfinite(risk_.max_drawdown) && !std::isfinite(threshold)) {
25217+
engine_command_value_invalid_or_count("risk.threshold",
25218+
EngineValueStage::risk, EngineValueReason::numeric_overflow);
25219+
}
25220+
max_drawdown_breached = risk_.fill_peak_equity - equity >= threshold;
25221+
// Latch before the forced close so its fill cannot trigger
25222+
// another drawdown test or a second close.
25223+
if (max_drawdown_breached) risk_.halted = true;
25224+
}
25225+
}
25226+
}
2520025227
if (placement_snapshot && placement_snapshot->opening) {
2520125228
detail::ExitScratchRows<native_order::RequestHandle> paired_closes(*this);
2520225229
for (const auto& handle : live_handles_) {
@@ -26589,6 +26616,29 @@ void PineExecutionAdapter::on_applied(const native_order::ExecutionAppliedEvent&
2658926616
risk_.intraday_cancel_pending = true;
2659026617
}
2659126618
}
26619+
if (max_drawdown_breached) {
26620+
// Close every remaining position, including a reversal's new side.
26621+
if (detail::run_position(require_host()).signed_units != 0.0) {
26622+
native_order::Request request;
26623+
request.intent = native_order::Flatten{};
26624+
request.comment = kMaxDrawdownComment;
26625+
PlacementSnapshot snapshot;
26626+
// This close does not start a separate intraday-loss block.
26627+
snapshot.family = PineOrderFamily::CloseAll;
26628+
snapshot.source_id = "__max_drawdown__";
26629+
snapshot.comment = request.comment;
26630+
snapshot.sizing = sizing_snapshot();
26631+
snapshot.forced_execution_price = event.resolved_price;
26632+
const auto accepted = submit_or_replace(
26633+
std::move(request), std::move(snapshot), false,
26634+
"__max_drawdown_close__");
26635+
if (accepted) {
26636+
(void)require_host().execute_current(
26637+
{*accepted, NativeCurrentPriceRule::NearestTick});
26638+
}
26639+
}
26640+
cancel_all();
26641+
}
2659226642
if (preclose_intraday_loss) {
2659326643
risk_.intraday_block_day = chart_day_key(context.sub_bar_open_ms);
2659426644
risk_.intraday_cancel_pending = true;

‎src/source/pine_state_hash.cpp‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,9 @@ void source::PineExecutionAdapter::hash_state(BrokerStateHashSink& f) const {
805805
f.b(risk_.max_intraday_loss_percent); f.d(risk_.max_position_size); f.b(risk_.halted);
806806
f.d(risk_.observed_peak_equity); f.d(risk_.observed_max_drawdown);
807807
f.i(risk_.intraday_block_day); f.b(risk_.intraday_cancel_pending);
808+
// Decision state of the max-drawdown rule, folded only under a drawdown
809+
// limit, so every run without one keeps its digest.
810+
if (risk_.max_drawdown > 0.0) f.d(risk_.fill_peak_equity);
808811
hash_short_seed_plan(f, short_seed_);
809812
hash_short_seed_plan(f, pending_short_seed_.plan);
810813
f.u(pending_short_seed_.expected_open_epoch); f.b(pending_short_seed_.ready);

‎src/source/pine_strategy_host.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,6 +1132,8 @@ void source::PineStrategyHost::on_native_applied(
11321132
row.close_cause = execution::CloseCause::FillCap;
11331133
else if (row.exit_comment.rfind(source::kIntradayLossComment, 0) == 0)
11341134
row.close_cause = execution::CloseCause::RiskLimit;
1135+
else if (row.exit_comment.rfind(source::kMaxDrawdownComment, 0) == 0)
1136+
row.close_cause = execution::CloseCause::RiskLimit;
11351137
}
11361138
adapter_.invalidate_exit_group(index); if (row.close_cause != previous_cause || index < trades_.base()) trades_.replace(index, row);
11371139
}

‎tests/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ set(TEST_SOURCES
106106
test_report_terminal_quote
107107
test_adapter_margin_relower
108108
test_adapter_risk_relower
109+
test_adapter_drawdown_fill_halt
109110
test_adapter_range_end_relower
110111
test_native_margin_kernel_r5
111112
test_adapter_brackets_relower

‎tests/adapter_risk_relower_expectations.inc‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,22 @@
3030

3131
namespace {
3232

33+
// No units close before the final mark; the same-side opening is admitted.
34+
// Tape d1 SHA-256: 5beeac719db4c7b6d84c31bf94f8bd9ac80cecaac8483e9900ec0b9532f36fd5
35+
// Tape d4b SHA-256: 0acb1158cea715b0e6cb5c6a838d997c6baf358c79df2433ad21a12fece399ac
3336
const Expected kDrawdownCadence{
3437
"MG10-a",
3538
"L 100 @0:100->3:99 pnl=-100 id='' c='' cause=6 | L 100 @2:99->3:99 pnl=0 id='' c='' cause=6 | pos=200",
3639
"pos=100"};
3740

41+
// expectation corrected: two reversals and an open long -> one reversal
42+
// followed by its drawdown close, because TradingView tests closing fills.
43+
// The long loses 100 * (94 - 100) = -600; the short closes at its own 94
44+
// entry for zero, with an empty exit id and risk close cause (4); the book is flat.
45+
// Tape d4a SHA-256: 8a5bd165a195e74ecf72ce6336a369b7892828acef6ee5dccf662be38440dc4a
3846
const Expected kDrawdownReversal{
3947
"MG10-b",
40-
"L 100 @0:100->2:94 pnl=-600 id='S' c='' cause=1 | S 100 @2:94->3:94 pnl=0 id='L' c='' cause=1 | L 100 @3:94->4:94 pnl=0 id='' c='' cause=6 | pos=100",
48+
"L 100 @0:100->2:94 pnl=-600 id='S' c='' cause=1 | S 100 @2:94->2:94 pnl=0 id='' c='Close Position (Max Drawdown)' cause=4 | pos=0",
4149
"pos=100"};
4250

4351
const Expected kLossDaysOrdered{

‎tests/test_abi_layout_probe.cpp‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,14 @@ using Scratch = std::remove_reference_t<
5757
#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__)
5858
// The ABI pins apply to Linux x86_64 builds that use GNU libstdc++.
5959
// PlacementTable members added in #756 grow both enclosing layouts by 32 bytes.
60+
// The fill-time peak of the drawdown rule (one double) grows both by 8 bytes.
6061
static_assert(sizeof(Scratch) == 672, "RetiredRowScratch size changed");
61-
static_assert(sizeof(Adapter) == 90352, "PineExecutionAdapter size changed");
62+
static_assert(sizeof(Adapter) == 90360, "PineExecutionAdapter size changed");
6263
#ifndef PINEFORGE_RUNTIME_LAYOUT_MEASURE_ONLY
6364
// Linux x86_64 GNU libstdc++ compiler diagnostics agree in Release and Debug
6465
// on the integrated tree. Measurement mode skips this pin and is never a
6566
// passing ABI gate.
66-
static_assert(sizeof(Host) == 109256, "PineStrategyHost size changed; measure and pin the final layout");
67+
static_assert(sizeof(Host) == 109264, "PineStrategyHost size changed; measure and pin the final layout");
6768
#endif
6869
static_assert(PF_STREAM_ENGINE_LAYOUT_VERSION == 4u, "runtime contexts require layout stamp 4");
6970
static_assert(!HasRosterRoots<Scratch>::value,
@@ -133,9 +134,9 @@ int main() {
133134
#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__)
134135
bool pins_hold = true;
135136
pins_hold &= pin("sizeof RetiredRowScratch", sizeof(Scratch), 672);
136-
pins_hold &= pin("sizeof PineExecutionAdapter", sizeof(Adapter), 90352);
137+
pins_hold &= pin("sizeof PineExecutionAdapter", sizeof(Adapter), 90360);
137138
#ifndef PINEFORGE_RUNTIME_LAYOUT_MEASURE_ONLY
138-
pins_hold &= pin("sizeof PineStrategyHost", sizeof(Host), 109256);
139+
pins_hold &= pin("sizeof PineStrategyHost", sizeof(Host), 109264);
139140
#else
140141
// A successful measurement command is never a successful layout test.
141142
pins_hold = false;
@@ -197,11 +198,11 @@ int main() {
197198
pins_hold &= pin("RetiredRowScratch::origin_fronts_pinned",
198199
member_offset(adapter.*access(RetiredScratch{}), &Scratch::origin_fronts_pinned), 664);
199200
pins_hold &= pin("PineExecutionAdapter::pine_view_",
200-
member_offset(adapter, access(BeforeScratch{})), 89072);
201+
member_offset(adapter, access(BeforeScratch{})), 89080);
201202
pins_hold &= pin("PineExecutionAdapter::retired_row_scratch_",
202-
member_offset(adapter, access(RetiredScratch{})), 89080);
203+
member_offset(adapter, access(RetiredScratch{})), 89088);
203204
pins_hold &= pin("PineExecutionAdapter::staged_scopes_",
204-
member_offset(adapter, access(AfterScratch{})), 89752);
205+
member_offset(adapter, access(AfterScratch{})), 89760);
205206
pins_hold &= pin("PineStrategyHost::adapter_",
206207
member_offset(host, access(HostAdapter{})), 6440);
207208
return pins_hold ? 0 : 1;

0 commit comments

Comments
 (0)