v1.0.2

Host Engine Integration

Embed the Kafal quantitative engine securely into your Python backend. Execute user-provided scripts against your proprietary market data and return strictly-typed JSON payloads directly to your frontend.

The Integration Lifecycle

Integrating Kafal bypasses network overhead by running locally within your infrastructure. The process operates in three deterministic stages:

  1. Ingestion: Provide historical OHLCV market data as a standard Pandas DataFrame.
  2. Execution: Run the user script inside the AST evaluation sandbox.
  3. Serialization: Coerce Python objects into a strict, UI-compliant JSON schema.

1. Prepare the Data

The engine requires a time-indexed Pandas DataFrame containing standard lowercase columns: open, high, low, close, and volume.

import pandas as pd

# The engine requires a DataFrame with open, high, low, close, volume columns
df = pd.read_csv("market_data.csv", parse_dates=True, index_col=0)

2. Initialize the Interpreter

The KafalInterpreter manages the sandbox and strategy state. Base simulation rules are passed during instantiation.

from kafal.core.interpreter import KafalInterpreter

interpreter = KafalInterpreter(
    initial_equity=100000.0,
    commission_perc=0.0005,  # 0.05% commission
    slippage=0.0,
    pyramiding=1,
    execution_mode="realistic", # Options: "backtest" | "realistic"
    intrabar_model="none"       # Options: "none" | "random_walk"
)

3. Execute the Script

Pass the raw script and your DataFrame into the run method. The execution mode optimizes internal state tracking:

  • chart: Prioritizes visual outputs (plots, fills, shapes) for charting integrations.
  • strategy: Prioritizes trade logs, order queues, and margin tracking.
  • research: Bypasses visuals to extract cross-sectional factor series.
user_script = """
fast = ta.sma(close, 10)
slow = ta.sma(close, 30)

plot(fast) - color="blue" title="Fast SMA"
plot(slow) - color="red" title="Slow SMA"
"""

# Modes: "chart" (visuals), "strategy" (trading stats), "research" (factors)
raw_result = interpreter.run(user_script, df, mode="chart")

4. Serialize for the Frontend

The raw result contains native Pandas Series and NumPy arrays. To prevent encoding errors and handle invalid floats, pass the output through KafalSerializer.

import json
from kafal.utils.serializer import KafalSerializer

# Coerces DataFrames, drops NaNs, and converts timestamps to Unix milliseconds
json_payload = KafalSerializer.serialize_payload(raw_result)
print(json.dumps(json_payload))

Injecting External Data (Host API)

To allow user scripts to query secondary symbols or timeframes via request_security, provide a data-fetching callback via the host_api parameter.

def fetch_external_ohlcv(symbol: str, timeframe: str) -> pd.DataFrame:
    # Query your internal database or external data provider
    return my_database.get_data(symbol, timeframe)

interpreter = KafalInterpreter(
    host_api={
        "request_ohlcv": fetch_external_ohlcv
    }
)