Bybit Trading Skill
Trade on Bybit using natural language. Supports spot, linear perpetuals (USDT/USDC), inverse contracts, options, and earn products.
Rule Priority
When rules in this skill conflict, follow this order: Safety > User Responsiveness > Convenience. For example, never skip confirmation to be faster; never block the user's first request to run an auto-update check.
Auto Update (MUST follow at session start)
This skill supports self-update with integrity verification. At the start of each new session, launch the update check as a background sub-agent so it never blocks the user's first request:
FOREGROUND (main agent — immediate):
1. Respond to the user's request using the current local version. Do NOT wait for the update check.
BACKGROUND (sub-agent — parallel):
1. LOCAL_VERSION = metadata.version (from YAML frontmatter above)
2. SKILL_DIR = directory where this SKILL.md is located
3. MANIFEST = curl -sf -H "User-Agent: bybit-skill/1.7.12" https://api.bybit.com/skill/manifest
(returns JSON: {"version":"x.y.z", "files":{"SKILL.md":"sha256:...","modules/market.md":"sha256:...",...}})
4. If fetch fails: return {status: "error", reason: "fetch_failed"}
5. Path validation: For each file in manifest.files, reject the entire update if ANY path:
- Does not match `SKILL.md`, `modules/<name>.md`, or `modules/<name>.js` (where <name> is [a-z0-9-]+)
- Contains `..`, starts with `/` or `~`, contains backslashes, or has an extension other than `.md` or `.js`
If any path is invalid: return {status: "error", reason: "invalid_path", path: "<rejected>"}
6. Version comparison (semver): split by ".", compare major → minor → patch numerically.
If manifest.version > LOCAL_VERSION:
a. For each file in manifest.files:
- Download: curl -sf -H "User-Agent: bybit-skill/1.7.12" https://raw.githubusercontent.com/bybit-exchange/skills/main/<file>
- Save content to temp file, then compute SHA256: shasum -a 256 <temp_file> | awk '{print $1}'
- Compare with manifest checksum (strip "sha256:" prefix)
- If mismatch: ABORT entire update. return {status: "error", reason: "checksum_mismatch", file: "<file>"}
- If file extension is `.js` AND the local file already exists at SKILL_DIR/<file>:
→ Show to user: "⚠️ Code module update: <file> (LOCAL_VERSION → manifest.version). Allow? [Y/n]"
→ If user declines: skip this file, continue with remaining files
- If match: save to SKILL_DIR/.skill-update-tmp/<file>
b. ALL files verified → move from temp to SKILL_DIR:
- For each file: mkdir -p parent dir, then mv .skill-update-tmp/<file> SKILL_DIR/<file>
- rm -rf SKILL_DIR/.skill-update-tmp/
c. return {status: "updated", from: LOCAL_VERSION, to: manifest.version}
If manifest.version == LOCAL_VERSION:
d. return {status: "current"}
WHEN SUB-AGENT COMPLETES (main agent receives result):
- If status="updated": notify user "Skill updated from {from} to {to}. Using latest version." Re-read updated SKILL.md.
- If status="current" or status="error": silently continue with current version.
- Cache manifest (if returned) in session memory for module loading (see Module Router).
Rules:
- Check at most ONCE per session. Do not re-check during the same conversation.
- If any network request fails (timeout, 404, etc.), skip silently and proceed with current version. (See Graceful Degradation below for unified fallback rules.)
- Never block the user's first request. The sub-agent runs in the background; the main agent responds immediately. If a module is needed before the sub-agent finishes, use the current local version.
- If checksum algorithm prefix is not "sha256:", refuse the update (fail closed).
Quick Start
Step 1: Get an API Key
Pick one of the two paths below. The AI Subaccount path is strongly preferred — it's Bybit's purpose-built account type for AI trading, with built-in cap limits and a public-key-based key flow.
Path A — AI Subaccount (Recommended)
Bybit's official AI-trading account type (help article).
- Create it (Bybit mobile app): Profile icon → Settings → Subaccount → Create → enter a name → select AI Subaccount → Confirm + security verification.
- Get the API key (Public Key flow): after creation, Bybit asks for a Public Key. Run your AI assistant and ask it to generate one (Claude Code, Open Claw, Cursor, etc. all support this); paste the public key into Bybit → it returns the API key + secret bound to that key. Configure them per Step 2 below.
- Built-in safety defaults: Cap Limit defaults to 5,000 USD (adjustable from main account → Subaccount → your AI Subaccount → More → Permissions). API key expires in 30 days; for permanent keys, IP whitelist, finer permission scoping, or higher rate limits, use the Bybit web platform instead of the app.
- Why prefer this: blast radius is bounded by the cap limit, permissions are managed centrally from the main account (Request Transfer In/Out, Move from Trading/Funding, Max Leverage, etc.), and the subaccount can be killed in one click if anything goes wrong.
Path B — Manual API Key (Fallback)
Use this only if AI Subaccount isn't available in your region or you need a non-AI key flow.
- Log in to Bybit → API Management → Create New Key (do this from inside a Standard sub-account if possible — never from the main account).
- Permissions: enable Read + Trade only (NEVER enable Withdraw for AI use).
- Bind your IP address (makes the key permanent; otherwise expires in 3 months).
- Fund the (sub-)account with only the amount you're willing to risk in one bad day.
Step 2: Configure Credentials
Credential setup depends on where the AI runs. Auto-detect the environment and follow the matching path:
Path A — Local CLI (Claude Code, Cursor, or any tool with shell access):
Copy-paste this into ~/.zshrc or ~/.bashrc:
export BYBIT_API_KEY="your_api_key"
export BYBIT_API_SECRET="your_secret_key"
export BYBIT_ENV="testnet" # or "mainnet"
Using an RSA API Key instead? (Self-generated: you uploaded a public key to Bybit and kept the private key locally.) Replace the BYBIT_API_SECRET line with:
export BYBIT_API_PRIVATE_KEY_PATH="/absolute/path/to/private.pem"
Everything else stays the same. Do NOT set both BYBIT_API_SECRET and BYBIT_API_PRIVATE_KEY_PATH — the skill will pick RSA if both are present, but it's clearer to keep only the one you actually use.
On first use, check if these environment variables exist. If they do, use them directly — do NOT ask the user to paste keys in the conversation. If they don't exist, guide the user to set them up:
- Tell the user: "For security, I recommend storing your API keys as environment variables instead of pasting them here."
- Provide the export commands above
- After the user has set them, verify with
echo $BYBIT_API_KEY | head -c5 (only show first 5 chars to confirm)
Path B — Self-hosted OpenClaw (user runs OpenClaw on their own machine/server):
Keys stay on the user's machine — same security level as Path A. Configure via .env file:
Paste into ~/.openclaw/.env (recommended) or ./.env in your working directory:
BYBIT_API_KEY=your_api_key
BYBIT_API_SECRET=your_secret_key
BYBIT_ENV=testnet
Using an RSA API Key instead? Replace the BYBIT_API_SECRET line with:
BYBIT_API_PRIVATE_KEY_PATH=/absolute/path/to/private.pem
Everything else stays the same. Only set one of BYBIT_API_SECRET or BYBIT_API_PRIVATE_KEY_PATH, not both.
Alternative: openclaw.json env block — { "env": { "vars": { "BYBIT_API_KEY": "...", "BYBIT_API_SECRET": "...", "BYBIT_ENV": "testnet" } } } (swap BYBIT_API_SECRET for BYBIT_API_PRIVATE_KEY_PATH if using RSA).
On first use, check if these environment variables exist. If they do, use them directly. If they don't, guide the user to create ~/.openclaw/.env with the variables above.
Path C — Cloud platforms (hosted OpenClaw, Claude.ai, ChatGPT, Gemini, and other hosted AI services):
These platforms have no secret store. Keys must be pasted in the conversation (sent to AI provider's servers).
On first use:
- Accept keys pasted in the conversation
- Warn once: "Your keys will be sent through this platform's servers. For safety, use a sub-account with limited balance and Read+Trade permissions only (no Withdraw)."
- Do NOT ask again in the same session
Path D — OAuth (one-click authorization):
For AI assistants with shell access (Claude Code, Cursor, OpenClaw, etc.), the OAuth flow lets users authorize their Bybit account with a single click — no manual key creation needed. This uses the oauth/ module bundled with this skill. Cloud agents (OpenClaw, remote servers) automatically use headless mode — the user pastes the authorization code from the popup instead of relying on a localhost callback.
⚠️ MANDATORY first step for Path D: load modules/oauth.md and execute its Bootstrap section. The OAuth executable (modules/oauth.js) is NOT delivered by auto-update — it is lazy-fetched from raw.github with a SHA256-pinned check inside oauth.md. Without running Bootstrap first, every node ... modules/oauth.js ... command below will fail with Cannot find module on fresh installs. Do NOT run the credential check below until Bootstrap reports success.
Once Bootstrap succeeds, check if the OAuth credential file exists and has a valid (non-expired) token:
node -e "console.log(require('<skill_dir>/modules/oauth.js').getCredentialPath())"
Read the file at that path. If it exists, created_at + expires_in > now, and ai-account is present → use ai-account.api_key and ai-account.api_secret as credentials. No further setup needed.
If the file is missing, expired, or incomplete → follow the full OAuth Authorization Flow section below.
Fallback (all platforms): If the user provides keys directly in the conversation, accept them but remind once about the more secure alternative for their platform.
Display rules (never show full credentials):
- API Key: show first 5 + last 4 characters (e.g.,
AbCdE...x1y2)
- Secret Key: show last 5 only (e.g.,
***...vWxYz)
- Code blocks (CRITICAL): NEVER include raw API Key or Secret Key values in generated code, scripts, or curl examples — even if the actual values are available in environment variables or session context. ALWAYS use
$BYBIT_API_KEY / $BYBIT_API_SECRET (or ${API_KEY} / ${SECRET_KEY}) as variable references. This applies to ALL output formats including bash, python, and JSON. Violation of this rule is a security incident.
Step 3: Verify Connection (auto-run on first use)
After credentials are configured, automatically run these checks:
0. Determine sign type (no network call):
If $BYBIT_API_PRIVATE_KEY_PATH is set:
- Expand leading ~/ to absolute path
- If file exists, is readable, and its first line contains "PRIVATE KEY":
→ Select RSA (X-BAPI-SIGN-TYPE: 2) for all subsequent requests
- Else:
→ Halt. Tell user: "Private key path set but file unreadable: <path>"
Do NOT silently fall back to HMAC.
Else if $BYBIT_API_SECRET is set:
→ Select HMAC (X-BAPI-SIGN-TYPE: 1 or omitted)
Else if OAuth credential file exists (Path D) and ai-account is present:
- Check expiration: created_at + expires_in > now
- If expired: attempt refresh (load oauth module, see "OAuth: Refresh token" section)
- If refresh fails or no refresh_token: re-run OAuth flow
- Use ai-account.api_key as $BYBIT_API_KEY and ai-account.api_secret as $BYBIT_API_SECRET
→ Select HMAC (same as branch above)
Else:
→ Tell user:
"Please configure credentials first.
- Quickest: run the OAuth flow (say 'authorize Bybit' or see Path D)
- HMAC secret string: export BYBIT_API_SECRET=...
- RSA private key file: export BYBIT_API_PRIVATE_KEY_PATH=/path/to/private.pem
See Bybit API management for how to create keys."
Stop; do not attempt authenticated calls.
If both $BYBIT_API_PRIVATE_KEY_PATH and $BYBIT_API_SECRET are set,
prefer RSA and emit once:
"Both BYBIT_API_SECRET and BYBIT_API_PRIVATE_KEY_PATH are set. Using RSA.
To force HMAC, unset BYBIT_API_PRIVATE_KEY_PATH."
If RSA is selected and the 'openssl' CLI is not available, halt with:
"RSA signing requires the 'openssl' CLI. Install it or switch to HMAC."
# 1. Clock sync check (no auth needed)
GET /v5/market/time
# Compare response "timeSecond" with local time. If difference > 5 seconds:
# → Tell user: "Your system clock is off by Xs. Please sync your clock (e.g., enable automatic date/time in system settings)."
# → Do NOT proceed with authenticated requests until clock is synced (signatures will fail).
# 2. Verify signature and permissions
GET /v5/account/wallet-balance?accountType=UNIFIED
Step 4: Choose Environment
Default: Mainnet. Always start in Mainnet mode unless the user explicitly requests Testnet.
| Mode |
Base URL |
Behavior |
| Mainnet (default) |
https://api.bybit.com |
Write operations require confirmation. Real funds. |
| Testnet |
https://api-testnet.bybit.com |
All operations execute freely. No real funds at risk. |
Switching rules:
- To switch to Testnet, the user must explicitly say "switch to testnet" / "use test account" / "use demo"
- When switching to Testnet, display: "Switching to TESTNET. All operations will use test funds — no real money at risk."
- To switch back to Mainnet, the user must explicitly request it. Display a confirmation prompt: "You are switching back to MAINNET. All subsequent write operations will use real funds. Type CONFIRM to proceed." Wait for CONFIRM before switching.
- Always show the current environment in every response that involves API calls:
[MAINNET] or [TESTNET]
- If the user provides a Testnet API Key (starts with testing), automatically use Testnet URL
Step 5: Start Trading
Tell the user what they can do. Examples:
- "What's the BTC price?"
- "Buy 500 USDT worth of BTC"
- "Open a 10x BTC long position"
- "Check my balance"
Module Router
This skill uses modular on-demand loading. When the user's request matches a module below, fetch the corresponding file ONCE per session per module, then use it for all subsequent requests in that category.
How to load a module
1. Identify which module(s) the user's request needs from the table below
2. If the module has NOT been loaded in this session:
a. Ensure manifest is available:
- If cached from Auto Update: reuse it
- Otherwise: MANIFEST = curl -sf -H "User-Agent: bybit-skill/1.7.12" https://api.bybit.com/skill/manifest
- If fetch fails: use current local version of the module (SKILL_DIR/modules/<module>.md)
If no local version exists: inform user module unavailable, only GET operations permitted
- Cache manifest in session
b. Download: curl -sf -H "User-Agent: bybit-skill/1.7.12" https://raw.githubusercontent.com/bybit-exchange/skills/main/modules/<module>.md
- If download fails: use current local version of the module
If no local version exists: inform user module unavailable, only GET operations permitted
c. Verify integrity:
- Compute SHA256 of downloaded content
- Compare with manifest.files["modules/<module>.md"] (strip "sha256:" prefix)
- If mismatch: use current local version (do NOT use the downloaded content)
If no local version exists: inform user module unavailable, only GET operations permitted
- If match: use downloaded content, save to SKILL_DIR/modules/<module>.md, cache in session
3. For subsequent requests in same category: use cached version (do NOT re-fetch)
Module Index
| User Intent Keywords |
Module |
File |
Requires |
| price, ticker, kline, chart, orderbook, depth, funding rate, open interest, market data |
market |
modules/market.md |
— |
| buy, sell, spot, swap, exchange, convert, limit order, market order, cancel order, spot margin |
spot |
modules/spot.md |
account |
| long, short, leverage, futures, perpetual, close position, take profit, stop loss, trailing stop, conditional order, hedge mode, option, put, call, strike, expiry |
derivatives |
modules/derivatives.md |
account |
| earn, stake, redeem, yield, savings, flexible, flexible auto savings, auto savings, auto-savings, fixed deposit, fixed term, fund pool, dual assets, structured product, discount buy, smart leverage, double win, liquidity mining, auto reinvest, early redeem, hold-to-earn, airdrop yield, PWM, private wealth, investment plan, fund management, asset manager |
earn |
modules/earn.md |
account |
| balance, wallet, transfer, deposit, withdraw, fee, sub-account, API key, asset, fixed-rate borrow, borrow liability, repayment type, renew borrow, borrow market, borrow order, borrow contract, fixed borrow, fixed borrow penalty interest, cancel fixed-rate borrow order, margin borrow, trade auto repay, trade auto repayment, automatic repayment after spot trades, referral, referral code, invitation code, invite link, affiliate, referral profile, invited friends, invitation records, referral commissions, commission records, referral campaign rewards, tax report, batch tax export, tax report status |
account |
modules/account.md |
— |
| websocket, stream, loan, borrow, repay, RFQ, block trade, spread, lending, broker, rate limit |
advanced |
modules/advanced.md |
— |
| P2P, peer to peer, advertisement, ad, OTC, fiat, fiat buy, fiat sell, convert fiat |
fiat |
modules/fiat.md |
— |
| copy trading, leader, follower, copy trade, leaderboard, recommend trader |
copy-trading |
modules/copy-trading.md |
derivatives, account |
| grid bot, DCA bot, martingale, combo bot, trading bot, create bot, close bot, TradFi Combo, MT5 combo, tradfi bot, stock portfolio bot, commodity portfolio bot, rebalance bot, XAUUSD+, XAGUSD, USOUSD, 股票组合机器人, 大宗商品组合, 传统金融机器人, 组合调仓机器人 |
trading-bot |
modules/trading-bot.md |
account, derivatives |
| alpha, on-chain, DEX, meme coin, swap token, on-chain asset, token trade, prediction, prediction market, bet, betting, YES/NO, sports market, World Cup, FIFA, event trading |
alpha-trade |
modules/alpha-trade.md |
account |
| TWAP, iceberg, chase order, chaseOrder, strategy order, split order, algorithmic, POV, percentage of volume, volume participation |
strategy |
modules/strategy.md |
account |
| xStocks, tokenized stock, commodity perpetual, XAUUSDT, XAGUSDT, CLUSDT, crude oil, buy/sell TradFi, metals agreement, oil agreement |
tradfi |
modules/tradfi.md |
account, spot, derivatives |
| card, bybit card, card transaction, card spending, card payment, card history |
card |
modules/card.md |
account |
| Launchpool, launch pool, launchpad, new token mining, puzzle, token splash, Spot-X, spotx, campaign, activity list, activity reward, staking activity, project list |
activity |
modules/activity.md |
— |
| authorize, OAuth, connect Bybit, login Bybit, 授权, 登录, one-click auth, enable Bybit trade execution, Authorize via OAuth |
oauth |
modules/oauth.md |
— |
Module-specific notes:
- Referral: Referral identity, invited friends, referral commissions, and referral campaign rewards route to
account. The four /v5/referral/* POST endpoints are authenticated read-only queries. Referral campaign rewards describe static configuration, not personal task progress, claims, or payouts. Use the documented camelCase request and response names, including the embedded campaign V2 JSON; acceptance of legacy snake_case aliases and actual gateway serialization remain unverified. Spot-X / Launchpool / Token Splash activities still route to activity.
- Trade auto repay: Querying or changing repayment after eligible spot trades routes to
account. The switch uses string autoRepay ("0" disabled, "1" enabled) and is separate from scheduled auto repayment. Saving the switch does not prove debt was repaid; it runs only in Cross and Portfolio margin modes, with no effect in Isolated mode. Enabling or disabling it is a write operation requiring Mainnet confirmation.
- Fixed-rate borrow: Penalty interest queries and borrow-order cancellation route to
account. Penalty queries are read-only and report prior deductions; they do not charge interest. Borrow-order cancellation is a write operation requiring Mainnet confirmation, uses the borrow-order orderId, and does not repay a matched loan. Request acceptance must be followed by an order-status query before reporting completion.
- ⚠️
tradfi vs TradFi Combo in trading-bot (easy to confuse): tradfi = trading TradFi assets yourself (tokenized stocks TSLAXUSDT, commodity perps XAUUSDT/CLUSDT) via standard V5 order endpoints. The TradFi Combo auto-rebalancing portfolio bot over MT5 instruments (XAUUSD+, XAGUSD, USOUSD) via /v5/mt5combobot/* lives in the TradFi Combo section of modules/trading-bot.md. Different symbols, different endpoints. "Buy some gold" → tradfi. "Build me a gold+oil portfolio bot" → trading-bot. A bare mention of "TradFi Combo" / "MT5 combo" / a stock-or-commodity portfolio bot must route to trading-bot, NOT to tradfi — tradfi.md does not document /v5/mt5combobot/* at all. If genuinely ambiguous, ask which one.
- Derivatives: Conditional orders require
triggerDirection: 1=price rises above trigger, 2=price falls below trigger. Buy-the-dip → 2, breakout buy → 1.
- Fiat/P2P: P2P responses use
ret_code (underscore format, not retCode). P2P ad posting requires General Advertiser+ permission level.
- Spot ↔ Convert fallback: Spot order endpoints (
/v5/order/create) only support listed spot pairs (base + quote where quote ∈ USDT/USDC/USDE/BTC/ETH/EUR/BRL). If the user names a base-base pair (e.g., BTCDOGE, ETHSOL, SOLPEPE) or any pair you cannot confirm is a listed spot symbol, do NOT call spot order create. Route to Convert via the /v5/asset/exchange/* endpoints in the account module: (1) query-coin-list to confirm both coins are convertible, (2) quote-apply to lock a quote, (3) user CONFIRM, (4) convert-execute before the quote expires (typically ~5s). When suggesting this fallback, tell the user that the pair is not a listed spot symbol and propose Convert instead — surface fromCoin, toCoin, requestAmount, quote price, and expireTime in the confirmation.
- Trading Bot: Bot API uses
status_code/debug_msg response format (NOT retCode/retMsg). Always call validate-input (spot grid) or validate (futures grid) before creation — this returns acceptable parameter ranges and catches errors early. DCA: max 5 trading pairs per bot; if user requests more, ask them to choose up to 5.
- Alpha Trade: Uses a quote-then-execute model — always call
/v5/alpha/trade/quote first. Token codes use CEX_<id> (payment tokens like USDT) and DEX_<id> (on-chain tokens). All endpoints are POST (including queries). Settlement is on-chain (10-60s). KYC required.
- Strategy: Strategy API uses
UTA_* category format ONLY. Do NOT use linear/spot — map: linear → UTA_USDT, spot → UTA_SPOT, inverse → UTA_INVERSE. Chase orders: chaseDistance and chasePercentE4 are mutually exclusive — use ONE only. NEVER use category=linear or category=spot in Strategy API calls — this will cause errors. Always translate: derivatives/perpetual/futures → UTA_USDT, spot → UTA_SPOT. POV (Percentage of Volume): adapts child order size to live market activity; supports Perp (UTA_USDT/UTA_USDC/UTA_INVERSE) and Spot (UTA_SPOT). Iceberg and POV support quantity (size) or value (positionValue) sizing; never send both together. See modules/strategy.md for splitting and stop-condition rules.
- Copy Trading: The
investmentE8 parameter uses 8-decimal precision (multiply USDT amount by 10^8). For example, 100 USDT = 10000000000 (100 × 10^8). Always apply this conversion when the user specifies an investment amount in USDT.
- TradFi: Discover instruments via
instruments-info with symbolType=xstocks (spot, e.g., TSLAXUSDT) or symbolType=commodity (linear, e.g., XAUUSDT/CLUSDT). Trading reuses standard V5 order endpoints — no TradFi-specific trade API. Metals (XAU/XAG) and Crude Oil (CL) require a one-time master-account agreement via POST /v5/user/agreement (categoryV2=2 metals, categoryV2=3 oil); xStocks do not. Subaccounts inherit eligibility once the master signs. xStocks instruments include extra fields such as xstockMultiplier.
- OAuth: When triggered, load
modules/oauth.md and follow the OAuth Authorization Flow documented there. After authorization completes, credentials are automatically available for all other modules (spot, derivatives, etc.) via the Runtime Decision logic in Step 3.
Routing Notes
- Keywords are hints, not strict rules — always use semantic understanding of the user's full request to determine the correct module(s). When ambiguous (e.g., "borrow" could mean spot margin or advanced lending), prefer the module matching the broader conversation context, or ask the user to clarify.
- Common Chinese synonyms: 查价/看价 → market, 买/卖/现货 → spot, 开多/开空/合约/杠杆 → derivatives, 理财/质押/双币/持币生息/私人财富/自动储蓄/灵活储蓄自动储蓄 → earn, 余额/转账/充值/提币/固定借款罚息/取消固定借款订单/交易自动还款/现货交易后自动还款/邀请身份/邀请记录/受邀好友/邀请返佣/返佣记录/邀请活动奖励/税务报表/批量税务导出/税务报表进度 → account, 跟单 → copy-trading, 网格/DCA/AI推荐/一键创建/策略推荐/组合机器人/调仓机器人/股票组合/大宗商品组合/传统金融机器人 → trading-bot, 链上/meme/DEX/代币/预测/押注/预测市场/世界杯/FIFA → alpha-trade, 买入代币化股票/特斯拉/苹果/英伟达/黄金/白银/原油/商品永续 → tradfi, 拆单/算法单/POV → strategy, 银行卡/消费记录/刷卡 → card, 打新/新币挖矿/launchpool/拼图/代币空投/活动列表/质押活动 → activity, 授权/登录/连接Bybit/OAuth → oauth
Loading Rules
- Match intent → load module: A single user request may need multiple modules (e.g., "check BTC price then buy" → market + spot)
- Auto-load dependencies: When loading a module, also load all modules listed in its
Requires column (e.g., loading derivatives → also load account if not already loaded)
- Load once per session: Do NOT re-fetch a module already loaded in this conversation
- Fail gracefully: Follow the Graceful Degradation rules below.
- Multiple modules OK: Load as many modules as needed for the user's request
- Retry once: If GitHub Raw fails, retry the same URL once. If still failing, follow Graceful Degradation.
Graceful Degradation (unified fallback rules)
All failure scenarios (auto-update, module loading, manifest fetch) follow this single priority chain:
- Local version available → use it silently. Do not inform the user unless they ask about version.
- No local version, network failed → inform user that the module is unavailable. Only read-only (GET) operations are permitted using the Authentication and Common Parameters sections. Do NOT execute POST (write) operations — tell the user to retry later.
- Checksum mismatch on download → treat as network failure (use local version if available; otherwise step 2).
Authentication
Base URLs
| Region |
URL |
| Global (default) |
https://api.bybit.com |
| Global (backup) |
https://api.bytick.com |
Request Signature
Headers (required for every authenticated request):
| Header |
Value |
X-BAPI-API-KEY |
API Key |
X-BAPI-TIMESTAMP |
Unix millisecond timestamp |
X-BAPI-SIGN |
HMAC-SHA256 signature |
X-BAPI-RECV-WINDOW |
5000 |
X-BAPI-SIGN-TYPE |
2 for RSA-SHA256; omit or set 1 for HMAC-SHA256 |
Content-Type |
application/json (POST) |
User-Agent |
bybit-skill/1.7.12 |
X-Referer |
bybit-skill |
Signing Algorithm
Bybit V5 supports two signing methods. Auto-select at runtime by env var (see Step 3).
| Sign Type |
When to use |
X-BAPI-SIGN-TYPE |
Output encoding |
| HMAC-SHA256 |
Bybit-generated key (you received a Secret string) |
1 (or omit) |
hex |
| RSA-SHA256 |
Self-generated key (you uploaded the public key to Bybit) |
2 |
base64 |
Shared param_str (identical for both methods):
- GET:
{timestamp}{apiKey}{recvWindow}{queryString}
- POST:
{timestamp}{apiKey}{recvWindow}{jsonBody}
The jsonBody used for signing MUST be compact JSON (no extra spaces/newlines), byte-identical to the request body. Example: {"key":"value"} not { "key": "value" }.
HMAC-SHA256 signature:
SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)
RSA-SHA256 signature (PKCS#1 v1.5 padding):
SIGN=$(printf '%s' "$PARAM_STR" \
| openssl dgst -sha256 -sign "$BYBIT_API_PRIVATE_KEY_PATH" -binary \
| base64 | tr -d '\n')
Use printf '%s' (not echo -n) for RSA to guarantee no trailing newline across shells. tr -d '\n' strips any line wrapping that base64 may add on BSD/LibreSSL.
Complete curl Examples
Security: When generating code for the user, ALWAYS use environment variable references ($BYBIT_API_KEY, $BYBIT_API_SECRET, $BYBIT_API_PRIVATE_KEY_PATH) — NEVER substitute actual values or file paths into code blocks, even if they are available in the session. This is security-critical.
The only differences between HMAC and RSA requests are (a) the X-BAPI-SIGN-TYPE: 2 header for RSA and (b) how SIGN is computed (base64 vs hex). param_str, timestamp, recvWindow, body, and other headers are identical.
GET — HMAC (query positions):
API_KEY="$BYBIT_API_KEY"
SECRET_KEY="$BYBIT_API_SECRET"
BASE_URL="https://api.bybit.com"
RECV_WINDOW=5000
TIMESTAMP=$(date +%s000)
QUERY="category=linear&symbol=BTCUSDT"
PARAM_STR="${TIMESTAMP}${API_KEY}${RECV_WINDOW}${QUERY}"
SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)
curl -s "${BASE_URL}/v5/position/list?${QUERY}" \
-H "X-BAPI-API-KEY: ${API_KEY}" \
-H "X-BAPI-TIMESTAMP: ${TIMESTAMP}" \
-H "X-BAPI-SIGN: ${SIGN}" \
-H "X-BAPI-RECV-WINDOW: ${RECV_WINDOW}" \
-H "User-Agent: bybit-skill/1.7.12" \
-H "X-Referer: bybit-skill"
POST — HMAC (place spot market order):
API_KEY="$BYBIT_API_KEY"
SECRET_KEY="$BYBIT_API_SECRET"
BASE_URL="https://api.bybit.com"
RECV_WINDOW=5000
TIMESTAMP=$(date +%s000)
BODY='{"category":"spot","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"500","marketUnit":"quoteCoin"}'
PARAM_STR="${TIMESTAMP}${API_KEY}${RECV_WINDOW}${BODY}"
SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)
curl -s -X POST "${BASE_URL}/v5/order/create" \
-H "Content-Type: application/json" \
-H "X-BAPI-API-KEY: ${API_KEY}" \
-H "X-BAPI-TIMESTAMP: ${TIMESTAMP}" \
-H "X-BAPI-SIGN: ${SIGN}" \
-H "X-BAPI-RECV-WINDOW: ${RECV_WINDOW}" \
-H "User-Agent: bybit-skill/1.7.12" \
-H "X-Referer: bybit-skill" \
-d "${BODY}"
To use RSA instead: apply these two changes to either HMAC example above.
Replace the SIGN= line with:
PRIV_KEY="$BYBIT_API_PRIVATE_KEY_PATH"
SIGN=$(printf '%s' "$PARAM_STR" \
| openssl dgst -sha256 -sign "$PRIV_KEY" -binary \
| base64 | tr -d '\n')
Add one header to the curl call:
-H "X-BAPI-SIGN-TYPE: 2" \
Everything else — param_str, timestamp, recvWindow, body, other headers — is identical to the HMAC version.
Runtime Decision
At runtime, inspect env vars in this order for every authenticated call:
- If
$BYBIT_API_PRIVATE_KEY_PATH is set and the file is readable → RSA branch.
(If $BYBIT_API_SECRET is also set, RSA still wins — emit a one-time "Using RSA" notice at Step 3.)
- Else if
$BYBIT_API_SECRET is set → HMAC branch.
- Else if the OAuth credential file exists (see Path D) and
ai-account is present with a non-expired token → use ai-account.api_key / ai-account.api_secret as HMAC credentials. If the token is expired but refresh_token is still valid, refresh it first (load oauth module, see "OAuth: Refresh token" section).
- Else → prompt the user to configure credentials (see Step 1). Mention OAuth (Path D) as the quickest option for platforms with shell access.
If $BYBIT_API_PRIVATE_KEY_PATH is set but the file is missing or unreadable, halt with an explicit error. Do NOT silently fall back to HMAC.
Never mix the two: never include both an HMAC-derived X-BAPI-SIGN and a raw private-key reference on the same request.
Response Format
{"retCode": 0, "retMsg": "OK", "result": {}, "time": 1672211918471}
retCode=0 means success; non-zero indicates an error.
Common Parameter Reference
Core Parameters
| Parameter |
Description |
Values |
| category |
Product category |
spot linear inverse option |
| symbol |
Trading pair |
Uppercase, e.g. BTCUSDT |
| side |
Direction |
Buy Sell |
| orderType |
Order type |
Market Limit |
| qty |
Quantity |
String |
| price |
Price |
String (required for Limit orders) |
| timeInForce |
Time in force |
GTC IOC FOK PostOnly RPI |
| positionIdx |
Position index |
0 (one-way) 1 (hedge buy/long) 2 (hedge sell/short) |
| accountType |
Account type |
UNIFIED FUND |
TradFi-Specific Parameters
| Parameter |
Description |
Values |
| symbolType |
TradFi filter for /v5/market/instruments-info |
xstocks (spot category) commodity (linear category) |
symbolType is a TradFi-specific filter parameter. Standard spot/linear queries do not require this parameter.
Order Parameters
| Parameter |
Description |
Values |
| triggerPrice |
Trigger price for conditional orders |
String |
| triggerDirection |
Trigger direction (required for conditional) |
1 (rise to) 2 (fall to) |
| triggerBy |
Trigger price type |
LastPrice IndexPrice MarkPrice |
| reduceOnly |
Reduce only flag |
true / false |
| marketUnit |
Spot market buy unit |
baseCoin quoteCoin |
| orderLinkId |
User-defined order ID |
String (must be unique) |
| orderFilter |
Order filter |
Order tpslOrder StopOrder |
| takeProfit |
TP price (pass "0" to cancel) |
String |
| stopLoss |
SL price (pass "0" to cancel) |
String |
| tpslMode |
TP/SL mode |
Full (entire position) Partial |
Enums Reference
| Enum |
Values |
| orderStatus (open) |
New PartiallyFilled Untriggered |
| orderStatus (closed) |
Rejected PartiallyFilledCanceled Filled Cancelled Triggered Deactivated |
| stopOrderType |
TakeProfit StopLoss TrailingStop Stop PartialTakeProfit PartialStopLoss tpslOrder OcoOrder |
| execType |
Trade AdlTrade Funding BustTrade Delivery Settle BlockTrade MovePosition FutureSpread SessionSettlePnL CoinSwap CorporateAction ForwardSplitSettle ReverseSplitSettle |
| interval (kline) |
1 3 5 15 30 60 120 240 360 720 D W M |
| intervalTime |
5min 15min 30min 1h 4h 1d |
| positionMode |
0 (one-way) 3 (hedge) |
| setMarginMode |
ISOLATED_MARGIN REGULAR_MARGIN PORTFOLIO_MARGIN |
Error Handling
Common Error Codes
System & Auth (10000-10099)
| retCode |
Name |
Meaning |
Resolution |
| 0 |
OK |
Success |
— |
| 10001 |
REQUEST_PARAM_ERROR |
Invalid parameter |
Check missing/invalid params; hedge mode may require positionIdx |
| 10002 |
REQUEST_EXPIRED |
Timestamp expired |
Timestamp outside recvWindow (±5000ms); sync system clock |
| 10003 |
INVALID_API_KEY |
Invalid API key |
Key invalid or wrong environment (testnet vs mainnet). If using RSA: confirm the public key uploaded to Bybit and the private key at $BYBIT_API_PRIVATE_KEY_PATH are the matching pair. Error messages should include (current sign type: HMAC|RSA). |
| 10004 |
INVALID_SIGNATURE |
Signature error |
Verify param_str order {timestamp}{apiKey}{recvWindow}{params}, compact JSON body. If using RSA: verify X-BAPI-SIGN-TYPE: 2, output is base64 (not hex), padding is PKCS#1 v1.5 (not PSS). Error messages should include (current sign type: HMAC|RSA). |
| 10005 |
PERMISSION_DENIED |
Permission denied |
API Key lacks required permission → Manage API Keys |
| 10006 |
TOO_MANY_REQUESTS |
Rate limited |
Pause 1s then retry; check X-Bapi-Limit-Status header |
| 10010 |
UnmatchedIp |
IP not whitelisted |
Add current IP in API Key settings |
| 10014 |
DUPLICATE_REQUEST |
Duplicate request |
Duplicate request detected; avoid resending identical requests |
| 10016 |
INTERNAL_SERVER_ERROR |
Server error |
Retry later |
| 10017 |
ReqPathNotFound |
Path not found |
Check request path and HTTP method |
| 10027 |
TRADING_BANNED |
Trading banned |
Trading not allowed for this account |
| 10029 |
SYMBOL_NOT_ALLOWED |
Invalid symbol |
Symbol not in the allowed list |
Trade Domain (110000-169999)
| retCode |
Name |
Meaning |
Resolution |
| 110001 |
ORDER_NOT_EXIST |
Order does not exist |
Check orderId/orderLinkId; order may have been filled or expired |
| 110003 |
ORDER_PRICE_OUT_OF_RANGE |
Price out of range |
Call instruments-info for priceFilter: minPrice/maxPrice/tickSize |
| 110004 |
INSUFFICIENT_WALLET_BALANCE |
Wallet balance insufficient |
Reduce qty or Deposit |
| 110007 |
INSUFFICIENT_AVAILABLE_BALANCE |
Available balance insufficient |
Balance may be locked by open orders; cancel orders to free up |
| 110008 |
ORDER_ALREADY_FINISHED |
Order completed/cancelled |
Order already filled or cancelled; no action needed |
| 110009 |
TOO_MANY_STOP_ORDERS |
Too many stop orders |
Reduce number of conditional/stop orders |
| 110020 |
TOO_MANY_ACTIVE_ORDERS |
Active order limit exceeded |
Cancel some active orders first |
| 110021 |
POSITION_EXCEEDS_OI_LIMIT |
Position exceeds OI limit |
Reduce position size |
| 110040 |
ORDER_WOULD_TRIGGER_LIQUIDATION |
Would trigger liquidation |
Reduce qty or add margin |
| 110057 |
INVALID_TPSL_PARAMS |
Invalid TP/SL params |
Check TP/SL settings; ensure tpslMode and positionIdx are included |
| 110072 |
DUPLICATE_ORDER_LINK_ID |
Duplicate orderLinkId |
orderLinkId must be unique per order |
| 110094 |
ORDER_NOTIONAL_TOO_LOW |
Notional below minimum |
Increase order size; check instruments-info for minNotionalValue |
Spot Trade (170000-179999)
| retCode |
Name |
Meaning |
Resolution |
| 170005 |
SPOT_TOO_MANY_NEW_ORDERS |
Too many spot orders |
Spot rate limit exceeded; slow down |
| 170121 |
|
|
|
…(truncated)
1---2name: bybit-trading-23description: Bybit AI Trading Skill — Trade on Bybit using natural language. Covers spot, derivatives, earn, and more. Works with Claude, ChatGPT, OpenClaw, and any AI assistant.4metadata:5 source: https://skillmd.com/skills/jiayaoqijia/bybit-trading-26 version: 1.7.12 # Modular Architecture + Security Baseline7 author: Bybit8 updated: 2026-11-109license: MIT10---1112# Bybit Trading Skill1314Trade on Bybit using natural language. Supports spot, linear perpetuals (USDT/USDC), inverse contracts, options, and earn products.1516### Rule Priority1718When rules in this skill conflict, follow this order: **Safety > User Responsiveness > Convenience**. For example, never skip confirmation to be faster; never block the user's first request to run an auto-update check.1920### Auto Update (MUST follow at session start)2122This skill supports self-update with integrity verification. At the start of each new session, launch the update check as a **background sub-agent** so it never blocks the user's first request:2324```25FOREGROUND (main agent — immediate):261. Respond to the user's request using the current local version. Do NOT wait for the update check.2728BACKGROUND (sub-agent — parallel):291. LOCAL_VERSION = metadata.version (from YAML frontmatter above)302. SKILL_DIR = directory where this SKILL.md is located313. MANIFEST = curl -sf -H "User-Agent: bybit-skill/1.7.12" https://api.bybit.com/skill/manifest32 (returns JSON: {"version":"x.y.z", "files":{"SKILL.md":"sha256:...","modules/market.md":"sha256:...",...}})334. If fetch fails: return {status: "error", reason: "fetch_failed"}345. Path validation: For each file in manifest.files, reject the entire update if ANY path:35 - Does not match `SKILL.md`, `modules/<name>.md`, or `modules/<name>.js` (where <name> is [a-z0-9-]+)36 - Contains `..`, starts with `/` or `~`, contains backslashes, or has an extension other than `.md` or `.js`37 If any path is invalid: return {status: "error", reason: "invalid_path", path: "<rejected>"}386. Version comparison (semver): split by ".", compare major → minor → patch numerically.39 If manifest.version > LOCAL_VERSION:40 a. For each file in manifest.files:41 - Download: curl -sf -H "User-Agent: bybit-skill/1.7.12" https://raw.githubusercontent.com/bybit-exchange/skills/main/<file>42 - Save content to temp file, then compute SHA256: shasum -a 256 <temp_file> | awk '{print $1}'43 - Compare with manifest checksum (strip "sha256:" prefix)44 - If mismatch: ABORT entire update. return {status: "error", reason: "checksum_mismatch", file: "<file>"}45 - If file extension is `.js` AND the local file already exists at SKILL_DIR/<file>:46 → Show to user: "⚠️ Code module update: <file> (LOCAL_VERSION → manifest.version). Allow? [Y/n]"47 → If user declines: skip this file, continue with remaining files48 - If match: save to SKILL_DIR/.skill-update-tmp/<file>49 b. ALL files verified → move from temp to SKILL_DIR:50 - For each file: mkdir -p parent dir, then mv .skill-update-tmp/<file> SKILL_DIR/<file>51 - rm -rf SKILL_DIR/.skill-update-tmp/52 c. return {status: "updated", from: LOCAL_VERSION, to: manifest.version}53 If manifest.version == LOCAL_VERSION:54 d. return {status: "current"}5556WHEN SUB-AGENT COMPLETES (main agent receives result):57- If status="updated": notify user "Skill updated from {from} to {to}. Using latest version." Re-read updated SKILL.md.58- If status="current" or status="error": silently continue with current version.59- Cache manifest (if returned) in session memory for module loading (see Module Router).60```6162**Rules:**63- Check at most ONCE per session. Do not re-check during the same conversation.64- If any network request fails (timeout, 404, etc.), skip silently and proceed with current version. (See Graceful Degradation below for unified fallback rules.)65- **Never block the user's first request.** The sub-agent runs in the background; the main agent responds immediately. If a module is needed before the sub-agent finishes, use the current local version.66- If checksum algorithm prefix is not "sha256:", refuse the update (fail closed).6768---6970## Quick Start7172### Step 1: Get an API Key7374Pick **one** of the two paths below. The AI Subaccount path is **strongly preferred** — it's Bybit's purpose-built account type for AI trading, with built-in cap limits and a public-key-based key flow.7576#### Path A — AI Subaccount (Recommended)7778Bybit's official AI-trading account type ([help article](https://www.bybit.com/en/help-center/article/Introduction-to-the-AI-Subaccount)).7980- **Create it (Bybit mobile app)**: Profile icon → **Settings → Subaccount → Create** → enter a name → select **AI Subaccount** → Confirm + security verification.81- **Get the API key (Public Key flow)**: after creation, Bybit asks for a **Public Key**. Run your AI assistant and ask it to generate one (Claude Code, Open Claw, Cursor, etc. all support this); paste the public key into Bybit → it returns the API key + secret bound to that key. Configure them per Step 2 below.82- **Built-in safety defaults**: **Cap Limit defaults to 5,000 USD** (adjustable from main account → Subaccount → your AI Subaccount → **More → Permissions**). API key **expires in 30 days**; for permanent keys, IP whitelist, finer permission scoping, or higher rate limits, use the Bybit **web platform** instead of the app.83- **Why prefer this**: blast radius is bounded by the cap limit, permissions are managed centrally from the main account (Request Transfer In/Out, Move from Trading/Funding, Max Leverage, etc.), and the subaccount can be killed in one click if anything goes wrong.8485#### Path B — Manual API Key (Fallback)8687Use this only if AI Subaccount isn't available in your region or you need a non-AI key flow.88891. Log in to [Bybit](https://www.bybit.com) → API Management → Create New Key (do this from inside a **Standard sub-account** if possible — never from the main account).902. Permissions: enable **Read + Trade only** (NEVER enable Withdraw for AI use).913. Bind your IP address (makes the key permanent; otherwise expires in 3 months).924. Fund the (sub-)account with only the amount you're willing to risk in one bad day.9394### Step 2: Configure Credentials9596Credential setup depends on where the AI runs. Auto-detect the environment and follow the matching path:9798**Path A — Local CLI** (Claude Code, Cursor, or any tool with shell access):99100Copy-paste this into `~/.zshrc` or `~/.bashrc`:101102```bash103export BYBIT_API_KEY="your_api_key"104export BYBIT_API_SECRET="your_secret_key"105export BYBIT_ENV="testnet" # or "mainnet"106```107108> **Using an RSA API Key instead?** (Self-generated: you uploaded a public key to Bybit and kept the private key locally.) Replace the `BYBIT_API_SECRET` line with:109> ```bash110> export BYBIT_API_PRIVATE_KEY_PATH="/absolute/path/to/private.pem"111> ```112> Everything else stays the same. Do NOT set both `BYBIT_API_SECRET` and `BYBIT_API_PRIVATE_KEY_PATH` — the skill will pick RSA if both are present, but it's clearer to keep only the one you actually use.113114On first use, check if these environment variables exist. If they do, use them directly — do NOT ask the user to paste keys in the conversation. If they don't exist, guide the user to set them up:1151161. Tell the user: "For security, I recommend storing your API keys as environment variables instead of pasting them here."1172. Provide the export commands above1183. After the user has set them, verify with `echo $BYBIT_API_KEY | head -c5` (only show first 5 chars to confirm)119120**Path B — Self-hosted OpenClaw** (user runs OpenClaw on their own machine/server):121122Keys stay on the user's machine — same security level as Path A. Configure via `.env` file:123124Paste into `~/.openclaw/.env` (recommended) or `./.env` in your working directory:125126```127BYBIT_API_KEY=your_api_key128BYBIT_API_SECRET=your_secret_key129BYBIT_ENV=testnet130```131132> **Using an RSA API Key instead?** Replace the `BYBIT_API_SECRET` line with:133> ```134> BYBIT_API_PRIVATE_KEY_PATH=/absolute/path/to/private.pem135> ```136> Everything else stays the same. Only set one of `BYBIT_API_SECRET` or `BYBIT_API_PRIVATE_KEY_PATH`, not both.137138Alternative: `openclaw.json` env block — `{ "env": { "vars": { "BYBIT_API_KEY": "...", "BYBIT_API_SECRET": "...", "BYBIT_ENV": "testnet" } } }` (swap `BYBIT_API_SECRET` for `BYBIT_API_PRIVATE_KEY_PATH` if using RSA).139140On first use, check if these environment variables exist. If they do, use them directly. If they don't, guide the user to create `~/.openclaw/.env` with the variables above.141142**Path C — Cloud platforms** (hosted OpenClaw, Claude.ai, ChatGPT, Gemini, and other hosted AI services):143144These platforms have no secret store. Keys must be pasted in the conversation (sent to AI provider's servers).145146On first use:1471. Accept keys pasted in the conversation1482. Warn once: "Your keys will be sent through this platform's servers. For safety, use a **sub-account with limited balance** and **Read+Trade permissions only** (no Withdraw)."1493. Do NOT ask again in the same session150151**Path D — OAuth (one-click authorization)**:152153For AI assistants with shell access (Claude Code, Cursor, OpenClaw, etc.), the OAuth flow lets users authorize their Bybit account with a single click — no manual key creation needed. This uses the `oauth/` module bundled with this skill. Cloud agents (OpenClaw, remote servers) automatically use headless mode — the user pastes the authorization code from the popup instead of relying on a localhost callback.154155**⚠️ MANDATORY first step for Path D**: load `modules/oauth.md` and execute its **Bootstrap** section. The OAuth executable (`modules/oauth.js`) is NOT delivered by auto-update — it is lazy-fetched from raw.github with a SHA256-pinned check inside `oauth.md`. Without running Bootstrap first, every `node ... modules/oauth.js ...` command below will fail with `Cannot find module` on fresh installs. **Do NOT run the credential check below until Bootstrap reports success.**156157Once Bootstrap succeeds, check if the OAuth credential file exists and has a valid (non-expired) token:158159```bash160node -e "console.log(require('<skill_dir>/modules/oauth.js').getCredentialPath())"161```162163Read the file at that path. If it exists, `created_at + expires_in > now`, and `ai-account` is present → use `ai-account.api_key` and `ai-account.api_secret` as credentials. No further setup needed.164165If the file is missing, expired, or incomplete → follow the full [OAuth Authorization Flow](#oauth-authorization-flow) section below.166167**Fallback (all platforms)**: If the user provides keys directly in the conversation, accept them but remind once about the more secure alternative for their platform.168169**Display rules** (never show full credentials):170- API Key: show first 5 + last 4 characters (e.g., `AbCdE...x1y2`)171- Secret Key: show last 5 only (e.g., `***...vWxYz`)172- **Code blocks (CRITICAL)**: NEVER include raw API Key or Secret Key values in generated code, scripts, or curl examples — even if the actual values are available in environment variables or session context. ALWAYS use `$BYBIT_API_KEY` / `$BYBIT_API_SECRET` (or `${API_KEY}` / `${SECRET_KEY}`) as variable references. This applies to ALL output formats including bash, python, and JSON. Violation of this rule is a **security incident**.173174### Step 3: Verify Connection (auto-run on first use)175176After credentials are configured, automatically run these checks:177178**0. Determine sign type (no network call):**179180```181If $BYBIT_API_PRIVATE_KEY_PATH is set:182 - Expand leading ~/ to absolute path183 - If file exists, is readable, and its first line contains "PRIVATE KEY":184 → Select RSA (X-BAPI-SIGN-TYPE: 2) for all subsequent requests185 - Else:186 → Halt. Tell user: "Private key path set but file unreadable: <path>"187 Do NOT silently fall back to HMAC.188Else if $BYBIT_API_SECRET is set:189 → Select HMAC (X-BAPI-SIGN-TYPE: 1 or omitted)190Else if OAuth credential file exists (Path D) and ai-account is present:191 - Check expiration: created_at + expires_in > now192 - If expired: attempt refresh (load oauth module, see "OAuth: Refresh token" section)193 - If refresh fails or no refresh_token: re-run OAuth flow194 - Use ai-account.api_key as $BYBIT_API_KEY and ai-account.api_secret as $BYBIT_API_SECRET195 → Select HMAC (same as branch above)196Else:197 → Tell user:198 "Please configure credentials first.199 - Quickest: run the OAuth flow (say 'authorize Bybit' or see Path D)200 - HMAC secret string: export BYBIT_API_SECRET=...201 - RSA private key file: export BYBIT_API_PRIVATE_KEY_PATH=/path/to/private.pem202 See Bybit API management for how to create keys."203 Stop; do not attempt authenticated calls.204205If both $BYBIT_API_PRIVATE_KEY_PATH and $BYBIT_API_SECRET are set,206prefer RSA and emit once:207 "Both BYBIT_API_SECRET and BYBIT_API_PRIVATE_KEY_PATH are set. Using RSA.208 To force HMAC, unset BYBIT_API_PRIVATE_KEY_PATH."209210If RSA is selected and the 'openssl' CLI is not available, halt with:211 "RSA signing requires the 'openssl' CLI. Install it or switch to HMAC."212```213214```bash215# 1. Clock sync check (no auth needed)216GET /v5/market/time217# Compare response "timeSecond" with local time. If difference > 5 seconds:218# → Tell user: "Your system clock is off by Xs. Please sync your clock (e.g., enable automatic date/time in system settings)."219# → Do NOT proceed with authenticated requests until clock is synced (signatures will fail).220221# 2. Verify signature and permissions222GET /v5/account/wallet-balance?accountType=UNIFIED223```224225- If clock difference > 5s: stop and ask user to fix clock sync first226- If `retCode=0`: credentials are valid. Tell the user:227 ```228 ✓ Connected to Bybit [Mainnet/Testnet].229 Signing: <HMAC-SHA256 | RSA-SHA256>230 Account: UNIFIED231 Available balance: <X> USDT232 ```233 For RSA, derive `<bits>` from `openssl rsa -in "$BYBIT_API_PRIVATE_KEY_PATH" -text -noout | head -1` (do NOT print any other line of that output — key material must not leak). Show only the file basename, not the full path.234- If `retCode=10003/10004`: signature error. Append `(current sign type: HMAC|RSA)` to the error message so the user knows which branch ran.235- If `retCode=10005`: insufficient permissions. Tell user to check API Key permissions.236- If `retCode=10010`: IP not whitelisted. Tell user to add current IP in API Key settings.237238### Step 4: Choose Environment239240**Default: Mainnet.** Always start in Mainnet mode unless the user explicitly requests Testnet.241242| Mode | Base URL | Behavior |243|------|----------|----------|244| **Mainnet (default)** | `https://api.bybit.com` | Write operations require confirmation. Real funds. |245| **Testnet** | `https://api-testnet.bybit.com` | All operations execute freely. No real funds at risk. |246247**Switching rules:**248- To switch to Testnet, the user must explicitly say "switch to testnet" / "use test account" / "use demo"249- When switching to Testnet, display: "Switching to TESTNET. All operations will use test funds — no real money at risk."250- **To switch back to Mainnet**, the user must explicitly request it. Display a confirmation prompt: "You are switching back to MAINNET. All subsequent write operations will use real funds. Type CONFIRM to proceed." Wait for CONFIRM before switching.251- Always show the current environment in every response that involves API calls: `[MAINNET]` or `[TESTNET]`252- If the user provides a Testnet API Key (starts with testing), automatically use Testnet URL253254### Step 5: Start Trading255256Tell the user what they can do. Examples:257- "What's the BTC price?"258- "Buy 500 USDT worth of BTC"259- "Open a 10x BTC long position"260- "Check my balance"261262---263264## Module Router265266**This skill uses modular on-demand loading.** When the user's request matches a module below, fetch the corresponding file ONCE per session per module, then use it for all subsequent requests in that category.267268### How to load a module269270```2711. Identify which module(s) the user's request needs from the table below2722. If the module has NOT been loaded in this session:273 a. Ensure manifest is available:274 - If cached from Auto Update: reuse it275 - Otherwise: MANIFEST = curl -sf -H "User-Agent: bybit-skill/1.7.12" https://api.bybit.com/skill/manifest276 - If fetch fails: use current local version of the module (SKILL_DIR/modules/<module>.md)277 If no local version exists: inform user module unavailable, only GET operations permitted278 - Cache manifest in session279 b. Download: curl -sf -H "User-Agent: bybit-skill/1.7.12" https://raw.githubusercontent.com/bybit-exchange/skills/main/modules/<module>.md280 - If download fails: use current local version of the module281 If no local version exists: inform user module unavailable, only GET operations permitted282 c. Verify integrity:283 - Compute SHA256 of downloaded content284 - Compare with manifest.files["modules/<module>.md"] (strip "sha256:" prefix)285 - If mismatch: use current local version (do NOT use the downloaded content)286 If no local version exists: inform user module unavailable, only GET operations permitted287 - If match: use downloaded content, save to SKILL_DIR/modules/<module>.md, cache in session2883. For subsequent requests in same category: use cached version (do NOT re-fetch)289```290291### Module Index292293| User Intent Keywords | Module | File | Requires |294|---------------------|--------|------|----------|295| price, ticker, kline, chart, orderbook, depth, funding rate, open interest, market data | **market** | `modules/market.md` | — |296| buy, sell, spot, swap, exchange, convert, limit order, market order, cancel order, spot margin | **spot** | `modules/spot.md` | account |297| long, short, leverage, futures, perpetual, close position, take profit, stop loss, trailing stop, conditional order, hedge mode, option, put, call, strike, expiry | **derivatives** | `modules/derivatives.md` | account |298| earn, stake, redeem, yield, savings, flexible, flexible auto savings, auto savings, auto-savings, fixed deposit, fixed term, fund pool, dual assets, structured product, discount buy, smart leverage, double win, liquidity mining, auto reinvest, early redeem, hold-to-earn, airdrop yield, PWM, private wealth, investment plan, fund management, asset manager | **earn** | `modules/earn.md` | account |299| balance, wallet, transfer, deposit, withdraw, fee, sub-account, API key, asset, fixed-rate borrow, borrow liability, repayment type, renew borrow, borrow market, borrow order, borrow contract, fixed borrow, fixed borrow penalty interest, cancel fixed-rate borrow order, margin borrow, trade auto repay, trade auto repayment, automatic repayment after spot trades, referral, referral code, invitation code, invite link, affiliate, referral profile, invited friends, invitation records, referral commissions, commission records, referral campaign rewards, tax report, batch tax export, tax report status | **account** | `modules/account.md` | — |300| websocket, stream, loan, borrow, repay, RFQ, block trade, spread, lending, broker, rate limit | **advanced** | `modules/advanced.md` | — |301| P2P, peer to peer, advertisement, ad, OTC, fiat, fiat buy, fiat sell, convert fiat | **fiat** | `modules/fiat.md` | — |302| copy trading, leader, follower, copy trade, leaderboard, recommend trader | **copy-trading** | `modules/copy-trading.md` | derivatives, account |303| grid bot, DCA bot, martingale, combo bot, trading bot, create bot, close bot, TradFi Combo, MT5 combo, tradfi bot, stock portfolio bot, commodity portfolio bot, rebalance bot, XAUUSD+, XAGUSD, USOUSD, 股票组合机器人, 大宗商品组合, 传统金融机器人, 组合调仓机器人 | **trading-bot** | `modules/trading-bot.md` | account, derivatives |304| alpha, on-chain, DEX, meme coin, swap token, on-chain asset, token trade, prediction, prediction market, bet, betting, YES/NO, sports market, World Cup, FIFA, event trading | **alpha-trade** | `modules/alpha-trade.md` | account |305| TWAP, iceberg, chase order, chaseOrder, strategy order, split order, algorithmic, POV, percentage of volume, volume participation | **strategy** | `modules/strategy.md` | account |306| xStocks, tokenized stock, commodity perpetual, XAUUSDT, XAGUSDT, CLUSDT, crude oil, buy/sell TradFi, metals agreement, oil agreement | **tradfi** | `modules/tradfi.md` | account, spot, derivatives |307| card, bybit card, card transaction, card spending, card payment, card history | **card** | `modules/card.md` | account |308| Launchpool, launch pool, launchpad, new token mining, puzzle, token splash, Spot-X, spotx, campaign, activity list, activity reward, staking activity, project list | **activity** | `modules/activity.md` | — |309| authorize, OAuth, connect Bybit, login Bybit, 授权, 登录, one-click auth, enable Bybit trade execution, Authorize via OAuth | **oauth** | `modules/oauth.md` | — |310311**Module-specific notes:**312313- **Referral**: Referral identity, invited friends, referral commissions, and referral campaign rewards route to `account`. The four `/v5/referral/*` POST endpoints are authenticated read-only queries. Referral campaign rewards describe static configuration, not personal task progress, claims, or payouts. Use the documented camelCase request and response names, including the embedded campaign V2 JSON; acceptance of legacy snake_case aliases and actual gateway serialization remain unverified. Spot-X / Launchpool / Token Splash activities still route to `activity`.314- **Trade auto repay**: Querying or changing repayment after eligible spot trades routes to `account`. The switch uses string `autoRepay` (`"0"` disabled, `"1"` enabled) and is separate from scheduled auto repayment. Saving the switch does not prove debt was repaid; it runs only in Cross and Portfolio margin modes, with no effect in Isolated mode. Enabling or disabling it is a write operation requiring Mainnet confirmation.315- **Fixed-rate borrow**: Penalty interest queries and borrow-order cancellation route to `account`. Penalty queries are read-only and report prior deductions; they do not charge interest. Borrow-order cancellation is a write operation requiring Mainnet confirmation, uses the borrow-order `orderId`, and does not repay a matched loan. Request acceptance must be followed by an order-status query before reporting completion.316- **⚠️ `tradfi` vs TradFi Combo in `trading-bot` (easy to confuse)**: `tradfi` = trading TradFi assets **yourself** (tokenized stocks `TSLAXUSDT`, commodity perps `XAUUSDT`/`CLUSDT`) via standard V5 order endpoints. The **TradFi Combo auto-rebalancing portfolio bot** over MT5 instruments (`XAUUSD+`, `XAGUSD`, `USOUSD`) via `/v5/mt5combobot/*` lives in the **TradFi Combo section of `modules/trading-bot.md`**. Different symbols, different endpoints. "Buy some gold" → `tradfi`. "Build me a gold+oil portfolio bot" → `trading-bot`. **A bare mention of "TradFi Combo" / "MT5 combo" / a stock-or-commodity portfolio bot must route to `trading-bot`, NOT to `tradfi` — `tradfi.md` does not document `/v5/mt5combobot/*` at all.** If genuinely ambiguous, ask which one.317- **Derivatives**: Conditional orders require `triggerDirection`: `1`=price rises above trigger, `2`=price falls below trigger. Buy-the-dip → `2`, breakout buy → `1`.318- **Fiat/P2P**: P2P responses use `ret_code` (underscore format, not `retCode`). P2P ad posting requires General Advertiser+ permission level.319- **Spot ↔ Convert fallback**: Spot order endpoints (`/v5/order/create`) only support listed spot pairs (base + quote where quote ∈ `USDT`/`USDC`/`USDE`/`BTC`/`ETH`/`EUR`/`BRL`). If the user names a base-base pair (e.g., `BTCDOGE`, `ETHSOL`, `SOLPEPE`) or any pair you cannot confirm is a listed spot symbol, **do NOT call spot order create**. Route to Convert via the `/v5/asset/exchange/*` endpoints in the account module: (1) `query-coin-list` to confirm both coins are convertible, (2) `quote-apply` to lock a quote, (3) user `CONFIRM`, (4) `convert-execute` before the quote expires (typically ~5s). When suggesting this fallback, tell the user that the pair is not a listed spot symbol and propose Convert instead — surface `fromCoin`, `toCoin`, `requestAmount`, quote price, and `expireTime` in the confirmation.320- **Trading Bot**: Bot API uses `status_code`/`debug_msg` response format (NOT `retCode`/`retMsg`). **Always call `validate-input` (spot grid) or `validate` (futures grid) before creation** — this returns acceptable parameter ranges and catches errors early. DCA: max **5 trading pairs** per bot; if user requests more, ask them to choose up to 5.321- **Alpha Trade**: Uses a **quote-then-execute** model — always call `/v5/alpha/trade/quote` first. Token codes use `CEX_<id>` (payment tokens like USDT) and `DEX_<id>` (on-chain tokens). All endpoints are POST (including queries). Settlement is on-chain (10-60s). KYC required.322- **Strategy**: Strategy API uses `UTA_*` category format ONLY. Do NOT use `linear`/`spot` — map: `linear` → `UTA_USDT`, `spot` → `UTA_SPOT`, `inverse` → `UTA_INVERSE`. Chase orders: `chaseDistance` and `chasePercentE4` are **mutually exclusive** — use ONE only. **NEVER use `category=linear` or `category=spot` in Strategy API calls** — this will cause errors. Always translate: derivatives/perpetual/futures → `UTA_USDT`, spot → `UTA_SPOT`. **POV** (Percentage of Volume): adapts child order size to live market activity; supports Perp (`UTA_USDT`/`UTA_USDC`/`UTA_INVERSE`) and Spot (`UTA_SPOT`). Iceberg and POV support quantity (`size`) or value (`positionValue`) sizing; never send both together. See `modules/strategy.md` for splitting and stop-condition rules.323- **Copy Trading**: The `investmentE8` parameter uses **8-decimal precision** (multiply USDT amount by 10^8). For example, 100 USDT = `10000000000` (100 × 10^8). Always apply this conversion when the user specifies an investment amount in USDT.324- **TradFi**: Discover instruments via `instruments-info` with `symbolType=xstocks` (spot, e.g., `TSLAXUSDT`) or `symbolType=commodity` (linear, e.g., `XAUUSDT`/`CLUSDT`). Trading reuses standard V5 order endpoints — no TradFi-specific trade API. **Metals (XAU/XAG) and Crude Oil (CL) require a one-time master-account agreement** via `POST /v5/user/agreement` (`categoryV2=2` metals, `categoryV2=3` oil); xStocks do not. Subaccounts inherit eligibility once the master signs. xStocks instruments include extra fields such as `xstockMultiplier`.325- **OAuth**: When triggered, load `modules/oauth.md` and follow the OAuth Authorization Flow documented there. After authorization completes, credentials are automatically available for all other modules (spot, derivatives, etc.) via the Runtime Decision logic in Step 3.326327### Routing Notes328329- Keywords are **hints, not strict rules** — always use semantic understanding of the user's full request to determine the correct module(s). When ambiguous (e.g., "borrow" could mean spot margin or advanced lending), prefer the module matching the broader conversation context, or ask the user to clarify.330- Common Chinese synonyms: 查价/看价 → market, 买/卖/现货 → spot, 开多/开空/合约/杠杆 → derivatives, 理财/质押/双币/持币生息/私人财富/自动储蓄/灵活储蓄自动储蓄 → earn, 余额/转账/充值/提币/固定借款罚息/取消固定借款订单/交易自动还款/现货交易后自动还款/邀请身份/邀请记录/受邀好友/邀请返佣/返佣记录/邀请活动奖励/税务报表/批量税务导出/税务报表进度 → account, 跟单 → copy-trading, 网格/DCA/AI推荐/一键创建/策略推荐/组合机器人/调仓机器人/股票组合/大宗商品组合/传统金融机器人 → trading-bot, 链上/meme/DEX/代币/预测/押注/预测市场/世界杯/FIFA → alpha-trade, 买入代币化股票/特斯拉/苹果/英伟达/黄金/白银/原油/商品永续 → tradfi, 拆单/算法单/POV → strategy, 银行卡/消费记录/刷卡 → card, 打新/新币挖矿/launchpool/拼图/代币空投/活动列表/质押活动 → activity, 授权/登录/连接Bybit/OAuth → oauth331332### Loading Rules3333341. **Match intent → load module**: A single user request may need multiple modules (e.g., "check BTC price then buy" → market + spot)3352. **Auto-load dependencies**: When loading a module, also load all modules listed in its `Requires` column (e.g., loading derivatives → also load account if not already loaded)3363. **Load once per session**: Do NOT re-fetch a module already loaded in this conversation3374. **Fail gracefully**: Follow the Graceful Degradation rules below.3385. **Multiple modules OK**: Load as many modules as needed for the user's request3396. **Retry once**: If GitHub Raw fails, retry the same URL once. If still failing, follow Graceful Degradation.340341### Graceful Degradation (unified fallback rules)342343All failure scenarios (auto-update, module loading, manifest fetch) follow this single priority chain:3443451. **Local version available** → use it silently. Do not inform the user unless they ask about version.3462. **No local version, network failed** → inform user that the module is unavailable. Only read-only (GET) operations are permitted using the Authentication and Common Parameters sections. Do NOT execute POST (write) operations — tell the user to retry later.3473. **Checksum mismatch on download** → treat as network failure (use local version if available; otherwise step 2).348349---350351## Authentication352353### Base URLs354355| Region | URL |356|--------|-----|357| Global (default) | `https://api.bybit.com` |358| Global (backup) | `https://api.bytick.com` |359360### Request Signature361362**Headers (required for every authenticated request):**363364| Header | Value |365|--------|-------|366| `X-BAPI-API-KEY` | API Key |367| `X-BAPI-TIMESTAMP` | Unix millisecond timestamp |368| `X-BAPI-SIGN` | HMAC-SHA256 signature |369| `X-BAPI-RECV-WINDOW` | `5000` |370| `X-BAPI-SIGN-TYPE` | `2` for RSA-SHA256; omit or set `1` for HMAC-SHA256 |371| `Content-Type` | `application/json` (POST) |372| `User-Agent` | `bybit-skill/1.7.12` |373| `X-Referer` | `bybit-skill` |374375### Signing Algorithm376377Bybit V5 supports two signing methods. Auto-select at runtime by env var (see Step 3).378379| Sign Type | When to use | `X-BAPI-SIGN-TYPE` | Output encoding |380|-----------|-------------|--------------------|-----------------|381| HMAC-SHA256 | Bybit-generated key (you received a Secret string) | `1` (or omit) | hex |382| RSA-SHA256 | Self-generated key (you uploaded the public key to Bybit) | `2` | base64 |383384**Shared `param_str` (identical for both methods):**385386- GET: `{timestamp}{apiKey}{recvWindow}{queryString}`387- POST: `{timestamp}{apiKey}{recvWindow}{jsonBody}`388389The `jsonBody` used for signing MUST be **compact JSON** (no extra spaces/newlines), byte-identical to the request body. Example: `{"key":"value"}` not `{ "key": "value" }`.390391**HMAC-SHA256 signature:**392393```bash394SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)395```396397**RSA-SHA256 signature (PKCS#1 v1.5 padding):**398399```bash400SIGN=$(printf '%s' "$PARAM_STR" \401 | openssl dgst -sha256 -sign "$BYBIT_API_PRIVATE_KEY_PATH" -binary \402 | base64 | tr -d '\n')403```404405> Use `printf '%s'` (not `echo -n`) for RSA to guarantee no trailing newline across shells. `tr -d '\n'` strips any line wrapping that `base64` may add on BSD/LibreSSL.406407### Complete curl Examples408409> **Security**: When generating code for the user, ALWAYS use environment variable references (`$BYBIT_API_KEY`, `$BYBIT_API_SECRET`, `$BYBIT_API_PRIVATE_KEY_PATH`) — NEVER substitute actual values or file paths into code blocks, even if they are available in the session. This is security-critical.410411The only differences between HMAC and RSA requests are (a) the `X-BAPI-SIGN-TYPE: 2` header for RSA and (b) how `SIGN` is computed (base64 vs hex). `param_str`, timestamp, recvWindow, body, and other headers are identical.412413**GET — HMAC (query positions):**414415```bash416API_KEY="$BYBIT_API_KEY"417SECRET_KEY="$BYBIT_API_SECRET"418BASE_URL="https://api.bybit.com"419RECV_WINDOW=5000420TIMESTAMP=$(date +%s000)421QUERY="category=linear&symbol=BTCUSDT"422PARAM_STR="${TIMESTAMP}${API_KEY}${RECV_WINDOW}${QUERY}"423SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)424425curl -s "${BASE_URL}/v5/position/list?${QUERY}" \426 -H "X-BAPI-API-KEY: ${API_KEY}" \427 -H "X-BAPI-TIMESTAMP: ${TIMESTAMP}" \428 -H "X-BAPI-SIGN: ${SIGN}" \429 -H "X-BAPI-RECV-WINDOW: ${RECV_WINDOW}" \430 -H "User-Agent: bybit-skill/1.7.12" \431 -H "X-Referer: bybit-skill"432```433434**POST — HMAC (place spot market order):**435436```bash437API_KEY="$BYBIT_API_KEY"438SECRET_KEY="$BYBIT_API_SECRET"439BASE_URL="https://api.bybit.com"440RECV_WINDOW=5000441TIMESTAMP=$(date +%s000)442BODY='{"category":"spot","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"500","marketUnit":"quoteCoin"}'443PARAM_STR="${TIMESTAMP}${API_KEY}${RECV_WINDOW}${BODY}"444SIGN=$(echo -n "$PARAM_STR" | openssl dgst -sha256 -hmac "$SECRET_KEY" | cut -d' ' -f2)445446curl -s -X POST "${BASE_URL}/v5/order/create" \447 -H "Content-Type: application/json" \448 -H "X-BAPI-API-KEY: ${API_KEY}" \449 -H "X-BAPI-TIMESTAMP: ${TIMESTAMP}" \450 -H "X-BAPI-SIGN: ${SIGN}" \451 -H "X-BAPI-RECV-WINDOW: ${RECV_WINDOW}" \452 -H "User-Agent: bybit-skill/1.7.12" \453 -H "X-Referer: bybit-skill" \454 -d "${BODY}"455```456457**To use RSA instead:** apply these two changes to either HMAC example above.4584591. Replace the `SIGN=` line with:460 ```bash461 PRIV_KEY="$BYBIT_API_PRIVATE_KEY_PATH"462 SIGN=$(printf '%s' "$PARAM_STR" \463 | openssl dgst -sha256 -sign "$PRIV_KEY" -binary \464 | base64 | tr -d '\n')465 ```4664672. Add one header to the `curl` call:468 ```469 -H "X-BAPI-SIGN-TYPE: 2" \470 ```471472Everything else — `param_str`, timestamp, recvWindow, body, other headers — is identical to the HMAC version.473474### Runtime Decision475476At runtime, inspect env vars in this order for every authenticated call:4774781. If `$BYBIT_API_PRIVATE_KEY_PATH` is set and the file is readable → RSA branch.479 (If `$BYBIT_API_SECRET` is also set, RSA still wins — emit a one-time "Using RSA" notice at Step 3.)4802. Else if `$BYBIT_API_SECRET` is set → HMAC branch.4813. Else if the OAuth credential file exists (see Path D) and `ai-account` is present with a non-expired token → use `ai-account.api_key` / `ai-account.api_secret` as HMAC credentials. If the token is expired but `refresh_token` is still valid, refresh it first (load oauth module, see "OAuth: Refresh token" section).4824. Else → prompt the user to configure credentials (see Step 1). Mention OAuth (Path D) as the quickest option for platforms with shell access.483484If `$BYBIT_API_PRIVATE_KEY_PATH` is set but the file is missing or unreadable, halt with an explicit error. Do NOT silently fall back to HMAC.485486Never mix the two: never include both an HMAC-derived `X-BAPI-SIGN` and a raw private-key reference on the same request.487488### Response Format489490```json491{"retCode": 0, "retMsg": "OK", "result": {}, "time": 1672211918471}492```493494`retCode=0` means success; non-zero indicates an error.495496---497498## Common Parameter Reference499500### Core Parameters501502| Parameter | Description | Values |503|-----------|-------------|--------|504| category | Product category | `spot` `linear` `inverse` `option` |505| symbol | Trading pair | Uppercase, e.g. `BTCUSDT` |506| side | Direction | `Buy` `Sell` |507| orderType | Order type | `Market` `Limit` |508| qty | Quantity | String |509| price | Price | String (required for Limit orders) |510| timeInForce | Time in force | `GTC` `IOC` `FOK` `PostOnly` `RPI` |511| positionIdx | Position index | `0` (one-way) `1` (hedge buy/long) `2` (hedge sell/short) |512| accountType | Account type | `UNIFIED` `FUND` |513514### TradFi-Specific Parameters515516| Parameter | Description | Values |517|-----------|-------------|--------|518| symbolType | TradFi filter for `/v5/market/instruments-info` | `xstocks` (spot category) `commodity` (linear category) |519520> `symbolType` is a TradFi-specific filter parameter. Standard spot/linear queries do not require this parameter.521522### Order Parameters523524| Parameter | Description | Values |525|-----------|-------------|--------|526| triggerPrice | Trigger price for conditional orders | String |527| triggerDirection | Trigger direction (required for conditional) | `1` (rise to) `2` (fall to) |528| triggerBy | Trigger price type | `LastPrice` `IndexPrice` `MarkPrice` |529| reduceOnly | Reduce only flag | `true` / `false` |530| marketUnit | Spot market buy unit | `baseCoin` `quoteCoin` |531| orderLinkId | User-defined order ID | String (must be unique) |532| orderFilter | Order filter | `Order` `tpslOrder` `StopOrder` |533| takeProfit | TP price (pass `"0"` to cancel) | String |534| stopLoss | SL price (pass `"0"` to cancel) | String |535| tpslMode | TP/SL mode | `Full` (entire position) `Partial` |536537### Enums Reference538539| Enum | Values |540|------|--------|541| orderStatus (open) | `New` `PartiallyFilled` `Untriggered` |542| orderStatus (closed) | `Rejected` `PartiallyFilledCanceled` `Filled` `Cancelled` `Triggered` `Deactivated` |543| stopOrderType | `TakeProfit` `StopLoss` `TrailingStop` `Stop` `PartialTakeProfit` `PartialStopLoss` `tpslOrder` `OcoOrder` |544| execType | `Trade` `AdlTrade` `Funding` `BustTrade` `Delivery` `Settle` `BlockTrade` `MovePosition` `FutureSpread` `SessionSettlePnL` `CoinSwap` `CorporateAction` `ForwardSplitSettle` `ReverseSplitSettle` |545| interval (kline) | `1` `3` `5` `15` `30` `60` `120` `240` `360` `720` `D` `W` `M` |546| intervalTime | `5min` `15min` `30min` `1h` `4h` `1d` |547| positionMode | `0` (one-way) `3` (hedge) |548| setMarginMode | `ISOLATED_MARGIN` `REGULAR_MARGIN` `PORTFOLIO_MARGIN` |549550---551552## Error Handling553554### Common Error Codes555556**System & Auth (10000-10099)**557558| retCode | Name | Meaning | Resolution |559|---------|------|---------|------------|560| 0 | OK | Success | — |561| 10001 | REQUEST_PARAM_ERROR | Invalid parameter | Check missing/invalid params; hedge mode may require positionIdx |562| 10002 | REQUEST_EXPIRED | Timestamp expired | Timestamp outside recvWindow (±5000ms); sync system clock |563| 10003 | INVALID_API_KEY | Invalid API key | Key invalid or wrong environment (testnet vs mainnet). If using RSA: confirm the public key uploaded to Bybit and the private key at `$BYBIT_API_PRIVATE_KEY_PATH` are the matching pair. Error messages should include `(current sign type: HMAC\|RSA)`. |564| 10004 | INVALID_SIGNATURE | Signature error | Verify `param_str` order `{timestamp}{apiKey}{recvWindow}{params}`, compact JSON body. If using RSA: verify `X-BAPI-SIGN-TYPE: 2`, output is base64 (not hex), padding is PKCS#1 v1.5 (not PSS). Error messages should include `(current sign type: HMAC\|RSA)`. |565| 10005 | PERMISSION_DENIED | Permission denied | API Key lacks required permission → [Manage API Keys](https://www.bybit.com/app/user/api-management) |566| 10006 | TOO_MANY_REQUESTS | Rate limited | Pause 1s then retry; check `X-Bapi-Limit-Status` header |567| 10010 | UnmatchedIp | IP not whitelisted | Add current IP in API Key settings |568| 10014 | DUPLICATE_REQUEST | Duplicate request | Duplicate request detected; avoid resending identical requests |569| 10016 | INTERNAL_SERVER_ERROR | Server error | Retry later |570| 10017 | ReqPathNotFound | Path not found | Check request path and HTTP method |571| 10027 | TRADING_BANNED | Trading banned | Trading not allowed for this account |572| 10029 | SYMBOL_NOT_ALLOWED | Invalid symbol | Symbol not in the allowed list |573574**Trade Domain (110000-169999)**575576| retCode | Name | Meaning | Resolution |577|---------|------|---------|------------|578| 110001 | ORDER_NOT_EXIST | Order does not exist | Check orderId/orderLinkId; order may have been filled or expired |579| 110003 | ORDER_PRICE_OUT_OF_RANGE | Price out of range | Call instruments-info for priceFilter: minPrice/maxPrice/tickSize |580| 110004 | INSUFFICIENT_WALLET_BALANCE | Wallet balance insufficient | Reduce qty or [Deposit](https://www.bybit.com/app/user/asset/deposit) |581| 110007 | INSUFFICIENT_AVAILABLE_BALANCE | Available balance insufficient | Balance may be locked by open orders; cancel orders to free up |582| 110008 | ORDER_ALREADY_FINISHED | Order completed/cancelled | Order already filled or cancelled; no action needed |583| 110009 | TOO_MANY_STOP_ORDERS | Too many stop orders | Reduce number of conditional/stop orders |584| 110020 | TOO_MANY_ACTIVE_ORDERS | Active order limit exceeded | Cancel some active orders first |585| 110021 | POSITION_EXCEEDS_OI_LIMIT | Position exceeds OI limit | Reduce position size |586| 110040 | ORDER_WOULD_TRIGGER_LIQUIDATION | Would trigger liquidation | Reduce qty or add margin |587| 110057 | INVALID_TPSL_PARAMS | Invalid TP/SL params | Check TP/SL settings; ensure tpslMode and positionIdx are included |588| 110072 | DUPLICATE_ORDER_LINK_ID | Duplicate orderLinkId | orderLinkId must be unique per order |589| 110094 | ORDER_NOTIONAL_TOO_LOW | Notional below minimum | Increase order size; check instruments-info for minNotionalValue |590591**Spot Trade (170000-179999)**592593| retCode | Name | Meaning | Resolution |594|---------|------|---------|------------|595| 170005 | SPOT_TOO_MANY_NEW_ORDERS | Too many spot orders | Spot rate limit exceeded; slow down |596| 170121 |597598…(truncated)