AgentSkillsCN

ccxt-binance-expert

针对CCXT Binance期货API集成提供专家级指导,涵盖模拟交易、算法订单、WebSocket实时行情,以及2025年12月的API变更。适用于与Binance期货对接、处理止损/止盈订单,或排查身份验证相关问题的场景。

SKILL.md
--- frontmatter
name: ccxt-binance-expert
description: 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.

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-AgentPurposeInvoked When
connection-testerTests API connectivity and diagnoses issuesSetup, troubleshooting
order-testerTests all order types (regular + algo)Validation, verification
api-researcherResearches solutions for unknown errorsTest 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

CommandDescription
/ccxt-binance-expertShow usage help
/ccxt-binance-expert validateRun full integration validation
/ccxt-binance-expert troubleshoot "<error>"Diagnose and fix a specific error
/ccxt-binance-expert setupGuide through demo trading setup

Scripts

Available in scripts/:

ScriptPurpose
verify-connection.cjsTest API connectivity
cleanup-algo-orders.cjsCancel all algo orders
close-position.cjsClose open positions
test-order-types.cjsTest 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

PlatformURLStatusAPI Keys From
Demo Tradingdemo.binance.comActivedemo.binance.com
Futures Testnettestnet.binancefuture.comDeprecatedN/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

ContextFormatExample
CCXTBASE/QUOTE:SETTLEBTC/USDT:USDT
Binance APIBASEQUOTEBTCUSDT

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

Orchestrator Agent

Sub-Agents

Workflows

External