# OpenMarket kScript > kScript is OpenMarket's scripting language for building technical indicators, trade-flow analytics, order-book visualizations, and backtested strategies. These docs cover the language reference: core concepts (including the v3 collections, lambdas, user-defined types, na semantics, and multi-timeframe), the function library (drawing objects and primitives, styling, control flow, the reference-validated TA library, typed inputs, libraries, foreign-domain panes), releases, and the migration guides (v1 to v2, v2 to v3). ## Getting Started - **Intro —** [Introducing kScript v3](https://openmarket.xyz/kscript/getting-started/introduction.md): kScript is designed to be intuitive whether you're coming from PineScript or learning to code for the first time. Create technical indicators, analyze market trends, and study order flow with powerful yet accessible tools. The syntax is straightforward and easy to learn — you'll be building working indicators in minutes. - **Intro —** [kScript v3 Overview](https://openmarket.xyz/kscript/getting-started/overview.md): A complete guide to understanding how kScript works. Covers core concepts, rules, and patterns for building indicators. - **Intro —** [Quick Start Guide](https://openmarket.xyz/kscript/getting-started/quick-start.md): Get started with kScript in 5 minutes. Build your first EMA Difference indicator step by step. ## Strategies - **Backtesting —** [Strategies Overview](https://openmarket.xyz/kscript/strategies/overview.md): Turn a kScript into a backtest. Declare strategy(), place orders with strategy.*, and get trades, an equity curve, and performance stats. - **Backtesting —** [Build Your First Strategy](https://openmarket.xyz/kscript/strategies/first-strategy.md): A complete walkthrough, from a trading idea to a backtested result you can read critically. Write it, run it, read the disclosures, tune it. - **Backtesting —** [Reading the Strategy Tester](https://openmarket.xyz/kscript/strategies/reading-the-tester.md): A tour of the Strategy Tester panel: the Overview, Performance, and Trades tabs, the chart markers, the run-details disclosures, and compare mode. - **Backtesting —** [Writing Strategies](https://openmarket.xyz/kscript/strategies/writing-strategies.md): The strategy() declaration, the strategy.* order API, position rules, and sizing. - **Backtesting —** [Perps and Leverage](https://openmarket.xyz/kscript/strategies/perps-and-leverage.md): Declare perps strategies, understand leveraged margin sizing, liquidation, maker/taker fees, funding, and the perps-specific stats. - **Backtesting —** [Fill Simulation](https://openmarket.xyz/kscript/strategies/fill-simulation.md): How the backtester decides when and at what price orders fill, how intrabar ordering questions are resolved with finer data, and how precision is reported. - **Backtesting —** [Slippage and Costs](https://openmarket.xyz/kscript/strategies/slippage-and-costs.md): Commission (spot), maker/taker fees (perps), flat slippage, and slippageModel="bookEstimate", which prices fills from recorded order-book depth where the platform has it. - **Backtesting —** [Perps: Margin, Liquidation, and Funding](https://openmarket.xyz/kscript/strategies/perps.md): instrument="perps" switches the broker emulator to isolated-margin perpetual futures - leverage, maker/taker fees, funding settlement, and liquidation, each with disclosed counts. - **Backtesting —** [Stats Reference](https://openmarket.xyz/kscript/strategies/stats-reference.md): Every performance stat the Strategy Tester reports, its exact formula, and its edge cases. All formulas are locked by engine tests. - **Backtesting —** [Examples: Spot Strategies](https://openmarket.xyz/kscript/strategies/examples-spot.md): Three complete spot strategies you can paste and run, from a two-line trend follower to bracketed exits, each one an executed example from this documentation's probe suite. - **Backtesting —** [Examples: The Five Perps Scenarios](https://openmarket.xyz/kscript/strategies/examples-perps.md): The five canonical perps strategies behind the engine's acceptance battery, covering liquidation on both sides, fee classification, funding erosion, and bankruptcy accounting. - **Backtesting —** [Backtest a Hyperliquid Perp Strategy](https://openmarket.xyz/kscript/strategies/examples-hyperliquid.md): A complete Hyperliquid perps backtest: leverage, maker/taker fees, and funding settled from recorded venue data, in twenty lines of kScript. ## Core Concepts - **Reference —** [Data Types](https://openmarket.xyz/kscript/core-concepts/data-types.md): Understanding kScript's type system and the fundamental data types available for building trading algorithms. - **Reference —** [Variables: var, timeseries, persist](https://openmarket.xyz/kscript/core-concepts/core-variables.md): Variable declaration and bar-state behavior in kScript: var, timeseries, and persist. - **Reference —** [Type System](https://openmarket.xyz/kscript/core-concepts/type-system.md): A comprehensive guide to kScript's hybrid type system, covering type inference, variable declarations, and data types. - **Reference —** [Collections](https://openmarket.xyz/kscript/core-concepts/collections.md): Arrays and maps in kScript, the reducer methods that iterate them, in-place sorting with comparators, and the two limits that keep them safe. - **Reference —** [Lambdas & Reducers](https://openmarket.xyz/kscript/core-concepts/lambdas-and-reducers.md): Arrow-function lambdas, closures, and the reducer methods (map, filter, reduce, forEach, find, some, every) that replace most explicit loops. - **Reference —** [User-Defined Types](https://openmarket.xyz/kscript/core-concepts/user-defined-types.md): Define your own typed structs with fields and methods. Construct with named fields, call methods, and mutate state with this. Model trading state in the shape of the problem. - **Reference —** [na and Color](https://openmarket.xyz/kscript/core-concepts/na-and-scalar-types.md): Working with missing values in kScript: the na helpers (isna, nz, fixnan), how NaN behaves, and building colors with color.rgb and color.new. - **Reference —** [Named Streams](https://openmarket.xyz/kscript/core-concepts/named-streams.md): Multi-output indicators like bb, macd, and stoch return a result whose components you read by name, such as bb.upper, macd.signal, and stoch.k. No positional guessing. - **Reference —** [Multi-Timeframe](https://openmarket.xyz/kscript/core-concepts/multi-timeframe.md): Read higher and lower timeframes from any script with htf(), ltf(), and request(). Higher-timeframe values are confirmed and repaint-free by default, with calendar periods (1D/1W/1M/1Q/1Y) and confirmed/developing/offset modes. - **Reference —** [Multi-Source & Aggregation](https://openmarket.xyz/kscript/core-concepts/multi-source.md): Combine multiple data sources in one script: other symbols, other venues, other data types, aggregated metrics like cross-exchange CVD, and the request(), ltf(), and requestBars() helpers. - **Reference —** [Data Sources](https://openmarket.xyz/kscript/core-concepts/data-sources.md): The market feeds kScript can subscribe to, their column members, and how to load them with source() and ohlcv(). - **Reference —** [Execution Model](https://openmarket.xyz/kscript/core-concepts/execution-model.md): How kScript runs your code bar by bar, where barIndex and isLastBar come from, and how history indexing works. - **Reference —** [Keyword Arguments](https://openmarket.xyz/kscript/core-concepts/keyword-arguments.md): Learn how to use keyword arguments (kwargs) in kScript v3 for clear, readable, and maintainable function calls with named parameters. - **Reference —** [Color Constants](https://openmarket.xyz/kscript/core-concepts/color-constants.md): Predefined color constants available in kScript for chart visualization and plotting. - **Reference —** [User-Defined Functions](https://openmarket.xyz/kscript/core-concepts/user-functions.md): Learn how to create custom, reusable functions in kScript v3 using the func keyword for modular and maintainable code. ## Functions - **Reference —** [Script Definition](https://openmarket.xyz/kscript/functions/script-definition.md): Define an indicator's metadata and surface user-configurable inputs. Plus debugging and data-source helpers. - **Reference —** [Strategy Functions](https://openmarket.xyz/kscript/functions/strategy-functions.md): The strategy() declaration and every strategy.* method - orders, brackets, cancellation, and position getters - with full parameter tables. - **Reference —** [Control Flow](https://openmarket.xyz/kscript/functions/control-flow.md): if/else, for loops, ternary expressions, and switch, the building blocks of per-bar logic in kScript. - **Reference —** [Moving Averages](https://openmarket.xyz/kscript/functions/moving-averages.md): Moving averages and price-band helpers — SMA, EMA, ALMA, SWMA, HMA, WMA, VWMA, RMA, LinReg, Bollinger, Keltner, Donchian. - **Reference —** [Oscillators](https://openmarket.xyz/kscript/functions/oscillators.md): Momentum and volume oscillators — RSI, WPR, CMO, TSI, MACD, Stochastic, CCI, MFI, Momentum, ADX, and OBV. - **Reference —** [Trend Indicators](https://openmarket.xyz/kscript/functions/trend-indicators.md): ADX, Ichimoku Cloud, MACD, and Parabolic SAR — trend strength, momentum, and reversal indicators. - **Reference —** [Special Indicators](https://openmarket.xyz/kscript/functions/special-indicators.md): Anchored VWAP, Ichimoku Cloud, Supertrend, and Parabolic SAR. - **Reference —** [Volume Indicators](https://openmarket.xyz/kscript/functions/volume-indicators.md): Money Flow Index and On-Balance Volume — volume-weighted indicators that confirm price moves and flag divergences. - **Reference —** [TA Library](https://openmarket.xyz/kscript/functions/ta-library.md): The v3 technical-analysis library: the full indicator catalog, multi-output indicators, warmup and forward-fill conventions, and reference-validated accuracy. - **Reference —** [Volume Profile Functions](https://openmarket.xyz/kscript/functions/volume-profile.md): Accessor functions for the volume_profile source — extract buy/sell volume, delta, point of control, and price range from each bar's price-level ladder. - **Reference —** [Orderbook Functions](https://openmarket.xyz/kscript/functions/orderbook-functions.md): Order-flow analytics functions for measuring bid and ask depth at configurable depth percentages. - **Reference —** [Plotting & Visualization](https://openmarket.xyz/kscript/functions/plotting.md): Render lines, bars, histograms, candles, shapes, text, labels, tables, and rectangles on the chart. - **Reference —** [Foreign-Domain Panes](https://openmarket.xyz/kscript/functions/foreign-panes.md): Offchart panes that ignore the time axis: categorical grids (plotMatrix), numeric-X curves (plotCurve), and KPI tile dashboards (plotTiles), plus the shared structural rules and caps. - **Reference —** [Drawing Objects](https://openmarket.xyz/kscript/functions/drawing-objects.md): Create, restyle, and delete chart drawings you own — lines, boxes, labels, polylines, fills, and tables. - **Reference —** [Drawing Primitives](https://openmarket.xyz/kscript/functions/drawing-primitives.md): Per-bar visual primitives: the plotShape marker set with locations and character markers, barcolor(), fillBetween(), and rich table cells. - **Reference —** [Styling](https://openmarket.xyz/kscript/functions/styling.md): Size tiers, tooltips, alignment vocabulary, z-order, color palettes, and the value-driven styling pattern (per-element gradients, opacity, and glow). - **Reference —** [Typed Inputs](https://openmarket.xyz/kscript/functions/typed-inputs.md): Expose script settings with input(), covering number, select, color, slider, boolean, source, and more. - **Reference —** [Alerts](https://openmarket.xyz/kscript/functions/alerts.md): Fire notifications from a script with alert() and alertcondition(). - **Reference —** [Libraries](https://openmarket.xyz/kscript/functions/libraries.md): Share functions and types across your scripts: create a library in the editor, import it with @owner/name, pin versions, and publish when it is ready. Library code is frozen into your scripts at save, so charts never depend on a registry at runtime. - **Reference —** [Math Functions](https://openmarket.xyz/kscript/functions/math-functions.md): The math namespace, covering abs, rounding, powers, logs, trig, and hyperbolics for numeric work in kScript. - **Reference —** [Color Functions](https://openmarket.xyz/kscript/functions/color-functions.md): Build and transform colors with rgb, new, opacity, lighten, darken, blend, and data-driven gradients. - **Reference —** [String Functions](https://openmarket.xyz/kscript/functions/string-functions.md): String manipulation and transformation methods available in kScript v3 for text processing. - **Reference —** [Series Functions](https://openmarket.xyz/kscript/functions/series-functions.md): Crossovers, rolling extremes, change, percentile, correlation, and na handling for time series. - **Reference —** [Utility Functions](https://openmarket.xyz/kscript/functions/utility-functions.md): Series statistics, crossover detection, and value validation helpers used across indicators and signals. - **Reference —** [Conditionals & Loops](https://openmarket.xyz/kscript/functions/loops.md): Learn how to use for loops, while loops, and conditional statements in kScript v3 for iterative calculations and control flow logic within the per-bar execution model. ## Cookbook - **Recipes —** [Cookbook](https://openmarket.xyz/kscript/cookbook/overview.md): Complete, working kScript v3 recipes you can copy, run, and adapt. From a volume-spike detector to a four-venue aggregated CVD. - **Recipes —** [Volume Spike Detector](https://openmarket.xyz/kscript/cookbook/volume-spike.md): Flag bars whose volume blows past its trailing average, scored as a z-score against a rolling mean and standard deviation. - **Recipes —** [Anchored VWAP](https://openmarket.xyz/kscript/cookbook/anchored-vwap.md): Weekly and daily VWAP that reset on real UTC session boundaries, with bands and a live stretch readout for mean-reversion context. - **Recipes —** [Regime Filter (4h Trend Gate)](https://openmarket.xyz/kscript/cookbook/regime-filter.md): A no-repaint higher-timeframe trend gate that tints candles by regime and only marks entries when the confirmed 4h trend agrees with the signal. - **Recipes —** [Key Levels](https://openmarket.xyz/kscript/cookbook/key-levels.md): Prior-day and prior-week highs and lows plus the running day open, drawn as labeled horizontal levels that are calendar-correct on any chart interval. - **Recipes —** [Aggregated CVD](https://openmarket.xyz/kscript/cookbook/aggregated-cvd.md): One cumulative volume-delta line summed across four exchanges, with volatility bands and a live venue count. The multi-source recipe Pine can't easily write. - **Recipes —** [Whale vs Retail CVD](https://openmarket.xyz/kscript/cookbook/tape-reader.md): Separate whale flow from retail flow using the tape pre-bucketed into real USD order-size bands, with months of history and per-bar trade counts. - **Recipes —** [Zone Tracker](https://openmarket.xyz/kscript/cookbook/zone-tracker.md): Supply and demand zones as typed structs in a persisted collection, drawn as boxes that delete themselves when price mitigates them, with a live dashboard. - **Recipes —** [Historical Returns Matrix](https://openmarket.xyz/kscript/cookbook/historical-returns.md): Month-by-year percentage returns as a foreign-domain matrix pane: rows are years, columns are months, with AVG / MED / WIN% summary rows and the forming month highlighted. Identical on every chart interval. ## FAQ - **Topics —** [General FAQ](https://openmarket.xyz/kscript/faq/general.md): Frequently asked questions about kScript, covering everything from basic syntax to advanced topics. - **Topics —** [Best Practices](https://openmarket.xyz/kscript/faq/best-practices.md): Guidelines and recommendations for writing efficient, maintainable, and error-free kScript code. - **Topics —** [Limitations](https://openmarket.xyz/kscript/faq/limitations.md): What kScript does not do yet, and where to find the sandbox numbers. - **Topics —** [Common Errors](https://openmarket.xyz/kscript/faq/common-errors.md): The kScript errors you are most likely to hit, what causes each one, and how to fix it. - **Topics —** [Exchange & Symbol Format](https://openmarket.xyz/kscript/faq/symbol-format.md): Complete list of supported exchanges and their symbol format syntax for use in kScript. ## Reference - **Lookup —** [Reference](https://openmarket.xyz/kscript/reference/quick-reference.md): Comprehensive reference for all kScript functions, variables, and data types. Build powerful trading algorithms with our extensive library of technical indicators and utilities. - **Lookup —** [Limits Reference](https://openmarket.xyz/kscript/reference/limits.md): The sandbox limits every kScript runs under, what each one protects, and when you will hit it. ## Releases - **Docs —** [Overview](https://openmarket.xyz/kscript/releases/overview.md): How kScript versions are documented, what to expect in each release entry, and where to find migration context when upgrading from older language versions. - **Docs —** [Release Notes](https://openmarket.xyz/kscript/releases/changelog.md): kScript release history: features, fixes, and breaking changes, listed newest first with anchor links into full entries. ## Migration - **Guide —** [kScript v1 vs v2 — Key Differences](https://openmarket.xyz/kscript/migrations/v1-vs-v2.md): Major improvements and design changes between kScript v1 and v2. Learn what's new in the latest version. - **Guide —** [v2 vs v3](https://openmarket.xyz/kscript/migrations/v2-vs-v3.md): A migration guide for v2 script authors. v3 is additive (your scripts keep running), but TA builtins, negative timeseries subscripts, and a few conveniences need checking.