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

# Schema Reference

> Complete GraphQL schema for 15 indexed entities — Position, Account, PoolState, OracleRound, FixingPrice, ModeTransition, ProtocolState, FeeEvent, PositionReduction, VaultEvent, PoolTransaction, DailyStats, TxFeeAccumulator, TenorState, BucketState — with field types, indexes, and ID patterns

## Position

Tracks the full lifecycle of a trading position from open through close. Mutable -- updated on increase, reduction, margin changes, and settlement.

```graphql theme={null}
type Position @entity {
  id: ID!                          # positionId (uint256)
  account: Account!                # Owner (indexed for filtering)
  pairId: Bytes!                   # Currency pair identifier
  side: Int!                       # 0 = LONG, 1 = SHORT
  tenorSeconds: BigInt!            # Tenor duration in seconds (dynamic registry)
  notional: BigInt!                # Position size (USDC 6 decimals)
  entryStrike: BigInt!             # Forward price at open (18 decimals, signed)
  fixingTimestamp: BigInt!         # Maturity date
  imLocked: BigInt!                # Locked initial margin
  initialMargin: BigInt!           # Margin originally posted at open
  marginBeforeClose: BigInt!       # Snapshot of locked margin at close (for analytics)
  mmThreshold: BigInt!             # Maintenance margin threshold
  snapshotImBps: Int!              # IM factor at open
  snapshotMmBps: Int!              # MM factor at open
  openTradingFee: BigInt!          # Trading fee paid at open
  openOracleFee: BigInt!           # Oracle fee paid at open
  closeTradingFee: BigInt          # Trading fee paid at close (null while open)
  closeOracleFee: BigInt           # Oracle fee paid at close (null while open)
  closeLiquidationPenalty: BigInt  # Liquidation penalty (null unless liquidated)
  status: String!                  # "OPEN", "CLOSED_MATURITY", "CLOSED_EARLY", "LIQUIDATED", "REDUCED" (indexed)
  closeReason: String              # null while open
  closedPrice: BigInt              # Settlement price (null while open)
  realizedPnl: BigInt              # Capped PnL (null while open, signed)
  marketPnl: BigInt                # Uncapped PnL (null while open, signed)
  openTxHash: Bytes!
  closeTxHash: Bytes
  openBlock: BigInt!
  closeBlock: BigInt
  openTimestamp: BigInt!           # Indexed for time-range queries
  closeTimestamp: BigInt
  createdAt: BigInt!
  updatedAt: BigInt!
}
```

**Indexed fields:** `account`, `status`, `openTimestamp`

<Info>
  There is no `Tenor` enum in the contracts — tenors are stored as `uint32` seconds in a dynamic registry on `Config`. The subgraph mirrors this with `tenorSeconds: BigInt!` (e.g., `86400` for 1D, `2592000` for 1M). Use the string `status` field rather than enum ordinals when filtering positions.
</Info>

## Account

Tracks a trader's margin account state and LP position. Mutable -- updated on every collateral or position event.

```graphql theme={null}
type Account @entity {
  id: ID!                    # Ethereum address
  collateralBalance: BigInt! # Total deposited collateral
  imLockedTotal: BigInt!     # Total locked margin across positions
  availableBalance: BigInt!  # Free collateral (collateral - locked)
  positionCount: Int!        # Total positions ever opened
  openPositionCount: Int!    # Currently open positions
  positions: [Position!]!    # Derived from Position.account
  totalRealizedPnl: BigInt!  # Cumulative realized PnL (signed)
  lpShares: BigInt!          # Pool shares held
  lpAssetsDeposited: BigInt! # Total USDC deposited as LP
  createdAt: BigInt!
  updatedAt: BigInt!
}
```

The `positions` field is a reverse lookup derived from `Position.account` -- it does not store position IDs directly.

## PoolState

Singleton entity tracking the liquidity pool's aggregate state. ID is always `"pool"`.

```graphql theme={null}
type PoolState @entity {
  id: ID!                              # "pool"
  totalAssets: BigInt!                 # Total USDC in vault
  totalShares: BigInt!                 # Total pool shares outstanding
  netExposure: BigInt!                 # Net directional exposure (signed)
  grossNotional: BigInt!               # Total gross notional
  longNotional: BigInt!                # Aggregate long notional
  shortNotional: BigInt!               # Aggregate short notional
  sharePrice: BigDecimal!              # Current share price (division result)
  totalPnlApplied: BigInt!             # Cumulative PnL applied (signed)
  totalFeesCollected: BigInt!          # Total fees across all types
  tradingFeesCollected: BigInt!        # Trading fees (every close)
  liquidationPenaltiesCollected: BigInt! # Penalty portion of liquidations only
  earlyTerminationFeesCollected: BigInt! # Reserved bucket; currently 0
  maturityFeesCollected: BigInt!         # Reserved bucket; currently 0
  oracleFeesCollected: BigInt!         # Oracle fees collected from positions
  totalBadDebt: BigInt!                # Cumulative bad debt absorbed by the pool
  depositCount: Int!                   # Total LP deposits
  withdrawCount: Int!                  # Total LP withdrawals
  updatedAt: BigInt!
}
```

## OracleRound

Tracks forward price rounds published by the publisher. Append-only — to find the latest round for a fixing timestamp, query `oracleRounds(orderBy: publishTime, orderDirection: desc, first: 200)` and dedupe by `fixingTimestamp` client-side.

```graphql theme={null}
type OracleRound @entity(immutable: true) {
  id: ID!                    # "fixingTimestamp-roundId"
  fixingTimestamp: BigInt!   # Indexed
  forwardPrice: BigInt!      # Forward price (18 decimals, signed)
  roundId: BigInt!
  publishTime: BigInt!       # Indexed
  createdAt: BigInt!
}
```

**Indexed fields:** `fixingTimestamp`, `publishTime`

## FixingPrice

Immutable record of a settlement fixing price recorded from Pyth. One per (pairId, fixingTimestamp) combination.

```graphql theme={null}
type FixingPrice @entity(immutable: true) {
  id: ID!                    # "pairId-fixingTimestamp"
  pairId: Bytes!
  fixingTimestamp: BigInt!
  price: BigInt!             # Fixing price (18 decimals)
  txHash: Bytes!
  block: BigInt!
  timestamp: BigInt!
}
```

## ModeTransition

Immutable audit trail of every operating mode change.

```graphql theme={null}
type ModeTransition @entity(immutable: true) {
  id: ID!                    # "txHash-logIndex"
  fromMode: Int!             # 0 = NORMAL, 1 = DEGRADED, 2 = REDUCE_ONLY, 3 = PAUSED
  toMode: Int!               # Same ordinals as fromMode
  reasonCode: Bytes!         # keccak256 of reason string
  actor: Bytes!              # Address that triggered the transition
  timestamp: BigInt!
  block: BigInt!
  txHash: Bytes!
}
```

## ProtocolState

Singleton tracking current protocol mode and transition history. ID is always `"protocol"`.

```graphql theme={null}
type ProtocolState @entity {
  id: ID!                          # "protocol"
  currentMode: Int!                # Current operating mode ordinal
  lastModeTransition: ModeTransition  # Reference to most recent transition
  modeTransitionCount: Int!
  oracleInvalidatedCount: Int!
  updatedAt: BigInt!
}
```

## FeeEvent

Immutable record of fee collection events from SettlementEngine.

```graphql theme={null}
type FeeEvent @entity(immutable: true) {
  id: ID!                    # "txHash-logIndex"
  feeType: Int!              # 0 = LIQUIDATION_PENALTY, 1 = EARLY_TERMINATION, 2 = MATURITY, 3 = TRADING
  amount: BigInt!            # Fee amount (USDC 6 decimals)
  positionId: BigInt!
  txHash: Bytes!
  block: BigInt!
  timestamp: BigInt!
}
```

## PositionReduction

Immutable record of each partial position reduction.

```graphql theme={null}
type PositionReduction @entity(immutable: true) {
  id: ID!                    # "txHash-logIndex"
  position: Position!        # Reference to the reduced position
  account: Bytes!
  reductionNotional: BigInt! # Notional amount reduced
  remainingNotional: BigInt! # Notional remaining after reduction
  settledPnl: BigInt!        # PnL settled on the reduced portion (signed)
  fee: BigInt!               # Fee charged on reduction
  txHash: Bytes!
  block: BigInt!
  timestamp: BigInt!
}
```

## VaultEvent

Immutable record of LP deposit and withdrawal events.

```graphql theme={null}
type VaultEvent @entity(immutable: true) {
  id: ID!                    # "txHash-logIndex"
  type: String!              # "DEPOSIT" or "WITHDRAW"
  sender: Bytes!
  owner: Bytes!
  assets: BigInt!            # USDC amount (6 decimals)
  shares: BigInt!            # Pool shares minted or burned
  txHash: Bytes!
  block: BigInt!
  timestamp: BigInt!         # Indexed for time-range queries
}
```

**Indexed fields:** `timestamp`

## PoolTransaction

Unified activity feed combining all position-related events into a single timeline. Immutable.

```graphql theme={null}
type PoolTransaction @entity(immutable: true) {
  id: ID!                    # "txHash-logIndex"
  type: String!              # "OPEN", "INCREASED", "MATURED", "EARLY_CLOSE", "LIQUIDATED", "REDUCED"
  positionId: BigInt!
  account: Bytes!
  notional: BigInt!          # Context-dependent: open notional, additional notional, reduction notional
  pnl: BigInt                # Realized PnL (null for opens/increases, signed)
  tradingFee: BigInt         # Trading/liquidation/termination fee (null if none)
  oracleFee: BigInt          # Oracle fee (null if none)
  txHash: Bytes!
  block: BigInt!
  timestamp: BigInt!         # Indexed for time-range queries
}
```

**Indexed fields:** `timestamp`

## DailyStats

Daily aggregate analytics. Mutable -- updated throughout each day.

```graphql theme={null}
type DailyStats @entity {
  id: ID!                    # Unix day number (timestamp / 86400)
  date: String!              # Human-readable date
  positionsOpened: Int!
  positionsClosed: Int!
  totalVolume: BigInt!       # Total notional volume
  totalPnl: BigInt!          # Aggregate PnL (signed)
  totalFees: BigInt!         # Aggregate fees collected
  forwardRounds: Int!        # Forward price updates
  totalAssets: BigInt!       # Pool TVL snapshot (end-of-day-so-far)
  sharePrice: BigDecimal!    # Pool share price snapshot
}
```

## TxFeeAccumulator

Per-transaction accumulator that lets the subgraph attribute trading and oracle fees collected through multiple events in the same tx to a single PoolTransaction row. Mutable.

```graphql theme={null}
type TxFeeAccumulator @entity {
  id: ID!                    # txHash
  tradingFee: BigInt!        # Sum of trading fees collected in this tx
  oracleFee: BigInt!         # Sum of oracle fees collected in this tx
}
```

## TenorState

Per-tenor open-interest snapshot. Mutable — updated on every position open / increase / close that lands in this tenor.

```graphql theme={null}
type TenorState @entity {
  id: ID!                    # tenorSeconds (as string)
  tenorSeconds: BigInt!
  openInterest: BigInt!      # Aggregate open notional in this tenor
  longNotional: BigInt!
  shortNotional: BigInt!
  positionCount: Int!        # Currently open positions in this tenor
}
```

## BucketState

Per-(pair, maturity) cohort tracking the pool's bucket-level exposure. The pool's risk caps are enforced against `Σ |bucketNetExposure|` across active buckets, so this entity exposes the same shape the contract uses internally. Mutable.

```graphql theme={null}
type BucketState @entity {
  id: ID!                    # "pairId-fixingTimestamp"
  pairId: Bytes!             # Currency pair (indexed)
  tenorSeconds: BigInt!      # Tenor that produced this maturity
  fixingTimestamp: BigInt!   # Maturity timestamp (indexed)
  longNotional: BigInt!
  shortNotional: BigInt!
  netExposure: BigInt!       # longNotional - shortNotional (signed)
  positionCount: Int!        # Open positions in this bucket
  updatedAt: BigInt!
}
```

**Indexed fields:** `pairId`, `fixingTimestamp`

## Field Type Conventions

| GraphQL Type | Usage                                            |
| ------------ | ------------------------------------------------ |
| `BigInt`     | Money amounts, timestamps, block numbers, prices |
| `BigDecimal` | Division results only (share price)              |
| `Int`        | Counters, enum ordinals, basis points            |
| `Bytes`      | Addresses, tx hashes, pair IDs                   |
| `String`     | Status labels, event type labels, dates          |
| `Boolean`    | Flags                                            |

## Related Pages

<Columns cols={3}>
  <Card title="Query Examples" icon="magnifying-glass" href="/build/subgraph-queries">
    Common query patterns for each entity.
  </Card>

  <Card title="Pagination" icon="arrow-right" href="/build/subgraph-pagination">
    Cursor-based pagination and filtering.
  </Card>

  <Card title="Types Reference" icon="code" href="/build/types-reference">
    Solidity enum ordinals and struct definitions.
  </Card>
</Columns>
