Market LabDocs
Scripting V2 - PythonPlain Python Files

Scripts

Define a Python V2 manifest and implement its runtime hooks.

A Python V2 script is a normal .py module. It needs a script dictionary and on_data(ctx, history).

script = {
    "name": "sma-crossover",
    "version": "2",
    "description": "Trade a moving-average crossover",
    "lookback": 100,
    "params": {
        "fast": {"type": "number", "default": 5},
        "slow": {"type": "number", "default": 20},
    },
}


def on_data(ctx, history):
    pass

No Market Lab import or base class is required.

Manifest

FieldRequiredMeaning
nameYesScript name shown in jobs and reports.
versionYesMust be "2".
descriptionNoHuman-readable metadata.
lookbackNoRecords retained per exact selector, from 2 to 5,000.
paramsNoRuntime parameter definitions.

V2 does not use script.sources, --source, or TOML [sources]. Calls to history.source(...) declare the job's sources.

Parameters

"params": {
    "window": {"type": "number", "required": True},
    "armed": {"type": "boolean", "default": False},
    "label": {"type": "string", "default": "baseline"},
}
--param window=20 --param armed=true --param label=experiment-a

Read resolved values from ctx.params:

window = int(ctx.params["window"])

on_data(ctx, history)

The required data hook runs once for every accepted source event. The new record is inserted into history before the hook runs.

CANDLES = "btc@candles@binancef:timeframe=60"
SOURCE = "btc@candles@binancef"


def on_data(ctx, history):
    if ctx.source != SOURCE:
        return

    candle = history.source(CANDLES, 0)

on_execution(ctx)

The optional execution hook receives order, fill, position, and account lifecycle updates through ctx.execution:

def on_execution(ctx):
    print(ctx.execution)

It may call ctx.trade, ctx.order, or ctx.cancel.

on_finish(ctx, history)

The optional finish hook runs after the final backtest event or when a live session stops normally. Use it for reports and artifacts:

def on_finish(ctx, history):
    points = ctx.pnl()
    path = ctx.artifact_path("pnl.json")

Execution methods are disabled during on_finish.

Process Lifecycle

One persistent Python process handles a session. Module globals survive between hook calls, and hooks run synchronously in event order.

Market Lab may import the module during CLI validation, daemon validation, and runtime startup. Keep import-time work limited to imports, constants, the manifest, and safe initialization.

Hooks may return None or a dictionary containing metrics, meta, or both. Returned values do not place orders.

See API Reference for the complete contract.

On this page