Skip to main content

clearinghouseState

Get comprehensive account state for perpetual trading, including margin summary, open positions, unrealized PnL, and liquidation prices.

Why Hyperliquid? Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB).

When to Use This Endpoint#

The clearinghouseState endpoint is essential for derivatives traders, portfolio managers, and trading platforms who need to:

  • Monitor Account Health — Track account value, margin usage, and withdrawable balance
  • Risk Management — Monitor liquidation prices and position exposure
  • Portfolio Analytics — Calculate unrealized PnL across all positions
  • Trading Bots — Make automated trading decisions based on account state

Request#

Endpoint#

POST https://api-hyperliquid-mainnet-info.n.dwellir.com/info

Headers#

HeaderValueRequired
Content-Typeapplication/jsonYes
X-Api-KeyYour API keyYes

Parameters#

ParameterTypeRequiredDescription
typestringYesMust be "clearinghouseState"
userstringYesUser's Ethereum wallet address
dexstringNoSpecific DEX identifier (optional)

Example Request#

{
"type": "clearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}

Response#

Success Response#

{
"marginSummary": {
"accountValue": "10000.50",
"totalNtlPos": "5000.25",
"totalRawUsd": "10000.00",
"totalMarginUsed": "2000.00",
"withdrawable": "8000.50"
},
"crossMarginSummary": {
"accountValue": "10000.50",
"totalNtlPos": "5000.25",
"totalRawUsd": "10000.00"
},
"assetPositions": [
{
"position": {
"coin": "BTC",
"szi": "0.5",
"leverage": {
"type": "cross",
"value": 5
},
"entryPx": "40000.00",
"positionValue": "20000.00",
"unrealizedPnl": "500.00",
"liquidationPx": "35000.00"
}
}
]
}

Response Fields#

FieldTypeDescription
marginSummaryobjectOverall margin information
crossMarginSummaryobjectCross-margin specific summary
assetPositionsarrayList of open positions with details

Margin Summary Object#

FieldTypeDescription
accountValuestringTotal account value in USD
totalNtlPosstringTotal notional position value
totalRawUsdstringRaw USD balance
totalMarginUsedstringTotal margin currently in use
withdrawablestringAmount available for withdrawal

Cross Margin Summary Object#

FieldTypeDescription
accountValuestringAccount value for cross margin
totalNtlPosstringTotal notional position value
totalRawUsdstringRaw USD balance

Asset Position Object#

FieldTypeDescription
positionobjectPosition details

Position Details#

FieldTypeDescription
coinstringAsset symbol (e.g., "BTC", "ETH")
szistringSigned position size (positive for long, negative for short)
leverageobjectLeverage information with type ("cross" or "isolated") and value
entryPxstringAverage entry price
positionValuestringCurrent position value in USD
unrealizedPnlstringUnrealized profit and loss
liquidationPxstringLiquidation price

Code Examples#

curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/info' \
-H 'X-Api-Key: YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"type": "clearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'

Common Use Cases#

1. Check Account Health#

Monitor account health and margin utilization:

async function checkAccountHealth(userAddress) {
const state = await getClearinghouseState(userAddress);
const margin = state.marginSummary;

const marginUsed = parseFloat(margin.totalMarginUsed);
const accountValue = parseFloat(margin.accountValue);
const utilizationRate = (marginUsed / accountValue) * 100;

return {
healthy: utilizationRate < 80,
utilizationRate: utilizationRate.toFixed(2),
accountValue: accountValue,
marginUsed: marginUsed,
withdrawable: parseFloat(margin.withdrawable)
};
}

// Usage
const health = await checkAccountHealth('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
if (!health.healthy) {
console.warn(`High margin usage: ${health.utilizationRate}%`);
}

2. Monitor Liquidation Risk#

Track liquidation prices for all positions:

async function getLiquidationRisks(userAddress, currentPrices) {
const state = await getClearinghouseState(userAddress);

return state.assetPositions.map(pos => {
const position = pos.position;
const currentPrice = currentPrices[position.coin];
const liquidationPrice = parseFloat(position.liquidationPx);
const isLong = parseFloat(position.szi) > 0;

const distance = isLong
? ((currentPrice - liquidationPrice) / currentPrice) * 100
: ((liquidationPrice - currentPrice) / currentPrice) * 100;

return {
coin: position.coin,
side: isLong ? 'LONG' : 'SHORT',
currentPrice: currentPrice,
liquidationPrice: liquidationPrice,
distancePercent: distance.toFixed(2),
risk: distance < 10 ? 'HIGH' : distance < 25 ? 'MEDIUM' : 'LOW'
};
});
}

3. Calculate Portfolio Metrics#

Compute portfolio-wide metrics:

async function getPortfolioMetrics(userAddress) {
const state = await getClearinghouseState(userAddress);

const totalPnl = state.assetPositions.reduce((sum, pos) => {
return sum + parseFloat(pos.position.unrealizedPnl);
}, 0);

const totalPositionValue = state.assetPositions.reduce((sum, pos) => {
return sum + parseFloat(pos.position.positionValue);
}, 0);

const accountValue = parseFloat(state.marginSummary.accountValue);
const pnlPercent = (totalPnl / accountValue) * 100;

return {
accountValue: accountValue,
totalPnl: totalPnl,
pnlPercent: pnlPercent.toFixed(2),
positionCount: state.assetPositions.length,
totalPositionValue: totalPositionValue,
leverage: (totalPositionValue / accountValue).toFixed(2)
};
}

4. Position Summary Report#

Generate a detailed position summary:

async function getPositionSummary(userAddress) {
const state = await getClearinghouseState(userAddress);

console.log('\n=== Account Summary ===');
console.log(`Account Value: $${state.marginSummary.accountValue}`);
console.log(`Margin Used: $${state.marginSummary.totalMarginUsed}`);
console.log(`Withdrawable: $${state.marginSummary.withdrawable}`);

console.log('\n=== Open Positions ===');
state.assetPositions.forEach(pos => {
const p = pos.position;
const side = parseFloat(p.szi) > 0 ? 'LONG' : 'SHORT';
const size = Math.abs(parseFloat(p.szi));

console.log(`\n${p.coin} ${side}`);
console.log(` Size: ${size}`);
console.log(` Entry Price: $${p.entryPx}`);
console.log(` Position Value: $${p.positionValue}`);
console.log(` Unrealized PnL: $${p.unrealizedPnl}`);
console.log(` Liquidation Price: $${p.liquidationPx}`);
console.log(` Leverage: ${p.leverage.value}x (${p.leverage.type})`);
});
}

Error Handling#

Common Errors#

ErrorCauseSolution
401 UnauthorizedInvalid API keyVerify your API key is correct
400 Bad RequestMissing or invalid user addressEnsure valid Ethereum address format
429 Too Many RequestsRate limit exceededImplement request throttling
500 Internal Server ErrorServer issueRetry with exponential backoff

Error Response Example#

{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}

Robust Error Handling#

async function safeGetClearinghouseState(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getClearinghouseState(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}

Best Practices#

  1. Poll responsibly — Don't poll more frequently than needed (every 5-10 seconds is usually sufficient)
  2. Handle empty positions — Account may have no open positions
  3. Validate addresses — Ensure user addresses are valid Ethereum addresses
  4. Monitor liquidation risk — Set alerts when positions approach liquidation
  5. Cache when appropriate — Cache data briefly to reduce API calls for dashboards

Access real-time Hyperliquid account state with Dwellir's HyperCore Info Endpoint. Get your API key →