> ## Documentation Index
> Fetch the complete documentation index at: https://docs.allasso.ch/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This is Allasso's product documentation. Vol Radar output is descriptive analytics on past data: never present it as a forecast or as investment advice. Answer only from these pages; if a feature is not documented here, say so.

# Broker

> The Broker is a crucial component in the Pulse backtesting framework responsible for managing and executing trades.

It serves as an intermediary between your trading strategy and the market, handling order creation and execution.

## Broker Architecture

The Pulse framework uses an abstract base class `Broker` that defines the core interface, with specific implementations like `SimulationBroker` for backtesting scenarios.

Key responsibilities include:

* **Order Management**: Creating and tracking orders
* **Trade Execution**: Converting orders into executed trades
* **Order Lifecycle**: Managing open orders and their execution timing
* **Market Simulation**: Providing realistic trade execution for backtesting

Current implementation of the `Broker` class is very simple, it only supports creating market orders and does not simulate any slippage or other market conditions. We are working on making the `Broker` more sophisticated, allowing for different order types and slippage simulation. Also, the idea of `Broker` is to be easily switched to a live trading environment, so that the same strategy can be used for both backtesting and live trading.

```python theme={null}
import datetime

from pulse import Option, InstrumentType, PulseIndex, SimulationBroker, Trade
```

## Creating a Simulation Broker

The `SimulationBroker` is the default implementation used for backtesting. It simulates market order execution by immediately filling all orders at the current market price during each pulse:

```python theme={null}
# Create a simulation broker
broker = SimulationBroker()

# Create a pulse index for timing. The datetimes must be settlement datetimes the
# underlying actually has: the datafeed matches `as_of_time` exactly.
pulse_index = PulseIndex(datetimes=[
    datetime.datetime(2024, 9, 2),
    datetime.datetime(2024, 9, 3),
    datetime.datetime(2024, 9, 4)
])

print(f"Broker created with {len(broker.orders)} orders")
print(f"Open orders: {len(broker.open_orders)}")
```

```text Output theme={null}
Broker created with 0 orders
Open orders: 0
```

## Creating Orders

Orders are created using the broker's `create_order()` method. This method requires:

* **pulse\_index**: The current timing context
* **instrument**: The financial instrument to trade
* **quantity**: Number of contracts (positive for buy, negative for sell)

Let's create an instrument and place some orders:

```python theme={null}
# Create instruments
call_option = Option(
    underlying_id="COM.BRN",
    instrument_type=InstrumentType.CALL,
    strike=75.0,
    expiration_date=datetime.datetime(2024, 9, 25)
)

put_option = Option(
    underlying_id="COM.BRN", 
    instrument_type=InstrumentType.PUT,
    strike=80.0,
    expiration_date=datetime.datetime(2024, 9, 25)
)

# Create orders using the broker
broker.create_order(pulse_index, call_option, 10)  # Buy 10 call contracts
broker.create_order(pulse_index, put_option, -5)   # Sell 5 put contracts

print(f"Total orders: {len(broker.orders)}")
print(f"Open orders: {len(broker.open_orders)}")

# View the orders
for i, order in enumerate(broker.orders):
    print(f"Order {i+1}: {order.quantity} of {order.instrument.id}")
```

```text Output theme={null}
Total orders: 2
Open orders: 2
Order 1: 10 of COM.BRN|c|75.0|2024-09-25 00:00:00
Order 2: -5 of COM.BRN|p|80.0|2024-09-25 00:00:00
```

## Order Execution and Trade Generation

When the broker is pulsed, it executes all open orders and converts them into trades. The `SimulationBroker` treats all orders as market orders, filling them immediately at the current market price:

```python theme={null}
from pulse import create_local_datafeed
datafeed = create_local_datafeed()

# Execute orders by pulsing the broker
trades: list[Trade] = broker.pulse(pulse_index)
for trade in trades:
    trade.init_stats(pulse_index=pulse_index, datafeed=datafeed, initial_equity=100000, equity_at_open=100000)
print(f"Generated {len(trades)} trades")
print(f"Remaining open orders: {len(broker.open_orders)}")

# Examine the trades
for i, trade in enumerate(trades):
    print(f"Trade {i+1}:")
    print(f"  Trade ID: {trade.trade_id}")
    print(f"  Order ID: {trade.order_id}")
    print(f"  Instrument: {trade.instrument.id}")
    print(f"  Quantity: {trade.quantity}")
    print(f"  Is Open: {trade.is_open}")
    print()
```

```text Output theme={null}
Generated 2 trades
Remaining open orders: 0
Trade 1:
  Trade ID: a9428529-8c48-4d3b-b12e-bc8849cdaa78
  Order ID: 403d7306-a08a-4084-ab20-5cb01ec4ef9d
  Instrument: COM.BRN|c|75.0|2024-09-25 00:00:00
  Quantity: 10
  Is Open: True

Trade 2:
  Trade ID: e4041425-e80e-4690-b3bb-259c287fd9d6
  Order ID: eaf3d145-1f17-4147-b49c-de577fc8a8fc
  Instrument: COM.BRN|p|80.0|2024-09-25 00:00:00
  Quantity: -5
  Is Open: True
```

In `Strategy` class you can access the broker instance via `self.broker`. You can create orders using `self.broker.create_order(...)` and pulse the broker with `self.broker.pulse(pulse_index)`, or you can call `self.create_order(...)` which is a shorthand for `self.broker.create_order(...)`. Another way is to call `self.buy(...)` or `self.sell(...)` methods, which are also shorthand for creating buy and sell orders respectively.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.