Metadata-Version: 2.3
Name: trading-engine-interface
Version: 0.56.25
Summary: Strategy contract for the Martian Mobile trading engine: StrategyProtocol, models, enums and the maker-fill kernel
License: MIT
Author: Martian Mobile
Author-email: help@martianmobile.com
Requires-Python: >=3.12,<4.0
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Dist: httpx (>=0.25,<1)
Requires-Dist: pydantic (>=2.7,<3)
Project-URL: Backtest runner, https://github.com/martianmobile/backtest2live
Project-URL: Homepage, https://martianmobile.com
Description-Content-Type: text/markdown

# trading-engine-interface

The strategy contract of the Martian Mobile trading engine. A strategy written against this package is written against the contract the engine itself runs: same `StrategyProtocol`, same input and output models, same venue and symbol enums.

What is in it:

| Module | What it is |
|---|---|
| `trading_engine_interface.runtime` | `StrategyProtocol` (the type the engine checks every strategy against), `register_strategy`, the strategy registry |
| `trading_engine_interface.trading_engine.models` | `StrategyInput` (order books, klines, public trades, positions, open orders, balances), `StrategyOutput` (orders to create, cancel, replace), configs, positions, fills |
| `trading_engine_interface.domain` | The maker-fill kernel (trade-through, OPTIMISTIC / CONSERVATIVE band), fill simulator, position math |
| `trading_engine_interface.common` | Enums (`VenueName`, `Symbol`, `Asset`, `TimeInterval`), errors, base model |

The fill kernel is mechanism only. Calibrated fill curves are not part of this package.

## Install

```bash
pip install trading-engine-interface
```

Python 3.12 or later.

## Quickstart

A strategy is any class that structurally satisfies `StrategyProtocol`: a `VERSION`, a `fees` attribute, and `decide`, `close_position` and `flush_output`. Register it with `@register_strategy(config=...)` so the engine can find the class and its config.

The smallest complete one is installed with the package, as `trading_engine_interface.examples.touch_bid_strategy`. It rests one limit buy at the best bid on every venue its config allows:

```python
class TouchBidConfig(BaseStrategyConfig):
    class_type: str = "TouchBidStrategy"
    position: PositionParams = PositionParams()
    quantity: Decimal = Decimal("0.001")


@register_strategy(config=TouchBidConfig)
class TouchBidStrategy:
    VERSION: int = 1

    def decide(self, input_data: StrategyInput, predictions: Optional[StrategyPredictions] = None) -> StrategyOutput:
        if input_data.open_orders:
            return self.flush_output(skip_reason=SkipReason.OPEN_ORDERS)
        for symbol, venues in self.config.symbol_to_venues.items():
            for venue in venues:
                book = input_data.market_data.order_books.get(symbol, {}).get(venue)
                bid = book.best_bid_price if book else None
                if bid is not None:
                    self._output.create_orders.append(
                        CreateOrderRequest(venue=venue, symbol=symbol, order_type=OrderType.LIMIT,
                                           side=Side.BUY, quantity=self.config.quantity, price=bid)
                    )
        return self.flush_output(skip_reason=None if self._output.create_orders else SkipReason.NO_DATA)
    ...
```

Run it once against a hand-built order book:

```bash
python -m trading_engine_interface.examples.touch_bid_strategy
```

Type-check it the way the engine does. `mypy --strict` fails if the class drifts from `StrategyProtocol`:

```bash
mypy --strict -m trading_engine_interface.examples.touch_bid_strategy
```

## Backtest it

A backtest runner builds your config itself, from the venues, symbols and risk limits you pass on the command line. Two things in the config class make that possible, and the example has both:

- `class_type` defaults to the strategy's class name. That is how a runner finds the config that belongs to a strategy.
- `position` has a default. `BaseStrategyConfig` requires it, and a runner does not supply one.

The runner replays public market data through the same `decide` the engine calls, on simulated time, and fills orders with the kernel in `trading_engine_interface.domain`. The runner is not part of this package. It is coming as `bt2live run` in [backtest2live](https://github.com/martianmobile/backtest2live); until that release, this package gives you the contract and the example, not a backtest command.

## Rules a strategy must follow

- A strategy is constructed once with its config. Each `decide` call receives everything it may use: market data, its position, its open orders and its balances.
- No network calls and no files. A strategy that needs data it is not given cannot run on a hosted engine.
- Keep no state of your own between calls. Decide from the `StrategyInput` you are given.
- `decide` is synchronous. Read time through `trading_engine_interface.now()`, never the system clock: the backtest replays on simulated time by patching it. Everything else a decision needs arrives in `StrategyInput` and `StrategyPredictions`.
- Set `StrategyOutput.skip_reason` on every path that returns no orders. A quiet strategy without a reason reads as uninstrumented, not as "found nothing".
- Bump `VERSION` when the decision logic changes.

## Versioning

The version number is the version of the contract the engine runs. Before 1.0 the contract can change between releases, so pin the exact version you build against.

## Licence

MIT. The licence text is installed with the package.

