User-Defined Functions
Learn how to create custom, reusable functions in kScript v2 using the func
keyword for modular and maintainable code.
Overview
kScript v2 introduces user-defined functions, allowing you to encapsulate logic into reusable modules. Functions can accept both var
and timeseries
arguments, support both positional and named parameter calling (kwargs), and must follow specific scoping rules.
Function Declaration
Basic Syntax
Kwargs Support
User-defined functions support both positional and named parameter calling conventions.
Function Name
Must follow standard identifier rules (letters, numbers, underscore). Cannot start with a number.
Parameters
Can accept var
and timeseries
arguments. Parameter types are inferred from usage. Support both positional and named parameter calling (kwargs).
Return Statement
Functions must explicitly return a value. The return type is inferred from the returned expression.
Function Examples
Simple Calculation
Basic mathematical operations with error handling.
Constraints and Rules
No Timeseries Declarations
Functions cannot declare new timeseries
inside their body. All timeseries must be declared in global scope.
func bad() { timeseries ts = ohlcv(...) }
Global Scope Only
Functions must be declared in global scope, not inside loops, conditionals, or other functions.
if (condition) { func bad() {...} }
Parameter Types
Functions can accept var
and timeseries
arguments. Types are inferred from how parameters are used.
func good(varParam, tsParam) {...}
Return Requirement
All functions must have an explicit return statement. The return type is inferred from the expression.
return someValue