> ## 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.

# Orders and Trades

> Orders and Trades are fundamental components in the Pulse backtesting framework that represent trading intentions and their executions respectively.

## Orders

An `Order` represents a trading instruction that specifies the intent to buy or sell a financial instrument. Orders contain essential information including:

* **Instrument**: The specific financial instrument to trade (options, futures, etc.)
* **Quantity**: The number of contracts (positive for buy orders, negative for sell orders)
* **Timing**: When the order was created and when it should be executed
* **Execution Details**: Information about how and when the order was filled

Orders serve as the bridge between strategy logic and actual trade execution in the backtesting environment.

Currently, Pulse only supports market orders, which are executed immediately at the close price. To prevent forward-looking bias, the first day PnL of a `Trade` is set to zero.

Let's start by importing the necessary components and exploring how to create and work with orders in Pulse.

```python theme={null}
from pulse import Order, Trade, Option, InstrumentType
import datetime
```

```python theme={null}
instrument = Option(
    underlying_id="COM.BRN",
    instrument_type=InstrumentType.CALL,
    strike=76.0,
    expiration_date=datetime.datetime(2024, 9, 25, 0, 0)
)
instrument.id
```

```text Output theme={null}
'COM.BRN|c|76.0|2024-09-25 00:00:00'
```

### Creating an Order

Now let's create an order to buy 10 contracts of our call option. Note that quantity is positive for buy orders and negative for sell orders:

```python theme={null}
mock_order = Order(
    open_datetime=datetime.datetime(2024, 9, 2, 0, 0),
    instrument=instrument,
    quantity=10, # Negative quantity for sell orders
)
mock_order
```

```text Output theme={null}
<pulse.core.order.Order at 0x108633770>
```

You won't need to create an order manually, as Its the job of the `Broker`. Broker has few helper methods to create orders, which will be covered in the next section.

### Order Properties

Each order automatically gets a unique identifier and contains references to all the trading details:

Instruments are value objects with no display helpers of their own: use `instrument.id` (`"U|c|strike|expiry"` for an option, `"U|f|expiry"` for a future, `"U|s"` for spot) when you want to read one.

```python theme={null}
mock_order.id
```

```text Output theme={null}
UUID('3b652701-b8ba-4c2f-9e3c-8e55ff94488c')
```

```python theme={null}
mock_order.instrument.id
```

```text Output theme={null}
'COM.BRN|c|76.0|2024-09-25 00:00:00'
```

```python theme={null}
mock_order.open_datetime
```

```text Output theme={null}
datetime.datetime(2024, 9, 2, 0, 0)
```

```python theme={null}
mock_order.execution_datetime
```

## Trade

When an order is executed, it results in a `Trade`. A `Trade` represents the actual execution of an order and contains detailed information about the trade, including:

* **Trade ID**: A unique identifier for the trade
* **Order Reference**: The order ID that triggered the trade
* **Instrument**: The financial instrument being traded
* **Quantity**: The number of contracts traded
* **Open Price**: The price at which the trade was opened (initialized when stats are set up)
* **PnL Tracking**: Cumulative and absolute profit/loss calculations
* **Historical Data**: Complete history of price movements, PnL, and quantity changes

Note that when creating a Trade, you need to provide the order ID, instrument, and quantity. The trade statistics (prices, PnL, etc.) are initialized separately using the `init_stats()` method with a pulse index and datafeed:

```python theme={null}
from pulse import create_local_datafeed, PulseIndex

# Real settlement datetimes for COM.BRN: `datafeed.instrument.last` matches `as_of_time` exactly.
pulse_index = PulseIndex(
    [
        datetime.datetime(2024, 9, 2, 0, 0),
        datetime.datetime(2024, 9, 3, 0, 0),
        datetime.datetime(2024, 9, 4, 0, 0),
    ]
)
datafeed = create_local_datafeed()
```

```python theme={null}
mock_trade = Trade(
    order_id=mock_order.id,
    instrument=instrument,
    quantity=10
)
mock_trade.init_stats(pulse_index=pulse_index, datafeed=datafeed, initial_equity=100000, equity_at_open=100000)
mock_trade
```

```text Output theme={null}
<Trade entry: 2024-09-02 00:00:00; exit: None; Instrument: COM.BRN|c|76.0|2024-09-25 00:00:00; Quantity: 10; PnL: 0.0; Cummulative PnL: 0.0>
```

```python theme={null}
# Explore trade properties
print(f"Trade ID: {mock_trade.trade_id}")
print(f"Order ID: {mock_trade.order_id}")
print(f"Instrument: {mock_trade.instrument.id}")
print(f"Quantity: {mock_trade.quantity}")
print(f"Is Open: {mock_trade.is_open}")
print(f"Tags: {mock_trade.tags}")
```

```text Output theme={null}
Trade ID: 479c88b2-83ad-4a49-81ea-69e39bacfdb3
Order ID: 3b652701-b8ba-4c2f-9e3c-8e55ff94488c
Instrument: COM.BRN|c|76.0|2024-09-25 00:00:00
Quantity: 10
Is Open: True
Tags: None
```

It is also possible to add Tags to the trade, which will be very useful later on when the Pulse fronted app is finished. Tags can be used to categorize trades, making it easier to filter and analyze them later.

Note: Tags should always be a string, otherwise we wont be able to serialize them properly.

```python theme={null}
mock_trade.add_tag("example_tag")
mock_trade.tags
```

```text Output theme={null}
['example_tag']
```

You can also access all of the historical data related to the trade.
For exmple, you can get the historical PnL of the trade:

```python theme={null}
mock_trade.pct_pnl_history
```

```text Output theme={null}
[0.0]
```

```python theme={null}
mock_trade.abs_pnl_history
```

```text Output theme={null}
[0.0]
```

As well as the historical price of the instrument:

```python theme={null}
mock_trade.price_history
```

```text Output theme={null}
[2.972760218804858]
```


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