bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 27쪽 중 17쪽
"type": "outcomeMetaUpdates" }`
2. Data format: `WsOutcomeMetaUpdates` 
24. `fastAssetCtxs` 
1. { "method": "subscribe", "subscription": { "type": "fastAssetCtxs" } }
2. Data format: base64 encoded and compressed `WsFastAssetCtx` 
3. To read data, apply in order:\
1\. base64-decode to bytes\
2\. decompress: a raw DEFLATE stream (RFC 1951) — there is no zlib (RFC 1950) or gzip (RFC 1952) wrapper. Python `zlib.decompress(b, wbits=-15)`, browsers `new DecompressionStream("deflate-raw")`, Node\
`fflate.inflateSync` \
3\. UTF-8 decode and parse as JSON\
4\. Example to test your implementation\
payload: `"q1ZyCnFWsqpWyk0syg6oULJSsjQ3NTDQM1Wq1VFyDfFAkTI2MzXQMwJLVVRWWfmFuTiiyBuamOoZKdXWAgA="`\
decoded: `{ "BTC": { "markPx": "97500.5" }, "ETH": { "markPx": "3650.25" }, "xyz:NVDA": { markPx": "145.2" }}`
4. The first message is a snapshot, subsequent messages contain only coins that have updated. Fields that have no updates are omitted.
### Data formats
The server will respond to successful subscriptions with a message containing the `channel` property set to `"subscriptionResponse"`, along with the `data` field providing the original subscription. The server will then start sending messages with the `channel` property set to the corresponding subscription type e.g. `"allMids"` and the `data` field providing the subscribed data.
The `data` field format depends on the subscription type:
* `AllMids`: All mid prices.
* Format: `AllMids { mids: Record<string, string> }`
* `Notification`: A notification message.
* Format: `Notification { notification: string }`
* `WebData2`: Aggregate information about a user, used primarily for the frontend.
* Format: `WebData2`
* `WsTrade[]`: An array of trade updates.
* Format: `WsTrade[]`
* `WsBook`: Order book snapshot updates.
* Format: `WsBook { coin: string; levels: [Array<WsLevel>, Array<WsLevel>]; time: number; }`
* `WsOrder`: User order updates.
* Format: `WsOrder[]`
* `WsUserEvent`: User events that are not order updates
* Format: `WsUserEvent { "fills": [WsFill] | "funding": WsUserFunding | "liquidation": WsLiquidation | "nonUserCancel": [WsNonUserCancel] }`
* `WsUserFills` : Fills snapshot followed by streaming fills
* `WsUserFundings` : Funding payments snapshot followed by funding payments on the hour
* `WsUserNonFundingLedgerUpdates`: Ledger updates not including funding payments: withdrawals, deposits, transfers, and liquidations
* `WsBbo` : Bbo updates that are sent only if the bbo changes on a block
* `WsSpotState` : Spot state update.
* `WsAllDexsClearinghouseState` : Clearinghouse states across all dexs for specific user
* `WsAllDexsAssetCtxs` : Asset contexts across all dexs
* `WsOutcomeMetaUpdates` : Changes to the outcome meta
For the streaming user endpoints such as `WsUserFills`,`WsUserFundings` the first message has `isSnapshot: true` and the following streaming updates have `isSnapshot: false`. 
### Data type definitions
Here are the definitions of the data types used in the WebSocket API:
```typescript
interface WsTrade {
coin: string;
side: string;
px: string;
sz: string;
hash: string;
time: number;
// tid is 50-bit hash of (buyer_oid, seller_oid).
// For a globally unique trade id, use (block_time, coin, tid)
tid: number;
users: [string, string] // [buyer, seller]
}
// Snapshot feed, pushed on each block that is at least 0.5 since last push
interface WsBook {
coin: string;
levels: [Array<WsLevel>, Array<WsLevel>];
time: number;
}
interface WsBbo {
coin: string;
time: number;
bbo: [WsLevel | null, WsLevel | null];
}
interface WsLevel {
px: string; // price
sz: string; // size
n: number; // number of orders
}
interface Notification {
notification: string;
}
interface AllMids {
mids: Record<string, string>;
}
interface Candle {
t: number; // open millis
T: number; // close millis
s: string; // coin
i: string; // interval
o: number; // open price
c: number; // close price
h: number; // high price
l: number; // low price
v: number; // volume (base unit)
n: number; // number of trades
}
type WsUserEvent = {"fills": WsFill[]} | {"funding": WsUserFunding} | {"liquidation": WsLiquidation} | {"nonUserCancel" :WsNonUserCancel[]};
interface WsUserFills {
isSnapshot?: boolean;
user: string;
fills: Array<WsFill>;
}
interface WsFill {
coin: string;
px: string; // price
sz: string; // size
side: string;
time: number;
startPosition: string;
dir: string; // used for frontend display
closedPnl: string;
hash: string; // L1 transaction hash
oid: number; // order id
crossed: boolean; // whether order crossed the spread (was taker)
fee: string; // negative means rebate
tid: number; // unique trade id
liquidation?: FillLiquidation;
feeToken: string; // the token the fee was paid in
builderFee?: string; // amount paid to builder, also included in fee
}
interface FillLiquidation {
liquidatedUser?: string;
markPx: number;
method: "market" | "backstop";
}
interface WsUserFunding {
time: number;
coin: string;
usdc: string;
szi: string;
fundingRate: string;
}
interface WsLiquidation {
lid: number;
liquidator: string;
liquidated_user: string;
liquidated_ntl_pos: string;
liquidated_account_value: string;
}
interface WsNonUserCancel {
coin: String;
oid: number;
}
interface WsOrder {
order: WsBasicOrder;
status: string; // See https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid for a list of possible values
statusTimestamp: number;
}
interface WsBasicOrder {
coin: string;
side: string;
limitPx: string;
sz: string;
oid: number;
timestamp: number;
origSz: string;
cloid: string | undefined;
}
interface WsActiveAssetCtx {
coin: string;
ctx: PerpsAssetCtx;
}
interface WsActiveSpotAssetCtx {
coin: string;
ctx: SpotAssetCtx;
}
type SharedAssetCtx = {
dayNtlVlm: number;
prevDayPx: number;
markPx: number;
midPx?: number;
};
type PerpsAssetCtx = SharedAssetCtx & {
funding: number;
openInterest: number;
oraclePx: number;
};
type SpotAssetCtx = SharedAssetCtx & {
circulatingSupply: number;
};
interface WsActiveAssetData {
user: string;
coin: string;
leverage: Leverage;
maxTradeSzs: [number, number];
availableToTrade: [number, number];
}
interface WsTwapSliceFill {
fill: WsFill;
twapId: number;
}
interface WsUserTwapSliceFills {
isSnapshot?: boolean;
user: string;
twapSliceFills: Array<WsTwapSliceFill>;
}
interface TwapState {
coin: string;
user: string;
side: string;
sz: number;
executedSz: number;
executedNtl: number;
minutes: number;
reduceOnly: boolean;
randomize: boolean;
timestamp: number;
}
type TwapStatus = "activated" | "terminated" | "finished" | "error";
interface WsTwapHistory {
state: TwapState;
status: {
status: TwapStatus;
description: string;
};
time: number;
}
interface WsUserTwapHistory {
isSnapshot?: boolean;
user: string;
history: Array<WsTwapHistory>;
}
// Additional undocumented fields in WebData3 will be removed on a future update
interface WebData3 {
userState: {
agentAddress: string | null;
agentValidUntil: number | null;
serverTime: number;
cumLedger: number;
isVault: boolean;
user: string;
optOutOfSpotDusting?: boolean;
dexAbstractionEnabled?: boolean;
};
perpDexStates: Array<PerpDexState>;
}
interface PerpDexState {
totalVaultEquity: number;
perpsAtOpenInterestCap?: Array<string>;
leadingVaults?: Array<LeadingVault>;
}
interface LeadingVault {
address: string;
name: string;
}
interface ClearinghouseState {
dex: string;
user: string;
clearinghouseState: InnerClearinghouseState;
}
interface InnerClearinghouseState {
assetPositions: Array<AssetPosition>;
marginSummary: MarginSummary;
crossMarginSummary: MarginSummary;
crossMaintenanceMarginUsed: number;
withdrawable: number;
}
interface MarginSummary {
accountValue: number;
totalNtlPos: number;
totalRawUsd: number;
totalMarginUsed: number;
}
interface AssetPosition { type: "oneWay"; position: Position }
interface OpenOrders {
dex: string;
user: string;
orders: Array<Order>;
}
interface TwapStates {
dex: string;
user: string;
states: Array<[number, TwapState]>;
}
interface WsSpotState {
user: string;
spotState: SpotState;
}
interface SpotState {
balances: Array<UserBalance>;
}
interface UserBalance {
coin: string;
token: number;
hold: string;
total: string;
entryNtl: string;
}
interface WsAllDexsClearinghouseState {
user: string;
clearinghouseStates: Array<[string, InnerClearinghouseState]>;
}
interface WsAllDexsAssetCtxs {
ctxs: Array<[string, Array<PerpsAssetCtx>]>;
}
type WsOutcomeMetaUpdates = [WsOutcomeMetaUpdate];
type WsOutcomeMetaUpdate =
| { outcomeCreated: OutcomeSpec }
| { outcomeSettled: number }
| { questionUpdated: QuestionSpec }
| { questionSettled: number };
type OutcomeSpec = {
outcome: number;
name: string;
description: string;
sideSpecs: [OutcomeSideSpec, OutcomeSideSpec];
};
type OutcomeSideSpec = {
name: string;
};
type QuestionSpec = {
question: number;
name: string;
description: string;
fallbackOutcome: number;
namedOutcomes: number[];
settledNamedOutcomes: number[];
};
type FFastAssetCtx = {
markPx?: number;
midPx?: number | null;
};
type WsFastAssetCtxs = Record<string, FFastAssetCtx>;
```
<details>
<summary>WsUserNonFundingLedgerUpdates</summary>
```typescript
interface WsUserNonFundingLedgerUpdate {
time: number;
hash: string;
delta: WsLedgerUpdate;
}
type WsLedgerUpdate =
| WsDeposit
| WsWithdraw
| WsInternalTransfer
| WsSubAccountTransfer
| WsLedgerLiquidation
| WsVaultDelta
| WsVaultWithdrawal
| WsVaultLeaderCommission
| WsSpotTransfer
| WsAccountClassTransfer
| WsSpotGenesis
| WsRewardsClaim;
interface WsDeposit {
type: "deposit";
usdc: number;
}
interface WsWithdraw {
type: "withdraw";
usdc: number;
nonce: number;
fee: number;
}
interface WsInternalTransfer {
type: "internalTransfer";
usdc: number;
user: string;
destination: string;
fee: number;
}
interface WsSubAccountTransfer {
type: "subAccountTransfer";
usdc: number;
user: string;
destination: string;
}
interface WsLedgerLiquidation {
type: "liquidation";
// NOTE: for isolated positions this is the isolated account value
accountValue: number;
leverageType: "Cross" | "Isolated";
liquidatedPositions: Array<LiquidatedPosition>;
}
interface LiquidatedPosition {
coin: string;
szi: number;
}
interface WsVaultDelta {
type: "vaultCreate" | "vaultDeposit" | "vaultDistribution";
vault: string;
usdc: number;
}
interface WsVaultWithdrawal {
type: "vaultWithdraw";
vault: string;
user: string;
requestedUsd: number;
commission: number;
closingCost: number;
basis: number;
netWithdrawnUsd: number;
}
interface WsVaultLeaderCommission {
type: "vaultLeaderCommission";
user: string;
usdc: number;
}
interface WsSpotTransfer = {
type: "spotTransfer";
token: string;
amount: number;
usdcValue: number;
user: string;
destination: string;
fee: number;
}
interface WsAccountClassTransfer = {
type: "accountClassTransfer";
usdc: number;
toPerp: boolean;
}
interface WsSpotGenesis = {
type: "spotGenesis";
token: string;
amount: number;
}
interface WsRewardsClaim = {
type: "rewardsClaim";
amount: number;
}
```
</details>
Please note that the above data types are in TypeScript format, and their usage corresponds to the respective subscription types.
### Examples
Here are a few examples of subscribing to different feeds using the subscription messages:
1. Subscribe to all mid prices:
```json
{ "method": "subscribe", "subscription": { "type": "allMids" } }
```
2. Subscribe to notifications for a specific user:
```json
{ "method": "subscribe", "subscription": { "type": "notification", "user": "<address>" } }
```
3. Subscribe to web data for a specific user:
```json
{ "method": "subscribe", "subscription": { "type": "webData", "user": "<address>" } }
```
4. Subscribe to candle updates for a specific coin and interval:
```json
{ "method": "subscribe", "subscription": { "type": "candle", "coin": "<coin_symbol>", "interval": "<candle_interval>" } }
```
5. Subscribe to order book updates for a specific coin:
```json
{ "method": "subscribe", "subscription": { "type": "l2Book", "coin": "<coin_symbol>" } }
```
6. Subscribe to trades for a specific coin:
```json
{ "method": "subscribe", "subscription": { "type": "trades", "coin": "<coin_symbol>" } }
```
### Unsubscribing from WebSocket feeds
To unsubscribe from a specific data feed on the Hyperliquid WebSocket API, you need to send an unsubscribe message with the following format:
```json
{
"method": "unsubscribe",
"subscription": { ... }
}
```
The `subscription` object should match the original subscription message that was sent when subscribing to the feed. This allows the server to identify the specific feed you want to unsubscribe from. By sending this unsubscribe message, you inform the server to stop sending further updates for the specified feed.
Please note that unsubscribing from a specific feed does not affect other subscriptions you may have active at that time. To unsubscribe from multiple feeds, you can send multiple unsubscribe messages, each with the appropriate subscription details.
# Post requests
This page describes posting requests using the WebSocket API.
### Request format
The WebSocket API supports posting requests that you can normally post through the HTTP API. These requests are either info requests or signed actions. For examples of info request payloads, please refer to the Info endpoint section. For examples of signed action payloads, please refer to the Exchange endpoint section.
To send such a payload for either type via the WebSocket API, you must wrap it as such:
```json
{
"method": "post",
"id": <number>,
"request": {
"type": "info" | "action",
"payload": { ... }
}
}
```
Note: The `method` and `id` fields are mandatory. It is recommended that you use a unique `id` for every post request you send in order to track outstanding requests through the channel.
Note: `explorer` requests are not supported via WebSocket.
### Response format
The server will respond to post requests with either a success or an error. For errors, a `String` is returned mirroring the HTTP status code and description that would have been returned if the request were sent through HTTP.
```json
{
"channel": "post",
"data": {
"id": <number>,
"response": {
"type": "info" | "action" | "error",
"payload": { ... }
}
}
}
```
### Examples
Here are a few examples of subscribing to different feeds using the subscription messages:
Sending an L2Book info request:
```json
{
"method": "post",
"id": 123,
"request": {
"type": "info",
"payload": {
"type": "l2Book",
"coin": "ETH",
"nSigFigs": 5,
"mantissa": null
}
}
}
```
Sample response:
```json
{
"channel": "post",
"data": {
"id": <number>,
"response": {
"type": "info",
"payload": {
"type": "l2Book",
"data": {
"coin": "ETH",
"time": <number>,
"levels": [
[{"px":"3007.1","sz":"2.7954","n":1}],
[{"px":"3040.1","sz":"3.9499","n":1}]
]
}
}
}
}
}
```
Sending an order signed action request:
```json
{
"method": "post",
"id": 256,
"request": {
"type": "action",
"payload": {
"action": {
"type": "order",
"orders": [{"a": 4, "b": true, "p": "1100", "s": "0.2", "r": false, "t": {"limit": {"tif": "Gtc"}}}],
"grouping": "na"
},
"nonce": 1713825891591,
"signature": {
"r": "...",
"s": "...",
"v": "..."
},
"vaultAddress": "0x12...3"
}
}
}
```
Sample response:
```json
{
"channel": "post",
"data": {
"id": 256,
"response": {
"type":"action",
"payload": {
"status": "ok",
"response": {
"type": "order",
"data": {
"statuses": [
{
"resting": {
"oid": 88383,
}
}
]
}
}
}
}
}
}
```
# Timeouts and heartbeats
This page describes the measures to keep WebSocket connections alive.
The server will close any connection if it hasn't sent a message to it in the last 60 seconds. If you are subscribing to a channel that doesn't receive messages every 60 seconds, you can send heartbeat messages to keep your connection alive. The format for these messages are:
```json
{ "method": "ping" }
```
The server will respond with:
```json
{ "channel": "pong" }
```
# Error responses
Order and cancel errors are usually returned as a vector with same length as the batched request.
Below is a list of possible batched error responses:
| Error source | Error type | Error string |
| ------------ | --------------------------------- | ---------------------------------------------------------------------------------- |
| Order | Tick | Price must be divisible by tick size. |
| Order | MinTradeNtl | Order must have minimum value of $10. |
| Order | MinTradeSpotNtl | Order must have minimum value of 10 {quote\_token}. |
| Order | PerpMargin | Insufficient margin to place order. |
| Order | ReduceOnly | Reduce only order would increase position. |
| Order | BadAloPx | Post only order would have immediately matched, bbo was {bbo}. |
| Order | IocCancel | Order could not immediately match against any resting orders. |
| Order | BadTriggerPx | Invalid TP/SL price. |
| Order | MarketOrderNoLiquidity | No liquidity available for market order. |
| Order | PositionIncreaseAtOpenInterestCap | Order would increase open interest while open interest is capped |
| Order | PositionFlipAtOpenInterestCap | Order would increase open interest while open interest is capped |
| Order | TooAggressiveAtOpenInterestCap | Order rejected due to price more aggressive than oracle while at open interest cap |
| Order | OpenInterestIncrease | Order would increase open interest too quickly |
| Order | InsufficientSpotBalance | (Spot-only) Order has insufficient spot balance to trade |
| Order | Oracle | Order price too far from oracle |
| Order | PerpMaxPosition | Order would cause position to exceed margin tier limit at current leverage |
| Cancel | MissingOrder | Order was never placed, already canceled, or filled. |
Important: Some errors are a deterministic function of the payload itself, and these are instead returned earlier as part of pre-validation. In this case only one error is returned for the entire payload, as some of these errors do not apply to a specific order or cancel.
Examples include: empty batch of orders, non-reduce-only TP/SL orders, order too far from reference price, and some forms of tick size validation. 
For API users that use batching, it's recommended to handle the case where a single error is returned for a batch of multiple orders. In this case, the response could be duplicated `n`times before being sent to the callback function, as the whole batch was rejected for this same reason.
For API users that use historical orders, a list of all the cancel / reject historical order statuses can be found [here](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#query-order-status-by-oid-or-cloid).
# Signing
It is recommended to use an existing SDK instead of manually generating signatures. There are many potential ways in which signatures can be wrong. An incorrect signature results in recovering a different signer based on the signature and payload and results in one of the following errors:\
`"L1 error: User or API Wallet 0x0123... does not exist."`\
`Must deposit before performing actions. User: 0x123...`\
where the returned address does not match the public address of the wallet you are signing with. The returned address also changes for different inputs.\
An incorrect signature does not indicate why it is incorrect which makes debugging more challenging. To debug this it is recommended to read through the Python SDK carefully and make sure the implementation matches exactly. If that doesn't work, add logging to find where the output diverges.
Some common errors:\
1\. Not realizing that there are two signing schemes (the Python SDK methods are `sign_l1_action` vs `sig프로젝트로 돌아가기