Advanced10 min read
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 bothvar and timeseries arguments, support both positional and named parameter calling (kwargs), and must follow specific scoping rules.
| Feature | Description |
|---|---|
func | Keyword used to define functions |
| Infinite Possibilities | Create any custom logic you need |
| Global Scope Required | Functions must be declared at top level |
Function Declaration
Basic Syntax
Kwargs Support
User-defined functions support both positional and named parameter calling conventions:Syntax Details
Function Name: Must follow standard identifier rules (letters, numbers, underscore). Cannot start with a number. Parameters: Can acceptvar 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:Average of Two Values
Custom Indicator Logic
Constraints and Rules
No Timeseries Declarations Inside Functions
Functions cannot declare newtimeseries inside their body. All timeseries must be declared in global scope.
Global Scope Only
Functions must be declared in global scope, not inside loops, conditionals, or other functions.Parameter Types
Functions can acceptvar and timeseries arguments. Types are inferred from how parameters are used.