Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
85b9100
Resolve empty timeframe arguments to the chart period
luisleo526 Nov 14, 2026
6e90b5a
Integrate empty timeframe handling with current main
luisleo526 Nov 14, 2026
6453949
Preserve timeframe arguments and generated-name safety
luisleo526 Nov 14, 2026
cd3b13f
Update anchor test expectations for conditional timeframe calls
luisleo526 Nov 14, 2026
8802058
Validate timeframe argument types
luisleo526 Nov 14, 2026
7a28a29
Register the timeframe argument diagnostic
luisleo526 Nov 15, 2026
49cab86
Refresh test reporting and timestamp controls
luisleo526 Nov 15, 2026
c04553d
Disambiguate diagnostic templates by argument kinds
luisleo526 Nov 15, 2026
f2f6ec8
Validate timeframe arguments using semantic types
luisleo526 Nov 15, 2026
c9bb034
Use the generated timeframe type diagnostic presentation
luisleo526 Nov 15, 2026
5beedda
Locate helper argument expectations inside the builtin call
luisleo526 Nov 15, 2026
bd8a3c6
Resolve registered argument types and report their source starts
luisleo526 Nov 15, 2026
95e5924
Preserve sizing string values across expressions and host settings
luisleo526 Nov 15, 2026
149cb9b
Exercise v5 receiver shadowing through an imported library
luisleo526 Nov 15, 2026
95b26d8
Preserve integer risk type boundary codes
luisleo526 Nov 15, 2026
6e9d119
Strengthen sizing regression and reserve generated name
luisleo526 Nov 15, 2026
d9a643e
Lower computed risk type arms at numeric boundary
luisleo526 Nov 15, 2026
57d0db6
Convert sizing selection arms at host boundaries
luisleo526 Nov 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@ supported as exact pairs; on the 0.x line they are independent. See the

## Unreleased (next release)

- Strategy sizing constants retain their string values in expressions, aliases
and helper calls. Host order and risk settings convert these values to their
numeric representation only at the setting boundary.

- `timeframe.in_seconds` and `timeframe.change` resolve an evaluated empty
string to the chart period, including input, variable, function-return and
named arguments. The argument is evaluated once, and nonempty strings keep
their explicit period. Bare `na` remains accepted; the value returned by
`timeframe.change(na)` is still awaiting verification against TradingView.
Non-string timeframe arguments are refused before C++ emission with the
stable `PF-E2095` type diagnostic and a source location, including input
values, reassignments, indicator results and helper parameters. Equally
specific diagnostic templates distinguish primitive types from qualifiers
using their catalog argument kinds. Dotted builtin signatures retain supplied
arguments, including escaped string literals and VWAP anchors. (#394)
- Script identifiers spelled like integer-to-float conversion temporaries,
including the underscore suffixes of nested conversions, now use the
generator's reserved-name escaping.
- A zone name the engine rejects now makes calendar-form `timestamp()` stop the
run at its first evaluation, instead of silently calculating a UTC value.
The paired engine reports a typed timezone error identifying the failed bar.
Expand Down
56 changes: 44 additions & 12 deletions pineforge_codegen/analyzer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
SymbolTable,
TypeSpec,
method_receiver_type_name,
public_type_name,
unify_pine_types,
)
from ..errors import SourceLocation, Diagnostic, CompileError, Level, Phase
Expand Down Expand Up @@ -7157,15 +7158,6 @@ def _operator_operand_type(
or authored_method
):
result = None
if result is None and isinstance(node, MemberAccess):
if isinstance(node.object, Identifier):
ns = node.object.name
if ns == "syminfo":
ptype = sigs.SYMINFO_VARIABLES.get(f"syminfo.{node.member}")
if ptype is not None:
result = TypeSpec.primitive(ptype.value)
elif ns == "timeframe" and node.member == "period":
result = TypeSpec.primitive("string")
if result is None and isinstance(node, FuncCall):
callee = node.callee
if isinstance(callee, Identifier):
Expand Down Expand Up @@ -7459,6 +7451,46 @@ def _visit_Ternary(self, node: Ternary) -> PineType:
return main_type
return result_type

def _check_timeframe_string_arguments(
self, node: FuncCall,
parameter_types: dict[str, PineType | TypeSpec] | None = None,
) -> None:
"""Check string signature slots using lexical and written-call types."""
if self._pine_version != 6 or self._in_v5_library_definition(node):
return
callee = node.callee
if (not isinstance(callee, MemberAccess)
or not isinstance(callee.object, Identifier)
or callee.object.name != "timeframe"
or self._value_bindings.declaration_bindings.get(id(callee.object)) is not None
or (parameter_types is not None and callee.object.name in parameter_types)):
return
intrinsic = sigs.BUILTIN_FUNCTIONS.get(f"timeframe.{callee.member}")
if intrinsic is None:
return
bound = self._bind_callable_args(node, intrinsic.param_names)
for parameter, value in zip(intrinsic.primary.params, bound):
if value is None or parameter.pine_type != PineType.STRING:
continue
actual = self._operator_operand_type(value, parameter_types)
if actual is None or actual in {
TypeSpec.primitive("string"), TypeSpec.primitive("na"),
}:
# Untyped helper parameters stay open until their written
# call supplies a type. Bare na adopts the string signature.
continue
function_name = intrinsic.name
argument_type = public_type_name(actual) or str(actual)
parameter_type = parameter.pine_type.value
name = parameter.name
from ..pine_spelling import expr_start

self._error(
f"Cannot call '{function_name}' with an argument of type {argument_type} "
f"for {parameter_type} parameter '{name}'.",
expr_start(value).loc or value.loc,
)

def _visit_FuncCall(self, node: FuncCall) -> PineType:
if self._pine_version == 6 and not self._in_v5_library_definition(node):
self._parameter_qualifiers.check_builtin(node)
Expand Down Expand Up @@ -7589,6 +7621,7 @@ def _visit_FuncCall(self, node: FuncCall) -> PineType:
visited_member_arg_types[id(arg)] = self._visit(arg)
for val in node.kwargs.values():
visited_member_arg_types[id(val)] = self._visit(val)
self._check_timeframe_string_arguments(node)
# UDT method call-site typing. Method definitions may contain an
# untyped parameter history read; resolve receiver + args here and
# apply the same deferred map-history gate as regular UDFs before
Expand Down Expand Up @@ -8958,6 +8991,8 @@ def _visit_MemberAccess(self, node: MemberAccess) -> PineType:
if drawing_all_kind(node) not in {None, "polyline"}:
# Collections use TypeSpec for their shape; PineType stays scalar.
return PineType.FLOAT
if self._builtin_sizing_constant(node) is not None:
return PineType.STRING
# Handle specific namespaces
if isinstance(node.object, Identifier):
ns = node.object.name
Expand All @@ -8967,9 +9002,6 @@ def _visit_MemberAccess(self, node: MemberAccess) -> PineType:
# Direction constants
if node.member in ("long", "short"):
return PineType.INT
# Qty type constants
if node.member in ("percent_of_equity", "fixed", "cash"):
return PineType.INT
# Commission type constants
if node.member in ("commission",):
return PineType.VOID # namespace prefix for .percent etc.
Expand Down
42 changes: 42 additions & 0 deletions pineforge_codegen/analyzer/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,26 @@ class TypeHelper:
docstring above.
"""

def _builtin_sizing_constant(self, value):
if not (isinstance(value, MemberAccess)
and isinstance(value.object, Identifier)):
return None
receiver = value.object
constant = sigs.get_sizing_constant(receiver.name, value.member)
if constant is None:
return None
parameters = getattr(self, "_parameter_types", None)
bindings = self._value_bindings.declaration_bindings
if ((self._pine_version == 6 and id(receiver) not in bindings)
or self._value_bindings.binding_of(receiver) is not None
or (self._pine_version != 6
and self._symbols.resolve(receiver.name) is not None)
or (parameters is not None and receiver.name in parameters)
or receiver.name in self._udt_fields
or receiver.name in self._enum_defs):
return None
return constant

def _split_top_level_type_args(self, text: str) -> list[str]:
args: list[str] = []
cur: list[str] = []
Expand Down Expand Up @@ -807,6 +827,8 @@ def direct_user_udt_ctor_name(node: ASTNode) -> str | None:
owner = self._type_spec_from_expr(value.object)
if owner is not None and owner.kind == "udt" and owner.name:
return (self._udt_field_type_specs.get(owner.name) or {}).get(value.member)
if self._builtin_sizing_constant(value) is not None:
return TypeSpec.primitive("string")
return None

@staticmethod
Expand Down Expand Up @@ -1535,6 +1557,9 @@ def _check_node(self, node):
op, operands = node.op, (node.operand,)
elif isinstance(node, Ternary):
op, operands = "?:", (node.condition, node.true_val, node.false_val)
elif isinstance(node, FuncCall):
self._analyzer._check_timeframe_string_arguments(node, self._parameter_types)
return
else:
return
self._analyzer._check_operator_operands(node, op, operands, self._parameter_types)
Expand All @@ -1544,6 +1569,23 @@ def _type_spec_from_expr(self, value, **kwargs):
return self._analyzer._operator_operand_type(
value, self._parameter_types,
)
if (isinstance(value, MemberAccess)
and isinstance(value.object, Identifier)
and self._pine_version == 6
and not self._in_v5_library_definition(value)):
receiver = value.object
bindings = self._value_bindings.declaration_bindings
# Require the receiver's recorded lexical namespace use. A
# missing record is not proof, and even an unresolved parameter
# or local in the written-call environment shadows a namespace.
if (id(receiver) in bindings and bindings[id(receiver)] is None
and (self._parameter_types is None
or receiver.name not in self._parameter_types)
and receiver.name not in self._udt_fields
and receiver.name not in self._enum_defs):
spec = sigs.get_variable_type_spec(receiver.name, value.member)
if spec is not None:
return spec
return super()._type_spec_from_expr(value, **kwargs)

def _visit(self, node):
Expand Down
16 changes: 10 additions & 6 deletions pineforge_codegen/codegen/emit_top.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@

import re

from ..signatures import STRATEGY_SIZING_CONSTANTS
from .run_stops import RUN_STOP_SHIMS_CPP, TIMEZONE_STOP_SHIM_CPP

from ..ast_nodes import (
Expand Down Expand Up @@ -1353,9 +1354,8 @@ def declared_or_v6_default(key: str):

# default_qty_type: strategy.fixed / strategy.percent_of_equity / strategy.cash
qty_type_map = {
"strategy.fixed": "QtyType::FIXED",
"strategy.percent_of_equity": "QtyType::PERCENT_OF_EQUITY",
"strategy.cash": "QtyType::CASH",
name: f"QtyType::{item.host_name}"
for name, item in STRATEGY_SIZING_CONSTANTS.items()
}
qty_type = declared_or_v6_default("default_qty_type")
if qty_type in qty_type_map:
Expand Down Expand Up @@ -1446,9 +1446,13 @@ def declared_or_v6_default(key: str):
lines.append(' } else if (key == "close_entries_rule") {')
lines.append(' overrides.close_entries_rule = (value == "ANY" || value == "any" || value == "1");')
lines.append(' } else if (key == "default_qty_type") {')
lines.append(' if (value == "fixed" || value == "strategy.fixed" || value == "0") overrides.default_qty_type = static_cast<int>(QtyType::FIXED);')
lines.append(' else if (value == "percent_of_equity" || value == "strategy.percent_of_equity" || value == "1") overrides.default_qty_type = static_cast<int>(QtyType::PERCENT_OF_EQUITY);')
lines.append(' else if (value == "cash" || value == "strategy.cash" || value == "2") overrides.default_qty_type = static_cast<int>(QtyType::CASH);')
for index, (name, item) in enumerate(STRATEGY_SIZING_CONSTANTS.items()):
branch = "if" if index == 0 else "else if"
lines.append(
f' {branch} (value == "{item.value}" || value == "{name}" '
f'|| value == "{item.host_value}") overrides.default_qty_type = '
f'static_cast<int>(QtyType::{item.host_name});'
)
lines.append(" else return;")
lines.append(' } else if (key == "commission_type") {')
lines.append(' if (value == "percent" || value == "strategy.commission.percent" || value == "0") overrides.commission_type = static_cast<int>(CommissionType::PERCENT);')
Expand Down
7 changes: 5 additions & 2 deletions pineforge_codegen/codegen/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ def cpp_code_only(cpp: str) -> str:
_pf_series_raw _pf_raw _pf_val_t _pf_out _pf_prior
_pf_hist_offset_raw _pf_hist_offset_numeric _pf_hist_offset _pf_hist_bar
_pf_calendar_ts _pf_calendar_tz
_pf_timeframe_arg _pf_qty_type
_tz _yr _mo _dy _hr _min _sc _res _old _old_tz _had_old _secs
_last_tz _last_yr _last_mo _last_dy _last_hr _last_min _last_sc
_last_res
Expand All @@ -542,15 +543,16 @@ def cpp_code_only(cpp: str) -> str:
_pf_number_text
_pf_substring_text _pf_substring_begin _pf_substring_end _pf_substring_error
_pf_array_new_size _pf_array_new_value _pf_array_new_size_type _pf_array_new_error
_pf_read _pf_v5_l _pf_v5_r _pf_wide_l _pf_wide_r
_pf_read _pf_v5_l _pf_v5_r _pf_wide_l _pf_wide_r _pf_w
_pf_symbol _pf_colon _pf_color _pf_bar_back _pf_ema_seeding
_pf_history_array _pf_history_offset _pf_matrix_target
_pf_array_index_type
_pf_sort_descending _pf_sort_element _pf_sort_indices _pf_sort_i _pf_sort_j
_pf_sort_left _pf_sort_right _pf_sort_left_na _pf_sort_right_na
""".split())
# These numbered members and locals keep their source-order spelling rather
# than allocating against authored names. Reserve their complete spellings,
# than allocating against authored names. Double coercions append underscores
# to _pf_w to distinguish nested temporaries. Reserve their complete spellings,
# just as for fixed temporaries, without reserving ordinary underscore names.
_CPP_TEMPORARY_PATTERN = re.compile(
r"_v\d+|_secval_\d+(?:_v\d+)?|_tuple_result_\d+(?:_elem_\d+)?|_tuple_unused_\d+|__switch_val_\d+"
Expand All @@ -560,6 +562,7 @@ def cpp_code_only(cpp: str) -> str:
r"|_pf_every_bar_ta_\d+|_pf_shared_\d+_\d+|__pf_array\w*|__pf_raw_\w+"
r"|_pf_collection_hist_\w+"
r"|_pf_substring_arg\d+"
r"|_pf_w_+"
r"|_req_sec_(?:lower_tf_)?\d+(?:_\d+)?|_precalc_\w+|_sec\d+_\w+"
r"|_pf_(?:sec|rec)_missing_\d+|_eval_security_\d+"
r"|_RuntimeSec\d+|_runtime_(?:feed|request)_\d+"
Expand Down
3 changes: 2 additions & 1 deletion pineforge_codegen/codegen/order_shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
TupleAssign, UnaryOp, VarDecl, WhileStmt,
)
from ..limits import iter_ast_nodes, syntax_children
from ..signatures import STRATEGY_SIZING_CONSTANTS
from .capabilities import READ_ONLY_STRATEGY_CALLS, _expression
from .host_members import HOST_MEMBER_NAMES

Expand All @@ -23,7 +24,7 @@
FINITE_BAR_VALUES = frozenset(("open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4"))
ENUM_VALUES = {
"strategy.oca.none": 0, "strategy.oca.cancel": 1, "strategy.oca.reduce": 2,
"strategy.fixed": 0, "strategy.percent_of_equity": 1, "strategy.cash": 2,
**{name: item.host_value for name, item in STRATEGY_SIZING_CONSTANTS.items()},
}
SETTING_DEFAULTS = {
"initial_capital": 10000.0, "default_qty_type": "fixed", "default_qty_value": 1.0,
Expand Down
8 changes: 6 additions & 2 deletions pineforge_codegen/codegen/strategy_declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from ..ast_nodes import EnumDecl, FuncDef, Identifier, StrategyDecl, StringLiteral, TypeDecl, VarDecl
from ..errors import CompileError, Diagnostic, Level, Phase, SourceLocation
from ..limits import iter_ast_nodes
from ..signatures import MATH_CONSTANTS, STRATEGY_PARAMETERS
from ..signatures import MATH_CONSTANTS, STRATEGY_PARAMETERS, STRATEGY_SIZING_CONSTANTS
from .constant_fold import NON_CONSTANT, NamedConstant, fold_constant_expression
from .tables import DAYOFWEEK_MAP, NAME_ECHO_STRING_MEMBERS

Expand All @@ -16,12 +16,16 @@
_NAMED_CONSTANTS = {
f"strategy.{name}": NamedConstant(f"strategy.{name}", name.rsplit(".", 1)[-1])
for name in (
"fixed", "cash", "percent_of_equity", "commission.percent",
"commission.percent",
"commission.cash_per_order", "commission.cash_per_contract",
"long", "short", "oca.none", "oca.cancel", "oca.reduce",
"direction.all", "direction.long", "direction.short",
)
}
_NAMED_CONSTANTS.update({
name: NamedConstant(name, item.value)
for name, item in STRATEGY_SIZING_CONSTANTS.items()
})
_NAMED_CONSTANTS.update({
f"{namespace}.{member}": NamedConstant(f"{namespace}.{member}", member)
for namespace in ("currency", "format")
Expand Down
22 changes: 22 additions & 0 deletions pineforge_codegen/codegen/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3061,6 +3061,8 @@ def _type_spec_from_expr_raw(
plan = getattr(self, "_array_widths", None)
return (plan.widen(spec, {("field", owner.name, node.member)})
if plan is not None else spec)
if self._builtin_sizing_constant(node) is not None:
return TypeSpec.primitive("string")
return None
if isinstance(node, FuncCall):
func_name, namespace = self._resolve_callee(node.callee)
Expand Down Expand Up @@ -6138,6 +6140,26 @@ def _infer_cpp_type_for_security_elem(self, node) -> str:
return "std::vector<double>"
return "double"

def _builtin_sizing_constant(self, node):
"""Resolve registered constants only through an unshadowed namespace."""
if not (isinstance(node, MemberAccess)
and isinstance(node.object, Identifier)):
return None
receiver = node.object
name = receiver.name
constant = sigs.get_sizing_constant(name, node.member)
if constant is None:
return None
if (self.ctx.identifier_decl_bindings.get(id(receiver)) is not None
or ValueBindings.declaration_of(receiver) is not None
or name in self._current_func_param_types
or name in self._current_func_locals
or name in self._current_loop_vars
or name in self._udt_defs
or name in self._enum_defs):
return None
return constant

def _text_type(self, node) -> str:
"""Pine bool provenance is consumed only by explicit text conversion."""
if not self._pine_v5_body:
Expand Down
Loading
Loading