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

# Pricing and Oracles

> Resolve Pyth spot feeds, verify 20-second freshness, read stored Historical Volatility from Market Data, and estimate premiums and collateral.

Trading instructions read live spot prices from Pyth and baseline Historical Volatility from Market Data (`MarketDataAccount`). SOS-SDK also includes a bit-exact Black-Scholes mirror and collateral estimators for UI previews.

## Pyth Spot Feed and Freshness

Trading builders take `priceUpdateAccount`, which must be the shard-0 Pyth price feed account for the underlying asset's feed ID.

Resolve the feed ID from `MarketDataAccount`, derive the shard-0 feed address, and check freshness before submitting a trade:

```ts theme={"dark"}
import {
  deriveMarketDataPda,
  evaluatePythPriceUpdate,
  fetchPythPriceUpdateAccountData,
  pythPriceFeedAddress,
  pythPriceToNumber,
  resolvePythFeedIdFromMarketData,
} from "@epicentral/sos-sdk";
import { rpc, UNDERLYING_MINT } from "./config";

const [marketData] = await deriveMarketDataPda(UNDERLYING_MINT);
const feedIdHex = await resolvePythFeedIdFromMarketData(rpc, marketData);
const priceUpdateAccount = await pythPriceFeedAddress(feedIdHex);

const data = await fetchPythPriceUpdateAccountData({
  rpc,
  priceUpdateAccount,
});

const freshness = evaluatePythPriceUpdate({
  data,
  feedIdHex,
  maxAgeSeconds: 15,
});

if (!freshness.usable || !freshness.update) {
  throw new Error(`Pyth price not usable: ${freshness.reason}`);
}

const spotUsd = pythPriceToNumber(freshness.update);
```

> [!WARNING]
>
> The onchain program rejects spot prices older than 20 seconds (`StaleOraclePrice`, `6016`). Pass `maxAgeSeconds` strictly below `20` (for example `15`) to `evaluatePythPriceUpdate` so the price stays fresh while your transaction is in flight.

## Historical Volatility

Baseline Historical Volatility is stored directly on `MarketDataAccount.historicalVolatilityPpm` in parts per million (`1_000_000` equals `100%`). An offchain volatility worker computes 90-day realized volatility and writes it onchain through `update_market_data`. Pricing instructions do not read an external volatility oracle account.

Read the stored baseline volatility and risk-free rate from `MarketDataAccount` for display pricing or opening margin estimates:

```ts theme={"dark"}
import {
  deriveMarketDataPda,
  fetchMarketDataAccount,
  ppmToFraction,
} from "@epicentral/sos-sdk";
import { rpc, UNDERLYING_MINT } from "./config";

const [marketDataAddress] = await deriveMarketDataPda(UNDERLYING_MINT);
const marketData = await fetchMarketDataAccount(rpc, marketDataAddress);

if (!marketData) {
  throw new Error("MarketDataAccount not found.");
}

const baselineVolPpm = marketData.historicalVolatilityPpm;
const baselineVolFraction = ppmToFraction(baselineVolPpm); // e.g. 0.65 for 65%
const riskFreeRatePpm = marketData.riskFreeRatePpm;
```

> [!WARNING]
>
> The onchain program enforces a 6-hour freshness limit (`21,600` seconds) on `MarketDataAccount.lastUpdated`. Pricing instructions fail with `StaleMarketData` (`6011`) if stored Historical Volatility is older than 6 hours, or `VolatilityQuoteUnavailable` (`6019`) if `historicalVolatilityPpm` is outside `[0, 4_000_000]`.

> [!NOTE]
>
> All trading and series-initialization builders populate the unused legacy `volatility_quote_account` instruction ABI slot internally.

## Black-Scholes Display Pricing

`priceOption` is a fixed-point Black-Scholes mirror of the onchain model. Its `premiumNanoUsd` and `thetaNanoUsd` match the program bit for bit, and it also returns client-side Greeks (`deltaNano`, `gammaNano`, `vegaNanoUsd`, `rhoNanoUsd`).

```ts theme={"dark"}
import {
  fractionToPpm,
  nanoUsdToUsd,
  priceOption,
  UNDERLYING_UNITS_PER_CONTRACT,
  usdToMicroUsd,
} from "@epicentral/sos-sdk";

const out = priceOption({
  spotMicroUsd: usdToMicroUsd(150),
  strikeMicroUsd: usdToMicroUsd(155),
  secondsToExpiry: 7n * 86_400n,
  ratePpm: fractionToPpm(0.05),
  volPpm: fractionToPpm(0.65),
  kind: "call",
});

const perUnitUsd = nanoUsdToUsd(out.premiumNanoUsd);
const perContractUsd = perUnitUsd * Number(UNDERLYING_UNITS_PER_CONTRACT);
```

> [!NOTE]
>
> `priceOption` prices **one unit** of the underlying. One listed contract covers `UNDERLYING_UNITS_PER_CONTRACT` (`100`) units. Use the high-level buy and close builders for executable premiums that include pool size adjustments and slippage caps.

## Estimating Writer Collateral

Use `calculateRequiredCollateral` to estimate Writer collateral in Collateral Mint base units before minting a Short:

```ts theme={"dark"}
import {
  calculateRequiredCollateral,
  contractsToBaseUnits,
} from "@epicentral/sos-sdk";

const collateralBaseUnits = BigInt(
  Math.ceil(
    calculateRequiredCollateral(
      contractsToBaseUnits(1),
      150, // strike price in USD
      1,   // positive conversionPrice (unused in cash mode)
      6,   // Collateral Mint decimals (e.g. 6 for USDC)
      "cash"
    )
  )
);
```

> [!WARNING]
>
> `calculateRequiredCollateral` defaults to `"physical"` when the fifth argument is omitted. Every Option Series on this program is cash-settled, so always pass `"cash"` and the Collateral Mint's decimals.

## Estimating Opening Margin

Every minted Short leg must clear the program's conservative post-fill opening margin check (`OpeningMarginNotMet`, `6171`). Use `computeMinimumOpeningOwnCollateralBaseUnits` to compute the exact minimum own collateral in Collateral Mint base units that satisfies both the opening margin check and the OMLP vault leverage floor:

```ts theme={"dark"}
import {
  computeMinimumOpeningOwnCollateralBaseUnits,
  contractsToBaseUnits,
  fractionToPpm,
  usdToMicroUsd,
} from "@epicentral/sos-sdk";

const margin = computeMinimumOpeningOwnCollateralBaseUnits({
  kind: "call",
  strikeMicroUsd: usdToMicroUsd(150),
  expirationDate: 1_767_225_600n,
  now: BigInt(Math.floor(Date.now() / 1000)),
  spotMicroUsd: usdToMicroUsd(150),
  riskFreeRatePpm: fractionToPpm(0.05),
  baselineVolPpm: fractionToPpm(0.65),
  quantity: contractsToBaseUnits(1),
  settlementDecimals: 6,
  vaultMaxLeverageMultiplier: 1_000n, // 10x vault
});

const ownCollateralBaseUnits = margin.minOwnCollateral;
const borrowedBaseUnits = margin.fullCollateral - ownCollateralBaseUnits;
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.