Open Source Runtime

The Embeddable Quant DSL.

Provide your platform users with a secure, PineScript-style language. Kafal evaluates operations natively across C-level Pandas and NumPy arrays, keeping your host infrastructure completely isolated.

View on PyPIRead the Specs
$ pip install kafal
strategy.kf
define name="VWAP Reversion" overlay=true

// Schemas automatically derived for your UI
@input dev:float = 2.0  min=0.5 max=5.0
@input len:int   = 20   min=10  max=100

// Vectorized TA-Lib & Custom Primitives
basis = ta.vwap(high, low, close, volume)
band  = dev * ta.stdev(close, len)
lower_band = basis - band
long_cond  = crossover(close, lower_band)

// Realistic Execution Routing
trade.limit_long(lower_band, size=1.0, tif="GTC")
trade.close(close > basis)

// Chart Contracts output as JSON
plot(basis) - title="VWAP" color="blue"
$45.5k$45.0k$44.5k$44.0k
10:0012:0014:0016:00

A Dual-Sided Architecture

Kafal is not a standalone trading platform. It is a strictly partitioned, embeddable interpreter designed to bridge the gap between your backend infrastructure and your end-users' trading logic.

1. Host Supplies Data

Your Python backend injects raw OHLCV DataFrames into the runtime.

2. User Runs Logic

The untrusted Kafal script executes securely inside the AST sandbox.

3. Host Renders UI

The runtime returns a strictly-typed JSON payload for your charting layer.

End 1: The Host Platform

Total Architecture Control

You own the data layer, the database, and the UI. Inject raw Pandas DataFrames and execution parameters directly into the interpreter. Kafal securely sandboxes the untrusted user script, executes it, and returns a strictly typed JSON payload ready for your charting frontend.

  • Zero-trust AST Sandbox
  • Data delegation via Pandas
  • UI-ready JSON Serialization
End 2: The End-User

Familiar Quant DSL

Your users focus entirely on alpha. They write familiar PineScript-style logic without needing to understand Python, C-level array alignment, or complex memory management. They get instant access to 150+ vectorized technical indicators and dynamic input parameters.

  • Native PineScript parity
  • 150+ Vectorized Primitives
  • Dynamic @input UI schemas
Part 1

Backend Infrastructure

Everything you need to securely execute untrusted user code, manage portfolio state, and extract clean JSON for your UI.

Built for Trading Platforms

A deterministic execution environment that bridges raw Python data engineering with a user-facing domain specific language.

01 // Vectorization

Native Array Evaluation

Operations process across full time-series datasets instantly using Pandas and NumPy arrays. By bypassing slow Python bar-by-bar loops, indicators and backtests evaluate with institutional-grade speed.

02 // Sandbox

AST Security Isolation

Untrusted scripts execute inside an isolated Abstract Syntax Tree. There is zero access to the host OS, filesystem, network, or unsafe Python dunder methods.

03 // Time Series

Lookahead Defense

Strict mathematical protection against repainting. Multi-timeframe requests explicitly shift to ensure scripts evaluate only closed historical bars.

04 // Contracts

JSON UI Serialization

The runtime exports strongly-typed JSON payloads. NaNs are automatically stripped and datetime indices are normalized to UNIX milliseconds, ready for modern frontend charting layers.

Minimal Host Contracts

Embed the interpreter into your Python backend with fewer than ten lines of code. You control the data; Kafal controls the strategy logic.

  • 1

    Host Data Delegation

    Inject OHLCV data through simple Python callback functions. No database coupling required.

  • 2

    Execution Realism

    Configure slippage, exact commissions, pyramiding limits, and intrabar tick models directly on the interpreter.

  • 3

    Dynamic Form Schemas

    Extract @input declarations into structured schemas to automatically render frontend sliders and selects.

host_app.py
import pandas as pd
from kafal.core.interpreter import KafalInterpreter
from kafal.utils.serializer import KafalSerializer

# 1. Initialize runtime with execution rules
intr = KafalInterpreter(
    initial_equity=100_000.0,
    commission_perc=0.0005,
    execution_mode="realistic"
)

# 2. Run script against primary DataFrame
result = intr.run(user_code, df, mode="strategy")

# 3. Serialize UI contract for frontend
ui_payload = KafalSerializer.serialize_payload(result)
print(ui_payload["strategy"]["stats"])

Accurate State Bookkeeping

Kafal handles the complex portfolio math internally. The runtime manages a strict internal ledger to track equity, open positions, and order fills so your backend application doesn't have to.

Accurate Order Fills

Limit and stop orders are evaluated strictly against the subsequent bar's High/Low array. In `realistic` mode, the system enforces same-bar high/low fill ordering to prevent over-optimistic backtest results.

Internal Position Ledger

The runtime maintains a continuous real-time ledger. Scripts can natively query their own performance via strategy.openprofit and strategy.equity without writing host callbacks.

Risk & Cost Models

Instantiate the interpreter with predefined parameters like commission_perc and slippage. The runtime automatically calculates and deducts transaction costs upon every simulated execution.

Part 2

The End-User Experience

A frictionless, PineScript-style language that gives your users instant access to 150+ technical indicators and advanced order routing.

Familiar Syntax. Solid Architecture.

Kafal provides a PineScript-style developer experience, enhanced with functional operators and institutional order routing.

PineScript Parity

Write logic using standard technical analysis primitives and math functions instantly recognized by quant developers.

fast = ta.sma(close, 10)
slow = ta.ema(close, 20)
long_cond = crossover(fast, slow)

Pipe Operators

Chain operations cleanly using the native pipe operator to keep complex signal transformations readable.

signal => close | rsi(14)
| zscore(50)
| math.abs()

Institutional Order API

Route signals to advanced execution modules including limit orders, stops, and automated OCO brackets.

trade.bracket_long(entry_px,
tp_px,
sl_px,
size=1.0)

The Complete Quant Lifecycle

Write your logic once. Deploy it across research, backtesting, and live charting environments using strict execution modes.

Factor Research

Set mode="research" to bypass trade simulations. Expose mathematical signals and alpha factors directly into Pandas DataFrames for downstream machine learning analysis.

Event-Driven Backtesting

Set mode="strategy" to simulate realistic market fills. Apply customizable slippage, commission structures, and HTF logic to generate accurate equity curves.

Frontend Charting

Set mode="chart" to serialize rich visual primitives. Strip NaNs, normalize timestamps, and export lines and shapes natively into your trading terminal's UI.

Beyond PineScript

While Kafal features a familiar language structure, its runtime is built to be strictly controlled and hosted by you.

Architecture MetricTradingView PineScriptKafal DSL
Ecosystem & HostingClosed platform. Execution is permanently locked into TradingView servers.Embeddable Python runtime. The host application wholly owns the data, UI, and execution routing.
Execution SpeedCalculations are processed via step-by-step historical bar loops.Vectorized by default across C-level Pandas and NumPy arrays for maximum throughput.
Security ModelCloud-hosted proprietary sandbox controlled by a third party.Strict local AST Sandbox. Blocked Python dunders, zero OS capabilities, and zero network access.
Indicator LibraryProprietary closed-source technical analysis functions.Over 150+ native TA-Lib bindings and standard SciPy quant helpers injected dynamically into the evaluation context.