> For the complete documentation index, see [llms.txt](https://docs.callput.app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.callput.app/ai-agents/trading-loop-and-recovery.md).

# Trading loop and recovery

This page defines the canonical operating loop for a Callput trading agent.

## Canonical loop

1. discover markets
2. apply policy gates
3. generate a quote or payload
4. validate allowance and funding
5. submit the transaction
6. capture the request key
7. poll for status
8. handle executed or cancelled outcomes
9. route to close or settlement when appropriate

The exact request-key and status model is documented in [Request Lifecycle Reference](/developers/request-lifecycle-reference.md).

## Policy gates

A production agent should enforce:

* allowed chain
* allowed underlyings
* allowed strategies
* minimum time to expiry
* maximum exposure
* stale-data checks

## Request-key capture

Preferred capture order:

1. the `bytes32` return value from `createOpenPosition`, `createOpenPositionNAT`, or `createClosePosition`
2. the `GenerateRequestKey(account, key, isOpen)` event in the receipt

Persist at least:

* network
* account
* request type
* request key
* transaction hash
* intended `optionTokenId` or display mapping
* creation time
* expiry

The transaction hash alone is not enough.

## Status handling

### `Pending`

The request exists but is not yet final.

### `Executed`

The request completed successfully. Reconcile the final state with the request getters and the resulting token balances.

### `Cancelled`

The request completed without execution. The agent should re-read current market data before attempting any retry.

## Close vs settlement routing

### Before expiry

Use the close-request path.

### After expiry

Use settlement.

## Required guardrails

* no trading inside the deadline buffer
* no blind retry after cancellation
* settlement only after expiry
* no reliance on `ViewAggregator` as the sole tradable market source
