Skip to content

Commit b1449c3

Browse files
luisleo526PineForge Factorial
andauthored
factorial: engine-symbol-r5 [engine] (#162)
Co-authored-by: PineForge Factorial <[email protected]>
1 parent e780321 commit b1449c3

16 files changed

Lines changed: 1862 additions & 90 deletions

‎include/pineforge/engine.hpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,6 +1356,14 @@ class BacktestEngine {
13561356
// short in ordinary historical dispatch; leveraged shapes stay fail-closed.
13571357
// Returns true when it emits a broker liquidation row.
13581358
bool process_carried_position_fx_rollover(const Bar& bar);
1359+
// finding-430: forced liquidation at the bar OPEN. A carried position
1360+
// with a finite liquidation price that already breaches the margin
1361+
// requirement at the open is sliced AT THE OPEN (quantity computed at
1362+
// the open price), before any resting order is evaluated there; the
1363+
// survivor keeps its ordinary adverse-extreme check, so one bar can book
1364+
// an open slice AND an extreme slice. Bars whose open does not breach
1365+
// are untouched. Returns true when a "Margin call" row was booked.
1366+
bool margin_call_slice_at_bar_open(const Bar& bar);
13591367

13601368
// --- Slippage helper ---
13611369
double round_to_mintick(double price) const {

‎include/pineforge/session_time.hpp‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,72 @@ std::string normalize_timezone_for_posix(const std::string& tz);
1414
// Pine time(timeframe, session?, timezone?) and time_close(...).
1515
// Returns Unix milliseconds, or na<int64_t>() when the bar is outside the
1616
// requested session (TradingView semantics for filtered sessions).
17+
//
18+
// `syminfo_tz` is the symbol's exchange timezone (Pine `syminfo.timezone`;
19+
// codegen passes `syminfo_.timezone`). It is the DEFAULT zone the `session`
20+
// window is interpreted in when `tz` is empty — Pine reads a tz-less session
21+
// in the exchange timezone, not UTC. An explicit `tz` always wins. It does
22+
// NOT influence the timeframe open/close computation (explicit `tz`, else
23+
// UTC, exactly as before); an empty `syminfo_tz` reproduces the historical
24+
// UTC session default byte-for-byte.
25+
//
26+
// Feature macro: generated code tests this to decide whether the trailing
27+
// `syminfo_tz` argument exists, so one transpiler output compiles against
28+
// both this header and older ones (`PF_PINE_TIME_SYMINFO_TZ_ARG(x)` in the
29+
// emitted prelude expands to `, (x)` only when it is defined).
1730
// ---------------------------------------------------------------------------
1831

32+
#define PF_PINE_TIME_HAS_SYMINFO_TZ 1
33+
34+
int64_t pine_time(int64_t bar_ms,
35+
const std::string& tf,
36+
const std::string& session,
37+
const std::string& tz,
38+
const std::string& chart_tf,
39+
const std::string& syminfo_tz = std::string());
40+
41+
int64_t pine_time_close(int64_t bar_ms,
42+
const std::string& tf,
43+
const std::string& session,
44+
const std::string& tz,
45+
const std::string& chart_tf,
46+
const std::string& syminfo_tz = std::string());
47+
48+
// Symbol-clock forms. `sym_tz` / `sym_session` are Pine's syminfo.timezone
49+
// and syminfo.session (the engine's runtime overrides). For a D/W/M `tf`
50+
// called WITHOUT a valid session argument the returned open / close is the
51+
// SYMBOL's daily/weekly/monthly bar (17:00 ET on OANDA forex, 09:30 ET RTH
52+
// on NASDAQ equities, 00:00 UTC on a 24x7 UTC symbol — see
53+
// session_period_open_ms in timeframe.hpp). A valid `session` argument
54+
// defines the day in its own `tz` exactly as the forms above do
55+
// (TradingView rolls `time("D", "0000-2359", "America/New_York")` at New
56+
// York midnight on a UTC symbol — measured), and its window is read in the
57+
// explicit `tz`, else `sym_tz` (the syminfo default above), else UTC.
58+
// Intraday tfs are unchanged.
59+
// With sym_tz="UTC" and an empty / "24x7" sym_session these are
60+
// bit-identical to the five-argument forms above.
61+
//
62+
// Feature macro: generated code tests this to decide whether the trailing
63+
// (sym_tz, sym_session) pair exists (`PF_PINE_TIME_SESSION_DAY_ARGS(tz, s)`
64+
// in the emitted prelude expands to `, tz, s` only when it is defined, so
65+
// the same generated.cpp collapses to the 5-arg call on older engines).
66+
#define PF_PINE_TIME_HAS_SESSION_DAY 1
67+
1968
int64_t pine_time(int64_t bar_ms,
2069
const std::string& tf,
2170
const std::string& session,
2271
const std::string& tz,
23-
const std::string& chart_tf);
72+
const std::string& chart_tf,
73+
const std::string& sym_tz,
74+
const std::string& sym_session);
2475

2576
int64_t pine_time_close(int64_t bar_ms,
2677
const std::string& tf,
2778
const std::string& session,
2879
const std::string& tz,
29-
const std::string& chart_tf);
80+
const std::string& chart_tf,
81+
const std::string& sym_tz,
82+
const std::string& sym_session);
3083

3184
// ---------------------------------------------------------------------------
3285
// Low-level session helpers (exposed for engine_run.cpp, unit tests,

‎include/pineforge/ta.hpp‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -947,26 +947,48 @@ class VWAP {
947947
// Sum of (price^2 * volume) for running variance computation used by
948948
// compute_bands(). Variance = cum_pv_sq_ / cum_vol_ - mean^2.
949949
double cum_pv_sq_ = 0.0;
950-
// Anchor day index (Unix-day = timestamp_ms / 86_400_000). On the
951-
// first compute() call we record this from the bar timestamp; on
952-
// every subsequent compute() the cumulator is reset whenever the
953-
// day index advances. Pine v6 `ta.vwap(source)` defaults to a Daily
954-
// anchor (`anchor = timeframe.change("1D")`); engine matches that.
950+
// Anchor day index: the SESSION day of the bar (session_day_index —
951+
// timestamp_ms / 86_400_000 on a UTC/24x7 symbol, the 17:00-ET-keyed
952+
// trading day on forex, the 09:30 RTH day on equities). On the first
953+
// compute() call we record this from the bar timestamp; on every
954+
// subsequent compute() the cumulator is reset whenever the day index
955+
// advances. Pine v6 `ta.vwap(source)` defaults to a Daily anchor
956+
// (`anchor = timeframe.change("1D")` on the SYMBOL's daily bar); the
957+
// engine matches that when the codegen threads syminfo tz + session.
955958
int64_t anchor_day_ = std::numeric_limits<int64_t>::min();
956959

957960
// Mirror the initial committed state (see RMA::RMA) so a recompute()
958961
// before the first compute() restores a well-defined pristine state.
959962
double saved_cum_pv_ = 0.0, saved_cum_vol_ = 0.0, saved_cum_pv_sq_ = 0.0;
960963
int64_t saved_anchor_day_ = std::numeric_limits<int64_t>::min();
961964

965+
void roll_anchor(int64_t day);
966+
962967
public:
963968
VWAP() = default;
969+
// tz-less forms key the anchor on the UTC day (the 24x7 corpus regime);
970+
// the tz/session forms key it on the symbol's session day and reduce to
971+
// the same integer math for tz="UTC" + empty/"24x7" session.
972+
// Feature macro PF_VWAP_HAS_SESSION_ANCHOR (below the class) lets
973+
// generated code compile the (tz, session) tail out on older engines.
964974
double compute(double src, double volume, int64_t timestamp_ms);
965975
double recompute(double src, double volume, int64_t timestamp_ms);
976+
double compute(double src, double volume, int64_t timestamp_ms,
977+
const std::string& tz, const std::string& session);
978+
double recompute(double src, double volume, int64_t timestamp_ms,
979+
const std::string& tz, const std::string& session);
966980
VWAPBandsResult compute_bands(double src, double volume, int64_t timestamp_ms, double stdev_mult);
967981
VWAPBandsResult recompute_bands(double src, double volume, int64_t timestamp_ms, double stdev_mult);
982+
VWAPBandsResult compute_bands(double src, double volume, int64_t timestamp_ms, double stdev_mult,
983+
const std::string& tz, const std::string& session);
984+
VWAPBandsResult recompute_bands(double src, double volume, int64_t timestamp_ms, double stdev_mult,
985+
const std::string& tz, const std::string& session);
968986
};
969987

988+
// Feature macro: the emitted prelude's PF_VWAP_SESSION_ANCHOR_ARGS(tz, s)
989+
// expands to `, tz, s` only when this is defined (see VWAP overloads above).
990+
#define PF_VWAP_HAS_SESSION_ANCHOR 1
991+
970992
// --- VWAP Bands wrapper class (3-tuple form: ta.vwap(src, anchor, stdev_mult)) ---
971993
// Wraps VWAP and routes compute/recompute to compute_bands/recompute_bands with
972994
// a fixed stdev_mult supplied at construction time. This lets the codegen use
@@ -982,6 +1004,14 @@ class VWAPBands {
9821004
VWAPBandsResult recompute(double src, double volume, int64_t timestamp_ms) {
9831005
return vwap_.recompute_bands(src, volume, timestamp_ms, stdev_mult_);
9841006
}
1007+
VWAPBandsResult compute(double src, double volume, int64_t timestamp_ms,
1008+
const std::string& tz, const std::string& session) {
1009+
return vwap_.compute_bands(src, volume, timestamp_ms, stdev_mult_, tz, session);
1010+
}
1011+
VWAPBandsResult recompute(double src, double volume, int64_t timestamp_ms,
1012+
const std::string& tz, const std::string& session) {
1013+
return vwap_.recompute_bands(src, volume, timestamp_ms, stdev_mult_, tz, session);
1014+
}
9851015
};
9861016

9871017
// --- Statistical ---

‎include/pineforge/timeframe.hpp‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,47 @@ bool crosses_boundary(int64_t prev_ms, int64_t curr_ms, CalendarPeriod period,
9797
bool tf_change(int64_t prev_ms, int64_t curr_ms, const std::string& tf,
9898
const std::string& tz, const std::string& session);
9999

100+
// ─── Symbol-clock D/W/M bar anchors ────────────────────────────────────────────
101+
//
102+
// TradingView's daily bar is the SESSION day, not the UTC (nor the local
103+
// calendar) day: OANDA:EURUSD (America/New_York, 1700-1700) opens its daily
104+
// bar at 17:00 ET and its week at Sunday 17:00 ET; NASDAQ:AAPL (0930-1600)
105+
// opens at 09:30 ET Monday..Friday; a 24x7 UTC symbol opens at 00:00 UTC.
106+
// Every chart-level consumer of "the symbol's daily bar" — ta.vwap's default
107+
// anchor, timeframe.change("1D"), time("D")/time_close("D") — has to key on
108+
// this clock, the same one request.security aggregation already uses
109+
// (crosses_boundary / session_period_key above). With tz="UTC" and an
110+
// empty / "24x7" session all of these reduce to plain epoch integer math,
111+
// bit-identical to the UTC forms the corpus pins.
112+
//
113+
// Period attribution follows TV's trading-date rule: a session that wraps
114+
// midnight (1700-1700) is the trading day of the date it CLOSES on (the
115+
// bar opening Sunday 17:00 ET is Monday's daily bar), so forex weeks open on
116+
// the Sunday session and a month opens on the session whose close date is
117+
// the 1st. Equity / 24x7 sessions close on their open date, so their weeks
118+
// stay Monday-partitioned and months calendar-partitioned exactly as before.
119+
// W/M opens are nominal (the Monday / 1st session-day); they do not consult
120+
// a holiday calendar.
121+
122+
/// Ordinal of the session day containing `ms` (days since epoch on the
123+
/// session clock). UTC + no session: ms / kMsPerDay.
124+
int64_t session_day_index(int64_t ms, const std::string& tz,
125+
const std::string& session);
126+
127+
/// Open (Unix ms) of the symbol's D/W/M bar that contains `ms`.
128+
/// CalendarPeriod::NONE returns `ms` unchanged.
129+
int64_t session_period_open_ms(int64_t ms, const std::string& tz,
130+
const std::string& session,
131+
CalendarPeriod period);
132+
133+
/// Exclusive close (Unix ms) of the symbol's D/W/M bar that contains `ms`:
134+
/// DAY -> session-day open + session length (16:00 ET on equities, the next
135+
/// 17:00 ET on forex, next midnight on 24x7); WEEK / MONTH -> the open of
136+
/// the next period's first session-day. CalendarPeriod::NONE returns `ms`.
137+
int64_t session_period_close_ms(int64_t ms, const std::string& tz,
138+
const std::string& session,
139+
CalendarPeriod period);
140+
100141
// ─── TimeframeAggregator ───────────────────────────────────────────────────────
101142

102143
class TimeframeAggregator {

0 commit comments

Comments
 (0)