Skip to content

Commit 24f75b9

Browse files
committed
Add observational default entry quantity query
Expose the configured fixed, cash, or percent entry size at a supplied fill price through the existing conversion leaf, without adding virtual methods or object fields. Add input-sensitive budget, FX, lot-grid, invalid-price and observation checks. The implementation is validated by targeted red-green and independent mutation controls.
1 parent 14e166a commit 24f75b9

4 files changed

Lines changed: 272 additions & 0 deletions

File tree

‎include/pineforge/source/pine_strategy_host.hpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,13 @@ class PineStrategyHost : public NativeStrategyHost, public BrokerStateHashProvid
371371
const std::string& comment = {},
372372
const std::string& oca_name = {}, int oca_type = 0,
373373
int qty_type = -1);
374+
// During a source calculation, query the configured default entry units
375+
// at the supplied fill price, using the current sizing equity, FX, point
376+
// value, fee policy and quantity grid. Fixed sizing uses its declared
377+
// units and grid. Open positions do not add reversal units. A nonpositive
378+
// or nonfinite fill price returns NaN; a valid below-grid size is zero.
379+
// Observation only: no order is placed and no driver point advances.
380+
double default_entry_qty(double fill_price) const;
374381
void strategy_close(const std::string& id, const std::string& comment = {},
375382
double qty = std::numeric_limits<double>::quiet_NaN(),
376383
double qty_percent = std::numeric_limits<double>::quiet_NaN(),

‎src/source/pine_adapter.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3416,6 +3416,21 @@ double PineExecutionAdapter::default_sizing_units(const PineSizingSnapshot& sizi
34163416
return quotient ? default_sizing_lot_floor(*quotient) : 0.0;
34173417
}
34183418

3419+
double PineStrategyHost::default_entry_qty(double fill_price) const {
3420+
// The placement leaf uses zero for an unresolvable price. A query must
3421+
// distinguish an invalid argument from a valid size below one lot.
3422+
if (!finite_positive(fill_price)) return kNaN;
3423+
if (adapter_.config_.default_qty_type == static_cast<int>(QtyType::FIXED)) {
3424+
return floor_quantity_grid(adapter_.config_.default_qty_value,
3425+
adapter_.staged_.quantity_grid);
3426+
}
3427+
auto sizing = adapter_.sizing_snapshot();
3428+
// Keep the calculation's equity and FX facts; only the hypothetical
3429+
// conversion price changes. It is already a fill, with no tick/slippage.
3430+
sizing.price = fill_price;
3431+
return adapter_.default_sizing_units(sizing);
3432+
}
3433+
34193434
// A typed quantity's units at `price`: the core converts the money the source
34203435
// chose, and reserves a percentage fee out of a percentage's money, exactly as
34213436
// for a default quantity; the source floors the quotient onto its grid, as

‎tests/CMakeLists.txt‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8306,3 +8306,9 @@ endforeach()
83068306
if(PINEFORGE_BUILD_SOURCE_LAYER)
83078307
add_custom_target(pineforge_pr_smoke DEPENDS ${PINEFORGE_PR_FAST_TESTS})
83088308
endif()
8309+
8310+
# The default-size query belongs only to the source-host surface.
8311+
if(PINEFORGE_BUILD_SOURCE_LAYER)
8312+
list(APPEND TEST_SOURCES test_default_entry_qty)
8313+
pineforge_add_unit_test(test_default_entry_qty)
8314+
endif()

‎tests/test_default_entry_qty.cpp‎

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
#include <pineforge/source/pine_strategy_host.hpp>
2+
3+
#include <algorithm>
4+
#include <cassert>
5+
#include <cmath>
6+
#include <cstdint>
7+
#include <limits>
8+
#include <type_traits>
9+
#include <vector>
10+
11+
using namespace pineforge;
12+
using pineforge::source::PineStrategyHost;
13+
14+
static_assert(std::is_same_v<decltype(&PineStrategyHost::default_entry_qty),
15+
double (PineStrategyHost::*)(double) const>);
16+
17+
namespace {
18+
19+
struct Inputs {
20+
QtyType type = QtyType::CASH;
21+
CommissionType fee_type = CommissionType::PERCENT;
22+
double fee = 0.0;
23+
double capital = 32000.0;
24+
double value = 1737.375;
25+
double point_value = 1.0;
26+
double fx = 1.0;
27+
double step = 0.0;
28+
std::int64_t fx_change_ms = 600000;
29+
bool fx_curve = false;
30+
bool seed_position = false;
31+
};
32+
33+
// Check conservation of the supplied budget and maximality on the lot grid.
34+
// This does not call the sizing leaf or copy its conversion/floor algorithm.
35+
void check_budget(double units, double budget, double unit_cost, double step) {
36+
assert(std::isfinite(units) && units >= 0.0);
37+
const double tolerance = 1e-9 * std::max(1.0, std::abs(budget));
38+
const double spent = units * unit_cost;
39+
assert(spent <= budget + tolerance);
40+
if (step > 0.0) {
41+
assert(std::abs(units / step - std::round(units / step)) < 1e-8);
42+
assert((units + step) * unit_cost > budget - tolerance);
43+
} else {
44+
assert(std::abs(spent - budget) <= tolerance);
45+
}
46+
}
47+
48+
class QueryHost final : public PineStrategyHost {
49+
public:
50+
QueryHost(const Inputs& inputs, bool query) : inputs_(inputs), query_(query) {
51+
source::PineStrategyConfig config;
52+
config.initial_capital = inputs.capital;
53+
config.default_qty_type = static_cast<int>(inputs.type);
54+
config.default_qty_value = inputs.value;
55+
config.commission_type = static_cast<int>(inputs.fee_type);
56+
config.commission_value = inputs.fee;
57+
// A hypothetical fill is already a price: do not add slippage or
58+
// snap it to mintick as if this query were placing a market order.
59+
config.slippage = 3;
60+
configure_pine_strategy(config);
61+
set_syminfo_mintick(0.25);
62+
set_syminfo_pointvalue(inputs.point_value);
63+
qty_step_ = inputs.step;
64+
account_currency_fx_ = inputs.fx;
65+
if (inputs.fx_curve) {
66+
const std::int64_t times[] = {0, inputs.fx_change_ms};
67+
const double rates[] = {inputs.fx, inputs.fx * 2.0};
68+
const bool installed = set_account_currency_fx_series(times, rates, 2);
69+
assert(installed);
70+
}
71+
}
72+
73+
int calculations = 0;
74+
int queries = 0;
75+
int held_calculations = 0;
76+
std::vector<double> answers;
77+
78+
void on_source_bar(const Bar& bar) override {
79+
++calculations;
80+
if (query_) {
81+
const auto hash = broker_state_hash();
82+
const auto floor = native_decision_floor();
83+
const auto position = physical_position();
84+
const int pending = pending_order_count();
85+
const int trades = trade_count();
86+
const int index = pine_bar_index();
87+
const auto events = native_events(0).size();
88+
if (position.lot_count > 0) ++held_calculations;
89+
const double fx = inputs_.fx_curve && bar.timestamp >= inputs_.fx_change_ms
90+
? inputs_.fx * 2.0 : inputs_.fx;
91+
const double equity = native_marked_equity(bar.close);
92+
const double prices[] = {
93+
bar.close * 0.625 + 0.03125,
94+
bar.close * 1.375 + 0.0625,
95+
inputs_.capital * inputs_.value * 10.0,
96+
};
97+
const PineStrategyHost& view = *this;
98+
for (const double price : prices) {
99+
const double units = view.default_entry_qty(price);
100+
++queries;
101+
answers.push_back(units);
102+
double budget = inputs_.value;
103+
double unit_cost = 1.0;
104+
if (inputs_.type != QtyType::FIXED) {
105+
unit_cost = price * inputs_.point_value * fx;
106+
if (inputs_.type == QtyType::PERCENT_OF_EQUITY) {
107+
budget = inputs_.value / 100.0 * equity;
108+
if (inputs_.fee_type == CommissionType::PERCENT) {
109+
unit_cost *= 1.0 + inputs_.fee / 100.0;
110+
} else if (inputs_.fee_type == CommissionType::CASH_PER_ORDER) {
111+
budget -= inputs_.fee;
112+
} else {
113+
unit_cost += inputs_.fee;
114+
}
115+
}
116+
}
117+
check_budget(units, budget, unit_cost, inputs_.step);
118+
assert(view.default_entry_qty(price) == units);
119+
}
120+
const double invalid_prices[] = {
121+
0.0, -0.0, -bar.close,
122+
std::numeric_limits<double>::quiet_NaN(),
123+
std::numeric_limits<double>::infinity(),
124+
-std::numeric_limits<double>::infinity(),
125+
};
126+
for (const double price : invalid_prices) {
127+
assert(std::isnan(view.default_entry_qty(price)));
128+
}
129+
assert(broker_state_hash() == hash);
130+
assert(native_decision_floor() == floor);
131+
assert(physical_position().signed_units == position.signed_units);
132+
assert(physical_position().lot_count == position.lot_count);
133+
assert(pending_order_count() == pending);
134+
assert(trade_count() == trades);
135+
assert(pine_bar_index() == index);
136+
assert(native_events(0).size() == events);
137+
}
138+
// Both runs submit the same explicit seed. The query must not include
139+
// its units as a reversal or otherwise change the order/driver state.
140+
if (inputs_.seed_position && pine_bar_index() == 0) {
141+
strategy_entry("seed", false,
142+
std::numeric_limits<double>::quiet_NaN(),
143+
std::numeric_limits<double>::quiet_NaN(), 2.0);
144+
}
145+
}
146+
147+
private:
148+
Inputs inputs_;
149+
bool query_;
150+
};
151+
152+
std::vector<Bar> bars() {
153+
std::vector<Bar> result;
154+
for (int index = 0; index < 4; ++index) {
155+
Bar bar{};
156+
bar.timestamp = 300000LL * index;
157+
bar.open = 100.0 + index * 4.0;
158+
bar.high = bar.open + 2.0;
159+
bar.low = bar.open - 2.0;
160+
bar.close = bar.open + 1.0;
161+
bar.volume = 1.0;
162+
result.push_back(bar);
163+
}
164+
return result;
165+
}
166+
167+
void check_query(const Inputs& inputs) {
168+
const auto feed = bars();
169+
QueryHost queried(inputs, true);
170+
QueryHost control(inputs, false);
171+
queried.run(feed.data(), static_cast<int>(feed.size()));
172+
control.run(feed.data(), static_cast<int>(feed.size()));
173+
assert(queried.last_error().empty());
174+
assert(control.last_error().empty());
175+
assert(queried.calculations == static_cast<int>(feed.size()));
176+
assert(control.calculations == queried.calculations);
177+
assert(queried.queries == queried.calculations * 3);
178+
assert(queried.broker_state_hash() == control.broker_state_hash());
179+
assert(queried.trade_count() == control.trade_count());
180+
if (inputs.seed_position) {
181+
assert(queried.held_calculations > 0);
182+
} else {
183+
assert(queried.trade_count() == 0);
184+
assert(queried.physical_position().lot_count == 0);
185+
}
186+
if (inputs.type != QtyType::FIXED) {
187+
assert(queried.answers[0] > queried.answers[1]);
188+
}
189+
}
190+
191+
} // namespace
192+
193+
int main() {
194+
for (const auto type : {QtyType::FIXED, QtyType::CASH, QtyType::PERCENT_OF_EQUITY}) {
195+
for (const double fx : {0.8, 1.6}) {
196+
for (const double point_value : {1.0, 7.5}) {
197+
for (const double step : {0.0, 0.25, 1.0}) {
198+
for (const auto fee_type : {CommissionType::PERCENT,
199+
CommissionType::CASH_PER_ORDER,
200+
CommissionType::CASH_PER_CONTRACT}) {
201+
Inputs inputs;
202+
inputs.type = type;
203+
inputs.value = type == QtyType::PERCENT_OF_EQUITY ? 17.5 : 1737.375;
204+
inputs.fx = fx;
205+
inputs.point_value = point_value;
206+
inputs.step = step;
207+
inputs.fee_type = fee_type;
208+
inputs.fee = 0.5;
209+
check_query(inputs);
210+
}
211+
}
212+
}
213+
}
214+
}
215+
Inputs curve;
216+
curve.fx = 0.8;
217+
curve.fx_curve = true;
218+
curve.point_value = 7.5;
219+
curve.step = 0.25;
220+
check_query(curve);
221+
curve.type = QtyType::PERCENT_OF_EQUITY;
222+
curve.value = 17.5;
223+
check_query(curve);
224+
225+
Inputs held;
226+
held.type = QtyType::PERCENT_OF_EQUITY;
227+
held.value = 17.5;
228+
held.point_value = 7.5;
229+
held.fx = 1.6;
230+
held.seed_position = true;
231+
check_query(held);
232+
233+
// Change the declaration and account independently of the matrix above.
234+
for (const auto type : {QtyType::FIXED, QtyType::CASH, QtyType::PERCENT_OF_EQUITY}) {
235+
Inputs varied;
236+
varied.type = type;
237+
varied.capital = 47000.0;
238+
varied.value = type == QtyType::PERCENT_OF_EQUITY ? 32.25 : 287.625;
239+
varied.point_value = 2.5;
240+
varied.fx = 1.25;
241+
varied.step = 0.5;
242+
check_query(varied);
243+
}
244+
}

0 commit comments

Comments
 (0)