# Instrument Expiry

## Overview

The engine supports both immediate and scheduled expiry of instruments, automatically closing out positions and canceling active orders when the expiry time is reached. This mechanism supports both normal settlement of term futures, and early settlement of perpetual swaps and term futures.

## What Happens at Expiry

At expiry:

- Every order on the instrument receives rejection reason `InstrumentExpired`. Any positions on the instrument are closed at the expiry price.
- The instrument state changes from `Live` to `Expired`. The expiry time is stored and returned on future queries.

## Scheduled expiry

If an `expiryTime` is specified when expiring an instrument, the engine will wait until that time to perform the expiry.

- The instrument's lifecycle state remains `Live` until the expiry time is reached
- All queries and subscriptions return the expiry time that was set, so clients know when the instrument will expire
- The engine will perform expiry once the expiry time is reached

If an instrument already has a pending scheduled expiry and expiry is triggered again:
- If `expiryTime` is specified, the expiry time is updated to the new time
- If `expiryTime` is not specified, the instrument is expired immediately

## Expiry price

If no price is specified on an instrument expiry request, the engine will use the current price of the instrument (either the mark price, or the last traded price, depending on the instrument's `MarkMethod`). The exchange is checked for mark price cap before expiry occurs:

| expiryPrice | expiryTime | Mark price cap on any instrument | Impact                                                  |
|-------------|------------|----------------------------------|---------------------------------------------------------|
| Specified | Not set    | (any)                            | Instrument is expired now                               |
| Not specified | Not set    | Not applied                      | Instrument is expired now                               |
| Not specified | Not set    | Applied                          | Rejected (violates mark price cap)                      |
| Not specified | Set        | Not applied                      | Instrument is expired at the expiry time                |
| Not specified | Set        | Applied                          | Instrument expiry is delayed until mark price is uncapped |

## Validation

- Attempting to expire an expired instrument is rejected
- Attempting to schedule expiry in the past is rejected (expiry does not happen immediately)
- Attempting to schedule expiry with a fixed price is rejected
