/hypergrok:hyperliquid-positionsfrom hypergrok
Manages Hyperliquid perpetual positions and margin: reads positions/margin, sets leverage and cross/isolated mode, adds isolated margin, closes positions with reduce-only IOC, and cleans up orphaned orders. Write actions require Execution Trader approval.
Ships in hypergrok. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Reads here are for everyone (Risk Manager first); the write actions (updateLeverage, updateIsolatedMargin, closes) are Execution Trader only, on a ticket approved by id or covered by a valid standing mandate. A mandate covers closes and setting leverage to what the ticket needs; isolated-margin top-ups and margin-mode changes the ticket does not need stay per-ticket. Order mechanics are in hyperliquid-orders.
strictIsolated and refuse removal; HIP-3 markets may be noCross).updateLeverage; it caps position size against margin. Max leverage is per market and tiered by notional (see margin tiers).meta.marginTables, matched to the asset via marginTableId) listing notional thresholds and the max leverage allowed above each. Bigger positions get less leverage.liquidationPx); use that, do not recompute.reduceOnly. Full close at market: reduce-only IOC at a slippage-bounded price for the live position size.ADDR=$HYPERLIQUID_ACCOUNT_ADDRESS
BASE=$([ "$HYPERLIQUID_NETWORK" = mainnet ] && echo https://api.hyperliquid.xyz || echo https://api.hyperliquid-testnet.xyz)
curl -sS -X POST $BASE/info -H 'Content-Type: application/json' -d "{\"type\":\"clearinghouseState\",\"user\":\"$ADDR\"}" | jq '{
accountValue: .marginSummary.accountValue, totalMarginUsed: .marginSummary.totalMarginUsed,
withdrawable, crossMaintenanceMarginUsed,
positions: [.assetPositions[].position | {coin, szi, entryPx, positionValue, unrealizedPnl, liquidationPx, marginUsed,
leverage: (.leverage.type + " " + (.leverage.value|tostring)), returnOnEquity, cumFunding: .cumFunding.sinceOpen}]}'
szi is signed size (positive long, negative short). leverage.type is cross or isolated; isolated positions also carry leverage.rawUsd (the isolated margin).
Margin tiers for a market:
curl -sS -X POST $BASE/info -H 'Content-Type: application/json' -d '{"type":"meta"}' \
| jq --arg c ETH '(.universe[] | select(.name==$c)) as $u | ($u.marginTableId // $u.maxLeverage) as $id
| {name:$u.name, szDecimals:$u.szDecimals, maxLeverage:$u.maxLeverage, marginTableId:$id,
tiers: (if $id < 50 then [{lowerBound:"0.0", maxLeverage:$id}]
else ((.marginTables[] | select(.[0]==$id) | .[1].marginTiers) // [{lowerBound:"0.0", maxLeverage:$u.maxLeverage}]) end)}'
marginTables is a list of [id, {description, marginTiers: [{lowerBound, maxLeverage}, ...]}] for ids of 50 and above; the tier whose lowerBound (position notional in USD) is the largest one at or below your notional applies. Ids below 50 are single-tier tables whose max leverage equals the id and they are not listed in marginTables (most altcoins), which the snippet handles. Testnet tiers are far tighter than mainnet (BTC drops from 40x to 25x above only 10k notional on testnet), so a testnet rehearsal does not prove mainnet leverage.
Python equivalents: info.user_state(ADDR), info.meta(); the header from hyperliquid-orders applies.
Do this before the entry the ticket refers to. Leverage is checked when a position is opened (margin required = size x mark / leverage); the leverage of an existing position can be raised without closing it, which frees margin and moves the isolated liquidation price, and lowering it needs enough free margin to cover the higher initial margin. Either way, tell the user what changes.
# header from hyperliquid-orders (info, exchange, ACCOUNT)
res = exchange.update_leverage(3, "ETH", is_cross=True) # 3x cross
# res = exchange.update_leverage(5, "ETH", is_cross=False) # 5x isolated
print(res) # {"status":"ok","response":{"type":"default"}}
print(next((p["position"]["leverage"] for p in info.user_state(ACCOUNT)["assetPositions"] if p["position"]["coin"] == "ETH"), "no open ETH position"))
If the market has no open position yet, confirm afterwards by placing the entry and reading leverage on the resulting position, or via activeAssetData ({"type":"activeAssetData","user":ADDR,"coin":"ETH"}), which reports the account's current leverage setting and available-to-trade for that market.
Add isolated margin to an existing isolated position (USD amount):
res = exchange.update_isolated_margin(50.0, "ETH") # adds 50 USDC of margin to the ETH isolated position
TypeScript: await exchange.updateLeverage({ asset: a, isCross: true, leverage: 3 }); await exchange.updateIsolatedMargin({ asset: a, isBuy: true, ntli: 50 * 1e6 }) (ntli is USD x 1e6).
Read the size live seconds before sending; the ticket states the slippage bound.
coin, slippage = "ETH", 0.003 # 30 bps bound
pos = next((p["position"] for p in info.user_state(ACCOUNT)["assetPositions"] if p["position"]["coin"] == coin), None)
if not pos: raise SystemExit("no open position")
szi = Decimal(pos["szi"]); is_buy = szi < 0 # closing a short buys
sz = round_sz(coin, abs(szi))
mid = info.all_mids()[coin]
px = bounded_px(coin, mid, slippage, is_buy)
cloid = new_cloid(); print("cloid", cloid.to_raw(), "bound", px, "size", sz)
res = exchange.order(coin, is_buy, sz, px, {"limit": {"tif": "Ioc"}}, reduce_only=True, cloid=cloid)
print(res)
# exchange.market_close also sends a reduce-only IOC, but its nearest price rounding can widen a ticket bound.
# Use bounded_px above for an exact approved floor/ceiling; an IOC can partially fill or leave a remainder.
Partial close: pass the reduced size. The position still exists afterwards and still needs a stop.
Clean-up depends on which happened, and reading clearinghouseState is what tells you:
assetPositions no longer contains the coin): list open_orders(ACCOUNT) and cancel the orphaned TP/SL for that market (their own ticket, the standing approval in desk.md, or a valid standing mandate), then confirm the position is gone.sz: "0.0", isPositionTpsl: true) already covers the smaller size and needs nothing. A fixed-size stop now covers more than the position: place the correctly sized replacement first, confirm it is resting, then cancel the old one, so the remainder is never naked between the two actions.Never run the orphan sweep on the assumption that a close was total. Confirm it from the exchange first.
A position is protected when a reduce-only trigger order on the opposite side is resting on the exchange, either sized at least to the position or position-tied (sz: "0.0", isPositionTpsl: true, meaning "the whole position"). Verify with frontendOpenOrders, which exposes trigger fields:
curl -sS -X POST $BASE/info -H 'Content-Type: application/json' -d "{\"type\":\"frontendOpenOrders\",\"user\":\"$ADDR\"}" \
| jq '[.[] | select(.isTrigger==true) | {coin, side, sz, triggerPx, triggerCondition, orderType, reduceOnly, isPositionTpsl, oid, cloid}]'
side is B (buy) or A (sell). A long's stop is an A trigger below mark with reduceOnly: true; a short's is a B trigger above mark. Missing, or undersized without being position-tied: report unprotected to the Desk Lead (desk-incident-response playbook D).
distance_pct = (mark - liquidationPx) / mark x 100 for longs (negative of that for shorts)
Report it per position in every book check. Cross accounts liquidate together; the per-position liquidationPx already accounts for that.
Gtc order by mistake; use Ioc and reduceOnly so nothing rests and nothing can flip the position.clearinghouseState seconds before the close.maxLeverage applies to your notional; read the tier.ntli field is USD x 1e6.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
hyperliquid, perp-trading, margin-management, position-management, defi
npx claudepluginhub galleonlabs/hypergrok-trading-desk --plugin hypergrok17 skills in this plugin
/desk-execution-protocolThe Execution Trader's procedure for turning an approved ticket into one Hyperliquid action and reconciling it - the pre-send checklist, order construction rules, single-send discipline, unknown-result handling and the execution report. Use before and after every send, cancel, modify, leverage change or close./desk-incident-responseWhat the desk does when something goes wrong on Hyperliquid - unknown send results, unexpected fills or positions, unprotected positions, stuck or orphaned orders, API outages, rate limiting, and suspected API wallet compromise. Contain first, reconcile from the exchange record, act only through approved tickets, then review. Use the moment anything does not match the ticket./desk-monitoringHow the desk watches markets and the account between trades using Grok Bot routines and WebSocket or polling watches - the desk brief, book checks, funding and price watches, alert conditions and what a watch may and may not do. Use when the user asks for briefings, alerts, "watch X" or scheduled checks./desk-operating-modelHow the HyperGrok trading desk works as a team of Grok Bots - roles, seats, shared workspace, evidence standard, approval model and handoff format. Use when setting up the desk, when a Bot is unsure who owns something, or when a request does not fit the normal trade lifecycle./desk-post-trade-reviewThe Trade Reviewer's procedure for journaling desk activity and reviewing trades from the exchange record - process graded separately from outcome, execution costs measured, one repeatable finding per review, plus the weekly desk review. Use after any send, when a trade closes, on the weekly routine, or when the user asks "how did that go"./desk-risk-limitsHow the Risk Manager writes the desk's risk limits with the user, sizes every proposed trade from live account state and Hyperliquid's real constraints, checks the book, and issues a PASS or REJECT with exact ticket fields. Use for setting up or changing limits, sizing any trade, and answering "how's the book".Other plugins' skills for the same job