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

# Trading Data Flows

> Sequence diagrams for position open, increase, reduce, margin adjustment, and maturity settlement — showing contract-to-contract interactions step by step

## Position Lifecycle Interactions

Each trading operation involves multiple contracts coordinating through the Protocol registry. These diagrams show the exact contract-to-contract call sequence for every position operation.

<Tabs>
  <Tab title="Open Position">
    A trader deposits collateral, then opens a position. The PositionManager coordinates oracle pricing, risk validation, margin locking, and fee collection in a single transaction.

    ```mermaid theme={null}
    sequenceDiagram
        participant Trader
        participant MA as MarginAccounts
        participant PM as PositionManager
        participant OM as OracleModule
        participant RM as RiskManager
        participant PV as PoolVault

        Trader->>MA: 1. deposit(amount)
        Note over MA: USDC transferred in

        Trader->>PM: 2. openPosition(pairId, side, tenor, notional, margin)
        PM->>OM: 3. getForwardPrice(pairId, tenor)
        OM-->>PM: forward price (entry strike)

        PM->>RM: 4. validateOpen(notional, side)
        RM->>PV: check pool exposure
        PV-->>RM: grossNotional, netExposure
        RM-->>PM: risk caps pass

        PM->>MA: 5. lockMargin(trader, imAmount)
        Note over MA: available → locked

        PM->>MA: 6. collect oracle fee (0.10 USDC)
        Note over MA: sent to oracleFeeReceiver

        PM->>MA: 7. collect trading fee (5 bps)
        Note over MA: treasury 30% + pool 70%

        PM->>PV: 8. updateExposure(notional, side)

        PM-->>Trader: 9. PositionOpened event
    ```

    For PnL and fee formulas, see [PnL Calculation](/protocol/pnl) and [Fee Structure](/protocol/fees).
  </Tab>

  <Tab title="Increase Position">
    Increasing an existing position adds notional at the current forward price, producing a weighted average entry strike. Fees apply only to the additional notional.

    ```mermaid theme={null}
    sequenceDiagram
        participant Trader
        participant PM as PositionManager
        participant OM as OracleModule
        participant RM as RiskManager
        participant MA as MarginAccounts

        Trader->>PM: 1. increasePosition(positionId, addNotional)
        PM->>OM: 2. getForwardPrice(pairId, tenor)
        OM-->>PM: current forward price

        Note over PM: 3. Weighted avg strike<br/>(oldStrike × oldN + newPrice × addN) / totalN

        PM->>RM: 4. validateOpen(addNotional, side)
        RM-->>PM: risk caps pass

        PM->>MA: 5. lockMargin(trader, proportional IM)
        Note over MA: additional margin locked

        PM->>MA: 6. collect trading fee (5 bps on addNotional)
        Note over MA: treasury 30% + pool 70%

        PM-->>Trader: PositionIncreased event
    ```
  </Tab>

  <Tab title="Reduce Position">
    Reducing a position partially closes it at the current forward price. PnL is realized proportionally, and margin is released for the reduced portion.

    ```mermaid theme={null}
    sequenceDiagram
        participant Trader
        participant SE as SettlementEngine
        participant OM as OracleModule
        participant MA as MarginAccounts
        participant PV as PoolVault

        Trader->>SE: 1. reducePosition(positionId, reduceAmount)
        SE->>OM: 2. getForwardPrice(pairId, tenor)
        OM-->>SE: current forward price

        Note over SE: 3. Proportional PnL on reduced portion

        SE->>MA: 4. release proportional margin
        Note over MA: locked → available

        SE->>MA: 5. collect trading fee (5 bps on reduceAmount)
        MA->>PV: pool's 70% fee share
        Note over MA: treasury gets 30%

        Note over SE: 6. Verify remaining >= minPositionNotional

        SE-->>Trader: PositionReduced event
    ```

    Remaining notional must stay above the minimum. See [Position Reduction](/protocol/position-reduction) for details.
  </Tab>

  <Tab title="Margin Adjustment">
    Traders can add or remove margin on open positions. Adding margin reduces liquidation risk; removing margin frees collateral but must leave sufficient coverage.

    ```mermaid theme={null}
    sequenceDiagram
        participant Trader
        participant PM as PositionManager
        participant MA as MarginAccounts

        Note over Trader,MA: ── Add Margin ──
        Trader->>PM: addPositionMargin(positionId, amount)
        Note over PM: Validate: owner, OPEN, not matured<br/>imLocked + amount <= notional
        PM->>MA: addMarginToPosition(trader, amount)
        Note over MA: available → locked
        PM-->>Trader: PositionMarginAdded event

        Note over Trader,MA: ── Remove Margin ──
        Trader->>PM: removePositionMargin(positionId, amount)
        Note over PM: Validate: owner, OPEN, not liquidatable<br/>remaining >= minIM, equity >= MM
        PM->>MA: removeMarginFromPosition(trader, amount)
        Note over MA: locked → available
        PM-->>Trader: PositionMarginRemoved event
    ```
  </Tab>

  <Tab title="Settlement">
    At maturity, anyone can settle a position. The SettlementEngine reads the fixing price recorded from Pyth, computes final PnL, collects fees, and applies the result to both the trader and the pool.

    ```mermaid theme={null}
    sequenceDiagram
        participant Caller as Anyone
        participant SE as SettlementEngine
        participant PM as PositionManager
        participant OM as OracleModule
        participant MA as MarginAccounts
        participant PV as PoolVault

        Note over Caller,OM: Pre-step: recordFixingPriceFromPyth(pairId, tenor, pythProof)

        Caller->>SE: 1. settlePosition(positionId)
        SE->>PM: 2. getPosition(positionId)
        PM-->>SE: position data

        Note over SE: 3. Verify matured & not liquidated

        SE->>OM: 4. getFixingPrice(pairId, fixingTimestamp)
        OM-->>SE: fixing price

        Note over SE: 5. PnL = notional × (fixing − entry) / entry<br/>(sign inverted for SHORT)

        SE->>MA: 6. collect trading fee (5 bps)
        MA->>PV: pool's 70% fee share

        SE->>MA: 7. settlePosition(trader, pnl)
        Note over MA: release locked margin, apply PnL

        SE->>PV: 8. applyPnl(pnl)
        Note over PV: pool absorbs inverse PnL

        SE->>PM: 9. closePosition(positionId, MATURED)
        SE->>OM: clearForwardRound(fixingTimestamp)
    ```

    Settlement is permissionless — the [Keeper](/deploy/keeper-automation) automates it, but anyone can call `settlePosition()` directly.
  </Tab>
</Tabs>

## Next Steps

<Columns cols={3}>
  <Card title="System Flows" icon="gears" href="/protocol/system-flows">
    Oracle publishing, keeper automation, fee distribution, and LP deposits.
  </Card>

  <Card title="Position Lifecycle" icon="arrows-spin" href="/protocol/position-lifecycle">
    State machine and status transitions for positions.
  </Card>

  <Card title="Fee Structure" icon="money-bill" href="/protocol/fees">
    Trading fees, oracle fees, and liquidation penalties.
  </Card>
</Columns>
