Code Structure
Fundamental patterns for organizing your kScript code.
Use the appropriate variable type for your data.
Use for constants and values that never change across bars (e.g., periods, thresholds, multipliers).
Use for dynamic values that change per bar but don't need historical access (e.g., signals, calculations).
Use only when absolutely necessary as they consume more memory. Declare as timeseries when you need to:
- Store data source outputs:
timeseries price_data = ohlcv(...)
- Access past values at previous candle indices:
sma_values[5]
While indicator functions like sma()
, ema()
, and rsi()
require a timeseries as input, their return values should be stored as var
unless you specifically need to access historical values (e.g., sma_values[5]
). This saves memory and improves performance.
Technical Indicators
Guidelines for working with technical indicators effectively.
Always specify parameters explicitly for clarity. This makes your code more readable and maintainable.
Plotting & Visualization
Create clear and informative visualizations.
Select the right plot function for your data type.
plotLine()
for continuous linesplotBar()
for histogram dataplotCandle()
for OHLC dataplotShape()
for discrete signals
Debugging
Best practices for debugging and inspecting your kScript code.
Always use printTimeSeries()
for timeseries objects instead of print()
. The print()
function only outputs the first value (e.g., only "open" for OHLCV data), while printTimeSeries()
displays the complete timeseries structure.
Error Prevention
Protect your code against common runtime errors.
Performance Optimization
Write efficient code that executes quickly.
Store frequently used calculations in variables instead of recalculating.
Code Organization
Structure your code for maximum readability and maintainability.
Organize your code into logical sections: inputs, data sources, calculations, signals, and plotting.
Always include label
and desc
parameters in your plotting functions. These parameters improve autocomplete functionality, make scripts more readable, and help with script organization in the editor.