141 lines
4.8 KiB
Plaintext
141 lines
4.8 KiB
Plaintext
# PnL & Risk
|
|
|
|
## How it works
|
|
|
|
Drift calculates your account's risk using a **health** metric (0-100) derived from total collateral vs margin requirements. Health 100 = no margin used, health 0 = liquidation eligible.
|
|
|
|
**PnL** (Profit and Loss) comes in two forms: **unrealized** (mark-to-market value of open positions) and **realized** (settled when positions close). Unrealized PnL is calculated by comparing your position's entry price to the current oracle price. For perps, you also have **funding PnL** from periodic funding rate payments between longs and shorts.
|
|
|
|
**Free collateral** is the amount of collateral not currently backing positions, it's what you can withdraw or use to open new positions. Margin requirements increase with position size and vary by market. Leverage is calculated as notional position value divided by total collateral. These metrics update in real-time as prices and positions change.
|
|
|
|
## SDK Usage
|
|
|
|
These helpers are commonly used for risk checks, dashboards, and liquidation logic.
|
|
|
|
### User health
|
|
|
|
Return an overall account health score from 0-100, where lower values mean higher liquidation risk.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getHealth" type="method" owner="User">
|
|
```js
|
|
const user = driftClient.getUser();
|
|
const health = user.getHealth(); // returns number 0-100
|
|
console.log(health); // e.g. 85 means 85% healthy
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Collateral, margin requirement, leverage
|
|
|
|
Get total account collateral value in quote units (typically USD precision).
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getTotalCollateral" type="method" owner="User">
|
|
```js
|
|
import { QUOTE_PRECISION, convertToNumber } from "@drift-labs/sdk";
|
|
|
|
// getTotalCollateral returns BN in QUOTE_PRECISION (1e6)
|
|
// marginCategory defaults to 'Initial'; pass 'Maintenance' for liquidation checks
|
|
const total = driftClient.getUser().getTotalCollateral();
|
|
console.log(convertToNumber(total, QUOTE_PRECISION)); // e.g. 1500.50 (USD)
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
Get the required margin for the account under initial or maintenance rules.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getMarginRequirement" type="method" owner="User">
|
|
```js
|
|
// getMarginRequirement(marginCategory, strict?)
|
|
// marginCategory: 'Initial' (for new positions) or 'Maintenance' (for liquidation)
|
|
const req = driftClient.getUser().getMarginRequirement('Initial');
|
|
console.log(convertToNumber(req, QUOTE_PRECISION)); // USD
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
Get currently available collateral that can be used for new positions or withdrawals.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getFreeCollateral" type="method" owner="User">
|
|
```js
|
|
const free = driftClient.getUser().getFreeCollateral();
|
|
console.log(convertToNumber(free, QUOTE_PRECISION)); // USD available
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
Get current account leverage as a scaled value (convert to human-readable x leverage).
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getLeverage" type="method" owner="User">
|
|
```js
|
|
import { TEN_THOUSAND } from "@drift-labs/sdk";
|
|
|
|
// getLeverage() returns BN scaled by 10000 (e.g. 2x = BN(20000))
|
|
const lev = driftClient.getUser().getLeverage();
|
|
console.log(lev.toNumber() / TEN_THOUSAND.toNumber()); // e.g. 2.5 (2.5x leverage)
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Unrealized PnL
|
|
|
|
Get unrealized PnL across open positions (optionally including funding effects).
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUnrealizedPNL" type="method" owner="User">
|
|
```js
|
|
// Returns BN in QUOTE_PRECISION. Positive = profit, negative = loss.
|
|
// Pass withWeightMarginCategory to apply asset/liability weights.
|
|
const pnl = driftClient.getUser().getUnrealizedPNL(true); // withFunding=true
|
|
console.log(convertToNumber(pnl, QUOTE_PRECISION)); // e.g. -25.50 (USD)
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
Get unrealized funding PnL only, separated from price-movement PnL.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="getUnrealizedFundingPNL" type="method" owner="User">
|
|
```js
|
|
// Funding PnL only (accumulated funding payments)
|
|
const fundingPnl = driftClient.getUser().getUnrealizedFundingPNL();
|
|
console.log(convertToNumber(fundingPnl, QUOTE_PRECISION)); // USD
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Entry price helper
|
|
|
|
Compute the effective entry price for a perp position from its cumulative trade data.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="calculateEntryPrice" type="function">
|
|
```js
|
|
import { calculateEntryPrice, PRICE_PRECISION, convertToNumber } from "@drift-labs/sdk";
|
|
|
|
const position = driftClient.getUser().getPerpPosition(0);
|
|
if (position) {
|
|
const entryPrice = calculateEntryPrice(position); // BN in PRICE_PRECISION
|
|
console.log(convertToNumber(entryPrice, PRICE_PRECISION)); // e.g. 150.25
|
|
}
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|
|
|
|
### Settle perp PnL
|
|
|
|
Realize and settle a user's perp PnL for a specific market into spot balances.
|
|
|
|
<SDKDoc>
|
|
<TypeScript name="settlePNL" type="method" owner="DriftClient">
|
|
```js
|
|
const user = driftClient.getUser();
|
|
await driftClient.settlePNL(user.userAccountPublicKey, user.getUserAccount(), 0);
|
|
```
|
|
</TypeScript>
|
|
</SDKDoc>
|