Markets, Oracles, and Positions
How it works
Drift has two types of markets: perp markets (perpetual futures with funding rates) and spot markets (token deposits/borrows that serve as collateral). Each market has an onchain account storing configuration like oracle source, fees, funding rates, AMM parameters, and current open interest.
Market Indexes
Markets are identified by a numeric index starting from 0. For example:
- Perp market 0 is typically SOL-PERP
- Spot market 0 is typically USDC
- Perp market 1 might be BTC-PERP, and so on
Where to find market indexes:
- State account: Query
driftClient.getStateAccount()which contains arrays of all perp and spot market configurations - SDK methods: Use
driftClient.getPerpMarketAccounts()ordriftClient.getSpotMarketAccounts()to get all markets and inspect their indexes - Market account directly: Each market account has a
marketIndexfield you can read - Symbol lookup: Most bots maintain their own mapping from symbol (e.g., “SOL-PERP”) to market index, or query all markets and build the mapping at startup
Each market integrates with an oracle (usually Pyth or Switchboard) that provides real-time price data. The SDK lets you read oracle prices, check if they’re valid/stale, and use them for quoting or risk calculations. Prices are stored in fixed-point precision (1e6 for PRICE_PRECISION).
Perp markets track funding rates, open interest, and AMM liquidity pools. Spot markets track total deposits, borrows, and utilization rates. When you trade, you’re interacting with these market accounts, opening positions on perp markets or borrowing/depositing in spot markets.
SDK Usage
These are the most common read-path helpers you’ll use to power bots, dashboards, and risk logic.
Market Accounts
const marketIndex = 0;
const spotMarket = driftClient.getSpotMarketAccount(marketIndex);
console.log(spotMarket?.marketIndex);Method DriftClient.getSpotMarketAccountReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number |
const marketIndex = 0;
const perpMarket = driftClient.getPerpMarketAccount(marketIndex);
console.log(perpMarket?.marketIndex);Method DriftClient.getPerpMarketAccountReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number |
const spotMarkets = driftClient.getSpotMarketAccounts();
console.log(spotMarkets.length);Method DriftClient.getSpotMarketAccountsReference ↗const perpMarkets = driftClient.getPerpMarketAccounts();
console.log(perpMarkets.length);Method DriftClient.getPerpMarketAccountsReference ↗Oracle Price
const marketIndex = 0;
const oracle = driftClient.getOracleDataForPerpMarket(marketIndex);
console.log(oracle.price.toString());Method DriftClient.getOracleDataForPerpMarketReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number |
const marketIndex = 0;
const oracle = driftClient.getOracleDataForSpotMarket(marketIndex);
console.log(oracle.price.toString());Method DriftClient.getOracleDataForSpotMarketReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number |
const marketIndex = 0;
const oracle = driftClient.getMMOracleDataForPerpMarket(marketIndex);
console.log(oracle.price.toString());Method DriftClient.getMMOracleDataForPerpMarketReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number |
Positions and Balances
const spotPosition = driftClient.getSpotPosition(0);
console.log(spotPosition);Method DriftClient.getSpotPositionReference ↗| Name | Type | Default |
|---|---|---|
marketIndex | number | |
subAccountId | number |
const perpPosition = driftClient.getPerpPosition(0);
console.log(perpPosition);Method DriftClient.getPerpPositionReference ↗getPerpPosition.Protocol State
const state = driftClient.getStateAccount();
console.log(state);Method DriftClient.getStateAccountReference ↗Working With the DLOB
The Decentralized Limit Order Book (DLOB) aggregates resting limit orders from all users. If you’re building a market maker, orderbook UI, or matching bot, you’ll want to build a local DLOB by subscribing to orders.
Key Classes
| Class | Purpose | When to Use |
|---|---|---|
OrderSubscriber | Subscribes to all user orders in real-time via WebSocket or polling | Always needed , this is the raw data source for the DLOB |
DLOBSubscriber | Builds and maintains an aggregated orderbook from the order stream | When you need a continuously-updated L2/L3 orderbook view |
SlotSubscriber | Tracks the current Solana slot | Needed for timing-sensitive operations like JIT auctions and order expiry |
DLOB | Core data structure with bid/ask sides and query methods | Used internally by DLOBSubscriber; access via dlobSubscriber.getDLOB() |
UserMap | Efficiently tracks and caches multiple user accounts | Useful for bulk operations across many users (e.g., liquidation bots) |
View OrderSubscriber import
import { OrderSubscriber } from "@drift-labs/sdk";Class OrderSubscriberReference ↗View DLOBSubscriber import
import { DLOBSubscriber } from "@drift-labs/sdk";Class DLOBSubscriberReference ↗View SlotSubscriber import
import { SlotSubscriber } from "@drift-labs/sdk";Class SlotSubscriberReference ↗View DLOB import
import { DLOB } from "@drift-labs/sdk";Class DLOBReference ↗View UserMap import
import { UserMap } from "@drift-labs/sdk";Class UserMapReference ↗Setting Up a Local DLOB
import { SlotSubscriber, OrderSubscriber, DLOBSubscriber } from "@drift-labs/sdk";
const slotSubscriber = new SlotSubscriber(connection);
await slotSubscriber.subscribe();
const orderSubscriber = new OrderSubscriber({
driftClient,
subscriptionConfig: { type: "websocket" },
fastDecode: true,
decodeData: true,
});
await orderSubscriber.subscribe();
const dlobSubscriber = new DLOBSubscriber({
driftClient,
dlobSource: orderSubscriber,
slotSource: slotSubscriber,
updateFrequency: 1000,
});
await dlobSubscriber.subscribe();Getting L2 Orderbook Data
Once the DLOB is subscribed, you can query the aggregated L2 orderbook (price levels with cumulative size):
import { MarketType, PRICE_PRECISION, BASE_PRECISION, convertToNumber } from "@drift-labs/sdk";
const dlob = dlobSubscriber.getDLOB();
const marketIndex = 0; // SOL-PERP
// For perp markets, use getMMOracleDataForPerpMarket (returns MMOraclePriceData)
const oraclePriceData = driftClient.getMMOracleDataForPerpMarket(marketIndex);
const slot = slotSubscriber.getSlot();
const l2 = dlob.getL2({
marketIndex,
marketType: MarketType.PERP,
oraclePriceData,
slot,
depth: 10, // number of price levels per side
});
// l2.bids and l2.asks are arrays of { price: BN, size: BN }
console.log("Top bid:", convertToNumber(l2.bids[0].price, PRICE_PRECISION),
"size:", convertToNumber(l2.bids[0].size, BASE_PRECISION));
console.log("Top ask:", convertToNumber(l2.asks[0].price, PRICE_PRECISION),
"size:", convertToNumber(l2.asks[0].size, BASE_PRECISION));Getting Best Bid/Ask
For quick access to the best bid and ask prices without fetching the full orderbook:
import { MarketType, PRICE_PRECISION, convertToNumber } from "@drift-labs/sdk";
const dlob = dlobSubscriber.getDLOB();
const marketIndex = 0;
const oraclePriceData = driftClient.getMMOracleDataForPerpMarket(marketIndex);
const slot = slotSubscriber.getSlot();
// Returns BN | undefined (undefined if no orders on that side)
const bestBid = dlob.getBestBid(marketIndex, slot, MarketType.PERP, oraclePriceData);
const bestAsk = dlob.getBestAsk(marketIndex, slot, MarketType.PERP, oraclePriceData);
if (bestBid && bestAsk) {
console.log("Best bid:", convertToNumber(bestBid, PRICE_PRECISION));
console.log("Best ask:", convertToNumber(bestAsk, PRICE_PRECISION));
console.log("Spread:", convertToNumber(bestAsk.sub(bestBid), PRICE_PRECISION));
}