# Python Reference (/scripting-v2/furge/reference)



## Script structure [#script-structure]

```python
script = {
    "name": "my-signal",
    "version": "2",
    "lookback": 20,
    "params": {"window": {"type": "number", "default": 5}},
}
SOURCE = "btc@candles@hyperliquidf:timeframe=60"


def on_data(ctx, history):
    candle = history.source(SOURCE, 0)
    if candle is not None:
        return {"metrics": {"close": candle["c"]}}
```

`script` and `on_data(ctx, history)` are required. No package import or base class is required. `version` must be `"2"`; `lookback` retains records per source (2 through 5,000).

## Parameters [#parameters]

Define defaults in `script["params"]`, then override them in the editor's **Parameters** field:

```text
window=10
```

Read the resolved value inside a hook:

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

Supported parameter types are `number`, `boolean`, and `string`. Literal defaults are prefilled in the editor. Computed defaults are resolved by the runtime. Changing parameters affects the next run, not an existing deployment.

## Hooks and context [#hooks-and-context]

| API                         | Purpose                                                                                                                                     |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `on_data(ctx, history)`     | Runs after an accepted source event has been added to history.                                                                              |
| `on_execution(ctx)`         | Receives lifecycle events through `ctx.execution`.                                                                                          |
| `on_finish(ctx, history)`   | Final reports on normal completion/stop; not guaranteed after a crash or resource kill. Execution methods are disabled here.                |
| `ctx.source`                | Triggering startup selector or dynamic subscription handle.                                                                                 |
| `ctx.subscribe(request)`    | Add a live market feed during a run.                                                                                                        |
| `ctx.unsubscribe(handle)`   | Release a dynamic market feed.                                                                                                              |
| `ctx.timestamp_ms`          | Triggering event time in Unix milliseconds.                                                                                                 |
| `ctx.state`                 | JSON dictionary checkpointed after successful hooks for recovery of the same live job; at most 1 MiB. New deployments start with new state. |
| `ctx.params`                | Resolved parameters for this run.                                                                                                           |
| `ctx.study`                 | Native studies such as SMA/EMA; they do not place orders.                                                                                   |
| `history.source(SOURCE)`    | Retained records, oldest to newest.                                                                                                         |
| `history.source(SOURCE, 0)` | Newest record or `None`.                                                                                                                    |

See [Data Sources](/scripting-v2/furge/sources) for records and [Execution](/scripting-v2/furge/execution) for trading actions. Multiple sources update independently; guard missing data and do not assume synchronized freshness.

## Editor types [#editor-types]

New starters include annotations for the Python editor. Add them to an existing script to see hook inputs, request keys, and return types.

```python
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from furge_scripting import Context, History


def on_data(ctx: "Context", history: "History"):
    ...
```

The runtime supplies these arguments. The type import is used by the editor.

## Artifacts [#artifacts]

Use `ctx.artifact_path(...)` for run-owned files. Do not write to arbitrary filesystem paths.

```python
import json


def on_finish(ctx, history):
    with open(ctx.artifact_path("summary.json"), "w") as output:
        json.dump({"candles": len(history.source(SOURCE))}, output)
```

Save figures instead of opening windows. Exported files appear under **Artifacts** after the run stops. Image/text previews are available for supported files up to 2 MiB; larger files can be downloaded. HTML output is downloaded, not executed inline.

## Available packages [#available-packages]

The runtime image bundles these packages; no per-user installation is needed:

| Package      | Import                              | Use                                            |
| ------------ | ----------------------------------- | ---------------------------------------------- |
| NumPy        | `import numpy as np`                | Arrays and numerical calculations              |
| pandas       | `import pandas as pd`               | Tables, rolling windows and time series        |
| SciPy        | `import scipy`                      | Statistics, optimization and signal processing |
| statsmodels  | `import statsmodels.api as sm`      | Regression and time-series models              |
| scikit-learn | `import sklearn`                    | Preprocessing and machine learning             |
| Matplotlib   | `import matplotlib.pyplot as plt`   | Save charts as images                          |
| Seaborn      | `import seaborn as sns`             | Statistical charts                             |
| Plotly       | `import plotly.graph_objects as go` | Interactive HTML charts                        |

Available versions follow the installed runtime image. Upgrade the runtime to receive package updates. Additional package installation, arbitrary network calls, and child processes/threads are blocked by the hosted sandbox; use a single worker where a library accepts `n_jobs`.

## Runtime safety [#runtime-safety]

User Python runs separately from execution credentials. Signing stays inside the daemon. The hosted sandbox restricts filesystem access, networking, processes, memory, and hook execution time. It does not make a strategy profitable or eliminate trading risk.

A failed check or exception can stop a run. Read the error and [Logs](/scripting-v2/furge/monitoring) before retrying. Never store secrets in code, parameters, output, or artifacts.
