# Agara architecture

> Follow an order through trading, live updates, recorded reads and settlement.

Agara matches orders off-chain and settles fills on Base. Use the order ID to track how much can still trade and the fill ID to track each execution through settlement.

The client sends an order through order ingestion to the matching engine. The engine connects to the Raft journal, on-chain pipeline and event stream. The event stream sends live events to the client and records to the persistence layer.

## Trading [#trading]

Trading covers order submission, validation, matching and cancellation. The placement response, open order quantity and individual fills describe different parts of the outcome.

**Example:** GTC limit BUY · 10 shares; 4 fill at the limit or better; 6 remain open, then are cancelled.

### Placement and matching [#placement-and-matching]

A client signs a GTC limit BUY for 10 shares. Step 1 submits it to order ingestion. Step 2 validates the signed request and checks engine admission; an invalid or inadmissible attempt is rejected before matching. Step 3 branches from engine admission into the Raft Replicated Journal, with no outgoing flow from the journal. Step 4 continues directly within the matching engine, matching four shares and leaving six resting in the order book. Separate dashed boundaries identify the matching engine and its order book. Step 5 returns the HTTP placement reply through ingestion, separately from the command path.

### 1. Sign and submit [#1-sign-and-submit]

* **Authenticate and sign.** Use an authorised wallet and the correct signing domain. Agara uses [EIP-712 typed-data signing](https://eips.ethereum.org/EIPS/eip-712) to authorise the order.
* **Keep the request consistent.** Submit the signed instruction with matching API fields. Keep its signed hash, original request and any returned order ID so you can resolve an uncertain response.
* **Preserve the original on retry.** Changing signed fields creates a new order identity. Read the original order's state before signing a replacement.

### 2. Validate the request and check admission [#2-validate-the-request-and-check-admission]

* **Request checks.** Authentication, signature, order fields, signing time and any expiry must be valid. A valid signature alone does not guarantee that the order can trade.
* **Trading checks.** The matching engine checks the current market state, supported price and size, available assets and execution constraints such as post-only or FOK.
* **Handle each result.** A refused request includes a reason to act on. Batch items have individual outcomes; a batch is not an atomic group of dependent trades.
* **Separate time limits.** All order types use a current signing timestamp. GTD additionally has a separate expiry deadline. The request's time checks still apply when retrying.

### 3. Record the trading instruction [#3-record-the-trading-instruction]

* **Support durability.** The Raft Replicated Journal maintains a record of trading instructions to support recovery of trading state.
* **Track the trading result separately.** Recording an instruction does not mean that its entire quantity filled. Use the returned order state and subsequent updates to follow the outcome.
* **Keep settlement distinct.** A trading result does not establish on-chain confirmation. Executed fills continue through the settlement layer.

Background: [Raft and replicated logs](https://raft.github.io/raft.pdf).

### 4. Match and retain the remainder [#4-match-and-retain-the-remainder]

* **Respect the limit.** A BUY executes at its limit price or lower; a SELL executes at its limit or higher. A limit controls the acceptable execution price, not whether a fill is guaranteed.
* **Track partial execution.** In the example, 4 shares fill and the GTC order's remaining 6 rest on the book. Only that open remainder can trade later or be cancelled.
* **Keep individual fills.** One order can produce several executions. Track the overall instruction by order ID and record each execution once by `fill_id`.

| Policy | What happens to unfilled quantity                                            |
| ------ | ---------------------------------------------------------------------------- |
| `GTC`  | Can remain open until filled or cancelled.                                   |
| `GTD`  | Can remain open, subject to its expiry deadline.                             |
| `FAK`  | Available quantity fills immediately; any remainder is cancelled.            |
| `FOK`  | The full quantity must execute immediately, otherwise the order is rejected. |

### 5. Interpret the response [#5-interpret-the-response]

* **Distinguish receipt from an outcome.** Router `202 PENDING` confirms receipt for processing. Order Service `202 UNKNOWN` leaves placement unresolved. Neither confirms that the order is resting.
* **Read the order state.** A successful response can describe an open, partly filled or completed order. Check its remaining quantity before deciding how much can still be cancelled.
* **Expect different arrival orders.** A fill can arrive before the placement reply. Correlate them with the same order and count the fill once; a later response does not undo a confirmed fill.
* **Reconcile uncertainty.** After a timeout or unresolved response, read the original order by ID or signed hash. A refused retry does not undo an earlier accepted order.

See [Responses, events and reads](/best-practices/order-management#responses-events-and-reads) and [Timeouts and uncertain outcomes](/best-practices/order-management#timeouts-and-uncertain-outcomes) for client recovery steps.

### Cancellation [#cancellation]

Cancellation affects the quantity still open when it is processed. Sending a cancel request does not freeze the order.

A cancellation sequence between the client, order ingestion and matching engine. Step 1 requests cancellation of the original order. Step 2 processes it against the current open quantity: six shares are still open, so six are cancelled; the four-share fill is retained. Step 3 returns the cancellation result through ingestion. The order is CANCELLED, with four shares filled, six cancelled and zero open.

* **Cancel the remainder.** All 6 remaining shares are still open in this example, so cancellation closes those 6. The 4-share fill stays valid.
* **Allow for races.** Another fill can occur before cancellation takes effect, leaving less quantity to cancel. If the order has already filled completely, nothing remains open.
* **Confirm uncertain results.** Reconcile or retry `CANCEL_UNKNOWN` for the same order. A cancellation request alone is not confirmation that the order is closed.
* **Size replacements from the final outcome.** Account for fills before placing a replacement. A cancelled order can still have executions awaiting settlement.

#### Cancel-all boundary [#cancel-all-boundary]

* A successful new cancel-all includes orders still resting when it is processed. An order confirmed open beforehand is included if its remainder is still resting at that point.
* A pending placement can become open afterward. Stop new submissions, resolve pending placements and check remaining orders before relying on cancel-all to leave no open orders.

See the [cancellation boundary](/best-practices/order-management#cancellation-boundary) and [cancel and replace](/best-practices/order-management#cancel-and-replace) guidance.

### Terminal order statuses [#terminal-order-statuses]

Use `is_terminal` to determine whether any quantity can still trade. Trading completion and settlement confirmation are separate.

| Status             | What it means                                                                                    |
| ------------------ | ------------------------------------------------------------------------------------------------ |
| `MATCHED`          | The full order executed. Its fills may still be awaiting settlement.                             |
| `PARTIALLY_FILLED` | A completed FAK has `is_terminal: true`. With `is_terminal: false`, a remainder can still trade. |
| `CANCELLED`        | The open remainder was cancelled. Earlier fills remain valid.                                    |
| `EXPIRED`          | The GTD remainder expired. Router can report this as `CANCELLED`.                                |
| `REJECTED`         | The placement was refused. Check its rejection reason.                                           |
| `FAILED`           | Placement could not complete. Check the reported failure.                                        |

## Event stream [#event-stream]

The matching engine produces order and fill updates. The account stream delivers them live, and the same activity becomes available through recorded order and trade reads. These paths can reach the client at different times.

The matching engine produces the order and fill updates that feed the event stream. The stream has two destinations. The client receives the 4-share fill with ID 8421 and a cancellation of the open six. The same activity feeds persistence for later reads. The HTTP placement reply comes independently from ingestion; it may arrive after the live fill.

### Live updates [#live-updates]

* **Correlate the order.** Use its order ID or signed hash to associate updates with the original instruction. Repeated order identifiers can describe different changes to the same order.
* **Count each execution once.** The example produces a 4-share `fill` with `fill_id: "8421"`. Deduplicate fills by that ID, rather than by order ID.
* **Update the open remainder.** `order_accepted` indicates that quantity rested; here, 6 shares remain open. A later `order_cancelled` closes those 6 while preserving the earlier fill.
* **Allow for independent delivery.** A fill may arrive before the HTTP placement reply or appear in history later. Preserve a confirmed fill when a later-arriving response has not yet caught up.

### After a disconnect [#after-a-disconnect]

* **Reconcile missed activity.** Reconnecting restores future messages; the account stream does not replay the gap. On a disconnect or `sequence_reset`, rebuild the affected account state.
* **Combine the stream with reads.** Buffer new updates while refreshing orders, fills and portfolio state through REST. Include balances and positions when checking the effect of missed activity.
* **Retain known executions.** Merge by stable identifiers and wait for reads to reflect fills already observed. Avoid creating a replacement order while the original outcome is unresolved.

See [Stream recovery](/best-practices/order-management#stream-recovery) for the client procedure, and [Reading recorded state](#reading-recorded-state) for the difference between order and trade records.

## Persistence layer [#persistence-layer]

The client reads recorded order and trade data through the API. The database holds the records: an order describes the instruction's state, while its trade history describes what actually executed.

The event stream feeds order and fill activity to the database. The client requests recorded state through the Read API, which reads the database and returns a response to the client. GET /trade/v1/orders/{order_id} shows PARTIALLY_FILLED, 4 matched and 6 open, with is_terminal false; after cancellation it shows CANCELLED, 4 matched and 0 open, with is_terminal true. GET /trade/v1/orders/{order_id}/trades retains the same single 4-share fill, ID 8421, after cancellation.

### Reading recorded state [#reading-recorded-state]

* **Read the order by its identity.** The order lookup reports its current state and quantities. Use `is_terminal` to determine whether any remainder can still trade.
* **Keep matched and open quantities separate.** After the example's fill, 4 shares are matched and 6 are open. After cancellation, the order is `CANCELLED`, 4 remain matched and 0 are open.
* **Read its executions independently.** The order-trades endpoint still returns the same 4-share fill, `8421`. Cancellation changes the order's remainder; it does not remove its earlier executions.

### Reconciling with live activity [#reconciling-with-live-activity]

* **Allow recent reads to catch up.** A live fill can arrive before recorded reads reflect it. Keep the fill and check again rather than treating its temporary absence as a reversal.
* **Match records by stable IDs.** Use the order ID or signed hash for the instruction and `fill_id` for each execution. Seeing the same fill in the stream and in history is one execution.
* **Use the appropriate read.** Order lookup answers what can still trade; order-trades lists its fills. Use portfolio trades when following settlement status and the transaction hash.
* **Complete the refresh.** Follow pagination where supported and handle partial or unavailable results before treating the history refresh as complete.

See [Responses, events and reads](/best-practices/order-management#responses-events-and-reads) for arrival-order handling, and [Reading settlement status](#reading-settlement-status) for trade confirmation.

## Settlement layer [#settlement-layer]

The matching engine passes executed fills into settlement on Base. The client follows confirmation through the trade API, separately from the state of the order's unfilled remainder.

The matching engine produces the 4-share fill 8421. The settlement layer submits a transaction to the Base blockchain and checks the transaction outcome. Confirmation updates the existing portfolio trade to CONFIRMED with its transaction_hash. The client requests that record through GET /trade/v1/portfolio/trades. The order is CANCELLED with four filled and six cancelled; only the executed four enter settlement.

### From execution to confirmation [#from-execution-to-confirmation]

* **Start with the executed quantity.** The 4-share fill exists after off-chain matching. Its trade can show `MATCHED` while settlement is still outstanding.
* **Distinguish the intermediate steps.** Submission and transaction checks are stages in settlement. They are not additional order statuses, and submitting a transaction alone does not confirm the fill.
* **Follow the same execution.** Confirmation updates the existing fill's settlement state. It does not create another trade to count.

### Reading settlement status [#reading-settlement-status]

* **Use portfolio trades.** Find the original `fill_id` in `GET /trade/v1/portfolio/trades`. The confirmed trade shows `CONFIRMED` and its `transaction_hash`. The hash can be unavailable earlier.
* **Keep order and trade states distinct.** The order can already be `CANCELLED` while its 4-share execution awaits confirmation. The 6 cancelled, unfilled shares never enter settlement.
* **Track an outstanding fill instead of replacing it.** A pending confirmation is not evidence that matching failed. Follow the original trade's state; placing another order would be a separate trading instruction.
