# Bybit MCP Server [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Node.js 20.6+](https://img.shields.io/badge/node-20.6+-blue.svg)](https://nodejs.org/) [![MCP](https://img.shields.io/badge/MCP-compatible-purple.svg)](https://modelcontextprotocol.io) [![Tools](https://img.shields.io/badge/Tools-400-orange.svg)](#-available-tool-categories) [![Bybit V5 API](https://img.shields.io/badge/Bybit-V5%20API-green.svg)](https://bybit-exchange.github.io/docs/v5/intro) **A production-ready MCP server for Bybit — 400 tools covering market data, trading, positions, account management, assets, loans, earn products, referral queries, tax reports, and real-time WebSocket streams** [Quick Start](#-quick-start) • [Features](#-features) • [Configuration](#-configuration-reference) • [Tools Reference](#-available-tool-categories) • [Troubleshooting](#-troubleshooting) • [Contributing](#-contributing) [中文文档](./README.zh.md)
--- ## Overview Bybit MCP Server enables AI assistants like **Claude**, **Cursor**, **VS Code**, and other MCP-compatible clients to interact directly with the Bybit cryptocurrency exchange. Query live market data, manage your account, and monitor real-time streams — all through natural language. ### Why Bybit MCP? - **Complete V5 Coverage** — 400 tools across market data, trading, positions, account, asset, loans, earn, referrals, tax reports, copy trading, WebSocket, and WS-trade categories - **Referral Queries** — View campaign reward rules, your referral identity, invitations, and commission records - **Strategy Trading** — POV for spot and derivatives with required quantity or value limits, Iceberg splitting into up to 200 child orders - **Secure by Design** — API credentials are read from environment variables at runtime, never hardcoded - **Read-Only Mode** — All 23 market data tools work without any API key - **Real-Time Streams** — 27 WebSocket tools for live orderbook, tickers, positions, and more - **Zero-Install Start** — Run instantly with `npx bybit-official-trading-server@latest` - **Universal Compatibility** — Works with Claude Desktop, Cursor, VS Code, and any MCP client POV execution requires a 5–3600 second interval and a positive quantity or value limit. A duration may add a time limit; it cannot replace the quantity or value limit. OneTime execution is unavailable through MCP because the API ignores those limits in that mode. --- ## Features
### Market Data - **Option Markets** — Discover option underlyings and filter by asset type - **Prices & Tickers** — Real-time spot and derivatives prices - **Orderbook** — Configurable depth snapshots - **Klines** — Historical OHLCV candlestick data - **Funding Rates** — Current and historical rates - **Open Interest** — Long/short ratio, ADL indicators - **Risk Limits** — Volatility index, delivery prices, insurance pool ### Account & Asset - **Wallet Balance** — Unified account overview - **Transaction Log** — Full trade and funding history - **Fee Rates** — Maker/taker rates by instrument - **Collateral** — Settings, Greeks, MMP state - **Asset Overview** — Portfolio margin, delivery/settlement records - **Multi-Account** — Aggregated parent and sub-account assets - **Trade Auto Repayment** — Query or change the account switch for repayment after eligible spot trades - **Tax Reports** — Create, track, download, and batch-query tax report export tasks
### User & Sub-Accounts - **API Key Info** — Permissions including Compliance, VIP level, rate limits - **Sub-Account Management** — List and query sub-accounts - **Member Types** — Account type queries per member - **Referral & Affiliate** — Campaign rewards, identity, invitations, and commission queries ### WebSocket Real-Time - **Public Streams** — Orderbook, tickers, klines, trades, liquidations - **Private Streams** — Executions, positions, wallet updates - **Options** — Greeks snapshots - **Block Trading** — RFQ updates - **Spread Trading** — Spread instrument streams - **Snapshot Model** — Single-call, no persistent connections needed
--- ## Quick Start **Step 1 — Get your Bybit API credentials** *(skip if you only need market data)* **Option A — HMAC-SHA256 (standard, recommended for most users)** 1. Log in to [Bybit](https://www.bybit.com) and go to **Account & Security → API Management** 2. Click **Create New Key**, select **System-generated API Key** 3. Set the permissions you need (read-only is recommended for safety) 4. Save the **API Key** and **API Secret** — the secret is shown only once 5. Use `BYBIT_API_KEY` + `BYBIT_API_SECRET` in your config **Option B — RSA-SHA256 (self-generated key pair)** 1. Generate an RSA key pair locally: ```bash openssl genrsa -out bybit_private.pem 2048 openssl rsa -in bybit_private.pem -pubout -out bybit_public.pem chmod 600 bybit_private.pem ``` 2. Log in to [Bybit](https://www.bybit.com) and go to **Account & Security → API Management** 3. Click **Create New Key**, select **Self-generated API Key** 4. Paste the contents of `bybit_public.pem` into the public key field 5. Save the **API Key** shown after creation 6. Use `BYBIT_API_KEY` + `BYBIT_API_PRIVATE_KEY_PATH` (absolute path to `bybit_private.pem`) in your config **Step 2 — Connect to your AI assistant** Choose the section below that matches your tool (Claude Desktop, Cursor, or VS Code). **Step 3 — Verify the connection** After configuring, restart your AI assistant and ask: > *"What's the current BTCUSDT price?"* If you get a live price back, the server is connected and working. **Step 4 — Let the AI learn the full capability in one prompt** *(optional but recommended)* Paste the following into your AI assistant to have it read the official documentation and start helping you trade: ``` Please read https://raw.githubusercontent.com/bybit-exchange/trading-mcp/main/README.md save it as a mcp, and help me trade on Bybit. ``` The AI will read the README, understand all available tools, and be ready to assist with market data queries, account management, and more. --- ## Configuration Reference | Variable | Required | Default | Description | |----------|----------|---------|-------------| | `BYBIT_API_KEY` | For auth endpoints | — | Your Bybit API key | | `BYBIT_API_SECRET` | HMAC mode | — | Your Bybit API secret (HMAC-SHA256 signing) | | `BYBIT_API_PRIVATE_KEY_PATH` | RSA mode | — | Absolute path to your RSA private key PEM file (RSA-SHA256 signing) | | `BYBIT_TESTNET` | No | `false` | Set to `true` to use the testnet | Market data tools work without credentials. Authenticated tools require `BYBIT_API_KEY` plus **exactly one** signing credential: - **HMAC-SHA256** (default) — set `BYBIT_API_SECRET`. Works with **System-generated API keys**. - **RSA-SHA256** — set `BYBIT_API_PRIVATE_KEY_PATH` pointing to a PEM file on disk. Required for **Self-generated (user-uploaded) RSA key pairs**. The server adds `X-BAPI-SIGN-TYPE: 2` automatically. > **Quick rule:** chose "System-generated" on Bybit → use HMAC. Chose "Self-generated" → use RSA. > > If both `BYBIT_API_SECRET` and `BYBIT_API_PRIVATE_KEY_PATH` are set (e.g. a system-level env var conflicts with your MCP config), RSA takes precedence and a warning is printed to the server log. Remove `BYBIT_API_SECRET` to suppress the warning. --- ## Usage with Claude Desktop > **First-time setup:** Claude Desktop may offer **"Always allow"** for tool access. Each write operation still requires a separate approval form. Use a trusted MCP client: the server relies on its approval response. **1. Find your config file** | Platform | Path | |----------|------| | macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` | | Windows | `%APPDATA%\Claude\claude_desktop_config.json` | Open the file in any text editor (create it if it doesn't exist). **2. Add the MCP server config** HMAC mode (System-generated API key): ```json { "mcpServers": { "bybit": { "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_SECRET": "your_api_secret" } } } } ``` RSA mode (Self-generated API key): ```json { "mcpServers": { "bybit": { "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_PRIVATE_KEY_PATH": "/absolute/path/to/bybit_private.pem" } } } } ``` > Replace the values with your actual Bybit credentials. Use one signing mode only — do not set both `BYBIT_API_SECRET` and `BYBIT_API_PRIVATE_KEY_PATH`. > If the file already has other MCP servers, add the `"bybit"` block inside the existing `"mcpServers"` object. **3. Restart Claude Desktop** Quit and reopen Claude Desktop. The Bybit tools will be available automatically on next launch. **For testnet:** ```json { "mcpServers": { "bybit": { "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_testnet_api_key", "BYBIT_API_SECRET": "your_testnet_api_secret", "BYBIT_TESTNET": "true" } } } } ``` --- ## Usage with Cursor **1. Find your config file** | Platform | Path | |----------|------| | macOS / Linux | `~/.cursor/mcp.json` | | Windows | `%USERPROFILE%\.cursor\mcp.json` | Create the file if it doesn't exist. **2. Add the MCP server config** HMAC mode (System-generated API key): ```json { "mcpServers": { "bybit": { "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_SECRET": "your_api_secret" } } } } ``` RSA mode (Self-generated API key): ```json { "mcpServers": { "bybit": { "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_PRIVATE_KEY_PATH": "/absolute/path/to/bybit_private.pem" } } } } ``` **3. Restart Cursor** After saving the file, restart Cursor. The Bybit MCP server will be listed under **Settings → MCP**. --- ## Usage with VS Code **1. Find or create your MCP config** In your project root (or workspace), create `.vscode/mcp.json`. HMAC mode (System-generated API key): ```json { "servers": { "bybit": { "type": "stdio", "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_SECRET": "your_api_secret" } } } } ``` RSA mode (Self-generated API key): ```json { "servers": { "bybit": { "type": "stdio", "command": "npx", "args": ["-y", "bybit-official-trading-server@latest"], "env": { "BYBIT_API_KEY": "your_api_key", "BYBIT_API_PRIVATE_KEY_PATH": "/absolute/path/to/bybit_private.pem" } } } } ``` **2. Enable MCP in VS Code settings** Open VS Code Settings (`Cmd+,` / `Ctrl+,`), search for `mcp`, and ensure **MCP support** is enabled for your AI extension (e.g. GitHub Copilot). **3. Reload the window** Run **Developer: Reload Window** from the Command Palette (`Cmd+Shift+P` / `Ctrl+Shift+P`) to pick up the new config. --- ## Available Tool Categories | Category | Auth | Tools | Description | |----------|------|------:|-------------| | `market` | No | 23 | Klines, orderbook, tickers, funding rates, open interest, volatility, risk limits, long/short ratio, delivery price, insurance pool, option underlyings and asset types | | `account` | Yes | 25 | Wallet balance, transaction log, fee rates, margin mode, collateral switch (single/batch), hedging mode, price limit, MMP modify and reset, option Greeks, DCP config, SMP group, account instruments, withdrawal info, UTA borrow/repay with borrow history, and UTA2.0-to-Pro account upgrade | | `trade` | Yes | 12 | Create, amend, cancel orders, batch order operations, open orders, order history, spot borrow quota, DCP, and order pre-check | | `position` | Yes | 12 | Position list, leverage, position mode, trading stop, auto-add margin, add/reduce margin, closed PnL, closed positions, move positions, risk limit confirmation, and futures symbol leverage info | | `rfq-trading` | Yes | 15 | Create/cancel RFQs and quotes, execute quotes, accept non-LP quotes, RFQ config, realtime and historical RFQs/quotes, trade history, public trades | | `spread-trading` | Mixed | 12 | Spread instruments, orderbook, tickers, recent trades, create/amend/cancel spread orders, open orders, order history, trade history, max order quantity | | `asset` | Yes | 35 | Asset overview, portfolio margin, delivery/settlement records, aggregated parent+sub account assets, funding history, coin/chain info, transfer & coin-balance queries, deposit record/address queries, withdraw record/address and withdrawable-amount queries, currency convert (quote/execute/history) and dust conversion | | `user` | Yes | 8 | Read-only user & sub-account info: API key info & permissions, sub-account and escrow sub-account listings, member account type, referral code and referral (invited-user) queries | | `referral` | Yes | 4 | Read-only campaign reward rules, referral identity, invitation records, and commission records | | `affiliate` | Yes | 2 | Affiliate user list and per-user referral information | | `broker` | Yes | 8 | Broker earnings and account info, award info/distribution/records, API rate-limit set and query (cap & per-UID) | | `bot` | Yes | 18 | Futures combo bot, futures grid bot, futures martingale bot, spot grid bot, spot DCA bot — create, close, detail, validate, and parameter limits | | `aurora` | Yes | 5 | Aurora AI strategy recommendations: home page, creation page, explore page, one-click EasyBot, and single-strategy detail lookup | | `copy-trading-classic` | Yes | 2 | Classic copy trading: recommended leader leaderboard, create follower binding | | `copy-trading-tradfi` | Yes | 2 | TradFi copy trading (MT5): recommended provider leaderboard, create follower binding | | `strategy` | Yes | 7 | TWAP, Chase Limit, Iceberg and POV strategies, quantity or value sizing, spot POV, up to 200 Iceberg child orders, lists and stops | | `spot-margin-uta` | Yes | 4 | Spot margin (UTA) market data: VIP margin data, tiered collateral ratio, historical interest rate, position tiers | | `spot-margin-trade-uta` | Mixed | 20 | UTA spot margin trading: switch mode, set leverage, trade state, max borrowable, coin state, repayment-available amount, scheduled auto-repay mode and trade auto-repayment switch (query/set), fixed-term borrow/renew with market/orders/contracts, penalty interest records, borrow order cancellation, borrow liability, and fixed/flexible available inventory | | `crypto-loan-new` | Mixed | 7 | Crypto loan (common): loanable & collateral data, max collateral amount, max loan, adjust LTV, positions, adjustment history | | `crypto-loan-flexible` | Yes | 7 | Flexible crypto loan: borrow, repay, repay with collateral, ongoing coins, borrow and repayment history, available inventory | | `crypto-loan-fixed-term` | Yes | 16 | Fixed-term crypto loan: borrow/supply order quotes, place borrow/supply, cancel orders, contract & order info, fully repay, repay with collateral, renew (with renew info), repayment history, available inventory | | `institutional-loan` | Mixed | 2 | Institutional lending product info, hedge product coin delta amount | | `fiat-convert` | Mixed | 7 | Fiat conversion: coin list, reference price, quote apply, trade execute, trade query, trade history, balance | | `earn` | Mixed | 11 | Earn product queries, stake/redeem orders, order history, positions, yield history, hourly yield, APR history, position modify, interest-rate coupons and reward cards, and Flexible Saving auto-savings settings | | `tax` | Yes | 6 | Create, track, download, and batch-query tax report export tasks, plus registration-time lookup | | `advanceearn` | Mixed | 5 | Advance Earn: product queries, place order, positions, order history, product extra info | | `smartleverage` | Yes | 1 | Smart Leverage: redeem estimation amount list | | `doublewin` | Yes | 1 | Double Win: leverage and expiry queries | | `fixedterm` | Mixed | 6 | Fixed-term deposits: product list, place/redeem orders, positions, order history, auto-invest settings | | `earntoken` | Mixed | 7 | Token earn products: place orders, positions, order history, daily/hourly yield, historical APR | | `liquiditymining` | Yes | 10 | Liquidity mining: add/remove/reinvest liquidity, add margin, claim interest, positions, orders, yield records, liquidation records | | `earnrwa` | Yes | 5 | Real-World Asset (RWA) earn: NAV-based product list, Stake/Redeem orders, positions, order history, historical NAV chart | | `holdtoearn` | Yes | 2 | Hold-to-Earn airdrop: product listings and personal yield history | | `launchpool` | Mixed | 4 | Launchpool activities: project (activity) list, current staking positions, staking operation log, completed staking history | | `puzzle` | No | 1 | Puzzle activity (project) list | | `tokensplash` | Mixed | 2 | Token Splash activities: project (activity) list and user trade-task progress | | `p2p` | Yes | 13 | P2P ad management and order queries: create/update/remove ads, browse online ads, query personal ads and details, order list, order detail, pending orders, mark order as paid, chat messages, counterparty info, payment methods | | `card` | Yes | 1 | Bybit Card asset (transaction) records: paginated query with status, last-four card digits, merchant, query type, transaction/order ID, card token, and time-range filters | | `alpha` | Mixed | 35 | On-chain trading, LP farming and prediction markets: trade quote/purchase/redeem, pay tokens, orders, biz tokens, asset detail; LP pool list/info, position list, orders, pay tokens & prices, LP stake, LP redeem; prediction engine status, event/token/order-book/price queries, portfolio/position/order/order-estimate, prediction buy/sell | | `websocket` | Mixed | 27 | Real-time snapshots via subscribe-snapshot pattern: orderbook, tickers, klines, trades, liquidations, executions, orders, positions, wallet, option Greeks, RFQ block trades, spread trading | | `wstrade` | Yes | 6 | WebSocket trade operations via /v5/trade: place order, cancel order, amend order, batch place, batch cancel, batch amend | | `subscription` | Yes | 4 | WebSocket subscription lifecycle: start/stop a subscription, list active subscriptions, read buffered messages | **Total: 400 tools** --- ## Example Prompts Once connected to an AI assistant, you can use natural language: **Market data:** - "What is the current BTC/USDT price?" - "Show me the order book for ETHUSDT with depth 50" - "Get the last 10 BTC perpetual klines on the 1-hour interval" - "What are the current funding rates for the top 5 perpetual contracts?" - "What's the open interest for BTCUSDT?" **Account & Asset:** - "What's my wallet balance?" - "Show me my recent transaction log" - "What are my maker/taker fee rates?" - "Show me my total assets across all sub-accounts" - "What's my portfolio margin status?" **User & Sub-accounts:** - "List all my sub-accounts" - "Show me the permissions and VIP level of my current API key" - "What account types do my sub-accounts use?" - "Who have I invited through the referral program?" **WebSocket / Real-time:** - "Subscribe to the BTCUSDT orderbook and give me a snapshot" - "Get the latest execution records from my account" - "What are my current open positions?" --- ## WebSocket Pattern Details WebSocket tools are compatible with MCP's request/response model: 1. The tool opens a WebSocket connection to Bybit's streaming endpoint 2. Subscribes to the requested channel (with auth handshake for private channels) 3. Collects the specified number of messages (default: 1) or waits up to `timeoutMs` (default: 5000 ms) 4. Returns the collected snapshot and closes the connection This makes real-time data accessible in a single tool call without managing persistent connections. --- ## Security Notes - API keys are read from environment variables at call time, never hardcoded - Two signing modes are supported: **HMAC-SHA256** (default, via `BYBIT_API_SECRET`) and **RSA-SHA256** (via `BYBIT_API_PRIVATE_KEY_PATH`) per Bybit's V5 API specification - For RSA mode, store the PEM file with `chmod 600` and never commit it to source control - Never share your API secret or commit it to source control - Use API keys with minimal required permissions (read-only where possible) --- ## Troubleshooting ### MCP Server Not Loading / "No MCP servers configured" If you've configured the server but your AI assistant shows no tools or "No MCP servers configured": #### 1. Check the correct configuration file Claude Code reads MCP server config from `~/.claude.json` (per-project), **not** from `~/.claude/settings.json`. The recommended way to add the server is via CLI: ```bash claude mcp add bybit -- npx -y bybit-official-trading-server@latest ``` This writes the config to the correct location. #### 2. Use the full path to `node` / `npx` if needed Some environments spawn subprocesses without loading your shell profile (`.zshrc` / `.zprofile`), so `PATH` may not include the Node.js bin directory. Find the full path and use it explicitly: ```bash # Find your npx path which npx # Example: /usr/local/bin/npx ``` #### 3. Restart your AI assistant after configuration changes MCP servers connect at session startup. After adding or changing config, you must **exit and restart** your AI assistant for changes to take effect. #### 4. Verify the server starts correctly Test that the server can start and respond to MCP protocol: ```bash echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"0.1"}}}' | npx -y bybit-official-trading-server@latest ``` #### 5. Don't run the server manually Your AI client manages the MCP server process itself via stdio. A manually started server instance is **completely separate** — the client won't connect to it. Let the client handle the lifecycle automatically. ### Quick Diagnosis Checklist | Symptom | Cause | Fix | |---------|-------|-----| | No tools shown after config | Config in wrong file | Use `claude mcp add` CLI command | | Config exists but tools don't load | `npx` / `node` not found in PATH | Use absolute path to `npx` | | Tools loaded before but not now | Session not restarted after config change | Restart your AI assistant | | Authentication errors | Missing or incorrect API credentials | Check `BYBIT_API_KEY` and `BYBIT_API_SECRET` (HMAC) or `BYBIT_API_PRIVATE_KEY_PATH` (RSA) | --- ## Local Development ```bash # Install dependencies npm install # Start the server in development mode npm run dev # Type check npm run typecheck # Build for production npm run build ``` --- ## Risk Warning Cryptocurrency trading involves substantial risk of loss. Please read the following before use: - **Protect Your API Credentials** — Use IP allowlists and grant only the minimum permissions required; disable withdrawal access unless explicitly needed - **Test Before You Trade** — Validate your setup on [Bybit Testnet](https://testnet.bybit.com/) before connecting to your live account (set `BYBIT_TESTNET=true`) - **You Are in Control** — All actions are initiated by you or your AI assistant; review orders carefully before execution - **Bybit Terms Apply** — Use of this server is subject to [Bybit's Terms of Service](https://www.bybit.com/en/terms-service/terms-of-use) --- ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request --- ## Resources | Resource | Description | |----------|-------------| | [Bybit V5 API Docs](https://bybit-exchange.github.io/docs/v5/intro) | Official Bybit API documentation | | [Bybit Testnet](https://testnet.bybit.com/) | Practice trading with test funds | | [MCP Specification](https://modelcontextprotocol.io/) | Model Context Protocol spec | | [npm Package](https://www.npmjs.com/package/bybit-official-trading-server) | Published npm package | --- ## License MIT