All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
First stable release of the 1.3.9 line. Consolidates all changes accumulated during the 1.3.9 beta cycle (see the [1.3.9-beta.1] through [1.3.9-beta.3] entries below for the full lists): new tr (Turkey) site, okx bot grid sub-orders pagination parity (--groupId/--after/--before/--limit) and the --pending flag for querying open sub-orders in both live and demo modes, a fix for the silently-dropped CLI --site flag, and 35 new okx outcomes eval probes.
- New
tr(Turkey) site in the site registry (https://tr.okx.com), selectable via--site tr,OKX_SITE=tr,site = "tr"in config.toml, or option4in the interactiveokx config initwizard. okx bot grid sub-ordersnow accepts--groupId,--after,--before, and--limit, restoring parity with thegrid_get_sub_ordersMCP tool.- (TRDATA-4187) 35
okx outcomeseval probes (eval/probes/outcomes/), validating LLM-driven tool invocation against live behavior.
okx bot grid sub-ordersnow uses--pendingto query open/pending sub-orders (works in both live and demo modes), replacing the overloaded--liveflag.--liveis retained as a deprecated alias for backward compatibility.- All skill packs'
metadata.versionand pinned@okx_ai/okx-trade-cliinstall version synced to1.3.9per the stable-release skill version sync policy.
- CLI
--siteflag was silently dropped before reaching config resolution, so--site eea|us|trhad no effect (requests always hitwww.okx.com). The flag is now wired through toloadConfigon both the main command anddiagnosepaths.
Beta release: skill metadata.version and the pinned @okx_ai/okx-trade-cli install version are intentionally NOT bumped (stable-release-only per CLAUDE.md).
okx bot grid sub-ordersnow uses--pendingto query open/pending sub-orders, replacing the overloaded--liveflag.--livedoubled as the global "force live trading mode" switch (mutually exclusive with--demo), so pending sub-orders could not be queried in demo mode.--liveis retained as a deprecated alias for backward compatibility, but prefer--pending(which works in both live and demo modes).
Beta release: skill metadata.version and the pinned @okx_ai/okx-trade-cli install version are intentionally NOT bumped (stable-release-only per CLAUDE.md).
- New
trsite (Turkey) in the site registry — both API base URL and web URL arehttps://tr.okx.com. Selectable via--site tr,OKX_SITE=tr,site = "tr"in config.toml, or option4in the interactiveokx config initwizard. okx bot grid sub-ordersnow accepts--groupId,--after,--before, and--limit, restoring parity with thegrid_get_sub_ordersMCP tool (which already supported pagination/filtering). Previously the CLI dropped these, so only the first 100 records were reachable.
- CLI
--siteflag was silently dropped before reaching config resolution, so--site eea|us|trhad no effect (requests always hitwww.okx.com); onlyOKX_SITEenv var or config.tomlsiteworked. The flag is now wired through toloadConfigon both the main command anddiagnosepaths.
Beta release: skill metadata.version and the pinned @okx_ai/okx-trade-cli install version are intentionally NOT bumped (stable-release-only per CLAUDE.md).
- (TRDATA-4187) Add 35
okx outcomeseval probes delivered across 5 phases (eval/probes/outcomes/), validating LLM-driven tool invocation against live behavior.
First stable release of the 1.3.8 line. Code is identical to 1.3.8-beta.7. Consolidates all changes accumulated during the 1.3.8 beta cycle (see the [1.3.8-beta.1] through [1.3.8-beta.7] entries below for the full Added / Fixed / Changed lists): okx outcomes CLI wrapper + okx-outcomes skill, aggregate balance tool account_get_balance_all, issue #200 algo-order fixes (spot_place_algo_order clOrdId, closeFraction full-position close, algoClOrdId mapping), Pilot proxy cache TTL expiry + dead-node HTTP failover, okx market filter / okx market indicator CLI output fixes with default indicator periods, and CI Sonar de-flake.
- All skill packs'
metadata.versionand pinned@okx_ai/okx-trade-cliinstall version synced to1.3.8per the stable-release skill version sync policy (includesokx-outcomes, previously pinned at1.3.5).
Note: the
okx outcomesentries below first shipped in1.3.8-beta.6, an independent release cut from thefeature_okx_predictionbranch (not from master). This is the first master-based release containing them.
okx outcomesCLI wrapper for OKX Outcomes Markets (YES/NO event contracts; formerly OKX Predictions). Forwards all subcommands to the externalokx-outcomesRust binary installed viacurl -fsSL https://raw.githubusercontent.com/okx/outcomes-cli/main/install.sh | sh(macOS/Linux; Windows users placeokx-outcomes.exeonPATHfrom the same GitHub Releases). IncludesPATHdiscovery withOKX_OUTCOMES_BINoverride, friendly install hint, and curated--helpsummary. Module is CLI-only (no MCP tools registered) — seedocs/designs/outcomes-wrapper.md. Authentication is OAuth sign-in (okx outcomes auth login) for authenticated reads, plus an EIP-712 signing key (PREDICTIONS_AGENT_PRIVATE_KEY, normally generated byokx outcomes setupand stored in the OS keyring) for on-chain writes. Theauth login --manualdevice-code flow (prints{verificationUri,userCode}and exits) plus the non-interactivesetup region/setup bindlet an agent drive the entire first-time setup end-to-end with no terminal. WebSocket (ws *) andclob cancel-client-order-idsubcommands are intentionally not exposed by the wrapper.okx-outcomesskill guides agents through onboarding (region → OAuth sign-in → wallet bind, with non-TTY/agent hand-off rules), event browsing, account queries (OAuth), live CLOB price / order-book queries, and dry-run-gated trade placement and CTF split/merge/redeem. Trigger list preserves bothprediction/预测andoutcomeskeywords to cover users still using legacy terminology. References split acrosssetup-auth.md,data-commands.md,account-commands.md,clob-commands.md,ctf-commands.md, andworkflows.md.
spot_place_algo_order: addclOrdIdsupport for OCO/algo orders (issue #200).clOrdIdwas missing from both the tool'sinputSchemaand handler, causing it to be silently dropped when placing spot algo orders (e.g. OCO) with a client order ID.swap_place_algo_orderandfutures_place_algo_orderalready exposedclOrdIdcorrectly; this fixes the parity gap in the spot equivalent.swap_place_algo_order/futures_place_algo_order:closeFractionfull-position-close support for conditional/oco orders (issue #200). Previouslyszwas unconditionally required, making it impossible to place a full-position-close TP/SL order usingcloseFraction. Now: (1) forordType=conditional|oco, exactly one ofszorcloseFractionmust be provided; (2)closeFractionmust equal"1"(only full-position close is supported); (3)closeFractionis only valid forconditionalandocoordTypes - other ordTypes still requiresz; (4) whencloseFractionis used withposSide=net,reduceOnlymust betrue; (5) spot orders do not supportcloseFraction(the field was previously forwarded silently viabuildAlgoConditionalCommonFields- this is now corrected); (6)closeFractiononly applies to market TP/SL orders -tpOrdPx/slOrdPx, when provided, must be"-1".- Algo place tools: client order ID now sent as
algoClOrdId(issue #200). All six tools posting to/api/v5/trade/order-algo(spot_place_algo_order,swap_place_algo_order,swap_place_move_stop_order,futures_place_algo_order,futures_place_move_stop_order,option_place_algo_order) previously sent the client-assigned ID asclOrdId, which is not a recognized parameter of the algo-order endpoint (the API expectsalgoClOrdId) - the ID was silently ignored server-side. The tool input schema now exposesalgoClOrdId; the legacyclOrdIdinput (and the CLI--clOrdIdflag) is still accepted as an alias and mapped toalgoClOrdIdon the wire. Regular order endpoints (/api/v5/trade/orderetc.) are unaffected -clOrdIdremains correct there.
- Pilot proxy cache TTL expiry —
resolvePilot()now ignores stale proxy cache entries. An entry is stale when its age exceedsmin(node.ttl × 1000, 1h). Zero or oversized TTL values are capped to 1 hour.mode=directentries are unaffected and never expire. - Pilot dead-node HTTP failover — a Pilot-proxied request that receives a non-2xx response whose body contains no parseable OKX JSON
code(e.g., HTML 405 from a dead CDN node) is now classified as a dead-node failure. The REST client callshandleNetworkFailure()and retries once (GET orretryOnNetworkErrorPOST only). Responses that carry a valid OKX JSON error code are not misclassified and surface to the caller unchanged. - CI: de-flake the SonarQube test stage (issue #199). Switched every
node:testinvocation fromnode --import tsx/esm --test(Node 20.6+ only) tonode_modules/.bin/tsx --testfor Node 18 compatibility with the OKG compliance Sonar scanner image. The--test-timeoutCLI flag is intentionally not used: it is Node 20+ only and the Node 18 scanner rejects it (bad option, exit 9), which zeroes coverage and fails the quality gate. The actual hang fix is the test hermeticity below, not a timeout flag. As a Node-version-agnostic backstop, the repounit-testCI job now carries atimeout: 10m(andsonaratimeout: 15m) so a hung test fails the job in minutes instead of running to the 1-hour default; per-test hard bounds, if needed, use the Node-18-safeit(name, { timeout }, fn)option. - CI: make
undici-proxy-bootstrap.test.tshermetic (issue #199). AddedAbortSignal.timeout(5000)to all fourfetch()calls in the file; added a file-scopebefore/afterpair that neutralises ambientHTTP_PROXY/HTTPS_PROXY/NO_PROXYenv vars and captures/restores the global undici dispatcher. The test now passes deterministically on CI runners that carry a corporate proxy environment.
- Aggregate balance tool
account_get_balance_all(OPRS-360). One-shot snapshot of trading + funding balances with optional cross-account valuation. Calls the server-side aggregate endpoint (/api/v5/aigc/forward/balance-aggregate) first and automatically falls back to direct parallel queries (Promise.allSettled) when it is unavailable; authentication failures are not retried, and an aggregate response reportingpartialFailureis returned as-is (no fallback). Partial failure semantics: per-sectionavailableflag +meta.partialFailure. Responsemetanow carriessource(aggregate|fallback) andsitefor observability;requestedAtis always an ISO 8601 string regardless of path. CLI:okx account balance-all [ccy] [--accounts trading,funding] [--no-valuation] [--no-aggregate] [--valuationCcy <ccy>]—--no-aggregateforces the parallel path (e.g. when you need the per-account valuation breakdown or a non-USD valuation currency). Skillokx-cex-portfolioupdated with new command and workflows. Ref: [TD] 聚合balance接口.
okx market filterempty output in non---jsonmode (Bug 1, array-unwrap). ThecmdMarketFiltertext-mode path treated theaigc/mcparray-shaped response as a single object, so the human-readable table rendered nothing while--jsonworked. Now unwraps the response with the canonical(Array.isArray(raw) ? raw[0] : raw)pattern (matchingcmdMarketOiHistory), so non---jsonoutput is populated.okx market indicatorsilent failure on empty results (Bug 2, Plan A). When an indicator/timeframe combination returned no values, the render loopcontinued on every empty timeframe and printed nothing — exit 0 with no output. The CLI now prints an explicit, actionable hint after the loop when nothing was rendered (No indicator values returned. This indicator may require a period — try --params (e.g. --params 14).) instead of failing silently.
okx market indicatorapplies a default period when--paramsis omitted (Bug 2, Plan B, CLI layer). Omitting--paramsfor a period-based indicator (e.g. EMA/MA/WMA/RSI[14], MACD[12,26,9], BB[20,2]) now applies a defaultparamListfrom a table inpackages/core(single source of truth) so the CLI renders values instead of empty output. This changes the meaning of omitting--paramson the CLI: previously empty, now default-period values. An explicit--paramsstill overrides the default. The change is applied at the CLI render layer only — the MCP raw-data path (market_filter/market_get_indicator) is unchanged.- Corrected
market_get_indicatorparams description (indicator.ts:212). The tool description previously claimed "Omit to use server defaults", which is factually wrong for period-based indicators (the server does not apply default periods). The description no longer makes that false claim.
Skills-only stable release: the packages/core·cli·mcp code is unchanged from 1.3.6; the @okx_ai/okx-trade-cli@1.3.7 package is a version-only bump. All functional changes are in the earn-hunter skill.
- earn-hunter: Flexible Earn (活期赚币) monitoring — monitors Simple Earn flexible lending rates for configured currencies (default USDT/USDC). Notifies when APY crosses above threshold (default 8%). Uses threshold-crossing dedup model: one notification per above-threshold period, resets when rate drops below. Activation flow updated to three-way multi-select (Flash/Fixed/Flexible) with independent currency and APY config per type.
- earn-hunter: macOS LaunchAgent fallback — when macOS cron daemon (
com.vix.cron) is not running, activation auto-falls back to a LaunchAgent plist (~/Library/LaunchAgents/com.okx.earn-hunter.plist). No sudo required, survives reboot. Pause/Resume/Uninstall supportlaunchagentscheduler type.
- earn-hunter: cron PATH issue + stderr swallowed — macOS cron runs with
PATH=/usr/bin:/bin, unable to find node/okx. Addedresolve_bin+env.snapshotfor tool path resolution; activation writesenv.snapshotwith absolute paths.2>/dev/nullreplaced with stderr-to-tempfile separation so node's[UNDICI-EHPA] Warningno longer pollutes JSON output. Emptylast_erroralerts now show "likely cron PATH issue" guidance. - earn-hunter: single feed failure aborted entire scan — if flash returned OKX Code 8116 (system error), fixed and flexible feeds were never processed. Now continues with whichever feeds succeeded; only counts as scan failure when ALL enabled feeds fail.
- earn-hunter: transient server error retry —
retry_cmdretries up to 3 times (3s interval) for transient errors like Code 8116. Auth errors (401) bail immediately. - earn-hunter: CTA hardcoded "Claude Code" — notification CTA now adapts to channel: session uses interactive CTA ("回复申购金额"), TG/Lark uses generic push CTA without client-specific branding.
- earn-hunter: flexible diff cleanup test namespace immunity — removed incorrect
test:key immunity from flexible cleanup (threshold-crossing semantics differ from flash/fixed offer-existence semantics). - earn-hunter: notification channel silently defaulted to session — activation now always asks user to choose notification channel. Choosing session shows explicit warning about offline blindness.
- All skill packs'
metadata.versionand pinned@okx_ai/okx-trade-cliinstall version synced to1.3.7per the stable-release skill version sync policy.
First stable release of the 1.3.6 line. Consolidates all changes accumulated during the 1.3.6 beta cycle (see the [1.3.6-beta.1] entry below for the full Added / Fixed list): earn-hunter skill, Ed25519 + SHA-256 skill signature verification, automatic HTTP/HTTPS proxy support, linux-arm64 auth CDN fallback, earn_get_fixed_earn_products tool, and MCP tool title exposure.
- All skill packs'
metadata.versionsynced to1.3.6per the stable-release skill version sync policy.
- earn-hunter skill — OpenClaw in-session cron scheduling: on OpenClaw, the earn-hunter scheduled scan is now set up inside the conversation via the in-session
cronagent tool (isolated session +lightContext) and delivered back to the chat via cronannounce, instead of OS crontab. No CLI commands are emitted (theopenclaw cronCLI path has permission issues).platform.jsonscheduler.typeis"openclaw-cron"on OpenClaw; Claude Code / Hermes keep"cron"(OS crontab + curl) and Generic stays"manual". earn_get_fixed_earn_productsMCP tool andokx earn savings fixed-productsCLI command for querying Simple Earn Fixed-term product pool with APR, term, remaining quota, and sold-out status- Automatic HTTP/HTTPS proxy support via environment variables (TRDATA-4023). Set
HTTPS_PROXYorHTTP_PROXYenv vars and all undici-backed fetch calls (CLI, MCP server, mcp-gateway) are automatically routed through the proxy.NO_PROXYis honored for per-host bypass. Implemented viaEnvHttpProxyAgentglobal undici dispatcher inpackages/core/src/runtime/undici-proxy-bootstrap.ts. No configuration change needed; per-requestproxy_urlconfig still takes precedence when both are set. - Skill signature verification:
okx skill addnow verifies Ed25519 signature and SHA-256 file integrity before installing a skill, with server-side fallback when local verification cannot proceed. Use--forceto bypass on verification failure. New commandokx skill verify <name>re-verifies an installed skill on demand and persists the result to the local registry. New SDK exports:verifySkillSignature,getPublicKey,serverSideVerify,tryReadMetaJson,VerificationResult,VerificationStatus. - All 163 MCP tools now expose a human-readable
titleat both top-level (Tool.title, per MCP spec 2025-06-18) and insideannotations.titlefor backward compatibility, so clients like MCP Inspector render readable labels instead of snake_case names. .env.bakadded to.gitignoreso local backup env files are never committed.
EnvHttpProxyAgentexperimental warning on every command: the undici proxy bootstrap registeredEnvHttpProxyAgentunconditionally at load time, which made Node emit a[UNDICI-EHPA] ExperimentalWarningon every CLI command — including local-only ones likeokx skill listthat never make a request. Registration is now gated on the presence of a proxy env var (HTTPS_PROXY/HTTP_PROXY, upper- or lower-case), so proxy users keep automatic proxy support while everyone else gets a clean, warning-free CLI.- linux-arm64:
okx auth statusandokx auth logoutfailed with "All CDN sources failed (HTTP 404)" (TRDATA-4135). Added a probe-based CDN fallback inresolveAuthPlatformDir(): when running on linux-arm64 and CDN returns HTTP 404 for the nativelinux-arm64/checksum.json, the auth installer transparently falls back to thelinux-x64binary and emits a warning that x86_64 emulation is required. Once a native linux-arm64 binary is uploaded to CDN, the fallback self-deactivates (probe returns HTTP 200 first). earn savings fixed-redeemdocumentation used positional arg instead of--reqIdflag: SKILL.md, cli-registry, and savings-commands.md all documentedfixed-redeem <reqId>(positional), but the CLI router readsv.reqId(named flag). Agents following the docs would passundefinedas reqId. Now correctly documented as--reqId <reqId>.earn savings rate-history --limitdocumentation default was 100, actual code default is 7: savings-commands.md previously documented the default as 100, but the CLI implementation usesreadNumber(args, "limit") ?? 7. Now corrected to match the actual default of 7.earn savings rate-historyandfixed-productsCLI output usedratecolumn but OKX API returnsapr: fixed-term offers table always showed emptyratecolumn. Now correctly readsaprfield.
- Per-tool
annotations.destructiveHintandidempotentHintare now accurate to MCP spec semantics: 24 additive writes (place_order, transfer, subscribe, redeem) are no longer marked destructive, and 37 destructive idempotent writes (cancel, amend, close, set_leverage) are now marked idempotent. Two 3-in-1 batch routers (swap_batch_orders,spot_batch_orders) keep the safe write defaults. - Non-ASCII cleanup completed -- round 2 (TRDATA-3977, !325). Cleared the remaining 5 residual non-ASCII characters still leaking via TAP output in test
describe/itblock names, reducing the count to 0. Completes the TRDATA-3977 series begun in 1.3.5-beta.1.
Stable rollup of 1.3.5-beta.1 plus a follow-up cleanup. All skill metadata.version synced from 1.3.3 to 1.3.5.
- Pair spread tool (1.3.5-beta.1, !315).
market_get_pair_spread. Compute spread statistics (mean/stdDev/median/min/max for both absolute and ratio) between two instruments over a configurable lookback window. Supports backtest mode. CLI command:okx market pair-spread. No credentials required.
- CLI startup performance (1.3.5-beta.1, TRDATA-3954).
okxno longer pins the Node.js event loop on startup. Four layers: (B0)OKX_UPDATE_CHECK=falsekill switch; (B1) update checks use the user's configured npm mirror; (A') fetch usesAbortSignal.timeout(3000); (B1.5) failed fetches write a negative-cache entry (1 h TTL).
grid_stop_order/dca_stop_orderworkflow guidance (1.3.5-beta.1, !305). Tool descriptions now document the two-step close pattern for bots with residual positions.- Smartmoney V7 funnel semantics doc sync (1.3.5-beta.1). Aligned design / module / context-kg / skill / eval docs with the shipped V7 signal funnel. Docs only.
- Non-ASCII typographic punctuation cleanup (TRDATA-3977). Two-round sweep replacing em-dash, en-dash, right-arrow, ellipsis with ASCII equivalents across CLI help, tool descriptions, and tests. Round 1 (1.3.5-beta.1) handled the primary surface; round 2 (this release) cleaned 5 residual chars leaking through TAP. No functional change; addresses OKG SonarQube TAP lexer compatibility.
- Skill
metadata.versionbumped to1.3.5across all 9 skills (okx-cex-trade,okx-cex-market,okx-cex-earn,okx-cex-bot,okx-cex-portfolio,okx-cex-skill-mp,okx-cex-auth,okx-cex-smartmoney,okx-sentiment-tracker). Catches up1.3.3→1.3.5(skill versions were not bumped in1.3.4stable).
- Pair spread tool (!315).
market_get_pair_spread. Compute spread statistics (mean/stdDev/median/min/max for both absolute and ratio) between two instruments over a configurable lookback window. Supports backtest mode. CLI command:okx market pair-spread. No credentials required.
- CLI startup performance (TRDATA-3954).
okxno longer pins the Node.js event loop on startup. Four layers: (B0)OKX_UPDATE_CHECK=falsekill switch; (B1) update checks use the user's configured npm mirror (npm_config_registryenv or.npmrcwalk) instead of hardcodingregistry.npmjs.org; (A') fetch usesAbortSignal.timeout(3000)whose internal unref'd timer prevents infinite event-loop hang; (B1.5) failed fetches write a negative-cache entry (1 h TTL) so repeated cold-starts on unreachable networks skip the fetch entirely.
grid_stop_order/dca_stop_orderworkflow guidance (!305). Tool descriptions now document the two-step close pattern for bots with residual positions: stopping withstopType="2"puts the bot intono_close_position(strategy paused, position still open); calling stop again withstopType="1"then closes the remaining position. Applies to both grid and DCA (contract and spot variants). Empirically verified on OKX demo API.- Smartmoney V7 funnel semantics doc sync. Aligned
docs/designs/smartmoney.md,docs/modules/smartmoney.md,context-kg/business/06-leaderboard-smartmoney-api.md,skills/okx-cex-smartmoney/references/signal-commands.md, andeval/README.mdwith the shipped V7 signal funnel. Docs only. - Replaced non-ASCII typographic punctuation (em-dash, en-dash, right-arrow, ellipsis) with ASCII equivalents in CLI help text, tool descriptions, and CLI output placeholders (TRDATA-3977, #190). No functional change; addresses OKG SonarQube TAP lexer compatibility.
Note:
market_get_pair_spreadwas historically tagged in1.3.4-beta.2but was deliberately excluded from thev1.3.4stable release tag (which is anchored atcd99d487, the1.3.4-beta.1bump commit). It ships in1.3.5-beta.1instead.
Stable rollup of 1.3.4-beta.1 only. The 1.3.4-beta.2 line below is retained as historical record but its content (market_get_pair_spread) does NOT ship in the v1.3.4 tag — see ## [1.3.5-beta.1] above.
- Economic calendar tools (1.3.4-beta.1, !298).
news_get_economic_calendar+news_list_calendar_regions. Query macro-economic events (GDP, CPI, NFP, FOMC, etc.) with region/importance filters and configurable time-window controls. CLI commands:okx news economic-calendar,okx news list-regions. Skillokx-sentiment-trackerupdated with calendar workflow guidance.
- Pair spread tool (
market_get_pair_spread). Compute spread statistics (mean/stdDev/median/min/max for both absolute and ratio) between two instruments over a configurable lookback window. Supports backtest mode. CLI command:okx market pair-spread. No credentials required.
- Economic calendar tools (
news_get_economic_calendar,news_list_calendar_regions). Query macro-economic events (GDP, CPI, NFP, FOMC, etc.) with region/importance filters and time-window controls. CLI commands:okx news economic-calendar,okx news list-regions. Skillokx-sentiment-trackerupdated with calendar workflow guidance.
Stable rollup of 1.3.3-beta.1 → 1.3.3-beta.3. See per-beta sections below for full implementation detail.
smartmoneymodule redesign — no compat shim (1.3.3-beta.1, !304). MCP/CLI surface fully rewritten for AI-agent disambiguation: 8 → 10 atomic tools (get_traders_by_filter,get_performance_by_trader,get_trader_orders_history,get_trader_positions,get_trader_positions_history,get_signal_overview_by_filter,get_signal_overview_by_trader,get_signal_trend_by_filter,get_signal_trend_by_trader,search_trader). Old tool/parameter/field names removed. Arrays replace CSV strings forauthorIds/instCcyList. Pool-filter rename (pnl/winRate/asset→minPnl/minWinRate/minAum). Output field renames (winRatio→winRate,maxRetreat→maxDrawdown). Full migration guide:docs/designs/smartmoney.md.
- Windows named-pipe OAuth token retrieval for
okx auth(packages/core/src/auth/, !310). Eliminates the WSL/elevated-privilege requirement on Windows; tokens are fetched via a per-invocation named pipe (\\.\pipe\okx-auth-<256-bit-random>) instead of fd-3 forwarding. --tpLevelmulti-tier take-profit flag (Phase 3b) (!292, #183). Repeatable onokx {swap,spot,futures} placeandalgo placefor independent TP tiers. CLI-only (not exposed in MCP / skill workflows).- Phase 3a+c CLI power-user flags (!291, #182). Six new optional flags:
--tpTriggerRatio/--slTriggerRatio(ratio-based TP/SL triggers),--closeFraction(partial-position close),--tradeQuoteCcy(SPOT quote currency),--banAmend(disable OKX auto-amend),--pxAmendType(price out-of-range correction). CLI-only. - LLM eval probe coverage 17/17 MCP modules (
eval/probes/, !303). All modules now have trace-based probes (findToolCall); CI gateeval-probe-checkenforces full coverage.
- Log disk usage bounded with retention sweep (
packages/core/src/logger.ts, !312). Startup sweep prunes~/.okx/logs/files beyond the configured retention window — prevents unbounded disk growth on long-running installations. event_browseconcurrent fetch cap (packages/core/src/tools/event-trade.ts, !300, #146). Semaphore caps concurrent market-fetches at 8 (OKX 20-req window minus 12 retry buffer). Switched toPromise.allSettledso a single failing series no longer aborts the browse.cmdAuthRemovepermission-denied error handling (packages/cli/src/commands/auth.ts, !299, #159). Added integration test coverage for the EACCES path (errorLinein text mode,{status:"failed",error:<msg>}in JSON mode,process.exitCode = 1).- Layered Architecture diagram corrected (
ARCHITECTURE.md,ARCHITECTURE.zh-CN.md, !296, #185). Replaced the single-path waterfall (which mislabeledpackages/mcp/src/index.tsas "CLI entry") with a two-binary diagram showingokx-trade-mcpandokxas independent binaries on top of@agent-tradekit/core.
smartmoneyschema:sortBy/period/granularitynow required (1.3.3-beta.2). All leaderboard + signal tools marksortByandperiodasrequired;signal-trend-*also requiresgranularity. Handlers inject defaults explicitly so MCP and CLI paths are deterministic. Compat: callers that already passed these params are unaffected.smartmoneysignal- tools: clarify linear-only scope* (1.3.3-beta.2, SIG-01).signal-*tools and skill docs now state thatinstCcyList/instCcyaggregate USDT/USDS-margined contracts only — coin-margined positions are silently excluded by upstream. Docs only.linux-arm64pilot binary routes to native arm64 (packages/core/src/pilot/installer.ts, !295). Removes the previouslinux-arm64 → linux-x64qemu/binfmt emulation fallback.- Smart Money skill refreshed (
skills/, !294). Trigger phrases, workflow guidance, and tool surface descriptions updated for the newsmartmoney_*tool set. context-kg/mapping sections updated (context-kg/business/06-leaderboard-smartmoney-api.md,07-dcd-api.md,08-dca-api.md, !302, #187). Rewrote "Mapping to…" sections to match the shipped tool surface; added "Backlog (not yet wrapped)" for V2-only upstream paths.
-
Windows named-pipe token retrieval for
okx auth(packages/core/src/auth/): On Windows hosts, OAuth bearer tokens are now fetched via a named pipe instead of fd3 forwarding, removing the requirement for WSL or elevated privileges. (!310) -
--tpLevelmulti-tier take-profit flag (Phase 3b): Pass--tpLevelmultiple times onokx {swap,spot,futures} placeandalgo placeto set independent TP tiers (e.g.--tpLevel "px:78000,sz:0.5,kind:limit" --tpLevel "px:81000,sz:0.5,kind:market"). Valid keys:px,sz,kind,triggerPx,triggerPxType,amendPxOnTrigger,clOrdId. Combining--tpLevelwith legacy--tpOrdPx/--tpTriggerPxis rejected at the CLI layer. Not exposed in MCP tool descriptions or skill workflows (intentional). (!292, #183) -
Phase 3a+c CLI power-user flags: Six new optional flags —
--tpTriggerRatio/--slTriggerRatio(ratio-based TP/SL triggers),--closeFraction(partial-position close, mutually exclusive with--sz),--tradeQuoteCcy(SPOT quote currency selection),--banAmend(disable OKX auto-amend on SPOT market orders),--pxAmendType(price out-of-range correction control). Applies tookx {swap,spot,futures} placeandokx {swap,futures} algo place. No MCP or skill exposure (intentional). (!291, #182) -
LLM eval probe coverage completed to 17/17 MCP modules (
eval/probes/): All remaining modules now have probe files ateval/probes/<module>/tier2-<tool_name>.live.test.tsusing trace-based assertions (findToolCall). Full-suite 17/17 module coverage is now enforced by the CIeval-probe-checkgate. (!303)
-
Log disk usage bounded with retention sweep (
packages/core/src/logger.ts): A startup sweep now prunes log files in~/.okx/logs/beyond the configured retention window, preventing unbounded disk growth on long-running installations. Previously, log files accumulated indefinitely. (!312) -
event_browseconcurrent fetch cap (packages/core/src/tools/event-trade.ts,event-helpers.ts): Replaced unboundedPromise.allwith a semaphore capped at 8 concurrent market-fetch requests (OKX window is 20 req; 12 reserved as buffer for retries). Switched toPromise.allSettledso a single failing series no longer aborts the entire browse — series with no active contracts are silently skipped. (!300, #146) -
cmdAuthRemovepermission-denied error handling (packages/cli/src/commands/auth.ts): The existing error path whenremoveAuthBinary()throws (e.g. EACCES) now has integration test coverage:errorLineis emitted in text mode,{status:"failed",error:<msg>}in JSON mode, andprocess.exitCodeis set to1in both cases with no rethrow. (!299, #159) -
Layered Architecture diagram (
ARCHITECTURE.md,ARCHITECTURE.zh-CN.md): Replaced the single-path waterfall diagram — which incorrectly labeledpackages/mcp/src/index.tsas "CLI entry" — with a two-binary diagram showingokx-trade-mcpandokxas independent binaries that both import from the shared@agent-tradekit/coreSDK. (!296, #185)
-
linux-arm64pilot binary now routes to native arm64 (packages/core/src/pilot/installer.ts): The previouslinux-arm64 → linux-x64stop-gap fallback is removed. The platform now routes directly to the native arm64 binary published at/upgradeapp/tools/pilot/linux-arm64/okx-pilot, eliminating qemu/binfmt emulation overhead on ARM64 Linux hosts. (!295) -
Smart money skill refreshed (
skills/): Updated trigger phrases, workflow guidance, and tool surface descriptions to reflect the currentsmartmoney_*tool set and signal semantics. (!294) -
context-kg/mapping sections updated (context-kg/business/06-leaderboard-smartmoney-api.md,07-dcd-api.md,08-dca-api.md): Rewrote the "Mapping to…" sections in all three docs to match the shipped tool surface:06now lists the 5 shippedsmartmoney_*tools;07lists the 6 flatdcd_*tools with bundling-decision notes;08lists the 5 unifieddca_*tools plus a new "Backlog (not yet wrapped)" subsection for the 10 V2-only upstream paths. (!302, #187)
signal-* tools and skill docs now state that instCcyList / instCcy aggregate USDT/USDS-margined contracts only — coin-margined (-USD-SWAP / -USD-DELIVERY) positions are silently excluded by upstream. No behavior change.
- All leaderboard + signal tools mark
sortByandperiodasrequired;signal-trend-*also requiresgranularity. Fixes silent reliance on backend defaults (e.g.perioddocumented as90but actually returning lifetime cumulative). performance-by-trader,signal-overview-by-trader,signal-trend-by-tradernewly acceptsortBy+period(T2 was period-only).- Handlers inject defaults explicitly (
sortBy=pnl; leaderboardperiod=90/ signalperiod=7; trendgranularity=1h) so MCP and CLI paths are deterministic.
Compat: callers that already passed these params or relied on documented defaults are unaffected.
Smart Money MCP/CLI surface is fully rewritten for AI-agent disambiguation. No compat shim — old tool/parameter/field names are removed. Full rationale in docs/designs/smartmoney.md.
CLI parity: each CLI command is the MCP tool name minus smartmoney_ and get_, snake → kebab (e.g. smartmoney_get_traders_by_filter ↔ okx smartmoney traders-by-filter). The --authorIds / --instCcyList flags accept comma-separated input (CLI splits to array at the boundary).
| Old (1.3.2) | New | Notes |
|---|---|---|
get_traders (pool-filter mode) |
get_traders_by_filter |
limit default 100 → 10 |
get_traders (authorIds mode) |
get_performance_by_trader |
direct lookup, no pool filter |
get_trader_records |
get_trader_orders_history |
aligns with *_get_orders family |
get_trader_positions |
get_trader_positions |
name unchanged |
get_trader_position_history |
get_trader_positions_history |
pluralized |
get_signal (pool-filter mode) |
get_signal_overview_by_filter |
ts removed; topInstruments (default 20) subsumes "top-coin overview" |
get_signal (authorIds mode) |
get_signal_overview_by_trader |
tighter input — pool filters removed (use _by_filter for tier discovery) |
get_signal_history |
get_signal_trend_by_filter |
renamed for symmetry with _by_trader sibling |
get_overview, get_top_coin_signals, get_trader_detail |
(removed) | superseded; _trader_detail was non-atomic |
| (new) | search_trader |
nickname → authorId resolution (≤10 matches, follower-count DESC) |
| (new) | get_signal_trend_by_trader |
single-asset time-series restricted to authorIds |
- Arrays replace CSV strings for
authorIdsandinstCcyList(typed arrays catch shape mistakes earlier than runtime CSV parsing). - Leaderboard pool-filter rename to disambiguate from signal-side
*Tierenums:pnl→minPnl,winRate→minWinRate,asset→minAum(maxDrawdownunchanged). Signal-side keepspnlTier/winRateTier/maxDrawdownTier/aumTier. - Time anchors split by family: leaderboard uses
updateTime(12-digityyyyMMddHHmmUTC+8); signal-trend uses optionalasOfTime(10-digityyyyMMddHHUTC, defaults to current hour); signal-overview takes no time input.tsanddataVersionremoved as inputs everywhere. signal_*_by_traderno longer takes pool filters — pool-filter axis is exclusive to_by_filtersiblings, seedocs/designs/smartmoney.md§13.- Trader-side
instCcy→instIdon_trader_positions/_positions_history/_orders_history: accepts fullinstIdor bare base ccy; handler extracts base. - Signal pool-filter
period(3/7/30/90, default 7) now exposed on every signal-side tool (previously leaderboard only). lmtNummax 500 → 2000 on signal-overview tools.
- Leaderboard fields renamed (everywhere):
winRatio→winRate,maxRetreat→maxDrawdown,dataVersion→updateTime(leaderboard-only; signal items keepdataVersionat bucket level). - Signal-overview reshaped to nested groups per OpenAPI
/overviewspec — outerccyplusnotional/longShortRatio/winRateobjects. Old flat fields (vs1h/vs24h/vs7d, top-levellongNotionalUsdt, etc.) removed. - Added
direction(derived"long" | "short"fromposSide+ sign ofpos) andupl(unrealized PnL, quote ccy) on_trader_positions. - Removed
topNUsed,currentPrice,priceChange24h,fundingRate,openInterest,longShortAccountRatio,tsfrom signal/overview output.
- MCP tool annotations (
readOnlyHint/idempotentHint/openWorldHint) on every tool. - Actionable error messages replace opaque
sCodestrings.
// Multi-coin overview — instCcyList still works; no time input
smartmoney_get_signal_overview_by_filter({ instCcyList: ["BTC", "ETH"] })
// Single-coin signal-history → signal-trend; asOfTime is optional
smartmoney_get_signal_trend_by_filter({ instCcy: "BTC", granularity: "1h", limit: 24 })
// trader_detail composite removed → fan out 3 atomic calls in parallel
Promise.all([
smartmoney_get_performance_by_trader({ authorIds: ["X"] }),
smartmoney_get_trader_positions({ authorId: "X" }),
smartmoney_get_trader_orders_history({ authorId: "X", limit: 50 }),
])- Windows support for OAuth token retrieval (
packages/core/src/auth/binary.ts).execAuthToken()now dispatches onprocess.platform: Unix keeps the existing fd-3 channel, while Windows creates a per-invocation named pipe\\.\pipe\okx-auth-<256-bit-random>, listens on it, and passes the name to the child via theOKX_AUTH_TOKEN_PIPEenvironment variable. Theokx-authRust binary opens that pipe withCreateFileW(FILE_GENERIC_WRITE, OPEN_EXISTING), writes the access token, and closes — signalling EOF to the parent. The pipe name is enforced to start with\\.\pipe\okx-auth-(the binary rejects arbitrary targets), andOKX_AUTH_TOKEN_PIPEis scrubbed by the child after read so it never leaks to grandchildren. Both platforms share the same exit-code → typed-error mapping (finalizeTokenhelper), so error messages are identical regardless of OS. Windows users can now complete the fullokx auth login→ token-backed REST flow end-to-end; previously the binary spawned successfully but the consumer's fd-3 read found nothing because Windows doesn't inherit POSIX file descriptors. The new code path is covered on POSIX hosts via UNIX-domain-socket substitution (net.createServerabstracts the transport), so CI does not require a Windows runner.
-
event_browseconcurrency cap (packages/core/src/tools/event-trade.ts,event-helpers.ts): replaced unboundedPromise.allwith a semaphore-basedwithConcurrencyhelper capped atMAX_CONCURRENT_MARKET_FETCHES = 8concurrent market-fetch requests (rate limit window is 20 req; 12 requests kept as buffer for retries and other calls in the same window:20 - 12 = 8). Also switched fromPromise.alltoPromise.allSettledsemantics so a single failing series fetch no longer aborts the entire browse — series with no active contracts are silently skipped and all successful series are still returned. Closes #146. -
cmdAuthRemoveerror handling (packages/cli/src/commands/auth.ts): the existing try/catch aroundremoveAuthBinary()now has test coverage. Added two unit tests topackages/cli/test/auth.test.tsthat verify whenremoveAuthBinary()throws (e.g. permission denied / EACCES): (a)errorLineis called with the error message in text mode, (b) JSON output{status:"failed", error:<msg>}is produced in json mode, and (c)process.exitCodeis set to1in both cases with no rethrow to the caller. Closes #159. -
Layered Architecture diagram (
ARCHITECTURE.md,ARCHITECTURE.zh-CN.md): replaced the single-path waterfall diagram that incorrectly labeledpackages/mcp/src/index.tsas "CLI entry" with a two-binary diagram showingokx-trade-mcpandokxas independent binaries that both import from@agent-tradekit/core(shared SDK). Closes #185. -
docs/faq.md— API key storage answer: added a clarifying sentence that the CLI (okx) and the MCP server (okx-trade-mcp) each read~/.okx/config.tomlindependently with no dependency between them.
-
linux-arm64hosts now use native arm64 pilot binary (packages/core/src/pilot/installer.tsPLATFORM_MAP+scripts/postinstall-notice.js). The previouslinux-arm64 → linux-x64fallback (introduced as a stop-gap when no native binary was on CDN) downloaded the x64 binary and ran it via qemu/binfmt emulation. The native arm64 binary has been published at/upgradeapp/tools/pilot/linux-arm64/okx-pilot(verified 2026-04-29); routing to it directly removes the emulation overhead — faster startup, lower CPU. -
context-kg/mapping sections refreshed for 06/07/08 (context-kg/business/06-leaderboard-smartmoney-api.md,07-dcd-api.md,08-dca-api.md): The "Mapping to …" sections in all three docs have been rewritten to reflect the as-shipped tool surface.06now lists the 5 shippedsmartmoney_*tools (replacing the pre-implementation 7-toolmarket_*proposal) with a note thatfeat/smartmoney-fixis in flight for a further redesign.07now lists the 6 flatdcd_*tools with an explanation of the deliberate quote→trade and redeem-quote→redeem bundling decisions.08now lists the 5 unifieddca_*tools that key offalgoOrdType: spot_dca | contract_dca, plus a new "Backlog (not yet wrapped)" subsection listing the 10 V2-only upstream API paths not yet implemented. Closes #187.
skills/okx-cex-auth/SKILL.md— strict display templates + wait-for-signal flow:- Login initiation: upgraded from "example reply format" to strict CN/EN templates with four mandatory fields (
site,verificationUri,userCode,expiresIn). Template wording is now normative — agents must not abbreviate, reword, reorder, or translate. - Polling removed: agents no longer auto-poll
okx auth status --jsonevery 5–10 s. They now wait for the user to signal completion (e.g. "done", "好了"), then runauth status --jsononce to verify. - Login success display: restricted to
site+scopesonly. Explicit negative list forbids surfacingexpiresAt/ttl(these are access-token TTL, not OAuth session lifetime — tokens auto-refresh transparently) andprofile(internal routing field). If asked about session longevity, agents must use the fixed phrase "Session stays active as long as you use the CLI periodically." and never quote a number. - Cross-section consistency: Step 0.3 table and Login Status Check table updated to reference the new strict templates and wait-for-signal semantics.
- Login initiation: upgraded from "example reply format" to strict CN/EN templates with four mandatory fields (
eval/probes/infrastructure + CI gateeval-probe-check(MR !303). Every new/modified MCP tool now requires a probe ateval/probes/<module>/tier2-<tool_name>.live.test.ts; the CI job isallow_failure: falseand runs on every merge_request_event. Probes use trace-based assertions (findToolCall(trace, { commandPatterns })) on the agent'stool_useblocks parsed fromanthropic-payload.jsonl— they verify the LLM picked the rightokx <module> <subcommand>with the right parameters, regardless of upstream API auth result. Module coverage to date: 12/17 modules (28 contributor probes covering market, spot, swap, futures, option, account, event, news, smartmoney, skills, bot.{grid,dca}, earn.{savings,onchain,dcd,flash}). Deferred:earn.autoearn(placeholder dir only),earn.fixed(no dir yet). Seeeval/README.mdfor the probe skeleton + CLI command pattern recipe table.- Phase 3b CLI power-user flag —
--tpLevel(multi-value, repeatable) (issue #183, CLI power-user flag — no MCP / skill exposure). Enables true multi-tier take-profit on a single order, replacing the manual workaround of placing a second algo order after entry. Pass--tpLevelmultiple times, each with a comma-separatedkey:valuemini-DSL string (e.g.--tpLevel "px:78000,sz:0.5,kind:limit" --tpLevel "px:81000,sz:0.5,kind:limit"). Valid keys:px(tpOrdPx),sz,kind(tpOrdKind),triggerPx(tpTriggerPx),triggerPxType,amendPxOnTrigger,clOrdId. Applies tookx {swap,spot,futures} placeandokx {swap,spot,futures} algo place. Conflict detection: passing both--tpLeveland--tpTriggerPx/--tpOrdPxraises a CLI-layer error. Backward compat: not passing--tpLevelproduces identical wire payload to Phase 3a+c. MCP toolinputSchema.propertiesis unchanged — this flag is not discoverable via MCP tool descriptions or skill workflows, intentionally limiting autonomous agent use. - Phase 3a+c CLI power-user flags —
--tpTriggerRatio,--slTriggerRatio,--closeFraction,--tradeQuoteCcy,--banAmend,--pxAmendType(issue #182, CLI power-user flags — no MCP / skill exposure). Six new optional CLI flags for advanced quant users.--tpTriggerRatio/--slTriggerRatio: ratio-based TP/SL triggers (percentage from entry price) for algo place orders across swap/spot/futures.--closeFraction: partial-position close fraction for conditional/oco algo orders (mutually exclusive with--sz; OKX server enforces, returns 51000 on conflict — no CLI-side validation).--tradeQuoteCcy: select quote currency for SPOT place orders (e.g. USDT|USDC|BTC).--banAmend: disable OKX auto-amend on SPOT market orders.--pxAmendType: disable OKX auto-correction on out-of-range prices ("0"=allow auto-correct, "1"=reject). All flags are optional with no defaults; not passing them produces identical wire payload as Phase 2. MCP toolinputSchema.propertiesis unchanged — these flags are not discoverable via MCP tool descriptions or skill workflows, intentionally limiting autonomous agent use. - Phase 2 algo ordTypes —
trigger,chase,iceberg,twap(issue #181). Four newordTypevalues onokx {swap,spot,futures} algo place, closing the remaining OKX OpenAPI v5 enum gap.trigger: submit a pending order that activates when the market reaches--triggerPx(provide--triggerPx+--orderPx).chase: smart-follow best bid/ask within configurable distance/ratio bounds (--chaseType,--chaseVal,--maxChaseType,--maxChaseVal).iceberg: split a large order into child orders at fixed intervals (--szLimit,--pxLimit,--timeInterval,--pxVar/--pxSpread).twap: time-weighted average price split using the same parameter set asiceberg. Backward compat: existingconditional/oco/move_order_stopinvocations produce identical wire payloads. Token budget delta: ~+600 tokens across 3 tools (4 new ordTypes × ~5 new fields each). - Phase 1 algo order flags —
--tpOrdKind,--tpTriggerPxType,--slTriggerPxType,--stpMode,--cxlOnClosePos(issue #178). Five new optional flags for trade order placement, closing the highest-ROI subset of the CLI/MCP↔OKX OpenAPI drift.--tpOrdKind limitplaces an immediate limit TP order (no trigger phase).--tpTriggerPxType/--slTriggerPxTypecontrol the TP/SL trigger price source (last/index/mark).--stpModeenables self-trade prevention (cancel_maker/cancel_taker/cancel_both).--cxlOnClosePosauto-cancels algo orders when the associated position closes. All flags are optional; not passing them yields identical wire payload as before. Applies to:okx {swap,spot,futures,option} place,okx {swap,futures} algo place,okx spot algo place.
suggestSubcommandno longer hallucinate non-existent subcommand paths (issue #179). Previously, thex-y → y xheuristic inpackages/cli/src/unknown-command.tswould suggest"<b> <a>"wheneverbappeared in the module'sknownActionslist, without verifying that the combined path actually exists. For example,okx swap set-leveragesuggestedokx swap leverage set, which is not a registered subcommand. Fix:suggestSubcommandnow accepts aknownPaths: readonly string[]parameter and only returns the suggestion when the combined path is explicitly listed. The legitimateplace-algo → algo placepositive case (#173) is preserved — callers pass["algo place", "algo cancel", ...]asknownPaths. Modules without multi-token subcommand paths default to[], suppressing spurious suggestions entirely.- Codex CLI blocked from loading
okx-cex-tradeskill — description field exceeded the 1024-char Codex limit (was 1448 chars). Trimmed by deduping synonymous trigger phrases; all concrete trade-type triggers preserved. Pre-emptively trimmedokx-sentiment-tracker(944 → 652 chars) andokx-cex-market(887 → 706 chars) for headroom. Added CI testpackages/cli/test/skill-description-length.test.tsto enforce the 1024-char ceiling going forward.
- OAuth Bearer token authentication (
okx auth): New authentication method via theokx-authRust binary. Supports OAuth 2.1 device flow —okx auth logininitiates browser-based login,okx auth statusshows session state,okx auth logoutrevokes tokens. The binary handles token storage, refresh (300 s TTL lead), and scrypt + AES-256-GCM encryption. Tokens are read via fd3 pipe at request time with a 60 s JS-side cache. Auth mode is selected dynamically per request: API key HMAC (if configured) takes priority; OAuth Bearer token is used as fallback. okx auth install/install-status/removeCLI commands: Manage theokx-authbinary installation. CDN download with checksum verification, atomic replacement, and multi-source fallback — mirrors the DoH installer pattern.skills/okx-cex-auth/SKILL.md: New skill documentation for OAuth authentication workflows.postinstallauto-download for okx-auth binary: Best-effort download alongside the existing DoH binary duringnpm install.context-kg/knowledge base: Addedtechnical/06-oauth-authentication.mdcovering OAuth subsystem architecture, binary distribution, fd3 token retrieval, auth priority, and CLI commands.
loadConfig()is now async (returnsPromise<OkxConfig>): Startup now callsexecAuthStatus()to detect OAuth login state.OkxConfigrequiresprofilefield: Resolved profile name is now included for OAuth token storage path resolution.OkxRestClient.buildHeaders()is now async: Supports dynamic auth method selection (API key HMAC or OAuth Bearer token) at request time.PLATFORM_MAP["linux-arm64"]now maps tolinux-x64(packages/core/src/pilot/installer.ts). This matches the standard Docker Desktop test environment on Apple Silicon, where containers run underlinux/amd64emulation. Nativelinux-arm64hosts will therefore install thelinux-x64binary and rely on the host's binfmt / emulation layer. This is a deliberate alias, not a regression of the issue #166 fix — the entry is still present, just pointing at the x64 directory. A nativelinux-arm64CDN directory is tracked as future work.
-
okx auth loginnow refuses to start OAuth when API-key credentials are already configured. Previously,cmdAuthLoginalways spawned theokx-authbinary regardless of~/.okx/config.tomlstate. An agent following older guidance could start an OAuth device flow on a machine whose API-key profile was already good, producing a confusing login prompt and a URL/code the user did not need.cmdAuthLoginnow callsreadFullConfig()first: if any profile has a non-emptyapi_key, it prints"API key already configured (profile: <name>). OAuth login skipped — API key will be used automatically."and returns exit 0 without spawning the binary. In--manualmode the same outcome is encoded as JSON{"status":"skipped","reason":"api_key_configured","profile":"<name>","message":"..."}so agents can detect it programmatically. This belt-and-suspenders with the REST client's existing API-key preference (rest-client.ts applyAuth— API key is checked first and never falls back to OAuth). -
skills/okx-cex-auth/SKILL.mdpre-flight decision tree rewritten to match the three-step flow: (1) check whether anysitehas been selected (union ofconfig show --jsonprofiles andauth status --json), and if not, present the site menu in chat verbatim before any login attempt; (2) checkapi_key— stop if present; (3) only then proceed to OAuth with the chosen--site. Previously the tree offered "First-Time Setup or Login Flow" as interchangeable paths for the "no credential" case, which let the model skip site selection and fall back to the OAuth binary's default (global). Also corrected the false claim thatokx config init"handles site selection and OAuth login in one flow" —cmdConfigInitis an API-key wizard (site + demo/live + AK/SK/PP) and never performs OAuth. A new Step 0.2.a section was added for the invalid-API-key case: when an API-key profile exists but the API call returns401 Unauthorized/Invalid Sign, OAuth login is not a valid remediation (the REST client still prefers the broken API key; any OAuth token obtained afterwards would go unused). The agent must present exactly two neutral options — replace the API key, or remove the broken profile before starting OAuth — and let the user choose. This prevents the Haiku 4.5 failure mode observed in openclaw where the agent silently labelled OAuth as "recommended" even though OAuth could not have worked without first clearing the broken profile. -
skills/_shared/preflight.mdandskills/okx-cex-portfolio/SKILL.mdauth-method detection corrected. Both files previously used theapiKeyfield fromokx auth status --jsonto branch between API-key and OAuth mode. That field reports theokx-authbinary's internal state and is alwaysfalseregardless of whether~/.okx/config.tomlcontains an API-key profile; it cannot detect API-key users. Consequence: an agent following the old preflight would seeapiKey: false, status: not_logged_in, conclude "no auth", and route the user into the OAuth login skill — even when a valid API-key profile already existed. Both files now require running bothokx config show --json(authoritative for API-key presence) andokx auth status --json(authoritative for OAuth session state), with a decision table that checks API-key first and never relies on the unreliableapiKeystatus field. -
skills/okx-cex-trade/SKILL.md,skills/okx-cex-bot/SKILL.md,skills/okx-cex-earn/SKILL.mdStep A auth detection corrected. Same class of bug as the preflight/portfolio fix above: the three skills' credential checks branched onauth status --json→apiKey(alwaysfalse), so API-key users were misrouted into the OAuth login skill. Step A now runs bothokx config show --jsonandokx auth status --json, checks API-key presence first, and only falls through to OAuth when no API-key profile is configured.
event_get_orders/event_get_fillsreturning empty arrays — root cause: for EVENTS instType,/api/v5/trade/fills(3-day window) often returns empty while/api/v5/trade/fills-history(3-month) contains the data. The wrapper lackedarchivemode and other query parameters. Addedarchivemode for fills,status(open/history/archive) routing for orders, time-range filters (begin/end), cursor pagination (after/before), andordIdfilter. Also confirmed thatinstFamilyis NOT supported for EVENTS on trade endpoints (causes HTTP 400). Response now includesrequestParamsfor debugging.
smartmoneydescription cleanup. MCP / CLI / skill now consistently use "instId takes precedence if both set". Pool-filter descriptions keep enums / defaults / key semantics (PNL_TOP20= top 20 %,period= win-rate window only) but drop verbose prose; tool descriptions now state ts-or-dataVersion requirement up front. Docs only, no runtime change.
-
smartmoney signal/smartmoney_get_signal: document--instIdas recommended;--instCcymay return empty. The/api/v5/journal/smartmoney/signalendpoint acceptsinstCcyper spec but in practice may returndata: []even when the sameinstCcyworks on/overview. Tool description, CLI reference, and API doc now steer callers to--instId(e.g.BTC-USDT-SWAP) for reliable single-currency signals. No code change —instCcyis still passed through. -
okx dohcommand replaced byokx pilot(issue #169). ThedohCLI module is removed and replaced bypilot(okx pilot status/install/remove). Runningokx dohwill now report an unknown command. -
CDN path unified: both
installer.tsandpostinstall-notice.jsnow use/upgradeapp/tools/pilot(issue #169). Previously the two files were out of sync —installer.tsused/upgradeapp/dohwhilepostinstall-notice.jswas already at/upgradeapp/tools/doh. Both now converge on/upgradeapp/tools/pilot. The old paths are no longer valid.
-
OKX_DOH_BINARY_PATHenvironment variable renamed toOKX_PILOT_BINARY_PATH. No backward-compatible shim is provided. Update any scripts or shell profiles that set this variable. -
OKX_DOH_CACHE_PATHenvironment variable renamed toOKX_PILOT_CACHE_PATH. No backward-compatible shim is provided. Update any scripts or shell profiles that set this variable. -
Cache file
~/.okx/doh-cache.jsonreplaced by~/.okx/pilot-cache.json. The old file is now obsolete and can be safely deleted (rm ~/.okx/doh-cache.json). The new cache will be populated automatically on the next request. -
okx dohcommand removed, replaced byokx pilot. All three subcommands are available asokx pilot status,okx pilot install,okx pilot remove.
-
okx market oi-historytable rendering fixed — no longer prints "No OI data" when data exists. The API returnsdataas an array[{ instId, bar, rows: [...] }], but the CLI was accessingdata["rows"]directly on the array, which yieldedundefinedand always fell into the empty-data branch. The handler now unwrapsdata[0]before readingrows/instId/bar.--jsonmode was unaffected and keeps its current output. Unit tests updated to mirror the real array-wrapped API shape so this class of bug cannot recur silently. -
linux-arm64platform now included in Pilot binary installer (issue #166).getPlatformDir()was missing an entry for"linux-arm64", causing install/update to fall back toundefinedand write the binary to the wrong path on ARM64 Linux hosts. The entry"linux-arm64": "linux-arm64"is now present. -
Pilot proxy re-resolution is now
await-ed before continuing on network failure (issue #166). Two call sites inrest-client.tsinvokedhandleNetworkFailure()as fire-and-forget (handleNetworkFailure().catch(() => {})), meaning the cache write and proxy state update could race with the retry request. Both sites now usetry { await this.pilot.handleNetworkFailure(); } catch {}, ensuring the proxy node is fully resolved and the cache is persisted before the retry is issued. -
marketdispatcher:orderbook,candles,trades,funding-rateno longer emit spuriousUnknown market commanderror and exit 1 (issue #175, regression introduced by commit9fd4717on 2026-04-14). ThehandleMarketFilterCommandrefactor in that commit left anerrorLine + exitCode=1block at its tail. BecausehandleMarketPublicCommandunconditionally tail-callshandleMarketFilterCommandas its fallback, the error fired beforehandleMarketDataCommandhad a chance to dispatch the action — all four subcommands produced correct JSON on stdout but also wrote an error to stderr and exited 1, causingset -escripts to hard-fail even though the underlying API call succeeded. Fix: removed the side-effect block fromhandleMarketFilterCommand(it now returnsundefinedsilently on no match, consistent with every other sub-handler), and addedunknownSubcommand("market", action, [...])inhandleMarketCommandafter both sub-dispatchers returnundefined— the same pattern used byswap,spot,futures,option,account, andbotpost-#173. Truly unknown market actions (e.g.okx market foo) continue to error with the structured diagnostic fromunknownSubcommand()and exit 1. -
account_get_asset_balancetotal asset valuation now defaults to USDT denomination (issue #174). Previously,showValuation=truecalled/api/v5/asset/asset-valuationwith noccyparameter, causing OKX to default to BTC — a user with $3,834 in assets would see0.049instead of3834. A newvaluationCcyparameter (default"USDT") is now passed to the valuation endpoint. Callers can override to any OKX-supported currency (e.g.valuationCcy="BTC"). The chosen denomination is stamped asvaluationCcyin the returned JSON. CLI:okx account asset-balance --valuationnow shows USDT-denominated totals by default; use--valuationCcy BTCfor BTC-denominated totals. -
CLI no longer silently exits 0 on unknown subcommands (issue #173). Previously, every second-level module dispatcher (
swap,spot,futures,option,account,bot) fell through toreturn undefinedwhen the action name didn't match any registered branch, producing an invisible failure —okx swap place-algowould exit 0 with no output, misleading scripts with&& echo OKand masking the real problem. Each dispatcher now calls the sharedunknownSubcommand()helper which emitsUnknown command: okx <mod> <action>to stderr, lists the available subcommands, suggests an MCP-name-to-CLI rewrite when applicable (place-algo→algo place), and sets a non-zero exit code. Reported via CS Telegram 2026-04-21 — customer'sokx --profile demo swap place-algo ...returned silently, leaving them unable to tell whether the feature was broken or the command wrong. -
skills/okx-cex-trade/reference docs now call out the CLI↔MCP naming mismatch.SKILL.mdhas a top-level note;references/swap-commands.mdhas a dedicated "Naming — CLI vs MCP tool" table mapping each tool identifier to its CLI subcommand path. Motivated by the same #173 report: customers seeswap_place_algo_orderin MCP tool listings and guess the CLI form isswap place-algo, which silently failed pre-fix and now errors explicitly.
-
spot_set_leverageMCP tool andokx spot leverageCLI command: Set the leverage ratio for a spot margin or cross-margin instrument. Accepts--instId(instrument-level) or--ccy(currency-level) alongside--leverand--mgnMode. Input is validated before the HTTP call — non-numeric, zero, or negativelevervalues are rejected immediately with an actionable error. Supports all 5 OKX leverage scenarios for SPOT/MARGIN. -
Smart Money module (
smartmoney): 5 new read-only MCP tools (smartmoney_get_overview,smartmoney_get_signal,smartmoney_get_signal_history,smartmoney_get_traders,smartmoney_get_trader_detail) and corresponding CLI commands for accessing trader leaderboard, position analysis, and smart money signals. -
context-kg/upstream API specs: Three new business-domain reference docs undercontext-kg/business/capturing upstream OKX API contracts consumed by the repo —06-leaderboard-smartmoney-api.md(7 leaderboard / smart-money endpoints backing issue #94, with live-probe status and field-drift notes),07-dcd-api.md(8 DCD structured-product endpoints with state machine and error codes),08-dca-api.md(19 Spot/Contract DCA bot endpoints with sync-copy restrictions). Intended as the source of truth for cross-checking tool design, request/response shapes, and enum values during implementation. -
grid_amend_orderMCP tool andokx bot grid amendCLI command — Amend a running grid bot without stopping it. Supports three modes combinable in a single call: price-range mode (maxPx+minPx+gridNum) to adjust the upper/lower boundary and grid count; TP/SL mode (instId+ any oftpTriggerPx/slTriggerPx/tpRatio/slRatio) to set or clear take-profit/stop-loss; and combined mode for both at once. Pass"-1"to explicitly clear an existing TP or SL. CLI:okx bot grid amend --algoId <id> [--maxPx ..] [--minPx ..] [--gridNum ..] [--instId ..] [--tpTriggerPx ..] [--slTriggerPx ..].
grid_stop_orderMCP tool:stopTypevalues"3","5", and"6"explicitly removed (ALGO-37613) — These values are no longer valid for grid bot stop operations and must not be used. The valid set is now["1","2"]only:"1"closes all positions immediately (default clean exit),"2"stops the strategy without selling. Callers passing"3","5", or"6"will fail schema validation. Migration: replace any usage of"3"/"5"/"6"with"1"(immediate close) or"2"(keep positions) based on the desired exit behaviour.
swap_set_leverage/futures_set_leverageinput validation: Invalidlevervalues (non-numeric, zero, negative) are now rejected before the HTTP call with a clear error message instead of surfacing an opaque OKX 51xxx error.mgnModeandposSideare validated against allowed enums. Thecross+long/shortcombination is explicitly blocked with the hint "posSide only valid with isolated margin mode", matching OKX's business rule and reducing the ~9.7% failure rate from callers sending invalid combinations. Tool descriptions are rewritten to enumerate the three applicable SWAP/FUTURES scenarios (cross index-level / isolated one-way / isolated hedge) and explicitly flag portfolio-margin cross as unsupported.
-
Smart Money signal API paths changed:
/api/v5/journal/public/smartmoney/*→/api/v5/journal/smartmoney/*to align with upstream OKX endpoint (4.1 signal, 4.2 signal-history, 4.3 overview). -
Removed demo-mode guard from Smart Money module — all 5 tools now work in both live and simulated trading mode. Previously they threw
ConfigErrorin demo mode. -
News CLI
--importancedefault switched tolowforokx news latest,okx news by-coin, andokx news search. Previously these commands forwardedundefinedto the server, which applies itshigh-only default and silently narrowed results. They now default tolow(returns all news, both high and low importance) for broader browsing. Pass--importance highexplicitly — or use the dedicatedokx news importantcommand — when you only want breaking / major news. MCPnews_get_latest/news_get_by_coin/news_searchtool descriptions updated to reflect the same semantics so AI agents picklowfor broad queries andhighonly when the user explicitly asks for major news. -
News skill: time-window handling for
--platformqueries. The API's default--beginwindow is 72 hours, too narrow for bursty news sources and a frequent cause of empty results.okx-sentiment-trackerSource-Filtered News and Empty Results fallback sections now instruct agents to broaden--beginto 7 then 30 days before concluding a source has no data. The Known Limitations "Source Coverage" table that hardcoded per-platform activity labels was removed — those labels were based on the narrow 72-hour assumption and could mislead agents into giving up prematurely. Replaced with a generic rule that platform cadence is uneven and candidates should be resolved fromokx news platformsrather than assumed.
-
newsmodule (restored): Orbit News API integration is back following compliance approval. Seven tools cover latest news, coin-specific news, search, article detail, platform listing, coin sentiment, and sentiment rankings. CLI:okx news latest / by-coin / search / detail / platforms / sentiment / sentiment-ranking. Supports--platformto filter by source (e.g.blockbeats,odaily_flash).Accept-Languageuses standard IETF BCP 47 format. All news tools return a clearConfigErrorin demo/simulated trading mode. (!251, !249, !235) -
Event contract module (
event): New binary prediction-markets module with 9 MCP tools and matching CLI commands — browse open events, query contract details, place and manage event-contract orders. (!216) -
Flash Earn module (
earn.flash): New instant-earn tools for flash-earn deposit and redemption operations. (!246) -
Three new market tools —
market_filter(screen instruments by multi-dimensional criteria),market_get_oi_history(open interest history), andmarket_get_oi_change_filter(filter by OI change magnitude). CLI:okx market filter / oi-history / oi-change-filter. (!245) -
Auto-generated CLI help from ToolSpec registry and
okx list-tools: CLI help is now derived from a declarativeCLI_REGISTRYsourced from ToolSpec objects in@agent-tradekit/core, keeping help text in sync with the MCP tool registry. A newokx list-tools [--json]command serializes the full registry into structured JSON for AI agent self-discovery. (!234) -
okx dohbinary management commands:okx doh statusreports binary path, size, SHA-256, and CDN match;okx doh installdownloads or updates the binary;okx doh removedeletes it (with confirmation or--force). DoH resolver status is also surfaced inokx --versionandokx diagnose. (!232) -
DoH (DNS-over-HTTPS) proxy for API requests: When the OKX API domain is unreachable (e.g. DNS poisoning), the SDK transparently resolves an alternative proxy node via a local
okx-doh-resolverbinary, with cache-first strategy and automatic failed-node exclusion.postinstalldownloads the platform binary to~/.okx/bin/; supports darwin-arm64, darwin-x64, linux-x64, linux-arm64, and win32-x64. (!230, !237) -
context-kg/agent knowledge base with accuracy drift test: Structured knowledge files for AI agents covering trading, market/account, earn/bot, errors, multi-site architecture, DoH proxy,tgtCcy=marginusage, and test quality rules. Automated drift test validates declared counts match actual code state at CI time. (#137, #160, !231, !238, !248)
-
Error code remediation hints now match OKX official API error reference: Custom suggestions replaced by verbatim text from OKX's official API error documentation. (#163, !250)
-
CLI
list-toolsrouting fix:okx list-toolsno longer falls through to "Unknown command" in the main router. (#161, !247) -
CLI help text: missing parameters audited and restored: All parameters identified as missing from CLI help output have been added back. (#155, !244)
-
market_list_indicators: improved descriptions and name validation: Indicator names are now validated; unknown names return a clear error instead of silently returning empty results. (#153, !243) -
market_get_funding_ratevalidates SWAPinstId: Non-SWAP instrument IDs are now rejected with a clear error before reaching the OKX API. (#152, !242) -
Market filter docs: SPOT queries require explicit
quoteCcy=USDT: Clarified in tool and CLI descriptions that SPOT market queries must includequoteCcy=USDTto avoid empty results. (!257) -
Skills language-neutral instructions: Removed hardcoded Chinese-language prompts from
SKILL.mdso agent behavior is consistent regardless of session locale. (!233) -
Skills: leverage error troubleshooting guidance: Added specific remediation steps for leverage-related errors plus a general safeguard requiring read-only diagnosis before any write-operation fix. (!229)
-
CLI miscellaneous fixes: Addressed cosmetic and behavioral issues flagged in code review. (#141, #142, #143, !236)
-
Skills download: two-step presigned URL flow:
skills_download(MCP) andokx skill download(CLI) now obtain a short-lived presigned URL before fetching the skill archive, improving download security and reliability. (!240) -
DoH resolver updated to v9: Binary updated with revised protocol and CDN endpoint list. (!255)
-
Skills docs: TP/SL amend workflow clarified: Skill documentation now guides users to
algo_amend_orderfor modifying TP/SL on existing algo orders, improving discoverability. (!241) -
CLI
okx news domainsrenamed tookx news platforms: Aligns CLI subcommand with the--platformparameter terminology. -
Skill renamed
okx-cex-news→okx-sentiment-tracker: Skill directory and frontmatter name updated. MCP tool names (news_*) and CLI commands (okx news) are unchanged.
importance=mediumenum value: Removed fromNEWS_IMPORTANCEvalidation. The OKX API does not supportmedium; passing it returned a parameter error (51000). Onlyhighandloware valid.
okx list-toolsrouting falls through to "Unknown command": Fixed command routing solist-toolsis correctly dispatched without falling through to the default unknown-command handler. (#161)
- Event Contract module: New
eventmodule with 9 MCP tools and CLI commands for binary prediction markets — browse series/events/markets, place/amend/cancel orders, query orders/fills, and direction analysis with index price enrichment. - DoH (DNS-over-HTTPS) proxy for REST API requests: Transparently resolves an alternative proxy node through a local
okx-pilotbinary when OKX API is unreachable via direct connection. Cache-first, zero overhead on cached paths. Supports--verboselogging. - Automatic DoH binary download on install:
postinstalldownloads the platform-specificokx-pilotbinary from CDN to~/.okx/bin/. Best-effort, never blocksnpm install. Supports darwin-arm64, darwin-x64, linux-x64, linux-arm64, and win32-x64. okx dohmanagement commands:okx doh status,okx doh install,okx doh removefor managing the DoH resolver binary. (#138)- DoH status in
okx --versionandokx diagnose: Version output shows DoH resolver install status;diagnosechecks binary existence and CDN checksum. (#138) - Auto-generated CLI help from ToolSpec registry: CLI help text generated from declarative
CLI_REGISTRYmap, sourced from ToolSpec objects in@agent-tradekit/core. Bidirectional drift test catches mismatches at test time. (#140) okx list-tools [--json]agent self-discovery command: Serializes the full CLI registry into structured JSON for programmatic enumeration of all capabilities, parameters, and tool names. (#140)- TP/SL amend discoverability:
{module}_amend_orderdescriptions route users to{module}_amend_algo_orderfor modifying attached TP/SL. Skillsworkflows.mdadds a "Modify existing TP/SL" scenario. (#151) - Market filter tools (
market): Three new MCP tools and CLI commands —market_filter/okx market filter(screen SPOT/SWAP/FUTURES by price, 24h change, market cap, volume, funding rate, OI with sort/limit support),market_get_oi_history/okx market oi-history(OI time-series with bar-over-bar delta),market_filter_oi_change/okx market oi-change(rank by OI change magnitude with filters). newsmodule restored: 7 MCP tools and CLI commands for crypto news querying —news_get_latest,news_get_by_coin,news_search,news_get_detail,news_get_domains,news_get_coin_sentiment. FixedAccept-Languageheader default.- Flash Earn module (
earn.flash): Newearn_get_flash_earn_projectsMCP tool andokx earn flash-earn projectsCLI command for browsing upcoming and in-progress Flash Earn opportunities. context-kg/knowledge base expanded: Added DoH subsystem doc,tgtCcy=margindocumentation, architecture updates, and full testing & QA specification. (#150)- Skills download two-step presign flow:
skills_download/okx skill downloadnow uses a presigned URL flow for more reliable binary downloads.
market_get_indicatorimproved descriptions and pre-call name validation: Descriptions now list common indicator names and link tomarket_list_indicators. Unknown names return aValidationErrorwith similar-name suggestions before any API call. (#153)market_filtermarketCapUsdis SPOT-only: Description clarified thatmarketCapUsdfilter only applies toinstType=SPOTper upstream API constraint.
- Event Contract endpoints use authenticated requests: All 4 event browse/query tools use
privateGet— OKX's/public/event-contract/*endpoints require auth headers. - Skill docs: error-suggested remediation safeguard: Agent must diagnose with read-only queries before acting on write-operation suggestions. MCP server returns
instructionssafeguard field. (#leverage) - CLI help missing params audit: Added missing parameters in
spot,swap,futuresCLI help entries. (#155) - Skills: remove hardcoded Chinese prompts: Replaced hardcoded Chinese disambiguation prompts in
SKILL.mdwith language-adaptive English instructions.
- DoH (DNS-over-HTTPS) proxy for REST API requests: When the OKX API domain is unreachable via direct connection (e.g. DNS poisoning), the SDK now transparently resolves an alternative proxy node through a local
okx-pilotbinary. Cache-first strategy: first request attempts direct connection; on network failure the binary is invoked and the result is cached. Subsequent requests reuse the cached node with zero overhead. Failed proxy nodes are automatically excluded and re-resolved. Supports--verboselogging for full DoH lifecycle visibility. - Automatic DoH binary download on install:
postinstallnow downloads the platform-specificokx-pilotbinary from CDN (with multi-source fallback) to~/.okx/bin/. Best-effort — never blocksnpm install. Supports darwin-arm64, darwin-x64, linux-x64, and win32-x64. context-kg/knowledge base: Bootstrap structured knowledge files for AI agents — 5 business domain docs (overview, trading, market/account, earn/bot, skills) + 4 technical docs (architecture, configuration, errors, multi-site) + quality placeholder. Includesconfig.toml.exampleknowledge_dirconfig entry. (#137)
- Skill docs: error-suggested remediation safeguard — Added a general safeguard rule: when an OKX API error suggests a fix involving write operations (cancel orders, close positions, stop bots), the agent must diagnose with read-only queries first and wait for user confirmation before acting. Also added specific leverage error troubleshooting guidance. Affected files:
swap-commands.md,futures-commands.md,workflows.md,SKILL.md. - MCP server: remediation safeguard — MCP server now returns
instructionsfield with safeguard rule; error responses whose message suggests write-operation remediation (cancel/close/stop) are automatically annotated with a warning to diagnose first and confirm with the user.
- Event Contract module: New
eventmodule with 9 MCP tools and CLI commands for binary prediction markets — browse series/events/markets, place/amend/cancel orders, query orders/fills, and direction analysis with index price enrichment.
- Event Contract endpoints use authenticated requests: All 4 event browse/query tools (
event_browse_contracts,event_get_series,event_get_events,event_get_markets) now useprivateGetinstead ofpublicGet. OKX's/api/v5/public/event-contract/*endpoints require auth headers despite the/public/path prefix; unauthenticated calls returned 401.
market_list_indicatorsMCP tool andokx market indicator listCLI command: Browse all supported OKX market indicators grouped by category, with range-filter support (--fearGreedIndexMin/Max,--longShortRatioMin/Max, etc.) for AI-driven sentiment screening. (#124)- Market tools
demoparameter: All market MCP tools now accept an optionaldemo: booleanparameter; CLI market commands respect the global--demoflag. Enables explicit querying of simulated-trading market data independently of the server's demo mode. - Simple Earn Fixed (定期赚币) tools (
earn.savings): Three new tools —earn_get_fixed_order_list,earn_fixed_purchase(two-step: preview then confirm),earn_fixed_redeem.earn_get_lending_rate_historynow also returns fixed-term offers with APR, term, min amount, and remaining quota. CLI:okx earn savings fixed-orders/fixed-purchase/fixed-redeem. - Margin-cost order mode (
tgtCcy=margin): SWAP, FUTURES, and options place/algo order tools now accepttgtCcy=margin, whereszrepresents the USDT margin cost. The system automatically queries current leverage and converts to contract count (contracts = floor(margin × lever / (ctVal × lastPx))). (#128) - CLI audit logging: CLI writes audit logs to
~/.okx/logs/trade-YYYY-MM-DD.logfor all tool executions, matching MCP server behavior.okx account audit-lognow works for CLI users. (#129) skills_downloadformatparameter: Accepts"zip"or"skill". MCP defaults to"skill"(agent-friendly extension), CLI defaults to"zip"(backward-compatible). File content is identical.
- CLI table output shows environment header: Table output now displays an
Environment: live/Environment: demo (simulated trading)header line. earn_get_lending_rate_historyfetches fixed-term offers: Makes an additional best-effortprivateGetcall; falls back gracefully (emptyfixedOffers) when no API key is configured.earn_get_lending_rate_historydefault limit reduced from 100 to 7: Reduces token usage in agent conversations.
- Indicator range-filter code mapping: Corrected internal code mappings and removed unsupported indicator types, preventing silent empty results.
- Skills docs indicator sync: Updated all indicator descriptions and examples to match live backend schema and new CLI commands.
- Skills docs account transfer type codes: Corrected
6=funding /18=trading in portfolio and earn docs — previously reversed. (#126) tgtCcy=quote_ccyconversion usesminSz/lotSz: Rounds down tolotSzprecision and validates againstminSzinstead of assuming integer contracts, fixing false "too small" errors for instruments withminSz < 1(e.g. BTC-USDT-SWAP). (#127)- CLI
--jsonenv wrapper is now opt-in via--envflag:--jsonreturns raw data by default (backward-compatible). Use--json --envfor the{env, profile, data}wrapper. (#131) - Unknown
tgtCcyvalues throwValidationError: Onlybase_ccy,quote_ccy, andmarginare accepted; other values throw with a helpful suggestion instead of silently passing through. (#133) --verboseflag now affects CLI audit log output: Verbose mode writes adebug-level entry with full request args and response; non-verbose records a compact summary only. (#130)- Market data defaults to live regardless of server demo mode: Market tools explicitly override the server-level demo flag, always returning live data unless
demo: trueis passed explicitly.
- Skill download
formatparameter:skills_downloadMCP tool andokx skill downloadCLI command now accept aformatoption ("zip"or"skill"). MCP defaults to"skill"(so agents like Claude Desktop can auto-detect the file type), CLI defaults to"zip"(backward-compatible). The file content is identical — only the extension changes. - Market tools
demoparameter: All 14 market MCP tools now accept an optionaldemo: booleanparameter, and CLI market commands now respect the global--demoflag. Whendemo=true/--demo, the request targets OKX's simulated trading market data environment (x-simulated-trading: 1). When omitted orfalse(default), live market data is always returned — independent of whether the server is started with--demo.
- Market data defaults to live regardless of server demo mode: Previously, starting the server with
--democaused all market data requests to return simulated trading data. Now market tools explicitly passsimulatedTrading: falseby default, overriding the server-level demo flag. Users can passdemo: trueto explicitly query simulated market data. Other modules (trading, account, earn, indicators) are unaffected and continue to follow the server demo flag. - Unknown
tgtCcyvalues now throwValidationErrorinstead of silent passthrough: Previously, typos like--tgtCcy margin_ccyor--tgtCcy QUOTE_CCYwere silently ignored andszwas sent to the API unconverted. Now onlybase_ccy,quote_ccy, andmarginare accepted; any other value throws aValidationErrorwith a helpful suggestion. (#133) --verboseflag now affects CLI audit log output: Previously,TradeLoggerwas always constructed with"info"level and all success logs used"info", so--verbosehad no effect on log file content. Now, verbose mode sets log level to"debug"and writes an additional debug-level entry with full request args and response data for each successful tool call, while non-verbose mode only records a compact summary. (#130)
- DoH (DNS-over-HTTPS) proxy for REST API requests: When the OKX API domain is unreachable via direct connection (e.g. DNS poisoning), the SDK now transparently resolves an alternative proxy node through a local
okx-pilotbinary. Cache-first strategy: first request attempts direct connection; on network failure the binary is invoked and the result is cached. Subsequent requests reuse the cached node with zero overhead. Failed proxy nodes are automatically excluded and re-resolved. Supports--verboselogging for full DoH lifecycle visibility. - Automatic DoH binary download on install:
postinstallnow downloads the platform-specificokx-pilotbinary from CDN (with multi-source fallback) to~/.okx/bin/. Best-effort — never blocksnpm install. Supports darwin-arm64, darwin-x64, linux-x64, and win32-x64.
- Simple Earn Fixed (定期赚币) tools (
earn.savings): Three new tools —earn_get_fixed_order_list(query fixed-term orders by ccy/state),earn_fixed_purchase(two-step purchase: preview with offer details then confirm; funds locked until maturity),earn_fixed_redeem(redeem a fixed-term order).earn_get_lending_rate_historynow also returns available fixed-term offers with APR, term, min amount, and remaining quota. CLI:okx earn savings fixed-orders,okx earn savings fixed-purchase,okx earn savings fixed-redeem. - Margin-cost order mode (
tgtCcy=margin): Newmarginvalue fortgtCcyparameter on SWAP, FUTURES, and options place/algo order tools. WhentgtCcy=margin,szrepresents the USDT margin cost; the system automatically queries the current leverage and converts to the correct number of contracts (formula:contracts = floor(margin * lever / (ctVal * lastPx))). Existingquote_ccy(notional value) andbase_ccy(contracts) modes are unchanged. Skills confirmation templates now require explicit disambiguation when a user says "500U" — is it notional value or margin cost? (#128) - CLI audit logging: CLI now writes audit logs to
~/.okx/logs/trade-YYYY-MM-DD.logfor all tool executions, matching MCP server behavior.okx account audit-lognow works for CLI users. (#129)
earn_get_lending_rate_historynow fetches fixed-term offers via authenticated API (earn.savings): This tool now makes an additionalprivateGetcall to retrieve fixed-term product offers. The call is best-effort — if the user has no API key configured, the tool still returns flexible lending rate history as before, with an emptyfixedOffersarray.earn_get_lending_rate_historydefault limit reduced from 100 to 7 (earn.savings): Whenlimitis omitted, the tool now returns the 7 most recent records instead of 100, reducing token usage in agent conversations.
- CLI
--jsonenv wrapper is now opt-in via--envflag: Reverts the breaking change from 1.3.0-beta.1 where--jsonoutput was wrapped in{env, profile, data}. Now--jsonreturns raw data by default (backward compatible). Use--json --envto get the wrapper with environment metadata. Table output environment header is unaffected. (#131) tgtCcy=quote_ccyconversion: useminSz/lotSzinstead ofMath.floor: The USDT-to-contract conversion now rounds down tolotSzprecision and compares againstminSzfrom the instruments API, instead of assuming integer contracts. Fixes false "too small" errors for instruments whereminSz < 1(e.g. BTC-USDT-SWAP withminSz=0.01). (#127)
market_list_indicatorsMCP tool andokx market indicator listCLI command: List OKX market indicators with filtering by category, page, and limit. Supports range-filter flags (--fearGreedIndexMin/Max,--longShortRatioMin/Max, etc.) for AI-driven market sentiment screening. (#124)
- Indicator range-filter code mapping: Corrected internal code mappings for range-filter parameters and removed indicator types unsupported by the OKX API, preventing silent empty results.
- Skills docs indicator sync: Updated all indicator-related descriptions and example outputs in skills docs to match the live backend data schema and new CLI commands.
- Skills docs account transfer type codes swapped: Corrected
6=funding /18=trading in portfolio and earn skills documentation — previously written in reverse. (#126)
- CLI
--jsonoutput now includes environment metadata:--jsonoutput changed from raw OKX API response to{"env", "profile", "data"}wrapper. Scripts usingjq '.[0].field'must update tojq '.data[0].field'. Table output now displays an environment header line (Environment: live/Environment: demo (simulated trading)). (#207, closes #117)
- Skills Marketplace third-party disclaimer: Added notices at key trust-decision points (marketplace prompt, install/download descriptions, and CLI install flow) to make clear that listed skills are created by independent third-party developers before installation.
- SWAP/FUTURES/options
tgtCcy=quote_ccyauto-conversion: Order handlers now automatically convert quote-currency amounts (for example, USDT) into contract counts before sending SWAP, FUTURES, and options orders/algo orders to the OKX API, preventing oversized positions caused by treating quote amounts as raw contract size. (#114) dcd_subscribeyield threshold comparison:annualizedYieldis now converted from decimal to percent before comparing againstminAnnualizedYield, so threshold filtering works correctly and invalid yield values are rejected.- Skills docs
tgtCcywording: Clarified thattgtCcyis handled by an internal conversion layer rather than passed through directly to the OKX API, reducing sizing confusion in skills documentation. - CLI docs: negative values must use
=form: Updated all skill references (swap/futures/spot command docs, workflows, SKILL.md) to use--tpOrdPx=-1/--slOrdPx=-1instead of the space form, which NodeparseArgs()misinterprets as a flag. Added notes to parameter tables clarifying this requirement. (#123, closes #115)
- Skills Marketplace third-party disclaimer: Added notices at key trust-decision points (SKILL.md agent prompt,
skills_downloadtool description, CLI install output, and module docs) to inform users that skills are created by independent third-party developers before installation.
- SWAP/FUTURES/options
tgtCcy=quote_ccyauto-conversion: whentgtCcy=quote_ccyis set on SWAP, FUTURES, or options algo orders, the handler now automatically converts the USDT amount to contract count before sending to the OKX API — preventing silent position amplification where e.g. "100 USDT" became "100 contracts (~$6,700)". Conversion fetchesctValandlastPxin parallel and logs a_conversionnote in the response. (#114) dcd_subscribeyield threshold comparison: OKX API returnsannualizedYieldas a decimal fraction (e.g.0.18= 18%), butminAnnualizedYieldwas compared directly against the raw value, causing all yield threshold checks to fail. Now correctly multiplies by 100 before comparison. Also rejects withINVALID_YIELD_VALUEwhen the quote returns a non-numeric yield.- DCD tool descriptions: Added yield unit clarification (
annualizedYieldis decimal, not percent) todcd_get_products,dcd_get_orders, anddcd_subscribedescriptions to prevent LLM misinterpretation.
market_get_instruments_by_categoryMCP tool andokx market instruments-by-categoryCLI command: Discover tradeable instruments byinstCategory— Stock tokens (3), Metals (4), Commodities (5), Forex (6), Bonds (7). Supersedesmarket_get_stock_tokensfor category 3. (#109)- Skills Marketplace module (
skills): Browse, search, and install AI trading skills. Tools:skills_get_categories,skills_search,skills_download. CLI:okx skill search/categories/add/download/remove/check/list. Enabled by default. --liveflag: Forces live trading mode even when the active profile hasdemo=true. Mutually exclusive with--demo. (#108)- Three-channel auto-update (
okx upgrade): Supports stable, beta, and latest dist-tag channels with automatic skill version sync after upgrade. account_get_asset_balanceshowValuationparameter: Returns total asset valuation breakdown across all account types (trading, funding, earn, etc.). CLI:okx account asset-balance --valuation. (#102)market_get_candleshistorical endpoint auto-routing: Automatically routes to/market/history-candleswhenafter/beforetimestamps are older than 2 days. Thehistoryparameter has been removed; no manual switching required. (#101)okx-cex-tradeSKILL.md restructured with reference files: Extracted detailed CLI param tables intoreferences/spot-commands.md,references/swap-commands.md,references/futures-commands.md,references/options-commands.md,references/workflows.md,references/templates.mdfor lighter agent loading.
- Contract order placement requires
ctVallookup:swap_place_order,futures_place_order, andoption_place_ordernow mandate callingmarket_get_instrumentsfirst to retrievectVal(contract face value) before placing orders. (#113) account_get_configsettleCcy/settleCcyList: These USDS-contract-only fields are now preserved in the response with added description to avoid AI model misinterpretation.- Earn write tools blocked in demo mode: All earn write operations now return a clear
ConfigErrorin simulated trading mode instead of an opaque 500 error from OKX API. account_get_asset_balancezero balance display: Correctly shows0instead of "(no data)" when account balance is exactly 0.--no-demoflag correctly overrides profiledemo=true: Three-state resolution:--liveforces live,--demoforces demo, otherwise profile is consulted. (#108)okx upgradesecurity fixes: Resolvesnpmviaprocess.execPath(S4036), eliminates ReDoS hotspot (S5852), replacesexecSyncwithspawnSync(S4721).- Preflight drift check skipped for prerelease CLI: Avoids false-positive warnings when local CLI version contains a prerelease suffix.
market_get_stock_tokens: Replaced bymarket_get_instruments_by_categorywithinstCategory="3". Retained for backward compatibility; will be removed in a future major version.okx market stock-tokens: Replaced byokx market instruments-by-category --instCategory 3. Retained for backward compatibility; will be removed in a future major version.
newsmodule: Orbit News API integration removed pending regulatory compliance approval. Will be re-introduced once approval is obtained.
newsmodule removed pending compliance approval: The Orbit News API integration introduced in [1.2.8-beta.4] has been reverted. All news tools (news_get_latest,news_get_by_coin,news_search,news_get_detail,news_get_domains,news_get_coin_sentiment,news_get_sentiment_ranking), CLI commands (okx news …), and theokx-sentiment-trackeragent skill have been removed until regulatory compliance approval is obtained. Theskills(Skill Marketplace) module is unaffected.
- Contract order placement now requires
ctVallookup first:swap_place_order,futures_place_order, andoption_place_ordertool descriptions now include a mandatory precondition to callmarket_get_instrumentsto retrievectVal(contract face value) before placing orders. Theszparameter description is also clarified with an example (e.g. ETH-USDT-SWAP: 1 contract = 0.1 ETH).okx-cex-tradeSKILL.md updated with a critical warning section. (#113) account_get_config: revert field stripping, add description instead: The beta.5 fix that strippedsettleCcy/settleCcyListfrom the response has been reverted. These fields are now preserved and explained in the tool description — they only apply to USDS-margined contracts and can be ignored for standard USDT/coin-margined trading.
market_get_instruments_by_categoryMCP tool andokx market instruments-by-categoryCLI command: Discover tradeable instruments byinstCategory— Stock tokens (3, e.g. AAPL-USDT-SWAP), Metals (4, e.g. XAUUSDT-USDT-SWAP), Commodities (5, e.g. OIL-USDT-SWAP), Forex (6, e.g. EURUSDT-USDT-SWAP), Bonds (7, e.g. US30Y-USDT-SWAP). Accepts--instCategory <3|4|5|6|7>, optional--instType(default SWAP) and--instId. Supersedesmarket_get_stock_tokens/okx market stock-tokensfor category 3. (#109)okx-cex-marketskill updated: Description, command index, instrument-commands reference, and workflows updated to cover all non-crypto asset categories. New "Non-crypto asset discovery" workflow guides agents from instrument discovery → price check → order sizing. (#109)- Skills Marketplace module (
skills): Browse, search, and install AI trading skills from the OKX Skills Marketplace. Enabled by default. Activate with--modules skills.skills_get_categories— List all available skill categories; usecategoryIdas input toskills_search.skills_search— Search skills by keyword and/or category; returnstotalPagefor pagination.skills_download— Download a skill zip to a local directory.- CLI:
okx skill search <keyword>,okx skill categories,okx skill add <name>,okx skill download <name> [--dir],okx skill remove <name>,okx skill check <name>,okx skill list. okx skill addautomatically extracts, validatesSKILL.md, runsnpx skills add, and records the install in~/.okx/skills/registry.json.- Agent Skill:
skills/okx-cex-skill-mp/SKILL.md.
market_get_stock_tokensMCP tool: Replaced bymarket_get_instruments_by_categorywithinstCategory="3". Retained for backward compatibility; will be removed in a future major version.okx market stock-tokensCLI command: Replaced byokx market instruments-by-category --instCategory 3. Retained for backward compatibility; will be removed in a future major version.
- Earn module: write operations now return a clear error in simulated trading (demo) mode instead of hitting OKX API and receiving an opaque 500 server error. A unified
withDemoGuardwrapper inearn/index.tsintercepts all earn write tools (savings purchase/redeem, DCD subscribe, on-chain staking, auto-earn) before execution and throws aConfigErrorwith the message: "Earn features (savings, DCD, on-chain staking, auto-earn) are not available in simulated trading mode." — with suggestion to switch to a live account. Read-only tools (balance queries, rate history, offer listings) remain accessible in demo mode.dcd_redeempreview mode (noquoteId, read-only price check) is also permitted. New earn tools added in the future are automatically protected based on theirisWriteflag. account_get_configresponse stripssettleCcy/settleCcyList: These USDS-contract-only fields are now removed from the response to avoid confusing AI models that interpret them as general account settings. (Reverted in [1.2.8-beta.6] — fields are preserved with added description instead.)
newsmodule (7 tools): Real-time crypto news, full-text search, and sentiment analytics via Orbit News API. All tools are read-only and require no fund permissions. Activate with--modules news.news_get_latest— Latest news sorted by time; supports importance filter (high/medium/low), coin filter, language, pagination.news_get_by_coin— News for specific coins (comma-separated, e.g.BTC,ETH).news_search— Full-text keyword search with optional coin, importance, sentiment, and sort filters.news_get_detail— Full article content (title + AI summary + original text) by news ID.news_get_domains— List available news source domains (e.g. CoinDesk, CoinTelegraph).news_get_coin_sentiment— Bullish/bearish snapshot or time-series trend for coins; passtrendPointsfor trend mode.news_get_sentiment_ranking— Rank coins by hotness or sentiment direction.- CLI:
okx news latest,okx news by-coin <coins>,okx news search <keyword>,okx news detail <id>,okx news domains,okx news sentiment <coins>,okx news sentiment-ranking. - Agent Skill:
skills/okx-sentiment-tracker/with workflows guide.
--liveflag for CLI and MCP server: Forces live trading mode even when the active profile hasdemo=true. Mutually exclusive with--demo(passing both throws an error). CLI:okx --live <module> <action>. MCP:--liveargument. (#108)
--no-demoflag now correctly overrides profiledemo=true: Previously,cli.demowas treated as always-truthy when the default wasfalse, so--no-demohad no effect against a profile withdemo=true. The resolution logic now uses a three-state check:--liveforces live,--demoforces demo, otherwise env vars and profile are consulted. (#108)
- Three-channel auto-update with skill version sync (
okx upgrade): Supports stable, beta, and latest dist-tag channels. Automatically syncs bundled agent-skills version after upgrade. ExportsfetchLatestVersion,isNewerVersion,fetchDistTagsfrom core for version resolution. okx-cex-tradeSKILL.md restructured with separate reference files: Reduced the monolithic 1,594-lineSKILL.mdto a lean 342-line index by extracting CLI param tables and workflows intoreferences/spot-commands.md,references/swap-commands.md,references/futures-commands.md,references/options-commands.md,references/workflows.md, andreferences/templates.md. Follows the same pattern asokx-cex-earnandokx-cex-market. Agents can dynamically load only the reference sections they need.
okx upgrade: resolvenpmviaprocess.execPathinstead of relying onPATHlookup, fixing upgrade failures in environments wherenpmis not on PATH (SonarQube S4036).okx upgrade: eliminate ReDoS hotspot — replaced regex-based string replace withsplit/join(SonarQube S5852).okx upgrade: replaceexecSyncwithspawnSyncto silence security hotspot (SonarQube S4721).- Preflight drift check skipped for prerelease CLI: When the local CLI version contains a prerelease suffix (e.g.
1.2.8-beta.3), the version drift check is now skipped to avoid false-positive warnings.
account_get_asset_balanceshows zero balance instead of "(no data)": When an account balance is exactly 0, the CLI now correctly displays0rather than the placeholder "(no data)" text.
market_get_candlesnow automatically routes to historical endpoint: Automatically uses/market/history-candleswhenafter/beforetimestamps are older than 2 days, enabling access to candlestick data back to 2021. Includes fallback: if the recent endpoint returns empty data for a timestamped request, it retries the history endpoint. Thehistoryparameter has been removed; no manual switching required. CLI:okx market candles BTC-USDT --after <timestamp>. (#101)account_get_asset_balancenow supportsshowValuationparameter: SetshowValuation=trueto also return total asset valuation breakdown across all account types (trading, funding, earn, etc.) via/api/v5/asset/asset-valuation. Default behavior is unchanged (backward compatible). CLI:okx account asset-balance --valuation. (#102)
- DoH (DNS-over-HTTPS) node resolution infrastructure (experimental — code was subsequently removed from the codebase via merge conflict and is not included in the stable 1.2.8 release): Introduced
packages/core/src/doh/withDohNodetype andresolveDoh()resolver. The REST client integrated DoH-based proxy node selection for improved connectivity in restricted network environments. Removed pending platform-specific native binary integration (@okx_ai/doh-darwin,doh-linux,doh-win32).
earn_auto_settool (earn.autoearn): Enable or disable auto-earn for a currency. SupportsearnType='0'for auto-lend+stake (most currencies) andearnType='1'for USDG earn (USDG, BUIDL). Cannot disable within 24 hours of enabling. CLI:okx earn auto on <ccy>/okx earn auto off <ccy>.- Contract grid supports coin-margined (inverse) instruments (e.g.
BTC-USD-SWAP): Updatedgrid_create_order,grid_get_orders, andgrid_stop_ordertool descriptions to document CoinM support, including coin-margined instId examples and margin unit clarification. grid_create_orderTP/SL params: AddedtpTriggerPx,slTriggerPx(trigger price) andtpRatio,slRatio(ratio-based, contract only) so users can set take-profit and stop-loss when creating a grid bot.grid_create_orderalgoClOrdId: User-defined algo order ID (alphanumeric, max 32 chars). Unique per user — enables idempotent creation and can be used to query or stop the bot later.tgtCcyparameter for algo place orders:spot_place_algo_order,swap_place_algo_order,futures_place_algo_order, andoption_place_algo_ordernow accepttgtCcy. SettgtCcy=quote_ccyto specify order size in USDT instead of contracts/base currency. (#86)okx diagnose --mcpmulti-client detection: Detects Cursor, Windsurf, Claude Code, and Claude Desktop configs; skips missing clients instead of failing; passes when at least one client is configured. (#90)okx diagnose --mcptool count limit check: Warns when total tool count exceeds known client limits (e.g. Cursor: 40/server, 80 total) and suggests--modulesto reduce. (#90)- Cursor tool limit guidance: Added warning, recommended module combinations table, and safe configuration examples to
docs/configuration.mdanddocs/faq.mdfor Cursor users affected by the ~40 tools/server limit. (#88) - Spot DCA support (
bot.dca): All 5 DCA tools now support both Spot DCA (algoOrdType=spot_dca) and Contract DCA (algoOrdType=contract_dca). New parameters:algoOrdType(required),algoClOrdId,reserveFunds,tradeQuoteCcyfordca_create_order;algoOrdTypeandstopTypefordca_stop_order;algoOrdTypefilter fordca_get_orders;algoOrdTyperequired fordca_get_order_detailsanddca_get_sub_orders. CLI commands updated with matching--algoOrdTypeoption (defaults tocontract_dcafor backward compatibility). dca_create_orderRSI trigger support:triggerStrategynow accepts"rsi"for both spot and contract DCA. New RSI parameters:triggerCond(cross_up|cross_down),thold(RSI threshold, e.g."30"),timeframe(e.g."15m"),timePeriod(default"14"). Note:pricetrigger is only supported forcontract_dca;spot_dcasupportsinstantandrsionly.- Agent Skills bundled in
skills/: All 5 skill modules (okx-cex-market,okx-cex-trade,okx-cex-portfolio,okx-cex-bot,okx-cex-earn) are now included directly in the repository underskills/. Includesskills/README.mdandskills/README.zh-CN.mdwith usage guide.
dca_create_ordermissingtagfield: Thetagfield (fromcontext.config.sourceTag) is now correctly included in the create request body, matchinggrid_create_orderbehavior.allowReinvesttype mismatch: Schema changed from string enum to boolean to match the backendBooleantype. Handler accepts both boolean and string "true"/"false" for CLI compatibility.cmdDcaSubOrderswrong table columns: When querying orders within a cycle (with--cycleId), the CLI now displays order-specific fields (ordId,side,ordType,filledSz, etc.) instead of cycle-list fields.okx market tickershowed wrong "24h change %" field: The field was incorrectly mapped tosodUtc8(UTC+8 daily open price) instead of being calculated fromopen24h. Now correctly displays24h open(theopen24hvalue) and a computed24h change %(derived fromopen24handlast).dca_create_ordertriggerStrategyvalidation byalgoOrdType:pricetrigger is rejected forspot_dcaat validation time with a clear error message.
grid_create_order:directionis now required for contract grids — MCP-side validation rejects requests missingdirectionwhenalgoOrdType=contract_grid, providing immediate client-side feedback without a network round-trip.grid_stop_order: defaultstopTypechanged from"2"to"1"— omittingstopTypenow defaults to close-all (stop grid and close positions) instead of keep-assets, which is the safer and more intuitive default for both spot and contract grids.grid_create_order: shortened tool descriptions — reducedgrid_create_orderJSON schema size by ~20% (2,017 → 1,610 chars) by tightening parameter descriptions without removing any information.- README updated with Agent Skills section: Features table and Documentation table updated to reflect the bundled
skills/directory.
dca_create_orderRSI trigger support:triggerStrategynow accepts"rsi"for both spot and contract DCA. New RSI parameters:triggerCond(cross_up|cross_down),thold(RSI threshold, e.g."30"),timeframe(e.g."15m"),timePeriod(default"14"). RSI trigger is supported by bothspot_dcaandcontract_dca.- Agent Skills bundled in
skills/: All 5 skill modules (okx-cex-market,okx-cex-trade,okx-cex-portfolio,okx-cex-bot,okx-cex-earn) are now included directly in the repository underskills/. Includesskills/README.mdandskills/README.zh-CN.mdwith usage guide.
dca_create_ordertriggerStrategyvalidation byalgoOrdType:pricetrigger is now rejected forspot_dcaat validation time with a clear error message (spot_dcasupportsinstantandrsionly).contract_dcacontinues to support all three strategies (instant,price,rsi).
- README updated with Agent Skills section: Features table and Documentation table updated to reflect the bundled
skills/directory.
okx diagnose --mcpmulti-client detection: detects Cursor, Windsurf, Claude Code, and Claude Desktop configs; skips missing clients instead of failing; passes when at least one client is configured (#90)okx diagnose --mcptool count limit check: warns when total tool count exceeds known client limits (e.g. Cursor: 40/server, 80 total) and suggests--modulesto reduce (#90)- Cursor tool limit guidance: added warning, recommended module combinations table, and safe configuration examples to
docs/configuration.mdanddocs/faq.mdfor Cursor users affected by the ~40 tools/server limit (#88) - Spot DCA support (
bot.dca): All 5 DCA tools now support both Spot DCA (algoOrdType=spot_dca) and Contract DCA (algoOrdType=contract_dca). New parameters:algoOrdType(required),algoClOrdId,reserveFunds,tradeQuoteCcyfordca_create_order;algoOrdTypeandstopTypefordca_stop_order;algoOrdTypefilter fordca_get_orders;algoOrdTyperequired fordca_get_order_detailsanddca_get_sub_orders. CLI commands updated with matching--algoOrdTypeoption (defaults tocontract_dcafor backward compatibility). Help text and agent-skills documentation updated.
dca_create_ordertriggerStrategyno longer supports"rsi": OKX DCA API does not support RSI trigger for DCA bots. ThetriggerStrategyenum is now["instant", "price"]. Users previously passingtriggerStrategy: "rsi"will receive a schema validation error.
dca_create_ordermissingtagfield: Thetagfield (fromcontext.config.sourceTag) is now correctly included in the create request body, matchinggrid_create_orderbehavior.allowReinvesttype mismatch: Schema changed from string enum to boolean to match the backendBooleantype. Handler accepts both boolean and string "true"/"false" for CLI compatibility.cmdDcaSubOrderswrong table columns: When querying orders within a cycle (with--cycleId), the CLI now displays order-specific fields (ordId,side,ordType,filledSz, etc.) instead of cycle-list fields.okx market tickershowed wrong "24h change %" field: The field was incorrectly mapped tosodUtc8(UTC+8 daily open price) instead of being calculated fromopen24h. Now correctly displays24h open(theopen24hvalue) and a computed24h change %(derived fromopen24handlast).
earn_auto_settool (earn.autoearn): Enable or disable auto-earn for a currency. SupportsearnType='0'for auto-lend+stake (most currencies) andearnType='1'for USDG earn (USDG, BUIDL). Cannot disable within 24 hours of enabling. CLI:okx earn auto on <ccy>/okx earn auto off <ccy>.- Contract grid now supports coin-margined (inverse) instruments (e.g.
BTC-USD-SWAP): Updatedgrid_create_order,grid_get_orders, andgrid_stop_ordertool descriptions to document CoinM support, including coin-margined instId examples and margin unit clarification. grid_create_ordernow supports TP/SL params: AddedtpTriggerPx,slTriggerPx(trigger price) andtpRatio,slRatio(ratio-based, contract only) so users can set take-profit and stop-loss when creating a grid bot.grid_create_ordernow supportsalgoClOrdId: User-defined algo order ID (alphanumeric, max 32 chars). Unique per user — enables idempotent creation and can be used to query or stop the bot later.tgtCcyparameter for algo place orders:spot_place_algo_order,swap_place_algo_order,futures_place_algo_order, andoption_place_algo_ordernow accepttgtCcy. SettgtCcy=quote_ccyto specify order size in USDT instead of contracts/base currency, consistent with regular place order tools added in v1.2.6. (#86)
grid_create_order:directionis now required for contract grids — MCP-side validation rejects requests missingdirectionwhenalgoOrdType=contract_grid, providing immediate client-side feedback without a network round-trip.grid_stop_order: defaultstopTypechanged from"2"to"1"— omittingstopTypenow defaults to close-all (stop grid and close positions) instead of keep-assets, which is the safer and more intuitive default for both spot and contract grids.grid_create_order: shortened tool descriptions — reducedgrid_create_orderJSON schema size by ~20% (2,017 → 1,610 chars) by tightening parameter descriptions (sz,algoClOrdId, TP/SL fields) without removing any information.
market_get_indicatortool (market): Query technical indicator values for any instrument via the OKX AIGC indicator API. Supports 70+ indicators across 10 categories — moving averages (MA, EMA, WMA, HMA…), trend (MACD, SuperTrend, SAR, ADX…), Ichimoku, momentum oscillators (RSI, KDJ, StochRSI…), volatility (BB, ATR, Keltner…), volume (OBV, VWAP, MFI…), statistics (LR, Slope, Sigma…), price auxiliary (TP, MP), candlestick patterns (15 types), and BTC crypto-cycle indicators (BTCRAINBOW, AHR999). No API credentials required. Accepts optionalparams,returnList,limit, andbacktestTime. CLI:okx market indicator <name> <instId> [--bar <tf>] [--params <p1,p2>] [--list] [--limit N] [--backtest-time <ms>].publicPost()onOkxRestClient: New unauthenticated POST method, symmetric withpublicGet. Used internally bymarket_get_indicator.tgtCcyparameter for place orders:spot_place_order,swap_place_order, andfutures_place_ordernow accepttgtCcy. SettgtCcy=quote_ccyto specify order size in USDT instead of contracts/base currency.
- CLI exits with code 1 on OKX business failure: Write endpoints return HTTP 200 even when an order is rejected (e.g.
sCode="51008"). The CLI now setsprocess.exitCode = 1when any item in the response has a non-zerosCode, making failures detectable by scripts and LLMs via exit code alone. - Friendly error for
config.tomlpassphrase with special characters: When a passphrase contains#,\,", or', the error now includes TOML quoting guidance instead of a cryptic parse error. - Insufficient balance errors now hint to check funding account: Error codes
51008(insufficient balance),51119(insufficient margin), and51127(insufficient available margin) now include a suggestion to check the funding account viaaccount_get_asset_balanceand transfer withaccount_transfer (from=18, to=6).
- CLI output layer abstracted (internal): Raw
process.stdout/stderrwrites unified behind an output abstraction. No user-facing behavior change.
dcd_subscribetool (earn.dcd): atomic DCD subscription that requests a quote and executes it in a single step, eliminating quote-expiry race conditions for MCP users. Accepts optionalminAnnualizedYield(in percent) — if the actual quote yield falls below this threshold, the order is rejected before execution. Returns the trade result with a quote snapshot (annualizedYield,absYield). Not supported in demo mode.dcd_redeemtool (earn.dcd): two-step early redemption designed for user confirmation before executing. First call (noquoteId): requests a redemption quote showing the early-exit cost. Second call (withquoteId): executes the redemption. If the quote has expired between the two calls, a fresh quote is automatically requested and executed atomically; response includesautoRefreshedQuote: true. Not supported in demo mode for the execute step.- CLI
okx diagnose --mcp: New MCP server troubleshooting mode. Checks package versions, Node.js compatibility, MCP entry-point existence and executability, Claude DesktopmcpServersconfiguration, recent MCP log tail, module-load smoke test (--version), and a live stdio JSON-RPC handshake (5 s timeout). Zero external dependencies — uses Node.js built-ins only. --output <file>forokx diagnose: Both the default and--mcpmodes now accept--output <path>to save the diagnostic report to a file for sharing.allToolSpecs()exported from@agent-tradekit/core: The function is now part of the public API, exposed for future external consumers that need to enumerate all registered tool specs.
- Low-level DCD split tools removed:
dcd_request_quote,dcd_execute_quote,dcd_request_redeem_quote, anddcd_execute_redeemhave been removed. Usedcd_subscribefor subscribe flows anddcd_redeemfor early redemption flows. earn_get_lending_rate_summarytool removed (earn.savings): The lending market rate summary endpoint has been removed from the MCP tool set. Useearn_get_lending_rate_historyto query market lending rates instead.
- Tool description semantics for
rate/lendingRatein Simple Earn tools: Corrected misleading descriptions inearn_get_savings_balance,earn_set_lending_rate,earn_get_lending_history, andearn_get_lending_rate_history. Theratefield is now clearly described as a minimum lending rate threshold (not market yield, not APY). ThelendingRatefield now documents the pro-rata dilution mechanism for stablecoins (USDT/USDC): when eligible supply exceeds borrowing demand, total interest is shared among all lenders solendingRate<rate; for non-stablecoins,lendingRateequalsratewith no dilution. Users should always uselendingRateas the true APY. - CLI
cancelcommands now support--clOrdId:okx spot/swap/futures cancelpreviously required--ordIdas a positional argument. Now accepts either--ordIdor--clOrdId(client order ID); throws a clear error if neither is provided. Affectsspot_cancel_order,swap_cancel_order,futures_cancel_order. - CLI
spot/swap/futures cancelwas ignoring--instIdflag:cmdSpotCancel,cmdSwapCancel, andcmdFuturesCancelused the positional argument (rest[0]) asinstIdinstead of the--instIdflag value, causing the cancel to silently use the wrong instrument ID. Fixed to correctly passv.instId.
- Tool descriptions optimized across all modules: Removed "Private endpoint", "Public endpoint", and "Rate limit" labels from all tool description strings to reduce MCP schema token overhead. Shortened descriptions for earn, grid, DCA, swap/futures/option modules.
[CAUTION]markers preserved. - TWAP bot moved to CLI-only:
bot.twapMCP tools removed; TWAP functionality remains available viaokx bot twapCLI commands. sanitize()utility: Masks UUIDs, long hex strings (≥32 chars), and Bearer tokens in diagnostic output before sharing.diagnose-utils.ts(internal): SharedReport,ok,fail,section, andsanitizehelpers extracted fromdiagnose.tsto enable reuse bydiagnose-mcp.ts.- File-level comments added to all tools modules (internal documentation).
- CLI
cancelcommands now support--clOrdId:okx spot/swap/futures cancelpreviously required--ordIdas a positional argument. Now accepts either--ordIdor--clOrdId(client order ID); throws a clear error if neither is provided. Affectsspot_cancel_order,swap_cancel_order,futures_cancel_order.
feat/add-more-bots-phase-1reverted: Removed all changes introduced by this branch, including bug fixes that are a side effect of the revert:dca_create_orderRSI trigger sub-parameters (triggerCond,thold,timePeriod,timeframe) and copy-trading params (trackingMode,profitSharingRatio)- 5 DCA CLI commands:
margin-add,margin-reduce,set-tp,set-reinvest,manual-buy - Spot Recurring Buy CLI commands:
okx bot recurring create|amend|stop|orders|details|sub-orders grid_create_order6 new optional parameters (tpTriggerPx,slTriggerPx,algoClOrdId,tradeQuoteCcy,tpRatio,slRatio)- 14 new grid CLI commands (
amend-basic-param,amend-order,close-position,cancel-close-order,instant-trigger,positions,withdraw-income,compute-margin-balance,margin-balance,adjust-investment,ai-param,min-investment,rsi-back-testing,max-quantity) - TWAP CLI commands:
okx bot twap place|cancel|orders|details - (side effect)
swap_cancel_algo_ordersinput format restored: the branch had broken the input schema from{ orders: [{ algoId, instId }] }to flat{ instId, algoId }; revert restores correct format. - (side effect)
dca_create_orderpxStepsMult/volMultthreshold corrected: the branch had misdocumented the required threshold asmaxSafetyOrds > 1; revert restores correct> 0.
copytradingmodule reverted: Removed the 5 CLI copy-trading commands (traders,trader-detail,status,follow,unfollow), thecopytradingMCP tool, related documentation (docs/cli-reference.mdcopytrading section), and README copy-trading entries introduced in v1.2.5-beta.2.
dcd_subscribetool (earn.dcd): atomic DCD subscription that requests a quote and executes it in a single step, eliminating quote-expiry race conditions for MCP users. Accepts optionalminAnnualizedYield(in percent) — if the actual quote yield falls below this threshold, the order is rejected before execution. Returns the trade result with a quote snapshot (annualizedYield,absYield). Not supported in demo mode.dcd_redeemtool (earn.dcd): two-step early redemption designed for user confirmation before executing. First call (noquoteId): requests a redemption quote showing the early-exit cost. Second call (withquoteId): executes the redemption. If the quote has expired between the two calls, a fresh quote is automatically requested and executed atomically; response includesautoRefreshedQuote: true. Not supported in demo mode for the execute step.- Removed low-level split DCD tools:
dcd_request_quote,dcd_execute_quote,dcd_request_redeem_quote, anddcd_execute_redeemhave been removed. Usedcd_subscribefor subscribe flows anddcd_redeemfor early redemption flows.
- CLI
okx diagnose --mcp: New MCP server troubleshooting mode. Checks package versions, Node.js compatibility, MCP entry-point existence and executability, Claude DesktopmcpServersconfiguration, recent MCP log tail, module-load smoke test (--version), and a live stdio JSON-RPC handshake (5 s timeout). Zero external dependencies — uses Node.js built-ins only. --output <file>forokx diagnose: Both the default and--mcpmodes now accept--output <path>to save the diagnostic report to a file for sharing.diagnose-utils.ts(internal): SharedReport,ok,fail,section, andsanitizehelpers extracted fromdiagnose.tsto enable reuse bydiagnose-mcp.ts.sanitize()utility: Masks UUIDs, long hex strings (≥32 chars), and Bearer tokens in diagnostic output before sharing.allToolSpecs()exported from@agent-tradekit/core: The function is now part of the public API, exposed for future external consumers that need to enumerate all registered tool specs (e.g. third-party MCP clients, testing utilities). It was already used internally bybuildTools()andcreateToolRunner(); this change makes the export public-facing for anticipated downstream use, not for use withindiagnose-mcp.ts.
market_get_stock_tokenstool: new dedicated tool to list stock token instruments (e.g.AAPL-USDT-SWAP,TSLA-USDT-SWAP). Fetches all instruments viaGET /api/v5/public/instrumentsand filters client-side byinstCategory=3. SupportsinstType(defaultSWAP) and optionalinstId. (#65)- CLI
okx market stock-tokens: new CLI sub-command mapping tomarket_get_stock_tokens. Usage:okx market stock-tokens [--instType <SPOT|SWAP>] [--instId <id>] [--json]. (#65) - Spot trailing stop support (
spot_place_algo_orderwithordType='move_order_stop'):spot_place_algo_ordernow supports trailing stop orders in addition to conditional/oco. PassordType='move_order_stop'withcallbackRatio(e.g.'0.01'for 1%) orcallbackSpread(fixed price distance), and optionallyactivePx. (#67) swap_place_algo_ordernow supports trailing stop (ordType='move_order_stop'): extended withcallbackRatio,callbackSpread, andactivePxparameters, replacing the need for the deprecatedswap_place_move_stop_ordertool. (#67)spot_get_algo_ordersnow includes trailing stop orders: When noordTypefilter is specified, the query now fetchesconditional,oco, andmove_order_stoporders in parallel. (#67)- CLI
okx spot algo trail: New CLI sub-command for placing a spot trailing stop order. Usage:okx spot algo trail --instId BTC-USDT --side sell --sz 0.001 --callbackRatio 0.01 [--activePx <price>] [--tdMode cash]. (#67) - CLI
okx futures algo trail: New CLI sub-command for placing a futures trailing stop order. Usage:okx futures algo trail --instId BTC-USD-250328 --side sell --sz 1 --callbackRatio 0.01 [--activePx <price>] [--posSide <net|long|short>] [--tdMode <cross|isolated>] [--reduceOnly]. (#68) - 4 new option algo core tools (
registerOptionAlgoTools):option_place_algo_order,option_amend_algo_order,option_cancel_algo_orders,option_get_algo_orders. These let AI agents and users place conditional TP/SL algo orders on option positions, amend or cancel them, and query pending/historical option algo orders. (#72) option_place_ordernow supports attached TP/SL (attachAlgoOrds): Pass--tpTriggerPx/--tpOrdPxand/or--slTriggerPx/--slOrdPxto attach a take-profit or stop-loss algo order to the option order in one step. (#72)- CLI
okx option algocommands:place,amend,cancel,orders— full lifecycle management for option TP/SL algo orders. (#72) - 7 new futures core tools for delivery contract (Phase 1 feature parity with swap):
futures_amend_order,futures_close_position,futures_set_leverage,futures_get_leverage,futures_batch_orders,futures_batch_amend,futures_batch_cancel. (#71) - 5 new futures algo tools (
registerFuturesAlgoTools):futures_place_algo_order,futures_place_move_stop_order,futures_amend_algo_order,futures_cancel_algo_orders,futures_get_algo_orders. (#71)
- Bot tools: added missing parameter descriptions for
algoId,algoOrdType, andgroupId— Grid and DCA tools were missingalgoIddescriptions, causing AI agents to pass invalid values (error51000) or mismatchedalgoOrdType(error50016). Also addedgroupIdforgrid_get_sub_ordersandnewSzforspot_amend_algo_order. - CLI:
okx bot dca ordersnow supports--algoIdand--instIdfilters — aligned withokx bot grid ordersbehavior. swap_get_algo_ordershardcodedinstType: Now accepts an optionalinstTypeparameter (default"SWAP", accepts"FUTURES"). (#71)callBackRatio/callBackSpreadparameter name mismatch: Fixed capital-B parameter names in POST body forswap_place_algo_orderandswap_place_move_stop_order. MCP input schema names remain unchanged. (#69)- CLI
algo placemissing trailing stop params:callbackRatio,callbackSpread, andactivePxwere silently dropped incmdSpotAlgoPlace,cmdSwapAlgoPlace, andcmdFuturesAlgoPlace. Now passed through correctly. (#74) - CLI
okx swap algo cancelformat: FixedcmdSwapAlgoCancelto wrap args as{ orders: [{ instId, algoId }] }matching the tool's required format. (#76)
swap_place_move_stop_order: Deprecated in favor ofswap_place_algo_orderwithordType='move_order_stop'. The tool remains functional for backward compatibility. (#67)
--modules allnow includes earn sub-modules:allnow expands to every module includingearn.savings,earn.onchain, andearn.dcd. Default modules remain unchanged. (#66)- CLI: removed direct
smol-tomldependency — TOML functionality now provided exclusively through@agent-tradekit/core. (#39) - Deduplicate postinstall script:
scripts/postinstall-notice.jsat monorepo root is the single source of truth; package copies are generated duringbuild. (#50) earnrestructured as sub-module directory (internal):earn.ts→tools/earn/savings.ts,onchain-earn.ts→tools/earn/onchain.ts. No public API changes. (#64)- Deduplicate
normalize()across tool modules: Removed 9 local copies; all now use sharednormalizeResponsefromhelpers.ts. (#70) - Extract
buildAttachAlgoOrds()helper: Shared TP/SL assembly helper inhelpers.ts, replacing 5 duplicate inline blocks. (#70) - Trim tool descriptions: Removed "Private endpoint", "Public endpoint", and "Rate limit" labels from all tool descriptions to reduce MCP schema token overhead.
[CAUTION]markers preserved. (#70)
- CLI
okx swap algo cancelreports "orders must be a non-empty array":cmdSwapAlgoCancelwas passing{ instId, algoId }directly toswap_cancel_algo_orders, but the tool requires{ orders: [{ instId, algoId }] }format, causing the command to always fail. Fixed to match the wrapping pattern used byfutures/option. (#76)
- CLI
algo placemissing trailing stop params:cmdSpotAlgoPlace,cmdSwapAlgoPlace, andcmdFuturesAlgoPlacewere silently droppingcallbackRatio,callbackSpread, andactivePxwhen passed by the user. Placing a trailing stop viaokx {spot,swap,futures} algo place --ordType move_order_stopwould return API error 50015 (missing required param). The three params are now passed through to the tool runner correctly. (#74)
-
4 new option algo core tools (
registerOptionAlgoTools):option_place_algo_order,option_amend_algo_order,option_cancel_algo_orders,option_get_algo_orders. These let AI agents and users place conditional TP/SL algo orders on option positions, amend or cancel them, and query pending/historical option algo orders. (#72) -
option_place_ordernow supports attached TP/SL (attachAlgoOrds): Pass--tpTriggerPx/--tpOrdPxand/or--slTriggerPx/--slOrdPxto attach a take-profit or stop-loss algo order to the option order in one step. (#72) -
CLI
okx option algo place: Place an option TP/SL algo order. Usage:okx option algo place --instId BTC-USD-250328-95000-C --side sell --ordType oco --sz 1 --tdMode cross --tpTriggerPx 0.006 --tpOrdPx -1 --slTriggerPx 0.003 --slOrdPx -1. (#72) -
CLI
okx option algo amend: Amend an existing option algo order's TP/SL levels. Usage:okx option algo amend --instId BTC-USD-250328-95000-C --algoId <id> [--newTpTriggerPx <p>] [--newSlTriggerPx <p>]. (#72) -
CLI
okx option algo cancel: Cancel an option algo order. Usage:okx option algo cancel --instId BTC-USD-250328-95000-C --algoId <id>. (#72) -
CLI
okx option algo orders: List pending or historical option algo orders. Usage:okx option algo orders [--instId <id>] [--history] [--ordType <conditional|oco>] [--json]. (#72) -
7 new futures core tools for delivery contract (Phase 1 feature parity with swap):
futures_amend_order,futures_close_position,futures_set_leverage,futures_get_leverage,futures_batch_orders,futures_batch_amend,futures_batch_cancel. These use futures-specific tool names (futures_*) instead of reusing swap tools, giving futures its own dedicated API surface. (#71) -
5 new futures algo tools (
registerFuturesAlgoTools):futures_place_algo_order,futures_place_move_stop_order,futures_amend_algo_order,futures_cancel_algo_orders,futures_get_algo_orders. These are analogues of the swap algo tools but useinstType: "FUTURES"and are registered under thefuturesmodule. (#71)
swap_get_algo_ordershardcodedinstType: The tool previously hardcodedinstType: "SWAP"in the API request body, making it impossible to query FUTURES algo orders. Now accepts an optionalinstTypeparameter (default"SWAP", accepts"FUTURES"). (#71)
- Deduplicate
normalize()across tool modules: Removed 9 localnormalize()copies fromspot-trade,swap-trade,futures-trade,option-trade,algo-trade,account,market,bot/grid,bot/dca; all now use the sharednormalizeResponsefromhelpers.ts. (#70) - Extract
buildAttachAlgoOrds()helper: Moved the inline TP/SL assembly pattern (tpTriggerPx,tpOrdPx,slTriggerPx,slOrdPx→attachAlgoOrds) into a shared helper inhelpers.ts, replacing 5 duplicate blocks inspot_place_order,spot_batch_orders(place),swap_place_order,swap_batch_orders(place), andfutures_place_order. (#70) - Trim tool descriptions: Removed "Private endpoint", "Public endpoint", and "Rate limit: X req/s per UID" labels from all tool description strings to reduce MCP schema token overhead.
[CAUTION]markers are preserved. (#70)
callBackRatio/callBackSpreadparameter name mismatch: OKX API expectscallBackRatioandcallBackSpread(capital B) but the POST body was sendingcallbackRatioandcallbackSpread(lowercase b), causing sCode 50015 errors. Fixed inswap_place_algo_orderandswap_place_move_stop_orderhandlers. The MCP input schema parameter names (callbackRatio/callbackSpread) remain unchanged. (#69)
market_get_stock_tokenstool: new dedicated tool to list stock token instruments (e.g.AAPL-USDT-SWAP,TSLA-USDT-SWAP). Fetches all instruments viaGET /api/v5/public/instrumentsand filters client-side byinstCategory=3. SupportsinstType(defaultSWAP) and optionalinstId. (#65)- CLI
okx market stock-tokens: new CLI sub-command mapping tomarket_get_stock_tokens. Usage:okx market stock-tokens [--instType <SPOT|SWAP>] [--instId <id>] [--json]. (#65) - Spot trailing stop support (
spot_place_algo_orderwithordType='move_order_stop'):spot_place_algo_ordernow supports trailing stop orders in addition to conditional/oco. PassordType='move_order_stop'withcallbackRatio(e.g.'0.01'for 1%) orcallbackSpread(fixed price distance), and optionallyactivePx. (#67) swap_place_algo_ordernow supports trailing stop (ordType='move_order_stop'): extended with the samecallbackRatio,callbackSpread, andactivePxparameters, replacing the need for the deprecatedswap_place_move_stop_ordertool. (#67)spot_get_algo_ordersnow includes trailing stop orders: When noordTypefilter is specified, the query now fetchesconditional,oco, andmove_order_stoporders in parallel. (#67)- CLI
okx spot algo trail: New CLI sub-command for placing a spot trailing stop order. Usage:okx spot algo trail --instId BTC-USDT --side sell --sz 0.001 --callbackRatio 0.01 [--activePx <price>] [--tdMode cash]. (#67) - CLI
okx futures algo trail: New CLI sub-command for placing a futures trailing stop order. Usage:okx futures algo trail --instId BTC-USD-250328 --side sell --sz 1 --callbackRatio 0.01 [--activePx <price>] [--posSide <net|long|short>] [--tdMode <cross|isolated>] [--reduceOnly]. (#68)
- Bot tools: added missing parameter descriptions for
algoId,algoOrdType, andgroupId— Grid tools (grid_get_orders,grid_get_order_details,grid_get_sub_orders,grid_stop_order) and DCA tools (dca_get_orders,dca_get_order_details) were missingalgoIddescriptions, causing AI agents to pass invalid values (error51000) or mismatchedalgoOrdType(error50016). Also addedgroupIddescription forgrid_get_sub_ordersandnewSzdescription forspot_amend_algo_order. - CLI:
okx bot dca ordersnow supports--algoIdand--instIdfilters — Previously the CLI did not pass these parameters to the underlyingdca_get_orderstool, even though the MCP tool already supported them. Now aligned withokx bot grid ordersbehavior.
swap_place_move_stop_order: Deprecated in favor ofswap_place_algo_orderwithordType='move_order_stop'. The tool remains functional for backward compatibility. (#67)
--modules allnow includes earn sub-modules:allnow expands to every module includingearn.savings,earn.onchain, andearn.dcd, on par with bot sub-modules. Previously, earn required explicit opt-in viaall,earn. The default modules remain unchanged. (#66)- CLI: removed direct
smol-tomldependency —packages/clino longer declaressmol-tomlas a direct dependency. The TOML functionality is now provided exclusively through@agent-tradekit/core. (#39) - Deduplicate postinstall script:
scripts/postinstall-notice.jsat monorepo root is now the single source of truth. The copies inpackages/cli/scripts/postinstall.jsandpackages/mcp/scripts/postinstall.jsare generated duringbuildand ignored by git. (#50) earnrestructured as sub-module directory (internal):earn.ts→tools/earn/savings.ts,onchain-earn.ts→tools/earn/onchain.ts, with a newtools/earn/index.tsaggregator. No public API changes. (#64)
- CLI
okx futures algo trail: New CLI sub-command for placing a futures trailing stop order. Usage:okx futures algo trail --instId BTC-USD-250328 --side sell --sz 1 --callbackRatio 0.01 [--activePx <price>] [--posSide <net|long|short>] [--tdMode <cross|isolated>] [--reduceOnly]. (#68)
- Spot trailing stop support (
spot_place_algo_orderwithordType='move_order_stop'):spot_place_algo_ordernow supports trailing stop orders in addition to conditional/oco. PassordType='move_order_stop'withcallbackRatio(e.g.'0.01'for 1%) orcallbackSpread(fixed price distance), and optionallyactivePx. (#67) swap_place_algo_ordernow supports trailing stop (ordType='move_order_stop'): The swap algo order tool is extended with the samecallbackRatio,callbackSpread, andactivePxparameters, replacing the need for the deprecatedswap_place_move_stop_ordertool. (#67)spot_get_algo_ordersnow includes trailing stop orders: When noordTypefilter is specified, the query now fetchesconditional,oco, andmove_order_stoporders in parallel (previously onlyconditionalandoco). (#67)- CLI
okx spot algo trail: New CLI sub-command for placing a spot trailing stop order. Usage:okx spot algo trail --instId BTC-USDT --side sell --sz 0.001 --callbackRatio 0.01 [--activePx <price>] [--tdMode cash]. (#67)
swap_place_move_stop_order: Deprecated in favor ofswap_place_algo_orderwithordType='move_order_stop'. The tool remains functional for backward compatibility. (#67)
--modules allnow includes earn sub-modules:allnow expands to every module includingearn.savings,earn.onchain, andearn.dcd, on par with bot sub-modules. Previously, earn required explicit opt-in viaall,earn. The default modules remain unchanged (spot,swap,option,account,bot.grid). (#66)
market_get_stock_tokenstool: new dedicated tool to list stock token instruments (e.g.AAPL-USDT-SWAP,TSLA-USDT-SWAP). Fetches all instruments viaGET /api/v5/public/instrumentsand filters client-side byinstCategory=3. SupportsinstType(defaultSWAP) and optionalinstId. (#65)- CLI
okx market stock-tokens: new CLI sub-command mapping tomarket_get_stock_tokens. Usage:okx market stock-tokens [--instType <SPOT|SWAP>] [--instId <id>] [--json]. - DCD module (
earn.dcd) — 8 new MCP tools and 10 CLI commands for OKX Dual Currency Deposit (双币赢):dcd_get_currency_pairs,dcd_get_products,dcd_request_quote,dcd_execute_quote,dcd_request_redeem_quote,dcd_execute_redeem,dcd_get_order_state,dcd_get_orders. CLI:okx earn dcd pairs,products,quote,buy,quote-and-buy,redeem-quote,redeem,redeem-execute,order,orders. Supports client-side product filtering (--minYield,--strikeNear,--termDays,--expDate), two-step early redemption flow, and demo-mode guard on all write operations.
- Bot tools: added missing parameter descriptions for
algoId,algoOrdType, andgroupId— Grid tools (grid_get_orders,grid_get_order_details,grid_get_sub_orders,grid_stop_order) and DCA tools (dca_get_orders,dca_get_order_details) were missingalgoIddescriptions, causing AI agents to pass invalid values (error51000) or mismatchedalgoOrdType(error50016). Also addedgroupIddescription forgrid_get_sub_ordersandnewSzdescription forspot_amend_algo_order. - CLI:
okx bot dca ordersnow supports--algoIdand--instIdfilters — Previously the CLI did not pass these parameters to the underlyingdca_get_orderstool, even though the MCP tool already supported them. Now aligned withokx bot grid ordersbehavior.
- CLI: removed direct
smol-tomldependency —packages/clino longer declaressmol-tomlas a direct dependency. The TOML functionality is now provided exclusively through@agent-tradekit/core, which bundlessmol-tomlinternally. (#39) - Deduplicate postinstall script:
scripts/postinstall-notice.jsat monorepo root is now the single source of truth. The copies inpackages/cli/scripts/postinstall.jsandpackages/mcp/scripts/postinstall.jsare generated duringbuildand ignored by git. (#50) earnrestructured as sub-module directory (internal):earn.ts→tools/earn/savings.ts,onchain-earn.ts→tools/earn/onchain.ts, with a newtools/earn/index.tsaggregator. Consistent with thebot/sub-module directory pattern. No public API changes. (#64)
market_get_stock_tokenstool: new dedicated tool to list stock token instruments (e.g.AAPL-USDT-SWAP,TSLA-USDT-SWAP). Fetches all instruments viaGET /api/v5/public/instrumentsand filters client-side byinstCategory=3. SupportsinstType(defaultSWAP) and optionalinstId. (#65)- CLI
okx market stock-tokens: new CLI sub-command mapping tomarket_get_stock_tokens. Usage:okx market stock-tokens [--instType <SPOT|SWAP>] [--instId <id>] [--json].
- Bot tools: added missing parameter descriptions for
algoId,algoOrdType, andgroupId— Grid tools (grid_get_orders,grid_get_order_details,grid_get_sub_orders,grid_stop_order) and DCA tools (dca_get_orders,dca_get_order_details) were missingalgoIddescriptions, causing AI agents to pass invalid values (error51000) or mismatchedalgoOrdType(error50016). Also addedgroupIddescription forgrid_get_sub_ordersandnewSzdescription forspot_amend_algo_order. - CLI:
okx bot dca ordersnow supports--algoIdand--instIdfilters — Previously the CLI did not pass these parameters to the underlyingdca_get_orderstool, even though the MCP tool already supported them. Now aligned withokx bot grid ordersbehavior.
- CLI: removed direct
smol-tomldependency —packages/clino longer declaressmol-tomlas a direct dependency. The TOML functionality is now provided exclusively through@agent-tradekit/core, which bundlessmol-tomlinternally. (#39) - Deduplicate postinstall script:
scripts/postinstall-notice.jsat monorepo root is now the single source of truth. The copies inpackages/cli/scripts/postinstall.jsandpackages/mcp/scripts/postinstall.jsare generated duringbuildand ignored by git. (#50) earnrestructured as sub-module directory (internal):earn.ts→tools/earn/savings.ts,onchain-earn.ts→tools/earn/onchain.ts, with a newtools/earn/index.tsaggregator. Consistent with thebot/sub-module directory pattern. No public API changes. (#64)
-
--modules allno longer includes earn sub-modules: Previously,--modules allexpanded to every module includingearn.savingsandearn.onchain. Nowallonly includes base modules and bot sub-modules. To enable earn modules, you must opt in explicitly:--modules all,earn— all modules + all earn sub-modules--modules all,earn.savings— all modules + Simple Earn only--modules all,earn.onchain— all modules + On-chain Earn only--modules earn— earn sub-modules only
Migration: if you previously used
--modules alland relied on earn tools being active, add,earnto your configuration:--modules all,earn.
- DCD module (
earn.dcd) — 8 new MCP tools and 10 CLI commands for OKX Dual Currency Deposit (双币赢):dcd_get_currency_pairs,dcd_get_products,dcd_request_quote,dcd_execute_quote,dcd_request_redeem_quote,dcd_execute_redeem,dcd_get_order_state,dcd_get_orders. CLI:okx earn dcd pairs,products,quote,buy,quote-and-buy,redeem-quote,redeem,redeem-execute,order,orders. Supports client-side product filtering (--minYield,--strikeNear,--termDays,--expDate), two-step early redemption flow, and demo-mode guard on all write operations. - HTTP/HTTPS proxy support: Configure
proxy_urlin your TOML profile to route all OKX API requests through a proxy server. Supports authenticated proxies via URL credentials (e.g.http://user:pass@proxy:8080). Only HTTP/HTTPS proxies are supported; SOCKS is not. (#53) - CLI
--verboseflag: Add--verboseto any command to see detailed network request/response info on stderr — method, URL, auth status (key masked), timing, HTTP status, OKX code, and trace ID. Useful for debugging connectivity and auth issues. - CLI
okx diagnosecommand: Step-by-step connectivity check that verifies environment (Node.js, OS, shell, locale, timezone, proxy), configuration (credentials, site, base URL), network (DNS → TCP → TLS → public API), and authentication. On failure, shows actionable hints. Prints a copy-paste diagnostic report block for sharing with support. - CLI place commands — attached TP/SL:
okx spot place,okx swap place, andokx futures placenow accept optional take-profit and stop-loss parameters:--tpTriggerPx,--tpOrdPx,--tpTriggerPxType,--slTriggerPx,--slOrdPx,--slTriggerPxType. These are forwarded directly to the OKX order API as attached TP/SL on the placed order. - Earn module — 7 new tools for OKX Simple Earn (savings/flexible lending):
earn_get_savings_balance,earn_savings_purchase,earn_savings_redeem,earn_set_lending_rate,earn_get_lending_history,earn_get_lending_rate_summary,earn_get_lending_rate_history. Includes CLI commands, dual-language documentation, and full test coverage.
- Contract DCA — optional parameters:
--slMode(stop-loss price type:limit/market),--allowReinvest(reinvest profit into next cycle, defaulttrue),--triggerStrategy(bot start mode:instant/price/rsi),--triggerPx(trigger price forpricestrategy). All are optional and only apply to contract DCA create. - Contract DCA orders —
instIdfilter:dca_get_ordersnow accepts an optional--instIdparameter to filter contract DCA bots by instrument (e.g.BTC-USDT-SWAP) - Contract DCA sub-orders —
cycleIdfilter:dca_get_sub_ordersnow accepts an optional--cycleIdparameter, allowing querying orders within a specific cycle - On-chain Earn module (6 tools): new
onchain-earnmodule for OKX On-chain Earn (staking/DeFi) products —onchain_earn_get_offers,onchain_earn_purchase,onchain_earn_redeem,onchain_earn_cancel,onchain_earn_get_active_orders,onchain_earn_get_order_history. CLI:okx earn onchain offers,okx earn onchain purchase,okx earn onchain redeem,okx earn onchain cancel,okx earn onchain orders,okx earn onchain history.
- DCA tools now contract-only: Removed Spot DCA support from all 5 DCA tools (
dca_create_order,dca_stop_order,dca_get_orders,dca_get_order_details,dca_get_sub_orders). Thetypeparameter has been removed — all DCA tools now operate exclusively on contract DCA. Spot DCA was removed due to product risk assessment. - Agent skill (
okx-cex-bot) updated for contract-only DCA: RewroteSKILL.mdto remove all Spot DCA references — description, quickstart examples, command index, cross-skill workflows, operation flow, CLI reference (create/stop/orders/details/sub-orders), MCP tool reference, input/output examples, edge cases, and parameter display name tables. DCA sections now document contract-only usage with--lever,--directionas required params and no--typeflag. - All order placement tools —
tagparameter removed, auto-injected: thetagfield has been removed from all order placement tool input schemas (spot, swap, futures, option, algo, grid). The server now automatically injectstag: "MCP"(or"CLI"for CLI usage) into every outgoing order request. Users who previously passed a customtagvalue will no longer be able to override it. Note: DCA bot tools do not injecttagas the Contract DCA API does not support this field.
- Contract DCA
side/directionmismatch (critical): MCP schema usedside(buy/sell) but API requiresdirection(long/short). Thesidefield was removed;directionis now used directly. Previously, short positions could not be created correctly. - Contract DCA
safetyOrdAmt,pxSteps,pxStepsMult,volMultconditionally required: These 4 parameters are business-required whenmaxSafetyOrds > 0(API returns 400 if omitted), but API-optional whenmaxSafetyOrds = 0. They are now schema-optional with descriptions noting the conditional requirement. - Contract sub-orders sent unsupported pagination: contract DCA orders-by-cycle path sent
after/beforeparams, but the API only supportslimit. Removedafter/beforefrom this path.
- Spot DCA endpoint paths updated: all 5 Spot DCA tool endpoints now use the new
/api/v5/tradingBot/spot-dcabase URL and renamed paths (create,stop,bot-active-list,bot-history-list,bot-detail,trade-list), aligning with the backend change in okcoin-bots MR #210. Contract DCA remains on/api/v5/tradingBot/dcaand is unaffected. grid_create_order—szdescription clarified: theszparameter description now says "investment amount in margin currency (e.g. USDT for USDT-margined contracts)" instead of "Investment amount in USDT", correctly covering both USDT-margined and coin-margined contract grids. Behavior is unchanged.--no-basePosCLI example removed from docs: the--no-basePosflag example has been removed fromdocs/cli-reference.mdasbasePosdefaults totrueand is not exposed as a standalone CLI flag.
dca_create_order— contract DCA now passesslPctandslMode: theslPct(stop-loss ratio) andslMode(stop-loss price type) parameters were accepted in the schema but not forwarded to the OKX API for contract DCA. This caused stop-loss settings to be silently ignored when creating contract DCA bots. Spot DCA was unaffected. Note: whenslPctis set for contract DCA,slMode("limit"or"market") is required by the OKX API.
grid_create_order—basePosdefaults totrue: contract grid bots now open a base position by default (long/short direction). Neutral direction ignores this parameter. PassbasePos: false(MCP) or--no-basePos(CLI) to disable. Spot grid is unaffected.
- Version bump.
- Version bump.
- Multi-level
--helpnavigation:okx --help,okx <module> --help, andokx <module> <subgroup> --helpnow print scoped help with per-command descriptions, so AI agents can discover available capabilities without reading source code.
--reserveFundsmissing frombot dca createhelp: the parameter was supported in code but absent from the help output.
--modules allnow includesbot.dca: previouslyallexpanded usingBOT_DEFAULT_SUB_MODULES(bot.grid only), silently excluding the DCA module. Now correctly uses all bot sub-modules.optionadded to default modules: the default module set is nowspot, swap, option, account, bot.grid. MCP server help text updated to match actual defaults.
- Git hash in
--versionoutput: both CLI and MCP server now display the build commit hash alongside the version, e.g.1.1.3 (abc1234), making it easy to verify which exact commit a published package was built from
- Spot
tdModenot configurable:okx spot place,okx spot algo place(TP/SL), MCPspot_place_algo_order, and MCPspot_batch_orderspreviously hardcodedtdModewith no way to override it. The--tdModeflag is now exposed as an optional parameter (default:cashfor non-margin accounts). Users on unified/margin accounts can pass--tdMode cross.
- One-line install scripts:
install.sh(macOS/Linux) andinstall.ps1(Windows) — install MCP server + CLI and auto-configure detected MCP clients in one command - Auto MCP client configuration: install script detects and configures Claude Code, Claude Desktop, Cursor, VS Code, and Windsurf automatically
config init --lang:--lang zhflag for Chinese-language interactive wizard; defaults to English- Smart default profile name:
config initinfers a sensible default profile name from the environment - CLI option module:
okx optioncommands for placing, cancelling, amending orders, querying positions, fills, instruments, and Greeks - CLI batch operations:
okx spot batchandokx swap batchfor bulk place/cancel/amend - CLI audit log:
okx trade historyto query the local NDJSON audit log - CLI contract DCA:
okx bot dca contractcommands with--typeflag to distinguish spot vs. contract DCA
- Version reporting: MCP server now reads its version from
package.jsonat runtime instead of a hardcoded string okx setupnpx command: setup config for standalone MCP clients (Claude Desktop, Cursor) now usesnpxso users don't need a global install- Bot write endpoints:
sCode/sMsgerrors from grid and DCA write endpoints are now surfaced correctly instead of being silently swallowed - Install script: installs both
@okx_ai/okx-trade-mcpand@okx_ai/okx-trade-cli(previously only installed one package)
- Bot sub-module refactor:
botmodule now includes abot.defaultsub-module; internal sub-module loading is unified and more robust - Docs: one-line install instructions moved from READMEs to
docs/configuration.md
- Build:
smol-tomlwas not bundled into the CLI output despitenoExternalconfig — npm registry1.1.0shipped with an externalimport from "smol-toml"that fails at runtime. Addedsmol-tomlto runtimedependenciesas a reliable fix and bumped version to republish.
- Contract DCA bot:
bot.dcasubmodule now supports contract (perpetual) DCA in addition to spot — new toolsdca_get_contract_orders,dca_get_contract_order_details,dca_create_contract_order,dca_stop_contract_order okx setupsubcommand: interactive wizard to generate and insert MCP server config into Claude Code, VS Code, Windsurf, and other MCP clients- CLI
--version/-vflag: print the current package version and exit - CLI
swap amendcommand: amend an open swap order via the CLI (okx swap amend)
- Duplicate tool: removed duplicate
swap_amend_ordertool registration that caused the tool to appear twice in tool listings - CLI swap amend dispatch:
okx swap amendnow correctly dispatches to the swap handler instead of the spot handler
bot.dcais opt-in: the DCA submodule is no longer loaded by default; enable it with--modules bot.dcaor by addingbot.dcato themoduleslist in~/.okx/config.toml- Bot tools reorganized into submodules:
botmodule now uses a submodule system —bot.gridandbot.dcacan be loaded independently - CLI architecture: CLI commands now invoke Core tool handlers directly via
ToolRunner, reducing duplication between MCP and CLI code paths
- algo orders:
swap_get_algo_ordersandspot_get_algo_ordersnow pass the requiredstateparameter when querying history (/api/v5/trade/orders-algo-history), defaulting toeffective(#28)
- npm org rename: packages moved from
@okx_retailto@okx_aiscope. Please reinstall:Binary names are unchanged —npm uninstall -g @okx_retail/okx-trade-mcp @okx_retail/okx-trade-cli npm install -g @okx_ai/okx-trade-mcp @okx_ai/okx-trade-cliokx-trade-mcpandokxstill work after reinstall.
- Scenario tests: added
scripts/scenario-test/with multi-step integration tests covering stateless read flows (account balance, market data, swap leverage) and stateful write flows (Spot place→query→cancel, Swap set-leverage→place→query→cancel). Stateless scenarios are CI-safe; stateful scenarios requireOKX_DEMO=1. - Multi-site support: users on OKX Global (
www.okx.com), EEA (my.okx.com), and US (app.okx.com) can now configure their site via--site <global|eea|us>CLI flag,OKX_SITEenv var, orsitefield in~/.okx/config.toml. The API base URL is automatically derived from the site; explicitOKX_API_BASE_URL/base_urloverrides remain supported for advanced use. config initsite selection: the interactive wizard now prompts for site before asking for API key, and opens the correct API management URL for the chosen site.config showsite display: thesitefield is now shown for each profile.- Region error context: error suggestions for OKX region-restriction codes (51155, 51734) now include the currently configured site to help users diagnose misconfigured site settings.
- docs/faq.md: added "General" section with 3 new Q&As — "What is OKX Trade MCP?", "What trading pairs are supported?", and "What risks should I understand?" (bilingual EN + ZH)
- docs/faq.md: added "API Coverage" section explaining which OKX REST API modules are supported vs. not yet supported by the MCP server and CLI (bilingual EN + ZH)
- CLI: ensure
main()is always invoked when executed via npm global symlink; add defensive comment and symlink regression test to prevent future regressions (#21)
- Release prep: version bump for publish
okx config init: site selection (Global / EEA / US) and demo/live choice are now asked upfront; the CLI opens the targeted API creation page with?go-demo-trading=1or?go-live-trading=1query param so users land directly on the correct tab. EEA (my.okx.com) and US (app.okx.com) sites are supported and saved asbase_urlin the profile.- docs/configuration.md, README.md, README.zh.md: updated API key creation links to direct URLs with
?go-demo-trading=1/?go-live-trading=1parameters (bilingual EN + ZH). - npm scope: packages are now published under the
@okx_retailorganisation. Please reinstall:Binary names are unchanged —npm uninstall -g okx-trade-mcp okx-trade-cli npm install -g @okx_retail/okx-trade-mcp @okx_retail/okx-trade-cliokx-trade-mcpandokxstill work after reinstall.
- Project rename: internal package
@okx-hub/corerenamed to@agent-tradekit/core
- Option module (10 tools): new
optionmodule for options trading —option_place_order,option_cancel_order,option_batch_cancel,option_amend_order(write);option_get_order,option_get_orders,option_get_positions(with Greeks),option_get_fills,option_get_instruments(option chain),option_get_greeks(IV + Delta/Gamma/Theta/Vega) (read)
- Total tools: 48 → 57 → 67
- Documentation restructure: split single
README.mdintoREADME.md(EN) +README.zh.md(ZH) with language toggle; addeddocs/configuration.md(all client setups + startup scenarios),docs/faq.md,docs/cli-reference.md, and per-module references underdocs/modules/ - GitHub issue templates: added
bug_report.mdandfeature_request.mdunder.github/ISSUE_TEMPLATE/ SECURITY.md: added supported versions table and GitHub Private Security Advisory link- Error handling — actionable suggestions:
OkxRestClientnow maps ~20 OKX error codes to retry guidance; rate-limit codes (50011,50061) throwRateLimitError; server-busy codes carry "Retry after X seconds"; region/compliance and account-issue codes carry "Do not retry" advice - Test coverage: function coverage raised from 76.5% → 93.4% (199 → 243 tests); every source file now exceeds 80% function coverage
- Coverage scripts: c8 now includes
packages/cli/srcandpackages/mcp/srcin coverage collection and runs all package tests
- Audit log —
trade_get_history: query the local NDJSON audit log of all MCP tool calls; supportslimit,tool,level, andsincefilters - Audit logging: MCP server automatically writes NDJSON entries to
~/.okx/logs/trade-YYYY-MM-DD.log;--no-logdisables logging,--log-levelsets the minimum level (defaultinfo); sensitive fields (apiKey, secretKey, passphrase) are automatically redacted - Error tracing:
traceIdfield added toToolErrorPayloadand all error classes — populated fromx-trace-id/x-request-idresponse headers when OKX returns them - Server version in MCP errors:
serverVersioninjected into MCP error payloads for easier bug reporting - CLI version in errors:
Version: okx-trade-cli@x.x.xalways printed to stderr on error;TraceId:printed when available - Market — index data:
market_get_index_ticker,market_get_index_candles(+ history),market_get_price_limit(3 new tools) - Spot — batch orders:
spot_batch_orders— batch place/cancel/amend up to 20 spot orders in one request - Spot/Swap — order archive:
status="archive"onspot_get_orders/swap_get_orders→/trade/orders-history-archive(up to 3 months) - Account — positions:
account_get_positions— cross-instType positions query (MARGIN/SWAP/FUTURES/OPTION) - Account — bills archive:
account_get_bills_archive— archived ledger up to 3 months - Account — sizing:
account_get_max_withdrawal,account_get_max_avail_size - README: "Reporting Issues / 报错反馈" section with example error payloads
- Grid Bot (module:
bot): 5 new tools for OKX Trading Bot grid strategies —grid_get_orders,grid_get_order_details,grid_get_sub_orders(read),grid_create_order,grid_stop_order(write). Covers Spot Grid, Contract Grid, and Moon Grid. - CLI
--demoflag: global--demooption to enable simulated trading mode directly from the command line (alternative toOKX_DEMO=1env var or profile config) - CLI bot grid commands:
bot grid orders,bot grid details,bot grid sub-orders,bot grid create,bot grid stop— full grid bot lifecycle management via CLI - CLI full coverage: extended
okx-trade-clito cover all 57 MCP tools — new commands acrossmarket(instruments,funding-rate,mark-price,trades,index-ticker,index-candles,price-limit,open-interest),account(positions,bills,fees,config,set-position-mode,max-size,max-avail-size,max-withdrawal,positions-history,asset-balance,transfer),spot(get,amend),swap(get,fills,close,get-leverage), and newfuturesmodule (orders,positions,fills,place,cancel,get) - CLI/MCP entry tests: new unit tests for
okxandokx-trade-mcpentrypoints to exercise help/setup flows and keep coverage accurate
- Grid bot endpoint paths: corrected all 5 grid tool endpoints to match OKX API v5 spec —
orders-algo-pending,orders-algo-history,order-algo,stop-order-algo(previously used wrong paths causing HTTP 404) grid_stop_order: request body now serialized as an array[{...}]as required by OKXstop-order-algoendpointgrid_create_order: removed spurioustdModeparameter (field does not exist inApiPlaceGridParam; was silently ignored by server but polluted the tool schema)grid_create_order: restrictedalgoOrdTypeenum to["grid", "contract_grid"]— server@StringMatchvalidation only accepts these two values for creation;moon_gridis valid for queries and stop operations onlygrid_stop_order: expandedstopTypeenum from["1","2"]to["1","2","3","5","6"]to match serverStopStrategyParamvalidation- CLI
bot grid create: removed--tdModeflag andalgoOrdTypenow restricted to<grid|contract_grid>, in sync with MCP tool changes - CLI
bot grid stop: updated--stopTypehint to<1|2|3|5|6> spot_get_algo_orders: fixed400 Parameter ordType errorwhen called without anordTypefilter — now fetchesconditionalandocotypes in parallel and merges results, matching the behaviour ofswap_get_algo_orders
- Market — 5 new tools:
market_get_instruments,market_get_funding_rate(+ history),market_get_mark_price,market_get_trades,market_get_open_interest - Market — candle history:
history=trueonmarket_get_candles→/market/history-candles - Spot/Swap — fills archive:
archive=trueonspot_get_fills/swap_get_fills→/trade/fills-history - Spot/Swap — single order fetch:
spot_get_order,swap_get_order— fetch byordId/clOrdId - Swap — close & batch:
swap_close_position,swap_batch_orders(batch place/cancel/amend up to 20) - Swap — leverage query:
swap_get_leverage - Account — 6 new tools:
account_get_bills,account_get_positions_history,account_get_trade_fee,account_get_config,account_set_position_mode,account_get_max_size - Account — funding balance:
account_get_asset_balance(funding account,/asset/balances) - System capabilities tool:
system_get_capabilities— machine-readable server capabilities for agent planning - MCP client configs: Claude Code CLI, VS Code, Windsurf, openCxxW setup examples added to README
- Update notifier package names corrected (
okx-trade-mcp,okx-trade-cli) - CLI typecheck errors resolved (strict
parseArgstypes,smol-tomlinterop)
- Total tools: 28 → 43
- Trailing stop order (
swap_place_move_stop_order) for SWAP — available in both CLI and MCP server - Update notifier — on startup, prints a notice to stderr when a newer npm version is available
- MCP server (
okx-trade-mcp): OKX REST API v5 integration via the Model Context Protocol - CLI (
okx-trade-cli): command-line trading interface for OKX - Modules:
market— ticker, orderbook, candles (no credentials required)spot— place/cancel/amend orders, algo orders (conditional, OCO), fills, order historyswap— perpetual order management, positions, leverage, fills, algo ordersaccount— balance query, fund transfer
- Algo orders: conditional (take-profit / stop-loss) and OCO order pairs for spot and swap
- CLI flags:
--modules,--read-only,--demo - Rate limiter: client-side token bucket per tool
- Config: TOML profile system at
~/.okx/config.toml - Error hierarchy:
ConfigError,ValidationError,AuthenticationError,RateLimitError,OkxApiError,NetworkErrorwith structured MCP error payloads