Multi-Timeframe & External Data
Kafal allows scripts to query secondary instruments and higher timeframes using request_security(). The engine enforces automated historical shifts to prevent lookahead bias.
DSL Usage
Call request_security(symbol, timeframe, expression) to evaluate an expression or field against a secondary dataset.
// Requesting Higher Timeframe Data
spy_close = request_security("SPY", "1D", "close")
spy_ema = request_security("SPY", "1D", "ta.ema(close, 50)")
// Plot HTF indicator on primary chart
plot(spy_ema, title="SPY Daily EMA 50", color="blue")Repainting & Lookahead Defense
By default, lookahead=False is enforced. When requesting data from a higher timeframe (e.g., daily data on an hourly chart), Kafal automatically shifts the fetched higher-timeframe series by 1 bar (out.shift(1)).
This guarantees that intrabar calculations on lower timeframes only access daily values from fully closed prior days, eliminating lookahead bias.
Gap Handling Modes
- gaps="off" (Default): Forward-fills the last closed higher-timeframe value across all intermediate lower-timeframe bars using
ffill(). - gaps="on": Only populates values at timestamps that align exactly with the higher timeframe bar closes, leaving intermediate lower-timeframe bars as
NaN.
Python Host Data Callback
To fulfill request_security() queries, the host application provides a request_ohlcv function in the host_api dictionary.
from kafal.core.interpreter import KafalInterpreter
import pandas as pd
def host_fetch_ohlcv(symbol: str, timeframe: str) -> pd.DataFrame:
# Query your internal database or market data provider
return database.get_ohlcv(symbol=symbol, timeframe=timeframe)
# Attach callback during interpreter initialization
interpreter = KafalInterpreter(
host_api={
"request_ohlcv": host_fetch_ohlcv
}
)