# Ccxt Binance Expert

> Expert guidance for CCXT Binance Futures API integration including demo trading, algo orders, WebSocket streaming, and the December 2025 API changes. Use when integrating with Binance Futures, handling stop-loss/take-profit orders, or troubleshooting authentication issues.

- Skill: `lirielgozi/ccxt-binance-expert` (Agent Skill, multi-file: 14 files)
- Install (CLI): `npx skillmds@latest add lirielgozi/ccxt-binance-expert`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lirielgozi/ccxt-binance-expert/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Integrations & APIs
- Author: lirielgozi (https://skillmd.com/u/lirielgozi)
- Updated: 2026-09-10
- Page: https://skillmd.com/skills/lirielgozi/ccxt-binance-expert

---


# CCXT Binance Expert

> Expert guidance for Binance Futures API integration using CCXT library

## When to Use

- Integrating with Binance Futures using CCXT
- Setting up demo trading (sandbox mode)
- Creating or canceling stop-loss/take-profit orders (Algo Orders)
- Troubleshooting authentication errors
- Implementing WebSocket streaming
- Handling the December 2025 Algo Order API migration

## When NOT to Use

- Spot trading (this skill focuses on Futures)
- Other exchanges (Kraken, Coinbase, etc.)
- Low-level REST API without CCXT

---

## Orchestrator

This skill coordinates the following sub-agents:

| Sub-Agent | Purpose | Invoked When |
|-----------|---------|--------------|
| `connection-tester` | Tests API connectivity and diagnoses issues | Setup, troubleshooting |
| `order-tester` | Tests all order types (regular + algo) | Validation, verification |
| `api-researcher` | Researches solutions for unknown errors | Test failures |

---

## Workflows

### Primary: Validate Integration
**Path**: `workflows/validate-integration.md`

Complete validation with auto-research on failures:
1. **Environment Check** → Verify credentials present
2. **Connection Test** → Test authentication and time sync
3. **Regular Order Test** → Test limit/market orders
4. **Algo Order Test** → Test stop-loss, take-profit, trailing stop
5. **Cleanup** → Remove test orders/positions
6. **Report** → Generate validation report

### Secondary: Troubleshoot
**Path**: `workflows/troubleshoot.md`

Diagnose and fix specific errors with automatic research.

---

## Commands

| Command | Description |
|---------|-------------|
| `/ccxt-binance-expert` | Show usage help |
| `/ccxt-binance-expert validate` | Run full integration validation |
| `/ccxt-binance-expert troubleshoot "<error>"` | Diagnose and fix a specific error |
| `/ccxt-binance-expert setup` | Guide through demo trading setup |

---

## Scripts

Available in `scripts/`:

| Script | Purpose |
|--------|---------|
| `verify-connection.cjs` | Test API connectivity |
| `cleanup-algo-orders.cjs` | Cancel all algo orders |
| `close-position.cjs` | Close open positions |
| `test-order-types.cjs` | Test all order types |

---

## Critical Knowledge: December 2025 API Change

**BREAKING CHANGE**: As of December 9, 2025, Binance migrated conditional orders to a new Algo Service.

### Affected Order Types
- `STOP` / `STOP_MARKET` (stop-loss orders)
- `TAKE_PROFIT` / `TAKE_PROFIT_MARKET`
- `TRAILING_STOP_MARKET`

### What Changed
- Old endpoint: `POST /fapi/v1/order` - **NO LONGER WORKS** for conditional orders
- New endpoint: `POST /fapi/v1/algoOrder` - **REQUIRED** for conditional orders
- Error code `-4120`: "Order type not supported for this endpoint"

### CCXT Handling
CCXT routes orders automatically, but you must use separate methods for algo order management:

```typescript
// Creating stop orders - CCXT handles routing
const stopOrder = await exchange.createOrder(
  'BTC/USDT:USDT',
  'stop_market',
  'sell',
  0.01,
  undefined,
  { stopPrice: 50000, reduceOnly: true }
);

// Canceling algo orders - use raw API
await exchange.fapiPrivateDeleteAlgoOrder({ algoId: stopOrder.id });

// Fetching open algo orders
const algoOrders = await exchange.fapiPrivateGetOpenAlgoOrders({ symbol: 'BTCUSDT' });
```

---

## Demo Trading Setup

### Binance Demo Trading vs Deprecated Testnet

| Platform | URL | Status | API Keys From |
|----------|-----|--------|---------------|
| Demo Trading | demo.binance.com | **Active** | demo.binance.com |
| Futures Testnet | testnet.binancefuture.com | **Deprecated** | N/A |

### Correct Setup (CCXT 4.5.6+)

```typescript
import * as ccxt from 'ccxt';

const exchange = new ccxt.pro.binance({
  apiKey: process.env.BINANCE_DEMO_API_KEY,
  secret: process.env.BINANCE_DEMO_SECRET,
  enableRateLimit: true,
  options: { defaultType: 'future' }
});

// Enable demo trading - REQUIRED for sandbox
exchange.enableDemoTrading(true);

await exchange.loadMarkets();
```

### Deprecated Method (DO NOT USE)

```typescript
// This NO LONGER WORKS for Futures
exchange.setSandboxMode(true);  // Throws: "testnet/sandbox mode is not supported for futures anymore"
```

---

## Order Operations

### Market Orders

```typescript
const order = await exchange.createMarketOrder(
  'BTC/USDT:USDT',  // CCXT symbol format
  'buy',
  0.01              // Amount in contracts
);
```

### Limit Orders

```typescript
// Note: Binance Futures has $100 minimum notional
const minNotional = 100;
const price = 50000;
const minAmount = Math.ceil((minNotional * 1.1) / price * 1000) / 1000;

const order = await exchange.createLimitOrder(
  'BTC/USDT:USDT',
  'buy',
  minAmount,
  price
);
```

### Stop-Loss Orders (Algo Orders)

```typescript
const stopOrder = await exchange.createOrder(
  'BTC/USDT:USDT',
  'stop_market',
  'sell',
  0.01,
  undefined,
  {
    stopPrice: 49000,
    reduceOnly: true  // CRITICAL: prevents position increase
  }
);

// The returned order.id is actually an algoId
console.log('Algo ID:', stopOrder.id);
```

### Take-Profit Orders (Algo Orders)

```typescript
const tpOrder = await exchange.createOrder(
  'BTC/USDT:USDT',
  'take_profit_market',
  'sell',
  0.01,
  undefined,
  {
    stopPrice: 55000,
    reduceOnly: true
  }
);
```

### Trailing Stop Orders (Algo Orders)

```typescript
// Trailing stop with callback rate (percentage)
const trailingOrder = await exchange.createOrder(
  'BTC/USDT:USDT',
  'trailing_stop_market',
  'sell',
  0.01,
  undefined,
  {
    activationPrice: 52000,  // Price at which trailing starts
    callbackRate: 1,         // 1% callback rate (range: 0.1-5%)
    reduceOnly: true
  }
);

// The order trails at 1% below the highest price after activation
console.log('Trailing Stop Algo ID:', trailingOrder.id);
```

**Trailing Stop Parameters**:
- `activationPrice`: Price at which trailing begins (optional)
- `callbackRate`: Percentage callback from peak (0.1% - 5%)
- If no `activationPrice`, trailing starts immediately

---

## Algo Order Management

### Fetching Open Algo Orders

```typescript
// Requires symbol in Binance format (no slashes)
const openAlgo = await exchange.fapiPrivateGetOpenAlgoOrders({
  symbol: 'BTCUSDT'
});

// Or for all symbols (higher rate limit cost)
exchange.options.warnOnFetchOpenOrdersWithoutSymbol = false;
const allAlgo = await exchange.fapiPrivateGetOpenAlgoOrders({});
```

### Canceling Algo Orders

```typescript
// Cancel by algoId
await exchange.fapiPrivateDeleteAlgoOrder({
  algoId: '1000000008663713'
});
```

### Algo Order Response Structure

```json
{
  "algoId": "1000000008663713",
  "clientAlgoId": "x-cvBPrNm97b21d9c4a4664050abf445",
  "algoType": "CONDITIONAL",
  "orderType": "STOP_MARKET",
  "symbol": "BTCUSDT",
  "side": "SELL",
  "quantity": "0.002",
  "algoStatus": "NEW",
  "triggerPrice": "71099.00",
  "reduceOnly": true
}
```

---

## Symbol Formats

| Context | Format | Example |
|---------|--------|---------|
| CCXT | `BASE/QUOTE:SETTLE` | `BTC/USDT:USDT` |
| Binance API | `BASEQUOTE` | `BTCUSDT` |

### Converting Between Formats

```typescript
// CCXT to Binance
const market = exchange.market('BTC/USDT:USDT');
const binanceSymbol = market.id;  // 'BTCUSDT'

// Binance to CCXT
const ccxtSymbol = Object.values(exchange.markets)
  .find(m => m.id === 'BTCUSDT')?.symbol;  // 'BTC/USDT:USDT'
```

---

## WebSocket Streaming

### Ticker Streaming

```typescript
const streamService = new BinanceStreamService(exchange);

for await (const tickers of streamService.watchTickers(['BTC/USDT:USDT'])) {
  console.log(tickers[0].last);
  if (shouldStop) {
    streamService.stop();
    break;
  }
}
```

### Position Streaming

```typescript
for await (const positions of exchange.watchPositions()) {
  const openPositions = positions.filter(p => p.contracts !== 0);
  console.log(openPositions);
}
```

---

## Common Errors and Solutions

### Error: `-4120` Order type not supported

**Cause**: Using old order endpoint for conditional orders
**Solution**: Ensure CCXT version >= 4.5.6, orders are auto-routed

### Error: Invalid Api-Key ID

**Cause**: Using testnet keys with demo trading or wrong environment
**Solution**: Get new API keys from `demo.binance.com`

### Error: Order's notional must be no smaller than 100

**Cause**: Order value < $100 minimum
**Solution**: Calculate minimum amount: `Math.ceil((110 / price) * 1000) / 1000`

### Error: testnet/sandbox mode is not supported for futures

**Cause**: Using deprecated `setSandboxMode(true)`
**Solution**: Use `exchange.enableDemoTrading(true)` instead

### Error: Timestamp outside of recvWindow

**Cause**: System clock out of sync
**Solution**: Sync system clock, check time diff < 5000ms

---

## Best Practices

### 1. Always Enable Rate Limiting

```typescript
const exchange = new ccxt.pro.binance({
  enableRateLimit: true  // CRITICAL: prevents IP bans
});
```

### 2. Use reduceOnly for Protective Orders

```typescript
// Always set reduceOnly: true for stop-loss and take-profit
// This prevents accidentally increasing position on wrong direction
{ reduceOnly: true }
```

### 3. Handle Algo Order Cleanup

```typescript
// Regular cancelOrder() doesn't work for algo orders
try {
  await exchange.cancelOrder(orderId, symbol);  // For regular orders
} catch {
  await exchange.fapiPrivateDeleteAlgoOrder({ algoId: orderId });  // For algo orders
}
```

### 4. Check Connection Before Operations

```typescript
const isConnected = exchange.markets && Object.keys(exchange.markets).length > 0;
```

---

## Environment Variables

```bash
# For demo trading
BINANCE_DEMO_API_KEY=your_demo_api_key
BINANCE_DEMO_SECRET=your_demo_secret

# For production (mainnet)
BINANCE_API_KEY=your_mainnet_api_key
BINANCE_SECRET=your_mainnet_secret
```

---

## Orchestrator Agent

This skill has an associated orchestrator agent at `.claude/agents/ccxt-binance-expert.md` that coordinates the sub-agents and workflows for complex tasks. The orchestrator:

- Dispatches connection-tester for setup and troubleshooting
- Dispatches order-tester for validation
- Automatically triggers api-researcher on failures
- Manages the full validation workflow sequence

---

## References

### Local Documentation
- [references/environments.md](references/environments.md) - **Testnet vs Demo vs Production guide**
- [references/algo-order-api.md](references/algo-order-api.md) - Algo Order API documentation
- [references/demo-trading-setup.md](references/demo-trading-setup.md) - Demo trading setup guide
- [references/session-findings.md](references/session-findings.md) - All findings from integration session

### Orchestrator Agent
- [../../agents/ccxt-binance-expert.md](../../agents/ccxt-binance-expert.md) - Orchestrator that coordinates sub-agents

### Sub-Agents
- [sub_agents/connection-tester.md](sub_agents/connection-tester.md) - Connection testing agent
- [sub_agents/order-tester.md](sub_agents/order-tester.md) - Order testing agent
- [sub_agents/api-researcher.md](sub_agents/api-researcher.md) - API research agent

### Workflows
- [workflows/validate-integration.md](workflows/validate-integration.md) - Full validation workflow
- [workflows/troubleshoot.md](workflows/troubleshoot.md) - Troubleshooting workflow

### External
- [Binance Change Log](https://developers.binance.com/docs/derivatives/change-log) - Official API changes
- [CCXT Documentation](https://docs.ccxt.com/) - CCXT library docs
- [Binance Futures API](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api) - REST API docs

