OKX CEX Portfolio & Account CLI
Account balance, positions, P&L, bills, fees, and fund transfers on OKX exchange. Requires API credentials.
Preflight
Before running any command, follow ../_shared/preflight.md.
Use metadata.version from this file's frontmatter as the reference for Step 2.
Prerequisites
- Install
okxCLI: - Configure credentials:
- Test with demo mode (simulated trading, no real funds):
Security: NEVER accept credentials in chat. Guide users to
okx config initfor setup.
Credential & Profile Check
Run this check before any authenticated command. The auth method is detected during preflight Step 2 and remembered for the session.
Step A — Verify credentials
Check both sources (see preflight Step 2 for the decision table). okx auth status --json alone is insufficient — its apiKey field is always false and does NOT reflect the TOML config.
Branch in this order — first match wins:
config showhas any profile with a non-emptyapi_key— API Key mode. Proceed to Step B.- No API-key profile AND
auth statusreturns"status": "logged_in"— OAuth mode. Proceed to Step B. - No API-key profile AND
auth statusreturns"status": "pending"— login in progress, wait. - No API-key profile AND
auth statusreturns"status": "not_logged_in"— stop all operations, loadokx-cex-authskill and follow login steps, wait for completion.
Step B — Confirm trading mode
Resolution rules:
- Current message intent is clear (e.g. "real" / "实盘" / "live" → live; "test" / "模拟" / "demo" → demo) → use it and inform the user
- Current message has no explicit declaration → check conversation context for a previous choice:
- Found → reuse it, inform user
- Not found → ask:
"Live (实盘) or Demo (模拟盘)?"— wait for answer before proceeding
How to apply the mode depends on auth method (detected in Step A):
- API Key users: run
okx config show --jsonto discover available profile names and theirdemosettings. Use--profile <name>to select the correct one. - OAuth users: omit flags for live trading; add
--demofor simulated trading. Do not use--profileto switch modes.
Handling Authentication Errors
Authentication error (error contains "401", "Session expired", or "Run okx auth login first"):
- Stop immediately — do not retry the same command
- Inform the user: "Authentication failed. Your session may have expired."
- Load
okx-cex-authskill and follow the re-authentication steps - After successful re-authentication, retry the original command
Demo vs Live Mode
Rules:
- Read commands (balance, positions, bills, etc.): always state which mode was used
- Write commands (
transfer,set-position-mode): mode must be confirmed before execution (see "Credential & Profile Check" Step B); transfer especially — wrong mode means wrong account - Every response after a command must append:
[mode: live]or[mode: demo]
Skill Routing
- For market data (prices, charts, depth, funding rates) → use
okx-cex-market - For account balance, P&L, positions, fees, transfers → use
okx-cex-portfolio(this skill) - For regular spot/swap/futures/algo orders → use
okx-cex-trade - For grid and DCA trading bots → use
okx-cex-bot
Quickstart
Command Index
Read Commands
Write Commands
Cross-Skill Workflows
Pre-trade balance check
User: "I want to buy 0.1 BTC — do I have enough USDT?"
Pre-bot balance check
User: "I want to start a BTC grid bot with 1000 USDT"
Net worth quick view
User: "What's my total balance?" / "总资产多少?"
Review open positions and P&L
User: "Show me my current positions and how they're performing"
Transfer and trade
User: "Move 500 USDT from my funding account to trade BTC"
Check max position size before entering
User: "How much BTC can I buy with cross margin?"
Operation Flow
Step 0 — Credential & Profile Check
Before any authenticated command: see Credential & Profile Check. Determine auth method and trading mode before executing.
After every command result: append [mode: live] or [mode: demo] to the response
Step 1: Identify account action
- Check all balances at once →
okx account balance-all(trading + funding + valuation in one call; recommended for "总资产 / net worth / all balances") - Check balance →
okx account balance(trading equity only) orokx account asset-balance(funding balances) orokx account asset-balance --valuation(total across all accounts in USDT) - View open positions →
okx account positions - View closed positions + PnL →
okx account positions-history - View transaction history →
okx account bills - Check fee tier →
okx account fees - Check account settings →
okx account config - Calculate order size →
okx account max-sizeorokx account max-avail-size - Check withdrawal limit →
okx account max-withdrawal - Transfer funds →
okx account transfer - Change position mode →
okx account set-position-mode
Step 2: Run read commands immediately — confirm profile (Step 0) then writes
Read commands (1–10): run immediately, no confirmation needed.
ccyfilter: use currency symbol likeUSDT,BTC,ETH--instTypefor fees/positions:SPOT,SWAP,FUTURES,OPTION--archivefor bills: access older records beyond the default window--tdModefor max-size:cash(spot),cross, orisolated
Write commands (11–12): confirm once before executing.
set-position-mode: confirm mode (net= one-directional,long_short_mode= hedge mode); switching may affect open positionstransfer: confirm--ccy,--amt,--from,--to(account types:6=funding,18=trading); verify source balance first
Step 3: Verify after writes
- After
set-position-mode: runokx account configto confirmposModeupdated - After
transfer: runokx account balanceandokx account asset-balanceto confirm balances updated
CLI Command Reference
Balance All — One-Shot Aggregate Snapshot
This command calls a server-side aggregate endpoint first and automatically falls back to direct parallel queries when it is unavailable; the output contract is identical either way.
Returns { trading, funding, valuation, meta }. Each section has available: boolean:
trading:totalEq,adjEq,details[](per-currency)funding:details[](per-currencyccy,bal,availBal,frozenBal)valuation:valuationCcy,totalBal,details[](per-account breakdown is only populated on the parallel path; use--no-aggregateto force it)meta:requestedAt(ISO 8601),elapsedMs,partialFailure,source(aggregateorfallback),site
When --json is NOT set: prints [PARTIAL] banner if meta.partialFailure=true, followed by three sections (Trading / Funding / Valuation), then a [source: ...] footer showing which path served the data. Failed sections show [ERROR: <msg>].
Account Balance — Trading Account
Returns table: currency, equity, available, frozen. Only shows currencies with balance > 0.
Asset Balance — Funding Account
Returns: ccy, bal, availBal, frozenBal. Only shows currencies with balance > 0.
With --valuation: additionally prints a valuation summary table with totalBal and per-account-type breakdown (classic/earn/funding/trading). The numbers are denominated in --valuationCcy (default USDT).
Important: ccy (balance filter) and --valuationCcy (valuation denomination) are independent parameters — ccy=BTC filters the balance list to BTC rows but does NOT change the valuation currency; set --valuationCcy BTC explicitly for BTC-denominated totals.
Positions — Open Positions
Returns: instId, instType, side (posSide), pos, avgPx, upl (unrealized PnL), lever. Only shows positions with size ≠ 0.
Positions History — Closed Positions
Returns: instId, direction, openAvgPx, closeAvgPx, realizedPnl, uTime.
Bills — Account Ledger
Returns: billId, instId, type, ccy, balChg, bal, ts.
Fees — Trading Fee Tier
Returns: level, maker, taker, makerU, takerU, ts.
Config — Account Configuration
Returns: uid, acctLv (account level), posMode (net/long_short_mode), autoLoan, greeksType, level, levelTmp.
Max Size — Maximum Order Size
Returns: instId, maxBuy, maxSell.
Max Available Size
Returns: instId, availBuy, availSell — the immediately available size for the next order.
Max Withdrawal
Returns table: ccy, maxWd, maxWdEx (with borrowing). Shows all currencies if no filter.
Set Position Mode
Warning: Switching modes when positions are open may cause unexpected behavior. Check
okx account positionsfirst.
Transfer Funds
Returns: transId, ccy, amt.
MCP Tool Reference
Input / Output Examples
"How much USDT do I have?"
"Show all my open positions"
"What's my trading history and realized PnL?"
"Show my recent account activity"
"What are my trading fees for SWAP?"
"How much BTC can I buy in cross margin?"
"Transfer 200 USDT from funding to trading"
"Check my account config"
Where Can the Money Live?
OKX splits assets across multiple sub-accounts. The --valuation breakdown maps directly:
Typical flow when user says "I have X USDT but can't trade":
okx account asset-balance --valuation→ look at eachdetails.*field- If
details.fundingis large anddetails.tradingis small → the funds are in the funding account - Transfer:
okx account transfer --ccy USDT --amt <n> --from 6 --to 18 - Confirm:
okx account balance USDT→ equity should now reflect the transferred amount
Edge Cases
- No balance shown: balance is filtered to > 0 — if nothing shows, all currencies have zero balance
- Positions command returns empty: no open contracts; spot holdings are not shown here (use
account balance) - bills --archive: required for transactions older than 7 days (default window); may be slower
- set-position-mode: cannot switch to
netif you have both long and short positions on the same instrument - transfer --from/--to codes:
6=funding account,18=trading account; other values exist for sub-account flows - max-size vs max-avail-size:
max-sizeis the theoretical maximum;max-avail-sizeaccounts for existing orders and reserved margin - Demo mode:
okx --demo account balance(OAuth) orokx --profile <demo-profile> account balance(API Key) shows simulated balances, not real funds
Global Notes
- All write commands require valid credentials (OAuth session or API key in
~/.okx/config.toml) - Auth method and trading mode are determined in "Credential & Profile Check"; see that section for parameter rules
- Every command result includes a
[mode: live]or[mode: demo]tag for audit reference --jsonreturns the raw OKX API v5 response by default. Add--envto wrap the output as{"env": "<live|demo>", "profile": "<name>", "data": <response>}- Rate limit: 10 requests per 2 seconds for account endpoints
- Positions shown are for the unified trading account; funding account assets are separate
- Account types:
6=Funding Account (deposits/withdrawals),18=Unified Trading Account (spot + derivatives)

