# Bybit Trading

> 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.

- Skill: `dvcrn/bybit-trading` (Agent Skill)
- Install (CLI): `npx skillmds@latest add dvcrn/bybit-trading`
- Raw SKILL.md: https://api.skillmd.com/api/skills/dvcrn/bybit-trading/raw
- Safety review: pending (external: skill-scanner WARNING, skillspector FAIL)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: dvcrn (https://skillmd.com/u/dvcrn)
- Updated: 2026-09-08
- Page: https://skillmd.com/skills/dvcrn/bybit-trading

---


# Bybit Trading Skill

Trade on Bybit using natural language. Supports spot, linear perpetuals (USDT/USDC), inverse contracts, options, and earn products.

**Version:** 1.0.0 | **Updated:** 2026-03-10 | **Architecture:** Monolithic (single file; modules inlined)


## Quick Start

### Step 1: Get an API Key

1. Log in to [Bybit](https://www.bybit.com) → API Management → Create New Key
2. Permissions: enable **Read + Trade only** (NEVER enable Withdraw for AI use)
3. Recommended: bind your IP address (makes the key permanent; otherwise expires in 3 months)
4. **Strongly recommended**: Create a dedicated **sub-account** for AI trading with limited balance

### 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):

```bash
# User sets once in shell profile (~/.zshrc or ~/.bashrc):
export BYBIT_API_KEY="your_api_key"
export BYBIT_API_SECRET="your_secret_key"
export BYBIT_ENV="mainnet"  # or "testnet"
```

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:

1. Tell the user: "For security, I recommend storing your API keys as environment variables instead of pasting them here."
2. Provide the export commands above
3. 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:

```bash
# Option 1: Global config (recommended) — ~/.openclaw/.env
BYBIT_API_KEY=your_api_key
BYBIT_API_SECRET=your_secret_key
BYBIT_ENV=mainnet

# Option 2: Project-level — ./.env in working directory (higher priority)
# Option 3: openclaw.json env block
# { "env": { "vars": { "BYBIT_API_KEY": "...", "BYBIT_API_SECRET": "...", "BYBIT_ENV": "mainnet" } } }
```

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:
1. Accept keys pasted in the conversation
2. 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)."
3. Do NOT ask again in the same session

**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: NEVER include raw API Key or Secret Key values in generated code, scripts, or curl examples. Use placeholder variables like `${API_KEY}` and `${SECRET_KEY}` instead of actual values. This applies to ALL output formats including bash, python, and JSON.

### Step 3: Verify Connection (auto-run on first use)

After credentials are configured, automatically run these checks:

```bash
# 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
```

- If clock difference > 5s: stop and ask user to fix clock sync first
- If `retCode=0`: credentials are valid. Tell user "Connected to Bybit [Mainnet/Testnet]. Account verified."
- If `retCode=10003/10004`: signature error. Check timestamp sync and signature calculation.
- If `retCode=10005`: insufficient permissions. Tell user to check API Key permissions.
- If `retCode=10010`: IP not whitelisted. Tell user to add current IP in API Key settings.

### 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."
- 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"
- If you'd like to practice first, say "switch to testnet" to use test funds.

---

## Modules (Inlined)

ClawHub skills do not support modular routing. This file includes all modules inline.

### Module Index (Intent Map)

| User Intent Keywords | Module |
|---------------------|--------|
| price, ticker, kline, chart, orderbook, depth, funding rate, open interest, market data | market |
| buy, sell, spot, swap, exchange, convert, limit order, market order, cancel order, spot margin | spot |
| long, short, leverage, futures, perpetual, close position, take profit, stop loss, trailing stop, conditional order, hedge mode, option, put, call, strike, expiry | derivatives |
| earn, stake, redeem, yield, savings, flexible, fixed deposit | earn |
| balance, wallet, transfer, deposit, withdraw, fee, sub-account, API key, asset | account |
| websocket, stream, loan, borrow, repay, RFQ, block trade, spread, lending, broker, rate limit | advanced |
| payment, pay, merchant, QR code, checkout, payout, refund, agreement, recurring, subscription, deduction | pay |
| P2P, peer to peer, advertisement, ad, OTC, fiat, fiat buy, fiat sell, convert fiat | fiat |

---

### Market Data

#### Scenario: Check Market Data

User might say: "What's the BTC price?", "Show me ETH chart", "What's the current funding rate?"

**Get real-time price**
```
GET /v5/market/tickers?category=spot&symbol=BTCUSDT
GET /v5/market/tickers?category=linear&symbol=BTCUSDT  (derivatives)
```

**Get candlestick/kline data**
```
GET /v5/market/kline?category=linear&symbol=BTCUSDT&interval=60&limit=100
```
interval: `1` `3` `5` `15` `30` `60` `120` `240` `360` `720` `D` `W` `M` (minutes or day/week/month)

**Get funding rate**
```
GET /v5/market/funding/history?category=linear&symbol=BTCUSDT&limit=10
```

**Get orderbook depth**
```
GET /v5/market/orderbook?category=linear&symbol=BTCUSDT&limit=50
```

> Market data endpoints require no authentication and can be called directly.

---

#### API Reference

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Kline | `/v5/market/kline` | GET | symbol, interval | category, start, end, limit | spot, linear, inverse |
| Mark Price Kline | `/v5/market/mark-price-kline` | GET | category, symbol, interval | start, end, limit | linear, inverse |
| Index Price Kline | `/v5/market/index-price-kline` | GET | category, symbol, interval | start, end, limit | linear, inverse |
| Premium Index Kline | `/v5/market/premium-index-price-kline` | GET | category, symbol, interval | start, end, limit | linear |
| Instruments Info | `/v5/market/instruments-info` | GET | category | symbol, baseCoin, limit, cursor, status | spot, linear, inverse, option |
| Orderbook | `/v5/market/orderbook` | GET | category, symbol | limit | spot, linear, inverse, option |
| Tickers | `/v5/market/tickers` | GET | category | symbol, baseCoin, expDate | spot, linear, inverse, option |
| Funding Rate History | `/v5/market/funding/history` | GET | category, symbol | startTime, endTime, limit | linear, inverse |
| Recent Trades | `/v5/market/recent-trade` | GET | category, symbol | baseCoin, limit | spot, linear, inverse, option |
| Open Interest | `/v5/market/open-interest` | GET | category, symbol, intervalTime | startTime, endTime, limit, cursor | linear, inverse |
| Historical Volatility | `/v5/market/historical-volatility` | GET | category | baseCoin, period, startTime, endTime | option |
| Insurance Fund | `/v5/market/insurance` | GET | — | coin | — |
| Risk Limit | `/v5/market/risk-limit` | GET | category | symbol | linear, inverse |
| Delivery Price | `/v5/market/delivery-price` | GET | category | symbol, baseCoin, limit, cursor | linear, inverse, option |
| Long/Short Ratio | `/v5/market/account-ratio` | GET | category, symbol, period | limit | linear, inverse |
| Price Limit | `/v5/market/price-limit` | GET | symbol | category | linear, inverse |
| Index Components | `/v5/market/index-price-components` | GET | indexName | — | — |
| Fee Group | `/v5/market/fee-group-info` | GET | productType | groupId | — |
| New Delivery Price | `/v5/market/new-delivery-price` | GET | category, baseCoin | settleCoin | linear, inverse, option |
| ADL Alert | `/v5/market/adlAlert` | GET | — | symbol | linear, inverse |
| RPI Orderbook | `/v5/market/rpi_orderbook` | GET | symbol, limit | category | spot |
| Server Time | `/v5/market/time` | GET | — | — | — |
| System Status | `/v5/system/status` | GET | — | id, state | — |
| Announcements | `/v5/announcements/index` | GET | — | locale, type, tag, page, limit | — |

#### Enums

* **interval** (kline): `1` | `3` | `5` | `15` | `30` | `60` | `120` | `240` | `360` | `720` | `D` | `W` | `M`
* **intervalTime** (open interest): `5min` | `15min` | `30min` | `1h` | `4h` | `1d`
* **period** (long/short ratio): `5min` | `15min` | `30min` | `1h` | `4h` | `1d`
* **category**: `spot` | `linear` | `inverse` | `option`


---

### Spot Trading

#### Scenario: Spot Trading

User might say: "Buy 500U of BTC", "Sell all my ETH", "Place a limit order"

**Market buy** (recommended: use quoteCoin to specify USDT amount)
```
POST /v5/order/create
{"category":"spot","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"500","marketUnit":"quoteCoin"}
```

**Market sell** (use baseCoin to specify coin quantity)
```
POST /v5/order/create
{"category":"spot","symbol":"ETHUSDT","side":"Sell","orderType":"Market","qty":"2.5"}
```

**Limit buy**
```
POST /v5/order/create
{"category":"spot","symbol":"BTCUSDT","side":"Buy","orderType":"Limit","qty":"0.01","price":"80000","timeInForce":"GTC"}
```

**View open orders**
```
GET /v5/order/realtime?category=spot&symbol=BTCUSDT
```

**Cancel order**
```
POST /v5/order/cancel
{"category":"spot","symbol":"BTCUSDT","orderId":"xxx"}
```

> **Important**: For spot market buy orders, using `marketUnit=quoteCoin` + USDT amount is recommended over specifying coin quantity — it is more reliable.

---

#### API Reference

##### Trade (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Rate Limit | Categories |
|----------|------|--------|----------------|-----------------|------------|------------|
| Place Order | `/v5/order/create` | POST | category, symbol, side, orderType, qty | price, timeInForce, orderLinkId, triggerPrice, takeProfit, stopLoss, tpslMode, reduceOnly, positionIdx, marketUnit... | 10-20/s | spot, linear, inverse, option |
| Amend Order | `/v5/order/amend` | POST | category, symbol | orderId/orderLinkId, qty, price, takeProfit, stopLoss, triggerPrice | 10/s | spot, linear, inverse, option |
| Cancel Order | `/v5/order/cancel` | POST | category, symbol | orderId/orderLinkId, orderFilter | 10-20/s | spot, linear, inverse, option |
| Get Open Orders | `/v5/order/realtime` | GET | category | symbol, baseCoin, orderId, orderLinkId, openOnly, limit, cursor | 50/s | spot, linear, inverse, option |
| Cancel All Orders | `/v5/order/cancel-all` | POST | category | symbol, baseCoin, settleCoin, orderFilter, stopOrderType | 10/s | spot, linear, inverse, option |
| Order History | `/v5/order/history` | GET | category | symbol, orderId, orderLinkId, orderFilter, orderStatus, startTime, endTime, limit, cursor | 50/s | spot, linear, inverse, option |
| Batch Place Order | `/v5/order/create-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |
| Batch Amend Order | `/v5/order/amend-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |
| Batch Cancel Order | `/v5/order/cancel-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |
| Spot Borrow Check | `/v5/order/spot-borrow-check` | GET | category, symbol, side | — | — | spot |
| Pre-check | `/v5/order/pre-check` | POST | (same as create) | — | — | spot, linear, inverse, option |
| DCP | `/v5/order/disconnected-cancel-all` | POST | timeWindow | — | — | option |

##### Spot Margin (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Switch Margin Mode | `/v5/spot-margin-trade/switch-mode` | POST | spotMarginMode | — | spot |
| Set Spot Leverage | `/v5/spot-margin-trade/set-leverage` | POST | leverage | — | spot |
| VIP Margin Data | `/v5/spot-margin-trade/data` | GET | — | — | spot |
| Interest Rate History | `/v5/spot-margin-trade/interest-rate-history` | GET | currency | startTime, endTime, vipLevel | spot |
| Margin Status | `/v5/spot-margin-trade/state` | GET | — | — | spot |
| Coin Status | `/v5/spot-margin-trade/coinstate` | GET | — | currency | spot |
| Tiered Collateral Rate | `/v5/spot-margin-trade/collateral` | GET | — | currency | spot |
| Auto Repay Mode | `/v5/spot-margin-trade/get-auto-repay-mode` | GET | — | — | spot |
| Set Auto Repay | `/v5/spot-margin-trade/set-auto-repay-mode` | POST | — | — | spot |
| Max Borrowable | `/v5/spot-margin-trade/max-borrowable` | GET | — | coin | spot |
| Position Tiers | `/v5/spot-margin-trade/position-tiers` | GET | — | — | spot |
| Repayable Amount | `/v5/spot-margin-trade/repayment-available-amount` | GET | — | — | spot |

#### Enums

* **side**: `Buy` | `Sell`
* **orderType**: `Market` | `Limit`
* **timeInForce**: `GTC` | `IOC` | `FOK` | `PostOnly` | `RPI`
* **orderStatus (open)**: `New` | `PartiallyFilled` | `Untriggered`
* **orderStatus (closed)**: `Rejected` | `PartiallyFilledCanceled` | `Filled` | `Cancelled` | `Triggered` | `Deactivated`
* **spotMarginMode**: `0` (off) | `1` (on)
* **marketUnit**: `baseCoin` | `quoteCoin` (spot market buy only)


---

### Derivatives Trading

#### Scenario: Derivatives Trading

User might say: "Open a BTC long with 10x leverage", "Close position", "Set take profit at 90000"

**Pre-trade preparation**
```bash
### 1. Check current account mode
GET /v5/account/info
### Returns marginMode: REGULAR_MARGIN / ISOLATED_MARGIN / PORTFOLIO_MARGIN

### 2. Check position mode (MUST do before any write operation)
GET /v5/position/list?category=linear&symbol=BTCUSDT
### Response positionIdx: 0 → one-way mode, 1 or 2 → hedge mode
### One-way: use positionIdx=0 for all orders
### Hedge: use positionIdx=1 (Buy/Long), positionIdx=2 (Sell/Short)

### 2b. (Optional) Switch position mode — only if user explicitly requests
POST /v5/position/switch-mode
{"category":"linear","coin":"USDT","mode":0}   # 0=one-way, 3=hedge
### retCode=0 → switched successfully
### retCode=110025 → already in target mode
### retCode=110026 → cannot switch while holding positions or active orders

### 3. Set leverage (buy and sell leverage must match)
POST /v5/position/set-leverage
{"category":"linear","symbol":"BTCUSDT","buyLeverage":"10","sellLeverage":"10"}
```

> **Position mode check**: Always query position mode via `/v5/position/list` before placing the first order in a session. Cache the result (one-way vs hedge) and use the correct `positionIdx` for all subsequent orders. One-way mode: `positionIdx=0`. Hedge mode: `positionIdx=1` (long), `positionIdx=2` (short). Never call switch-mode to "detect" — it changes state.

**Open long**
```
POST /v5/order/create
{"category":"linear","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"0.01","positionIdx":0}
### positionIdx=0 for one-way mode; use 1 for hedge mode long
```

**Open short**
```
POST /v5/order/create
{"category":"linear","symbol":"BTCUSDT","side":"Sell","orderType":"Market","qty":"0.01","positionIdx":0}
### positionIdx=0 for one-way mode; use 2 for hedge mode short
```

**Open position with take profit and stop loss**
```
POST /v5/order/create
{"category":"linear","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"0.01",
 "takeProfit":"90000","stopLoss":"78000","tpslMode":"Full"}
```

**View positions**
```
GET /v5/position/list?category=linear&symbol=BTCUSDT
```

**Close position (recommended: query size first, then close)**
```bash
### 1. Query actual position size
GET /v5/position/list?category=linear&symbol=BTCUSDT
### Read "size" from response to get exact position quantity

### 2. Close with exact quantity
POST /v5/order/create
{"category":"linear","symbol":"BTCUSDT","side":"Sell","orderType":"Market","qty":"<size_from_step_1>","reduceOnly":true,"positionIdx":0}
```
> **Shortcut**: On Bybit V5 linear/inverse, `qty="0"` + `reduceOnly=true` closes the entire position. Use this only when you're confident the symbol supports it. The query-first approach is safer and works across all categories.

**Modify take profit / stop loss**
```
POST /v5/position/trading-stop
{"category":"linear","symbol":"BTCUSDT","takeProfit":"92000","stopLoss":"79000","tpslMode":"Full","positionIdx":0}
```

**Hedge mode handling**:
- If an order returns `retCode=10001` "position idx not match position mode", the account is in hedge mode
- Use `positionIdx=1` for long, `positionIdx=2` for short
- Remember the account is in hedge mode and automatically include positionIdx in subsequent orders

> **Category confirmation**: When the user says "BTCUSDT", you must confirm whether they mean spot or derivatives — do not assume.

---

#### Scenario: Conditional Orders & Advanced Orders

User might say: "Buy BTC when it hits 85000", "Set a trailing stop"

**Conditional order (trigger price order)**
```
POST /v5/order/create
{"category":"linear","symbol":"BTCUSDT","side":"Buy","orderType":"Market","qty":"0.01",
 "triggerPrice":"85000","triggerDirection":2,"triggerBy":"LastPrice"}
```

> `triggerDirection` is **required** for conditional orders:
> - `1` = triggered when price **rises** to triggerPrice (triggerPrice > current price)
> - `2` = triggered when price **falls** to triggerPrice (triggerPrice < current price)
>
> Rule of thumb: buying the dip → `triggerDirection=2`; breakout buy → `triggerDirection=1`.

**Trailing stop**
```
POST /v5/position/trading-stop
{"category":"linear","symbol":"BTCUSDT","trailingStop":"500","activePrice":"88000","positionIdx":0}
```
> trailingStop="500" means the stop triggers when price retraces by $500. activePrice is the activation price (tracking begins only after this price is reached).

---

#### API Reference

##### Trade (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Rate Limit | Categories |
|----------|------|--------|----------------|-----------------|------------|------------|
| Place Order | `/v5/order/create` | POST | category, symbol, side, orderType, qty | price, timeInForce, orderLinkId, triggerPrice, takeProfit, stopLoss, tpslMode, reduceOnly, positionIdx, marketUnit... | 10-20/s | spot, linear, inverse, option |
| Amend Order | `/v5/order/amend` | POST | category, symbol | orderId/orderLinkId, qty, price, takeProfit, stopLoss, triggerPrice | 10/s | spot, linear, inverse, option |
| Cancel Order | `/v5/order/cancel` | POST | category, symbol | orderId/orderLinkId, orderFilter | 10-20/s | spot, linear, inverse, option |
| Get Open Orders | `/v5/order/realtime` | GET | category | symbol, baseCoin, orderId, orderLinkId, openOnly, limit, cursor | 50/s | spot, linear, inverse, option |
| Cancel All Orders | `/v5/order/cancel-all` | POST | category | symbol, baseCoin, settleCoin, orderFilter, stopOrderType | 10/s | spot, linear, inverse, option |
| Order History | `/v5/order/history` | GET | category | symbol, orderId, orderLinkId, orderFilter, orderStatus, startTime, endTime, limit, cursor | 50/s | spot, linear, inverse, option |
| Batch Place Order | `/v5/order/create-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |
| Batch Amend Order | `/v5/order/amend-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |
| Batch Cancel Order | `/v5/order/cancel-batch` | POST | category, request[] | — | per-order | spot, linear, inverse, option |

##### Position (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Get Position | `/v5/position/list` | GET | category | symbol, baseCoin, settleCoin, limit, cursor | linear, inverse, option |
| Set Leverage | `/v5/position/set-leverage` | POST | category, symbol, buyLeverage, sellLeverage | — | linear, inverse |
| Switch Position Mode | `/v5/position/switch-mode` | POST | category, mode | coin, symbol | linear, inverse |
| Set Trading Stop | `/v5/position/trading-stop` | POST | category, symbol, tpslMode, positionIdx | takeProfit, stopLoss, trailingStop, tpTriggerBy, slTriggerBy, activePrice, tpSize, slSize, tpLimitPrice, slLimitPrice | linear, inverse |
| Set Auto Add Margin | `/v5/position/set-auto-add-margin` | POST | category, symbol, autoAddMargin | positionIdx | linear, inverse |
| Add/Reduce Margin | `/v5/position/add-margin` | POST | category, symbol, margin | positionIdx | linear, inverse |
| Execution History | `/v5/execution/list` | GET | category | symbol, baseCoin, orderId, startTime, endTime, execType, limit, cursor | spot, linear, inverse, option |
| Closed PnL | `/v5/position/closed-pnl` | GET | category, symbol | startTime, endTime, limit, cursor | linear, inverse |
| Closed Options | `/v5/position/get-closed-positions` | GET | category | symbol, limit, cursor | option |
| Confirm Pending MMR | `/v5/position/confirm-pending-mmr` | POST | category, symbol | — | linear, inverse |

#### Enums

* **positionIdx**: `0` (one-way) | `1` (hedge-buy) | `2` (hedge-sell)
* **positionMode**: `0` (MergedSingle / one-way) | `3` (BothSide / hedge)
* **tradeMode**: `0` (cross margin) | `1` (isolated margin)
* **triggerBy**: `LastPrice` | `IndexPrice` | `MarkPrice`
* **tpslMode**: `Full` | `Partial`
* **stopOrderType**: `TakeProfit` | `StopLoss` | `TrailingStop` | `Stop` | `PartialTakeProfit` | `PartialStopLoss` | `tpslOrder` | `OcoOrder`
* **execType**: `Trade` | `AdlTrade` | `Funding` | `BustTrade` | `Delivery` | `Settle` | `BlockTrade` | `MovePosition`
* **setMarginMode**: `ISOLATED_MARGIN` | `REGULAR_MARGIN` | `PORTFOLIO_MARGIN`
* **autoAddMargin**: `0` (off) | `1` (on)

#### Take Profit / Stop Loss Parameters

| Parameter | Description |
|-----------|-------------|
| takeProfit | Take profit price (pass `"0"` to cancel) |
| stopLoss | Stop loss price (pass `"0"` to cancel) |
| tpslMode | `Full` (entire position) `Partial` (partial) |
| tpOrderType | Order type when TP triggers: `Market` (default) `Limit` |
| slOrderType | Order type when SL triggers: `Market` (default) `Limit` |
| trailingStop | Trailing stop distance (pass `"0"` to cancel) |
| activePrice | Trailing stop activation price |


---

### Earn

#### Scenario: Earn Products

User might say: "Show me available earn products", "Deposit USDT", "Redeem"

**View product list**
```
GET /v5/earn/product?category=FlexibleSaving&coin=USDT
```
> Use the returned `productId` for place-order requests.

**Stake**
```
POST /v5/earn/place-order
{"category":"FlexibleSaving","orderType":"Stake","accountType":"UNIFIED","coin":"USDT","amount":"1000","productId":"123","orderLinkId":"unique-id-123"}
```
> All 7 params above are required. Get `productId` from the product list first.

**View orders**
```
GET /v5/earn/order?category=FlexibleSaving
```

**View yield history**
```
GET /v5/earn/yield?category=FlexibleSaving&coin=USDT
```

**Redeem**
```
POST /v5/earn/place-order
{"category":"FlexibleSaving","orderType":"Redeem","accountType":"UNIFIED","coin":"USDT","amount":"500","productId":"123","orderLinkId":"unique-id-456"}
```

---

#### API Reference

##### Earn (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params |
|----------|------|--------|----------------|-----------------|
| Product | `/v5/earn/product` | GET | category | coin |
| Place Order | `/v5/earn/place-order` | POST | category, orderType, accountType, coin, amount, productId, orderLinkId | redeemPositionId, toAccountType |
| Query Order | `/v5/earn/order` | GET | category | orderId, orderLinkId, productId, startTime, endTime, limit, cursor |
| Position | `/v5/earn/position` | GET | category | productId, coin |
| Yield | `/v5/earn/yield` | GET | category | productId, startTime, endTime, limit, cursor |
| Hourly Yield | `/v5/earn/hourly-yield` | GET | category | productId, startTime, endTime, limit, cursor |

#### Enums

* **orderType**: `Stake` | `Redeem`
* **accountType**: `FUND` | `UNIFIED` (OnChain only supports FUND)
* **earn category**: `FlexibleSaving` | `OnChain`


---

### Account & Asset Management

#### Scenario: Account & Asset Management

User might say: "Check my balance", "Transfer from spot to derivatives", "Show today's trade history"

**View wallet balance**
```
GET /v5/account/wallet-balance?accountType=UNIFIED
```

**View fee rate**
```
GET /v5/account/fee-rate?category=linear&symbol=BTCUSDT
```

**Internal transfer (spot <-> derivatives <-> funding account)**
```
POST /v5/asset/transfer/inter-transfer
{"transferId":"uuid","coin":"USDT","amount":"1000","fromAccountType":"UNIFIED","toAccountType":"FUND"}
```

**View trade history**
```
GET /v5/execution/list?category=linear&symbol=BTCUSDT
```

**View realized PnL**
```
GET /v5/position/closed-pnl?category=linear&symbol=BTCUSDT
```

---

#### API Reference

##### Account (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Wallet Balance | `/v5/account/wallet-balance` | GET | accountType | coin | — |
| Asset Overview | `/v5/asset/asset-overview` | GET | — | accountType, coin | — |
| Account Info | `/v5/account/info` | GET | — | — | — |
| Borrow History | `/v5/account/borrow-history` | GET | — | currency, startTime, endTime, limit, cursor | — |
| Set Collateral | `/v5/account/set-collateral-switch` | POST | coin, collateralSwitch | — | — |
| Collateral Info | `/v5/account/collateral-info` | GET | — | currency | — |
| Coin Greeks | `/v5/asset/coin-greeks` | GET | — | baseCoin | option |
| Fee Rate | `/v5/account/fee-rate` | GET | category | symbol, baseCoin | spot, linear, inverse, option |
| Transaction Log | `/v5/account/transaction-log` | GET | — | accountType, category, currency, baseCoin, type, startTime, endTime, limit, cursor | — |
| Contract Transaction Log | `/v5/account/contract-transaction-log` | GET | — | currency, baseCoin, type, startTime, endTime, limit, cursor | — |
| Set Margin Mode | `/v5/account/set-margin-mode` | POST | setMarginMode | — | — |
| Set MMP | `/v5/account/mmp-modify` | POST | baseCoin, window, frozenPeriod, qtyLimit, deltaLimit | — | option |
| Reset MMP | `/v5/account/mmp-reset` | POST | baseCoin | — | option |
| MMP State | `/v5/account/mmp-state` | GET | baseCoin | — | option |
| Account Instruments Info | `/v5/account/instruments-info` | GET | category | symbol, limit, cursor | spot, linear, inverse, option |
| DCP Info | `/v5/account/query-dcp-info` | GET | — | — | — |
| SMP Group | `/v5/account/smp-group` | GET | — | — | — |
| Trading Behavior Config | `/v5/account/user-setting-config` | GET | — | — | — |
| Transferable Amount | `/v5/account/withdrawal` | GET | coinName | — | — |
| Manual Borrow | `/v5/account/borrow` | POST | coin, amount | — | — |
| Manual Repay | `/v5/account/repay` | POST | — | coin, amount | — |
| No-Convert Repay | `/v5/account/no-convert-repay` | POST | coin | amount | — |
| Quick Repay | `/v5/account/quick-repayment` | POST | — | coin | — |
| Batch Set Collateral | `/v5/account/set-collateral-switch-batch` | POST | request[] | — | — |
| Set Spot Hedging | `/v5/account/set-hedging-mode` | POST | setHedgingMode | — | spot |
| Set Price Limit Action | `/v5/account/set-limit-px-action` | POST | category, modifyEnable | — | linear, inverse |
| Set Delta Neutral Mode | `/v5/account/set-delta-mode` | POST | deltaHedgeMode | — | option |
| Apply Demo Funds | `/v5/account/demo-apply-money` | POST | — | adjustType, utaDemoApplyMoney | — |

##### Asset (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Funding History | `/v5/asset/fundinghistory` | GET | — | coin, startTime, endTime, limit, cursor | — |
| Coin Exchange Record | `/v5/asset/exchange/order-record` | GET | — | fromCoin, toCoin, limit, cursor | — |
| Delivery Record | `/v5/asset/delivery-record` | GET | category | symbol, expDate, limit, cursor | linear, inverse, option |
| USDC Settlement Record | `/v5/asset/settlement-record` | GET | category | symbol, limit, cursor | linear |
| Internal Transfer Record | `/v5/asset/transfer/query-inter-transfer-list` | GET | — | transferId, coin, status, startTime, endTime, limit, cursor | — |
| Spot Asset | `/v5/asset/transfer/query-asset-info` | GET | accountType | coin | — |
| All Balances | `/v5/asset/transfer/query-account-coins-balance` | GET | accountType | memberId, coin, withBonus | — |
| Single Coin Balance | `/v5/asset/transfer/query-account-coin-balance` | GET | accountType, coin | memberId, toAccountType, toMemberId, withBonus | — |
| Transferable Coins | `/v5/asset/transfer/query-transfer-coin-list` | GET | fromAccountType, toAccountType | — | — |
| Internal Transfer | `/v5/asset/transfer/inter-transfer` | POST | transferId, coin, amount, fromAccountType, toAccountType | — | — |
| Sub-account List | `/v5/asset/transfer/query-sub-member-list` | GET | — | — | — |
| Deposit Coins | `/v5/asset/deposit/query-allowed-list` | GET | — | coin, chain, cursor, limit | — |
| Set Deposit Account | `/v5/asset/deposit/deposit-to-account` | POST | accountType | — | — |
| Deposit Record | `/v5/asset/deposit/query-record` | GET | — | coin, startTime, endTime, limit, cursor | — |
| Sub-account Deposit Record | `/v5/asset/deposit/query-sub-member-record` | GET | subMemberId | coin, startTime, endTime, limit, cursor | — |
| Internal Deposit Record | `/v5/asset/deposit/query-internal-record` | GET | — | startTime, endTime, coin, cursor, limit | — |
| Master Deposit Address | `/v5/asset/deposit/query-address` | GET | coin | chainType | — |
| Sub-account Deposit Address | `/v5/asset/deposit/query-sub-member-address` | GET | coin, chainType, subMemberId | — | — |
| Coin Info | `/v5/asset/coin/query-info` | GET | — | coin | — |
| Withdrawal Record | `/v5/asset/withdraw/query-record` | GET | — | withdrawID, coin, withdrawType, startTime, endTime, limit, cursor | — |
| Withdrawable Amount | `/v5/asset/withdraw/withdrawable-amount` | GET | coin | — | — |
| Withdrawal Address List | `/v5/asset/withdraw/query-address` | GET | — | coin, chain, addressType, limit, cursor | — |
| VASP List | `/v5/asset/withdraw/vasp/list` | GET | — | — | — |
| Internal Transfer Record v2 | `/v5/asset/transfer/inter-transfer-list-query` | GET | — | coin, limit | — |
| Small Balance List | `/v5/asset/covert/small-balance-list` | GET | accountType | fromCoin | — |
| Small Balance Quote | `/v5/asset/covert/get-quote` | POST | accountType, fromCoinList, toCoin | — | — |
| Small Balance Convert | `/v5/asset/covert/small-balance-execute` | POST | quoteId | — | — |
| Small Balance History | `/v5/asset/covert/small-balance-history` | GET | — | accountType, quoteId, startTime, endTime, cursor, size | — |
| Exchange Coin List | `/v5/asset/exchange/query-coin-list` | GET | accountType | coin, side | — |
| Exchange Quote | `/v5/asset/exchange/quote-apply` | POST | accountType, fromCoin, toCoin, requestCoin, requestAmount | fromCoinType, toCoinType | — |
| Exchange Execute | `/v5/asset/exchange/convert-execute` | POST | quoteTxId | — | — |
| Exchange Result | `/v5/asset/exchange/convert-result-query` | GET | quoteTxId, accountType | — | — |
| Exchange History | `/v5/asset/exchange/query-convert-history` | GET | — | accountType, index, limit | — |
| Exchange Convert Limit | `/v5/asset/exchange/query-convert-limit` | GET | fromCoin, toCoin, accountType | — | — |
| Exchange Order List | `/v5/asset/exchange/query-order-list` | GET | accountType | index, limit | — |

##### User (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params | Categories |
|----------|------|--------|----------------|-----------------|------------|
| Sub-account List | `/v5/user/query-sub-members` | GET | — | — | — |
| API Key Info | `/v5/user/query-api` | GET | — | — | — |
| Member Type | `/v5/user/get-member-type` | GET | — | — | — |
| Affiliate User Info | `/v5/user/aff-customer-info` | GET | uid | — | — |
| Sub-account List (full) | `/v5/user/submembers` | GET | — | pageSize, nextCursor | — |
| Sub-account All Keys | `/v5/user/sub-apikeys` | GET | subMemberId | limit, cursor | — |
| Escrow Sub-accounts | `/v5/user/escrow_sub_members` | GET | — | pageSize, nextCursor | — |
| Create Demo Account | `/v5/user/create-demo-member` | POST | — | — | — |
| Affiliate User List | `/v5/affiliate/aff-user-list` | GET | — | size, cursor, need365, need30, needDeposit, startDate, endDate | — |
| Referral List | `/v5/user/invitation/referrals` | GET | — | limit, cursor | — |
| Sign Agreement | `/v5/user/agreement` | POST | agree, category | — | — |

#### Enums

* **accountType**: `UNIFIED` | `FUND`
* **collateralSwitch**: `ON` | `OFF`
* **frozen** (sub account): `0` (unfreeze) | `1` (freeze)
* **memberType** (sub account): `1` (normal) | `6` (custodial)


---

### Advanced Features

#### WebSocket

Use WebSocket when real-time push is needed. The REST API covers most scenarios.

##### Public Stream

URL: `wss://stream.bybit.com/v5/public/{category}`
Testnet: `wss://stream-testnet.bybit.com/v5/public/{category}`

| Topic | Format | Description |
|-------|--------|-------------|
| Orderbook | `orderbook.{depth}.{symbol}` | depth: 1, 50, 200, 500 |
| Trades | `publicTrade.{symbol}` | Real-time trades |
| Tickers | `tickers.{symbol}` | Ticker updates |
| Kline | `kline.{interval}.{symbol}` | Candlestick updates |
| Liquidation | `liquidation.{symbol}` | Liquidation events |

##### Private Stream

URL: `wss://stream.bybit.com/v5/private`

| Topic | Description |
|-------|-------------|
| `position` | Position changes |
| `execution` | Execution updates |
| `order` | Order status updates |
| `wallet` | Balance changes |

Subscribe: `{"op": "subscribe", "args": ["orderbook.50.BTCUSDT"]}`
Heartbeat: Send `{"op": "ping"}` every 20 seconds
Auth: `{"op": "auth", "args": ["<apiKey>", "<expires>", "<signature>"]}`

---

#### Crypto Loan

| Endpoint | Path | Method | Required Params | Optional Params | Auth | Status |
|----------|------|--------|----------------|-----------------|------|--------|
| Repay | `/v5/crypto-loan/repay` | POST | orderId, repayAmount | — | Yes | Current |
| Adjust LTV | `/v5/crypto-loan/adjust-ltv` | POST | currency, amount, direction | — | Yes | Current |
| Ongoing Orders | `/v5/crypto-loan/ongoing-orders` | GET | — | orderId, limit, cursor | Yes | Current |
| Borrow History | `/v5/crypto-loan/borrow-history` | GET | — | currency, limit, cursor | Yes | Current |
| Repayment History | `/v5/crypto-loan/repayment-history` | GET | — | orderId, limit, cursor | Yes | Current |
| Adjustment History | `/v5/crypto-loan/adjustment-history` | GET | — | currency, limit, cursor | Yes | Current |
| Loanable Data | `/v5/crypto-loan/loanable-data` | GET | — | — | No | Current |
| Collateral Data | `/v5/crypto-loan/collateral-data` | GET | — | — | No | Current |
| Max Collateral Amount | `/v5/crypto-loan/max-collateral-amount` | GET | currency | — | Yes | Current |
| Borrowable & Collateralisable | `/v5/crypto-loan/borrowable-collateralisable-number` | GET | — | — | Yes | Current |

##### Crypto Loan — Common (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params |
|----------|------|--------|----------------|-----------------|
| Position | `/v5/crypto-loan-common/position` | GET | — | — |
| Collateral Data | `/v5/crypto-loan-common/collateral-data` | GET | — | — |
| Loanable Data | `/v5/crypto-loan-common/loanable-data` | GET | — | — |
| Max Collateral Amount | `/v5/crypto-loan-common/max-collateral-amount` | GET | currency | — |
| Max Loan | `/v5/crypto-loan-common/max-loan` | GET | currency | — |
| Adjust LTV | `/v5/crypto-loan-common/adjust-ltv` | POST | currency, amount, direction | — |
| Adjustment History | `/v5/crypto-loan-common/adjustment-history` | GET | — | currency, limit, cursor |

##### Crypto Loan — Fixed Term (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params |
|----------|------|--------|----------------|-----------------|
| Borrow Contract Info | `/v5/crypto-loan-fixed/borrow-contract-info` | GET | orderCurrency | — |
| Borrow Order Quote | `/v5/crypto-loan-fixed/borrow-order-quote` | GET | orderCurrency | orderBy |
| Borrow Order Info | `/v5/crypto-loan-fixed/borrow-order-info` | GET | — | orderId |
| Cancel Borrow | `/v5/crypto-loan-fixed/borrow-order-cancel` | POST | orderId | — |
| Full Repay | `/v5/crypto-loan-fixed/fully-repay` | POST | orderId | — |
| Repay Collateral | `/v5/crypto-loan-fixed/repay-collateral` | POST | orderId | — |
| Repayment History | `/v5/crypto-loan-fixed/repayment-history` | GET | — | repayId |
| Renewal Info | `/v5/crypto-loan-fixed/renew-info` | GET | orderId | — |
| Renew | `/v5/crypto-loan-fixed/renew` | POST | orderId | — |
| Supply Contract Info | `/v5/crypto-loan-fixed/supply-contract-info` | GET | supplyCurrency | — |
| Supply Order Quote | `/v5/crypto-loan-fixed/supply-order-quote` | GET | orderCurrency | orderBy |
| Supply Order Info | `/v5/crypto-loan-fixed/supply-order-info` | GET | — | orderId |
| Cancel Supply | `/v5/crypto-loan-fixed/supply-order-cancel` | POST | orderId | — |

##### Crypto Loan — Flexible (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params |
|----------|------|--------|----------------|-----------------|
| Repay | `/v5/crypto-loan-flexible/repay` | POST | loanCoin, repayAmount | — |
| Repay Collateral | `/v5/crypto-loan-flexible/repay-collateral` | POST | orderId | — |
| Ongoing Coins | `/v5/crypto-loan-flexible/ongoing-coin` | GET | — | loanCurrency |
| Borrow History | `/v5/crypto-loan-flexible/borrow-history` | GET | — | limit |
| Repayment History | `/v5/crypto-loan-flexible/repayment-history` | GET | — | loanCurrency |

---

#### Institutional Loan (authentication required)

| Endpoint | Path | Method | Required Params | Optional Params |
|----------|------|--------|----------------|-----------------|
| Product Info | `/

…(truncated)
