Skip to content

Commit b18f75e

Browse files
luisleo526claude
andcommitted
Native sizing bases and fractional reduces (R5 lane L3)
native_order_v6: a sixth OrderIntent `Sized` (CashValue / EquityFraction basis, SizeTime AtMatch|AtAcceptance, ExecutionGridPolicy, fee-net option) resolved by the kernel where HostSized terms resolve today, so a bare host sizes by cash or percent-of-equity without overriding resolve_execution_terms (which keeps the last word); and a third ReductionSize `ScopeFraction` (fraction of the bound scope, Gross or NetOfSiblings) for Pine's qty_percent-style exits. Non-representable -> TermsUnresolved; invalid basis -> InvalidQuantityBasis. The adapter never emits either and is untouched. Tests: tests/test_native_sizing_bases.cpp (491 checks: differential Sized vs hand-resolved HostSized with fee and grid, sizing points, rejections, gross/net-of-siblings, pending bracket parent, adapter neutrality); fail-before against the v5 closure. ci_verify release PASS (495). Design: docs/design/native-feature-parity.md A.2. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01CSmYixVAp4NqWpBZxkrLPT (cherry picked from commit 9048b8f2ef14566272dae6b36f85a6e3ff49b3d0)
1 parent 471708d commit b18f75e

12 files changed

Lines changed: 989 additions & 76 deletions

‎docs/pages/native-engine.md‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ Serialized external C++ calls may command only **between realtime inputs**,
192192
never reentrantly during input processing. There is no C request API in this
193193
slice.
194194
195-
`native_order::Request` values belong to `native_order_v5`
195+
`native_order::Request` values belong to `native_order_v6`
196196
(`native_order.hpp:25`); identity types stay `native_order_v1`. Label/comment
197197
remain inert text. The market default path still constructs from:
198198
@@ -759,6 +759,69 @@ ticket and one settlement cycle. A `HostSized{Open}` is sized once; later
759759
candidate rematches may re-resolve price but not size. `CloseOpposite` uses the
760760
existing whole-book Flatten path when it must close an absorbed roster.
761761

762+
### Sizing without a host override
763+
764+
`native_order::Sized` is the sixth `OrderIntent`: an opening whose size the
765+
kernel resolves, so a bare host needs no `resolve_execution_terms` override to
766+
buy a cash amount or a share of equity.
767+
768+
```cpp
769+
no::Request request;
770+
request.intent = no::Sized{no::Side::Long, no::EquityFraction{0.10}};
771+
submit(request); // 10 % of marked equity
772+
```
773+
774+
`SizeBasis` is `CashValue{cash}` in account currency or `EquityFraction{f}`, a
775+
fraction in `(0, 1]` of marked equity at the sizing point. Resolution is
776+
`units = cash / (price * point_value * fx)`, where `price` is the candidate's
777+
default resolved price. `SizeTime::AtMatch` (the default) resolves at the
778+
matching candidate; `SizeTime::AtAcceptance` freezes the units against the
779+
command point when the request is accepted. `reserve_percent_fee` divides the
780+
sizing cash by `1 + fee` when the run's fee kind is `NativeFeeKind::Percent`,
781+
and is an exact no-op for every other fee kind. `grid_policy` reuses
782+
`ExecutionGridPolicy`: `SnapToGrid` floors the units onto the run's
783+
`quantity_grid`; `ExplicitUnits` keeps the literal quotient, which the ordinary
784+
on-grid terms gate then refuses as `InvalidTerms` when a grid is configured and
785+
the quotient is off it. The two are identical on an ungridded run.
786+
787+
The kernel resolves the basis *before* the host hook and publishes the result
788+
as the facts' `RemainingUnits`, so a `resolve_execution_terms` override still
789+
has the last word: return your own units to replace the kernel's, or the
790+
default identity terms to accept them. A basis that is not representable — not
791+
finite, not positive, or below one grid step after snapping — is
792+
`MatchRejectReason::TermsUnresolved` at the candidate. An invalid basis
793+
(`fraction` outside `(0, 1]`, `cash <= 0`) is `RequestRejectReason::InvalidQuantityBasis`
794+
at submit. A kernel-sized opening always settles as a signed book transaction
795+
on its declared side; the `ReverseTo` and `CloseOpposite` shapes remain
796+
`HostSized{Open}` only, and `Sized` requires the `Independent` owner.
797+
798+
### Fractional reduces
799+
800+
`ReductionSize` gains `ScopeFraction{fraction, claim}`, a fraction in `(0, 1]`
801+
of the scope the reduce is bound to, resolved at the matching candidate:
802+
803+
```cpp
804+
no::Request exit;
805+
exit.intent = no::Reduce{no::ScopeFraction{0.5, no::ScopeClaim::NetOfSiblings}};
806+
exit.owner = no::BindOpening{opening, cycle}; // half of that one lot
807+
```
808+
809+
The bound scope is the whole book for an unbound or book-bound close, the one
810+
opening for `BindOpening`, and the live selected roster for `BindOpenings`.
811+
`ScopeClaim::Gross` takes the fraction of that scope as it stands.
812+
`ScopeClaim::NetOfSiblings` first subtracts the units already claimed by the
813+
live sibling reduces bound to the same scope, so two 50 % siblings on one
814+
10-unit lot claim 5 + 5 gross and 5 + 2.5 net. Scope identity is the request's
815+
own authority — opening handles, position cycles and cohort handles — never a
816+
source identifier. A bracket child that is still waiting for its parent has no
817+
scope and resolves only after the parent fill. The fraction is floored onto
818+
`quantity_grid` like every other engine quantity; a fraction that does not buy
819+
one whole step is `TermsUnresolved`, and `fraction` outside `(0, 1]` is
820+
`InvalidQuantityBasis` at submit.
821+
822+
Neither kind is emitted by the Pine adapter, which keeps resolving its own
823+
`HostSized` terms; `native_order` values therefore belong to `native_order_v6`.
824+
762825
### Source-layer boundary (R4-C)
763826

764827
Pine/generated hosts derive from `pineforge::source::PineStrategyHost`, which

‎include/pineforge/native_order.hpp‎

Lines changed: 65 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,13 @@
2222
#include <vector>
2323

2424
namespace pineforge::native_order {
25-
inline namespace native_order_v5 {
25+
inline namespace native_order_v6 {
2626

2727
// Isolated working-request/value core: current LIVE requests and immutable
2828
// command history. It does not own positions, cash, paid fees, matching,
2929
// calendar, host phase, or a second physical book.
3030
//
31-
// Identity types remain native_order_v1. Request/core/event values are v5.
31+
// Identity types remain native_order_v1. Request/core/event values are v6.
3232
// Physical execution::Action is unchanged; native Reduce uses a typed size
3333
// source instead of a dummy units field. ExecutionPlan is a transient widening
3434
// used at the core/consumer boundary.
@@ -64,15 +64,66 @@ struct HostSized {
6464
std::optional<Side> side;
6565
};
6666

67+
// Resolved host sizing normally remains subject to the run's quantity grid.
68+
// A host may instead authenticate literal units for a pure reduction; the
69+
// consumer still proves that the positive quantity is representable within
70+
// the selected exposure before it can reach settlement.
71+
enum class ExecutionGridPolicy : std::uint8_t {
72+
SnapToGrid = 0,
73+
ExplicitUnits = 1,
74+
};
75+
76+
// Native sizing bases (L3). The kernel resolves them into units at the
77+
// sizing point; the Pine adapter never emits them and keeps HostSized.
78+
struct CashValue {
79+
double cash = 0.0; // account currency
80+
};
81+
struct EquityFraction {
82+
double fraction = 0.0; // of marked equity at the sizing point (0.10 = 10 %)
83+
};
84+
using SizeBasis = std::variant<CashValue, EquityFraction>;
85+
86+
// AtMatch resolves the basis at the matching candidate; AtAcceptance freezes
87+
// the resolved units when the request is accepted.
88+
enum class SizeTime : std::uint8_t { AtMatch = 0, AtAcceptance = 1 };
89+
90+
// A kernel-sized opening. units = cash / (price * point_value * fx), where
91+
// cash is the basis value or fraction * marked equity, and price is the
92+
// candidate's default resolved price. A host override of
93+
// resolve_execution_terms still has the last word: it sees the kernel-resolved
94+
// units as the facts' RemainingUnits and may return its own.
95+
struct Sized {
96+
Side side = Side::Long;
97+
SizeBasis basis{};
98+
SizeTime time = SizeTime::AtMatch;
99+
// SnapToGrid floors the resolved units onto the run's quantity grid.
100+
// ExplicitUnits keeps the literal quotient, which the ordinary on-grid
101+
// terms gate then refuses when a grid is configured and the quotient is
102+
// off it; the two are identical on an ungridded run.
103+
ExecutionGridPolicy grid_policy = ExecutionGridPolicy::SnapToGrid;
104+
// Divide the sizing cash by (1 + fee) when the run's fee kind is
105+
// NativeFeeKind::Percent. Every other fee kind is an exact no-op.
106+
bool reserve_percent_fee = false;
107+
};
108+
67109
struct ExplicitUnits {
68110
double units = 0.0;
69111
};
70112
struct OwnerOpenedUnits {};
71-
using ReductionSize = std::variant<ExplicitUnits, OwnerOpenedUnits>;
113+
// Gross claims the whole bound scope; NetOfSiblings first subtracts the units
114+
// already claimed by the live sibling reduces bound to that same scope. The
115+
// keys are opaque request/owner handles, never source identifiers.
116+
enum class ScopeClaim : std::uint8_t { Gross = 0, NetOfSiblings = 1 };
117+
// A fraction in (0, 1] of the bound scope, resolved at the matching candidate.
118+
struct ScopeFraction {
119+
double fraction = 1.0;
120+
ScopeClaim claim = ScopeClaim::Gross;
121+
};
122+
using ReductionSize = std::variant<ExplicitUnits, OwnerOpenedUnits, ScopeFraction>;
72123
struct Reduce {
73124
ReductionSize size;
74125
};
75-
using OrderIntent = std::variant<Flatten, Reduce, Transact, ReverseTo, HostSized>;
126+
using OrderIntent = std::variant<Flatten, Reduce, Transact, ReverseTo, HostSized, Sized>;
76127

77128
struct Market {};
78129
// `fill_through` makes the limit a touch trigger (market-if-touched): the
@@ -439,15 +490,6 @@ enum class OpeningShape : std::uint8_t {
439490
CloseOpposite = 2,
440491
};
441492

442-
// Resolved host sizing normally remains subject to the run's quantity grid.
443-
// A host may instead authenticate literal units for a pure reduction; the
444-
// consumer still proves that the positive quantity is representable within
445-
// the selected exposure before it can reach settlement.
446-
enum class ExecutionGridPolicy : std::uint8_t {
447-
SnapToGrid = 0,
448-
ExplicitUnits = 1,
449-
};
450-
451493
struct ExecutionTerms {
452494
double resolved_price = 0.0;
453495
std::optional<double> units;
@@ -836,6 +878,12 @@ struct CommandContext {
836878
std::optional<OpeningObservation> opening;
837879
CommandSurface surface = CommandSurface::General;
838880
std::vector<OpeningObservation> openings;
881+
// Kernel-resolved acceptance-time units for a Sized{AtAcceptance} request.
882+
// The execution consumer owns the account facts, so it supplies them here;
883+
// a producer that leaves it unset accepts the request with a deferred size
884+
// that the matching path then reports as TermsUnresolved. Appended last so
885+
// the existing positional aggregate initializers keep their meaning.
886+
std::optional<double> sizing_units;
839887
};
840888

841889
struct EvaluationContext {
@@ -1339,7 +1387,9 @@ static_assert(std::is_nothrow_move_constructible_v<NoEffectEvent>);
13391387
static_assert(std::is_nothrow_move_constructible_v<MatchRejectedEvent>);
13401388
static_assert(std::is_nothrow_move_constructible_v<ExecutionAppliedEvent>);
13411389
static_assert(std::is_nothrow_move_constructible_v<MatchCursor>);
1342-
static_assert(std::variant_size_v<OrderIntent> == 5);
1390+
static_assert(std::variant_size_v<OrderIntent> == 6);
1391+
static_assert(std::variant_size_v<ReductionSize> == 3);
1392+
static_assert(std::variant_size_v<SizeBasis> == 2);
13431393
static_assert(std::variant_size_v<Remaining> == 5);
13441394
static_assert(std::variant_size_v<RemainingProjection> == 5);
13451395
static_assert(std::variant_size_v<Allowance> == 4);
@@ -1348,7 +1398,7 @@ static_assert(std::variant_size_v<ExecutionPlan> == 4);
13481398
static_assert(std::variant_size_v<ExecutionScope> == 3);
13491399
static_assert(std::variant_size_v<TriggerState> == 9);
13501400

1351-
} // inline namespace native_order_v5
1401+
} // inline namespace native_order_v6
13521402
} // namespace pineforge::native_order
13531403

13541404
namespace std {

‎scripts/check_native_cpp_abi.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
CURRENT_RESULT_DIAGNOSTIC = "R4B_CURRENT_RESULT_ALTERNATIVES"
5555

5656
CURRENT_ORDER_VARIANT = 17
57-
CURRENT_ORDER_INTENT_VARIANT = 5
57+
CURRENT_ORDER_INTENT_VARIANT = 6
5858
CURRENT_CALENDAR_INTERVAL = 40
5959
CURRENT_COORDINATE = 80
6060

‎scripts/check_native_cpp_versions.py‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -210,47 +210,60 @@ def check_texts(files):
210210
identity = versioned(files[FILES[11]], "pineforge::native_order", "native_order_v1")
211211
require(identity, ("RunIdentity", "RequestHandle", "Birth"),
212212
"native_order_v1", r'\b(?:class|struct)\s+NAME\s*\{')
213-
order = versioned(files[FILES[0]], "pineforge::native_order", "native_order_v5")
213+
order = versioned(files[FILES[0]], "pineforge::native_order", "native_order_v6")
214214
require(order, ("WorkingRequestCore", "Request", "SubmitResult",
215215
"AcceptedEvent", "NoEffectEvent", "MatchRejectedEvent",
216216
"ExecutionAppliedEvent", "HostSized", "HostSizedKind", "ReverseTo",
217217
"RemainingDeferred", "RemainingProjectionDeferred", "NoTarget",
218218
"RemainingProjectionNoTarget", "CohortHandle", "BindCohort", "CohortClose",
219219
"CohortRoster", "CohortReceipt", "AllowanceDeferred",
220220
"OpeningShape", "ExecutionGridPolicy", "ExecutionTerms", "TermsResolvedInput",
221-
"TermsResolvedEvent", "NativeCandidatePriceKind"),
222-
"native_order_v5", r'\b(?:enum\s+class|class|struct)\s+NAME\s*(?::[^;{]+)?\{')
221+
"TermsResolvedEvent", "NativeCandidatePriceKind",
222+
"CashValue", "EquityFraction", "SizeTime", "Sized",
223+
"ScopeClaim", "ScopeFraction"),
224+
"native_order_v6", r'\b(?:enum\s+class|class|struct)\s+NAME\s*(?::[^;{]+)?\{')
223225
require(order, ("CommandEvent", "ExecutionPlan", "OrderIntent", "Remaining",
224-
"RemainingProjection", "Allowance"),
225-
"native_order_v5", r'\busing\s+NAME\s*=')
226+
"RemainingProjection", "Allowance", "ReductionSize", "SizeBasis"),
227+
"native_order_v6", r'\busing\s+NAME\s*=')
226228
for token in ('operator==(CohortHandle', 'operator<(CohortHandle',
227229
'struct hash<pineforge::native_order::CohortHandle>'):
228230
if token not in files[FILES[0]]:
229231
raise ValueError('CohortHandle requires C++17 equality/order/hash support')
230232
require_exact_alias(
231-
order, "OrderIntent", "std::variant<Flatten,Reduce,Transact,ReverseTo,HostSized>",
232-
"native_order_v5")
233+
order, "OrderIntent", "std::variant<Flatten,Reduce,Transact,ReverseTo,HostSized,Sized>",
234+
"native_order_v6")
235+
require_exact_alias(
236+
order, "ReductionSize", "std::variant<ExplicitUnits,OwnerOpenedUnits,ScopeFraction>",
237+
"native_order_v6")
238+
require_exact_alias(
239+
order, "SizeBasis", "std::variant<CashValue,EquityFraction>", "native_order_v6")
233240
require_exact_alias(
234241
order, "Remaining",
235242
"std::variant<RemainingUnbound,RemainingFlattenAll,RemainingUnits,RemainingDeferred,NoTarget>",
236-
"native_order_v5")
243+
"native_order_v6")
237244
require_exact_alias(
238245
order, "RemainingProjection",
239246
"std::variant<RemainingProjectionUnbound,RemainingProjectionFlattenAll,"
240-
"RemainingProjectionUnits,RemainingProjectionDeferred,RemainingProjectionNoTarget>", "native_order_v5")
247+
"RemainingProjectionUnits,RemainingProjectionDeferred,RemainingProjectionNoTarget>", "native_order_v6")
241248
require_exact_alias(
242249
order, "Allowance",
243250
"std::variant<AllowanceUnset,AllowanceUnits,AllowanceAllScope,AllowanceDeferred>",
244-
"native_order_v5")
251+
"native_order_v6")
245252
require_exact_alias(
246253
order, "ExecutionPlan",
247254
"std::variant<execution::Flatten,order_action::Reduce,order_action::Transact,"
248-
"execution::ReverseTo>", "native_order_v5")
255+
"execution::ReverseTo>", "native_order_v6")
249256
execution_terms = body(order, r'struct\s+ExecutionTerms\s*\{', 'execution terms')
250257
if ('ExecutionGridPolicygrid_policy=ExecutionGridPolicy::SnapToGrid;'
251258
not in re.sub(r'\s+', '', execution_terms)):
252259
raise ValueError('ExecutionTerms omits its default grid policy')
253-
require_namespace_functions(order, ("to_execution_plan",), "native_order_v5")
260+
sized = re.sub(r'\s+', '', body(order, r'struct\s+Sized\s*\{', 'native sizing'))
261+
for pinned in ('SizeTimetime=SizeTime::AtMatch;',
262+
'ExecutionGridPolicygrid_policy=ExecutionGridPolicy::SnapToGrid;',
263+
'boolreserve_percent_fee=false;'):
264+
if pinned not in sized:
265+
raise ValueError('Sized omits a pinned default: ' + pinned)
266+
require_namespace_functions(order, ("to_execution_plan",), "native_order_v6")
254267
required_order_members = (
255268
(r'\bPreparation<PreparedMutation>\s+prepare_terms\s*\(', "prepare_terms"),
256269
(r'\bstatic\s+Allowance\s+evaluated_allowance\s*\(', "evaluated_allowance"),
@@ -264,14 +277,14 @@ def check_texts(files):
264277
raise ValueError(name + " must be a native_order_v5 WorkingRequestCore member")
265278
if re.search(r'\b(?:class|struct)\s+RunIdentity\s*\{', order):
266279
raise ValueError("RunIdentity must remain in native_order_v1, not native_order_v5")
267-
order_src = versioned(files[FILES[1]], "pineforge::native_order", "native_order_v5")
280+
order_src = versioned(files[FILES[1]], "pineforge::native_order", "native_order_v6")
268281
require(order_src, ("WorkingRequestCore::reset", "WorkingRequestCore::find_live",
269282
"WorkingRequestCore::prepare_terms",
270283
"WorkingRequestCore::evaluated_allowance",
271284
"WorkingRequestCore::effective_host_units",
272285
"WorkingRequestCore::cohort_open", "WorkingRequestCore::cohort_add",
273286
"WorkingRequestCore::cohort_remove"),
274-
"native_order_v5", r'\bNAME\s*\(')
287+
"native_order_v6", r'\bNAME\s*\(')
275288

276289
calendar = versioned(files[FILES[2]], "pineforge::native_calendar", "native_calendar_v2")
277290
require(calendar, ("Timeframe", "SessionCalendar", "NativeInterval",
@@ -642,5 +655,5 @@ def check(root=ROOT):
642655

643656
if __name__ == "__main__":
644657
check()
645-
print("native_order identity v1 / values v5, native_calendar_v2, native_run_spec_v3, "
658+
print("native_order identity v1 / values v6, native_calendar_v2, native_run_spec_v3, "
646659
"native_driver_v5, native_fx_curve_v1 and host engine_script_run_v17 ownership verified")

0 commit comments

Comments
 (0)