Skip to content

Commit 4b05b62

Browse files
luisleo526claude
andcommitted
Adapter re-lowering: the TradingView margin call runs through the kernel margin model (R5 lane R5)
The Pine host selects spec.margin (per-side initial from the Pine margin inputs, RealizedOnly level base, ShortfallMultiple 4.0, PathAdverseExtremeMark, the liquidation ticket label/comment) and supplies TradingView policy through L4b's hooks: resolve_margin_requirement restates the requirement (ten-significant-digit money rounding) and the equity (percent-commission live equity), resolve_margin_call_units applies the exact flooring and the family-R whole-drop band, margin_check_allowed carries the rounded-whole-lot-tie veto and the 1x-long exclusion, and the kernel's liquidation request is recognised at precommit by its RequestOrigin; resolve_execution_terms books the tick-rounded fire price with exit-side slippage. The kernel's liquidation now replaces the adapter's path-slice construction; the 1x-long money call (not a maintenance liquidation) and the non-path checkpoints (script close, stream tick, FX rollover, pre-open) stay adapter-side. Kernel additions: NativeMarginModel::liquidation_label/comment (folded only when set) and a fix for re-flooring an already-on-grid liquidation quantity (one lot short). The presence of spec.margin is the margin-call switch. Differential: tests/test_adapter_margin_relower.cpp (46 checks, eight scenarios bit-for-bit against values harvested from the b0cec54 library); corpus 312/312 engine_trades.csv identical (the corpus exercises no margin call — the campaign sweep is the population proof); ci_verify release PASS (507). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01CSmYixVAp4NqWpBZxkrLPT (cherry picked from commit 66fcc68c996195bb85845e618f2613e31d162bf7)
1 parent 9f18115 commit 4b05b62

15 files changed

Lines changed: 1258 additions & 170 deletions

‎docs/pages/native-engine.md‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,8 @@ margin.liquidation_min_units = 1.0; // optional broker minimum trade
512512
margin.check = NativeLiquidationCheck::PathAdverseExtreme;
513513
margin.basis = NativeMarginEquityBasis::MarkedEquity; // policy, below
514514
margin.level_base = NativeLiquidationLevelBase::MarkedEquity; // policy, below
515+
margin.liquidation_label = ""; // empty = "__kernel_liquidation__"
516+
margin.liquidation_comment = ""; // empty = "Margin liquidation"
515517
spec.margin = margin;
516518
```
517519

@@ -670,16 +672,37 @@ side. The host sees
670672
`on_native_applied` first and `on_native_margin_call` immediately after, with
671673
the same cursor.
672674

673-
The TradingView margin call is **not** this model: its rounded-money rules,
674-
its 4× shortfall default, its one-contract long money call, its adverse-extreme
675-
fill pricing and its nineteen scheduling exceptions stay in the Pine adapter,
676-
which never sets `margin`. What this lane adds is the shape a host would use to
677-
express rules like those: a policy host that selects the bases, answers
678-
`resolve_margin_requirement` with its own money, sizes in
679-
`resolve_margin_call_units`, prices in `resolve_execution_terms` and gates its
680-
own check points reproduces TradingView's trigger, sizing and placement on this
681-
kernel bit for bit (`tests/test_native_margin_hooks.cpp`, the TWIN section).
682-
None of it is a kernel option.
675+
**Naming the ticket.** `liquidation_label` and `liquidation_comment` are the
676+
ticket the kernel books its own liquidation under. Left empty they are the
677+
kernel's own `"__kernel_liquidation__"` / `"Margin liquidation"`; set, they are
678+
used verbatim, and they reach the closed row's exit id and comment. That
679+
matters because the exit id is how a reporting layer says "this row was a
680+
forced liquidation" — pineforge's own C ABI derives `close_cause`
681+
`MARGIN_CALL` from exactly that id — and every broker spells its own. Each
682+
folds into the model's digest only when set, so a model that does not name its
683+
ticket digests as it did before they existed
684+
(`tests/test_native_margin_ticket.cpp`).
685+
686+
**The TradingView margin call is this model.** The Pine adapter sets `margin`
687+
from `strategy(margin_long=, margin_short=)` — the two percents are the
688+
maintenance fractions — with `ShortfallMultiple` 4.0, the symbol's lot as
689+
`liquidation_min_units`, `PathAdverseExtremeMark`, the equity basis its
690+
commission type implies, `RealizedOnly` for the reported level and
691+
`"__margin_call__"` / `"Margin call"` for the ticket. The kernel then solves,
692+
schedules, places, re-prices, books and reports every resting liquidation; the
693+
adapter answers `margin_check_allowed` with TradingView's scheduling,
694+
`resolve_margin_requirement` with its ten-significant-digit money and
695+
fee-adjusted equity, `resolve_margin_call_units` with its lot-floored 4×
696+
restore and whole-drop band, and `resolve_execution_terms` with its
697+
tick-quantized fill price. The presence of `margin` IS
698+
`set_margin_call_enabled()`. What stays adapter-side is what no check point of
699+
the kernel's can reach: the bar-open mark checkpoint and the script-close pass
700+
(the kernel checks once per point, at the remaining path's adverse mark), the
701+
account-currency FX rollover revaluation, the pre-open admission slice, and the
702+
one-contract 1×-long money call — which is not a maintenance liquidation
703+
at all and fires on the favorable side of the path. Measured against the
704+
adapter as it stood before the re-lowering, on the same books, bit for bit:
705+
`tests/test_adapter_margin_relower.cpp`.
683706

684707
### Risk limits
685708

‎include/pineforge/native_run_spec.hpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,17 @@ enum class NativeLiquidationLevelBase : std::uint32_t {
198198
// the reported level is solved from. Both default to the marked-equity model
199199
// the kernel has always used, and both fold into the run spec's digest only
200200
// when moved off it.
201+
//
202+
// `liquidation_label` / `liquidation_comment` name the TICKET the kernel's own
203+
// liquidation is booked under. A broker's forced liquidation carries the
204+
// broker's identifiers, and a reporting layer that classifies a closed row by
205+
// its ticket id -- which is the ordinary way to say "this row was a margin
206+
// call" -- can only do so if those identifiers are the broker's. Empty keeps
207+
// the kernel's own ("__kernel_liquidation__" / "Margin liquidation"); a set
208+
// value is used verbatim for the request's label and comment and therefore
209+
// for the closed row's exit id and comment. Like the two money bases, each
210+
// folds into the model's digest only when set, so a model that does not name
211+
// its ticket digests exactly as it did before they existed.
201212
struct NativeMarginModel {
202213
double initial_long = 0.0;
203214
double initial_short = 0.0;
@@ -209,6 +220,8 @@ struct NativeMarginModel {
209220
NativeLiquidationCheck check = NativeLiquidationCheck::PathAdverseExtreme;
210221
NativeMarginEquityBasis basis = NativeMarginEquityBasis::MarkedEquity;
211222
NativeLiquidationLevelBase level_base = NativeLiquidationLevelBase::MarkedEquity;
223+
std::string liquidation_label;
224+
std::string liquidation_comment;
212225
};
213226

214227
// One risk threshold (L9). `value` is account currency when `percent` is

‎include/pineforge/source/pine_adapter.hpp‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,12 +770,43 @@ class PineExecutionAdapter {
770770
// instrument and that point; nothing is remembered.
771771
bool core_sizes_default_opening(bool is_long) const;
772772
NativePrecommitVerdict validate_precommit(const NativePrecommitView&) const;
773+
// R5: the three policy answers the kernel's margin model asks of its
774+
// host. `margin_check_allowed` is TradingView's scheduling -- the kernel
775+
// offers its own check points and the adapter admits only the ones
776+
// TradingView would also check at; `resolve_margin_requirement` is
777+
// TradingView's money (its fee-adjusted equity basis and its
778+
// ten-significant-digit requirement); `resolve_margin_call_units` is its
779+
// sizing (the lot-floored 4x restore and the family R whole-drop band).
780+
// TradingView's margin money at one mark: the requirement (on its
781+
// ten-significant-digit ladder where a lot is worth under one unit of
782+
// account) against its fee-adjusted live equity. One implementation, read
783+
// by the adapter's own checkpoints and by the kernel's requirement hook.
784+
struct SourceMarginMoney {
785+
bool valid = false;
786+
double mark = 0.0;
787+
double held = 0.0;
788+
double unit_margin = 0.0;
789+
double exact_required = 0.0;
790+
double required = 0.0;
791+
double equity = 0.0;
792+
};
793+
SourceMarginMoney source_margin_money(double mark_price,
794+
std::int64_t sub_bar_open_ms) const;
795+
double source_margin_units(const SourceMarginMoney&, bool opening_checkpoint) const;
796+
double source_margin_fill_price(double fire, bool close_is_buy) const;
797+
798+
bool source_margin_rounded_tie_veto() const;
799+
bool margin_check_allowed(const NativeMarginCheckPoint&) const;
800+
std::optional<NativeMarginDecision> resolve_margin_requirement(
801+
const NativeMarginRequirementView&) const;
802+
std::optional<double> resolve_margin_call_units(const NativeMarginCallView&) const;
773803
// True when the request is a source exit leg carrying priced stop, limit
774804
// or trailing terms (L10j): its trade row folds the pre-fill path extremes.
775805
bool source_priced_exit(std::uint64_t incarnation) const noexcept;
776806
bool source_post_parent_calc_level_fill(std::uint64_t incarnation) const noexcept;
777807
std::optional<double> source_trail_offset_ticks(std::uint64_t incarnation) const noexcept;
778808
bool source_margin_exit(std::uint64_t incarnation) const noexcept;
809+
static bool source_kernel_liquidation(const native_order::DefinitionRef&) noexcept;
779810
bool has_pending_market_exit(int current_interval_index = -1) const noexcept;
780811
// The carried 1x long's opening money call precedes the bar's excursion
781812
// sample only ahead of one resting full-position priced exit that the
@@ -1059,7 +1090,6 @@ class PineExecutionAdapter {
10591090
bool execute_at_current);
10601091
void schedule_preopen_margin_slice(const Bar&, const NativeDecisionContext&);
10611092
bool submit_margin_call_slice(double mark_price, const NativeDecisionContext&,
1062-
bool execute_current,
10631093
bool opening_checkpoint = false);
10641094
bool submit_margin_call_units(double mark_price, const NativeDecisionContext&,
10651095
double units,
@@ -1320,6 +1350,20 @@ class PineExecutionAdapter {
13201350
NativePathPhase position_open_phase_ = NativePathPhase::None;
13211351
bool position_open_priced_ = false;
13221352
std::int64_t last_margin_call_script_bar_ = std::numeric_limits<std::int64_t>::min();
1353+
// R5: the driver point ordinal whose kernel margin check the adapter's
1354+
// own scheduling admitted. The kernel offers its check points at every
1355+
// bar; exactly the one TradingView also checks at is let through, and
1356+
// only for the driver point it was armed on.
1357+
//
1358+
// Deliberately NOT folded into the broker state hash. Driver point
1359+
// ordinals are strictly monotone within a run and this value is only ever
1360+
// compared for equality with the current point's, so from the first point
1361+
// after the one it names it can never match again: it carries no
1362+
// information across any observation boundary the hash identifies. Folding
1363+
// it would move every adapter state hash (and R1's pinned hash-neutrality
1364+
// evidence in tests/test_adapter_report_relower.cpp) for a value that is
1365+
// dead by the time the next one is taken.
1366+
std::uint64_t kernel_margin_path_point_ = std::numeric_limits<std::uint64_t>::max();
13231367
// Close-time carried-POOC-short checkpoint deferred behind this bar's
13241368
// market fills (ab9714be pine_scheduler.cpp:260 before :278).
13251369
std::int64_t pooc_close_checkpoint_deferred_ms_ = std::numeric_limits<std::int64_t>::min();

‎include/pineforge/source/pine_strategy_host.hpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,13 @@ class PineStrategyHost : public NativeStrategyHost, public BrokerStateHashProvid
4545
const NativeExecutionTermsFacts&) const final;
4646
NativePrecommitVerdict validate_execution_precommit(
4747
const NativePrecommitView&) const final;
48+
// R5: the kernel owns the margin mechanism; these three answer with the
49+
// TradingView policy the adapter holds.
50+
bool margin_check_allowed(const NativeMarginCheckPoint&) const final;
51+
std::optional<NativeMarginDecision> resolve_margin_requirement(
52+
const NativeMarginRequirementView&) const final;
53+
std::optional<double> resolve_margin_call_units(
54+
const NativeMarginCallView&) const final;
4855
// RULING A48: the source host owns per-lot excursion accounting (MFE/MAE)
4956
// on the switched route. It samples every completed source bar's H/L/C
5057
// with the owner's entry-bar masks, and supplies the closing row's two

‎scripts/broker_state_hash_waivers.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,4 @@ excursion_priced_fill_ # Transient excursion-sampler cache; re-derived from the
5151
excursion_range_end_projection_ # Report-only projection scope flag around range-end row building; it is false for every real settlement.
5252
excursion_trail_offset_ticks_ # Transient excursion-sampler cache; re-derived from the immutable native request trigger at every precommit and cleared at the applied boundary.
5353
precommit_held_units_ # Transient precommit cache; re-derived from the physical position at every precommit and cleared at the applied-fill boundary (same class as the excursion_* caches).
54+
kernel_margin_path_point_ # Transient within-point arming value for the kernel's margin check gate: driver point ordinals are strictly monotone and margin_check_allowed only compares this for equality with the current point's, so from the first point after the one it names it can never match again; it is re-decided from already-hashed adapter state at every point (same class as the excursion_* and precommit_held_units_ caches).

‎scripts/check_native_cpp_versions.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,8 @@ def check_texts(files):
425425
'NativeLiquidationCheckcheck=NativeLiquidationCheck::PathAdverseExtreme;'
426426
'NativeMarginEquityBasisbasis=NativeMarginEquityBasis::MarkedEquity;'
427427
'NativeLiquidationLevelBaselevel_base='
428-
'NativeLiquidationLevelBase::MarkedEquity;'):
428+
'NativeLiquidationLevelBase::MarkedEquity;'
429+
'std::stringliquidation_label;std::stringliquidation_comment;'):
429430
raise ValueError('native margin model must preserve its member order and shape')
430431
risk = body(spec, r'struct\s+NativeRiskLimits\s*\{', 'native risk limits')
431432
if (re.sub(r'\s+', '', risk)

‎src/native_execution_consumer.cpp‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2775,14 +2775,35 @@ bool NativeExecutionConsumer::kernel_submit_liquidation(
27752775
} else {
27762776
double sized = units;
27772777
if (spec->quantity_grid && *spec->quantity_grid > 0.0) {
2778-
sized = std::floor(units / *spec->quantity_grid) * *spec->quantity_grid;
2779-
if (!native_order::quantity_on_grid(sized, *spec->quantity_grid)) return false;
2778+
// A quantity that is ALREADY on the broker's grid is left exactly
2779+
// as it is. Reconstructing it as floor(q/step)*step can move it a
2780+
// whole step down, because the quotient of two on-grid binary64
2781+
// values need not be the integer it represents: 0.0392/0.0001 is
2782+
// 391.99999999999994, whose floor is 391, i.e. one lot short of
2783+
// the size the sizing policy (or the host's units hook) decided
2784+
// on. Only an off-grid quantity is floored onto the grid.
2785+
if (!native_order::quantity_on_grid(sized, *spec->quantity_grid)) {
2786+
sized = std::floor(units / *spec->quantity_grid) * *spec->quantity_grid;
2787+
if (!native_order::quantity_on_grid(sized, *spec->quantity_grid)) return false;
2788+
}
27802789
}
27812790
if (!std::isfinite(sized) || !(sized > 0.0)) return false;
27822791
request.intent = native_order::Reduce{native_order::ExplicitUnits{sized}};
27832792
}
2784-
request.label = label != nullptr ? label : kNativeLiquidationLabel;
2785-
request.comment = comment != nullptr ? comment : kNativeLiquidationComment;
2793+
// A caller that names the ticket owns it -- (L9) the risk block's flatten
2794+
// is not a margin liquidation and carries its own id. Otherwise the broker
2795+
// names its own liquidation ticket where it has one, and the kernel's
2796+
// constants are the default. This is the id a reporting layer classifies
2797+
// the closed row by, so it must be the broker's.
2798+
const auto* ticket = margin_model();
2799+
request.label = label != nullptr
2800+
? label
2801+
: (ticket && !ticket->liquidation_label.empty()
2802+
? ticket->liquidation_label : kNativeLiquidationLabel);
2803+
request.comment = comment != nullptr
2804+
? comment
2805+
: (ticket && !ticket->liquidation_comment.empty()
2806+
? ticket->liquidation_comment : kNativeLiquidationComment);
27862807
if (resting) request.trigger = native_order::Stop{level};
27872808
// The kernel is born AT the point it decided on, exactly as a request
27882809
// submitted from the pre-open callback is. It never inherits the input

‎src/native_run_spec.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,14 @@ std::uint64_t native_margin_model_digest(const NativeMarginModel& margin) noexce
642642
u(static_cast<std::uint64_t>(margin.basis));
643643
u(static_cast<std::uint64_t>(margin.level_base));
644644
}
645+
// Same conditional shape for the broker's own ticket names: a model that
646+
// leaves them empty keeps the number it had before they existed.
647+
if (!margin.liquidation_label.empty() || !margin.liquidation_comment.empty()) {
648+
u(margin.liquidation_label.size());
649+
bytes(margin.liquidation_label.data(), margin.liquidation_label.size());
650+
u(margin.liquidation_comment.size());
651+
bytes(margin.liquidation_comment.data(), margin.liquidation_comment.size());
652+
}
645653
return state;
646654
}
647655

0 commit comments

Comments
 (0)