trading-futures trading-futures

在Binance、Bybit、Hyperliquid、MEXC等4个交易所上进行永续合约交易,支持高达200倍杠杆,包含数据库跟踪、自定义策略和A/B测试功能。

算法交易 0 次安装 0 次浏览 更新于 3/5/2026

交易永续合约 在Binance、Bybit、Hyperliquid、MEXC上交易永续合约,最高可达200倍杠杆 emoji: “📈” 环境变量: envs: anyOf: - BINANCE_API_KEY - BYBIT_API_KEY - HYPERLIQUID_PRIVATE_KEY - MEXC_API_KEY

永续合约交易 - 完整的API参考

在4个交易所上交易带杠杆的永续合约,包含数据库跟踪、自定义策略和A/B测试。

200+方法覆盖4个交易所。这是完整的参考。

支持的交易所

交易所 类型 最大杠杆 KYC API方法
Binance Futures CEX 125倍 55+
Bybit CEX 100倍 50+
MEXC CEX 200倍 否(小额) 35+
Hyperliquid DEX 50倍 60+

必需的环境变量

# Binance Futures
BINANCE_API_KEY=your_api_key
BINANCE_API_SECRET=your_api_secret

# Bybit
BYBIT_API_KEY=your_api_key
BYBIT_API_SECRET=your_api_secret

# MEXC(小额无需KYC)
MEXC_API_KEY=your_api_key
MEXC_API_SECRET=your_api_secret

# Hyperliquid(完全去中心化,无需KYC)
HYPERLIQUID_PRIVATE_KEY=your_private_key
HYPERLIQUID_WALLET_ADDRESS=0x...

# 可选:数据库用于交易跟踪
DATABASE_URL=postgres://user:pass@localhost:5432/clodds

聊天命令

账户与余额

/futures balance [交易所]        # 检查保证金余额(全部或特定)
/futures positions                 # 查看所有开放仓位
/futures positions <交易所>      # 查看特定交易所的仓位

开仓

/futures long <符号> <大小> [杠杆]x    # 开多头仓位
/futures short <符号> <大小> [杠杆]x   # 开空头仓位

# 示例:
/futures long BTCUSDT 0.1 10x      # 以10倍杠杆开0.1 BTC多头
/futures short ETHUSDT 1 20x       # 以20倍杠杆开1 ETH空头
/futures long BTCUSDT 0.01         # 使用默认杠杆

止盈止损

/futures tp <符号> <价格>       # 设置止盈
/futures sl <符号> <价格>       # 设置止损
/futures tpsl <符号> <tp> <sl>   # 同时设置

# 示例:
/futures tp BTCUSDT 105000         # 在$105k止盈
/futures sl BTCUSDT 95000          # 在$95k止损
/futures tpsl BTCUSDT 105000 95000 # 同时设置

平仓

/futures close <符号>            # 平特定仓位
/futures close-all                 # 平全部仓位(所有交易所)
/futures close-all <交易所>      # 在特定交易所平所有仓位

市场数据

/futures markets [交易所]        # 列出可用市场
/futures price <符号>            # 获取当前价格
/futures funding <符号>          # 查看资金费率
/futures orderbook <符号>        # 查看订单簿深度

账户信息

/futures stats                     # 从数据库获取交易统计
/futures history [符号]          # 交易历史
/futures pnl [周期]              # 盈亏总结(日/周/月)

杠杆与保证金

/futures leverage <符号> <值> # 设置杠杆
/futures margin <符号> <模式>    # 设置保证金模式(全仓/逐仓)

TypeScript API参考

快速设置

import { setupFromEnv } from 'clodds/trading/futures';

// 从环境变量自动配置
const { clients, database, strategyEngine } = await setupFromEnv();

// 访问个别客户
const binance = clients.binance;
const bybit = clients.bybit;
const mexc = clients.mexc;
const hyperliquid = clients.hyperliquid;

手动客户端设置

import {
  BinanceFuturesClient,
  BybitFuturesClient,
  MexcFuturesClient,
  HyperliquidClient,
  FuturesDatabase,
  StrategyEngine,
} from 'clodds/trading/futures';

// Binance
const binance = new BinanceFuturesClient({
  apiKey: process.env.BINANCE_API_KEY!,
  apiSecret: process.env.BINANCE_API_SECRET!,
  testnet: false,  // true为测试网
});

// Bybit
const bybit = new BybitFuturesClient({
  apiKey: process.env.BYBIT_API_KEY!,
  apiSecret: process.env.BYBIT_API_SECRET!,
  testnet: false,
});

// MEXC(无需KYC)
const mexc = new MexcFuturesClient({
  apiKey: process.env.MEXC_API_KEY!,
  apiSecret: process.env.MEXC_API_SECRET!,
});

// Hyperliquid(去中心化,无需KYC)
const hyperliquid = new HyperliquidClient({
  privateKey: process.env.HYPERLIQUID_PRIVATE_KEY!,
  walletAddress: process.env.HYPERLIQUID_WALLET_ADDRESS!,
  testnet: false,
});

Binance Futures API(55+方法)

市场数据

// 价格与行情
await binance.getMarkPrice('BTCUSDT');
await binance.getTicker24h('BTCUSDT');
await binance.getAllTickers();
await binance.getBookTicker('BTCUSDT');

// 订单簿与交易
await binance.getOrderBook('BTCUSDT', 100);
await binance.getRecentTrades('BTCUSDT', 500);
await binance.getHistoricalTrades('BTCUSDT', 500);
await binance.getAggTrades('BTCUSDT');

// K线(蜡烛图)
await binance.getKlines('BTCUSDT', '1h', 100);
await binance.getContinuousKlines('BTCUSDT', '1h', 'PERPETUAL');
await binance.getIndexPriceKlines('BTCUSDT', '1h');
await binance.getMarkPriceKlines('BTCUSDT', '1h');
await binance.getPremiumIndexKlines('BTCUSDT', '1h');

// 资金费率
await binance.getFundingRate('BTCUSDT');
await binance.getFundingRateHistory('BTCUSDT', 100);

// 市场信息
await binance.getExchangeInfo();
await binance.getOpenInterest('BTCUSDT');
await binance.getOpenInterestHistory('BTCUSDT', '1h');

交易

// 下单
await binance.placeOrder({
  symbol: 'BTCUSDT',
  side: 'BUY',
  type: 'MARKET',
  quantity: 0.01,
});

await binance.placeOrder({
  symbol: 'BTCUSDT',
  side: 'BUY',
  type: 'LIMIT',
  quantity: 0.01,
  price: 95000,
  timeInForce: 'GTC',
});

// 带TP/SL
await binance.placeOrder({
  symbol: 'BTCUSDT',
  side: 'BUY',
  type: 'MARKET',
  quantity: 0.01,
  takeProfit: 105000,
  stopLoss: 95000,
});

// 批量下单
await binance.placeBatchOrders([
  { symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', quantity: 0.01, price: 94000 },
  { symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', quantity: 0.01, price: 93000 },
]);

// 修改与撤销
await binance.modifyOrder('BTCUSDT', orderId, { quantity: 0.02 });
await binance.cancelOrder('BTCUSDT', orderId);
await binance.cancelAllOrders('BTCUSDT');
await binance.cancelBatchOrders('BTCUSDT', [orderId1, orderId2]);

// 自动撤销
await binance.setAutoCancel(60000);  // 60秒后全部撤销
await binance.cancelAutoCancel();

账户与仓位

// 账户信息
await binance.getAccountInfo();
await binance.getBalance();
await binance.getPositions();
await binance.getPositionRisk();

// 订单与历史
await binance.getOpenOrders();
await binance.getOpenOrders('BTCUSDT');
await binance.getAllOrders('BTCUSDT');
await binance.getOrder('BTCUSDT', orderId);
await binance.getTradeHistory('BTCUSDT');
await binance.getIncomeHistory();
await binance.getIncomeHistory('BTCUSDT', 'REALIZED_PNL');

// 佣金
await binance.getCommissionRate('BTCUSDT');

风险管理

// 杠杆
await binance.setLeverage('BTCUSDT', 10);
await binance.getLeverageBrackets();
await binance.getLeverageBrackets('BTCUSDT');

// 保证金模式
await binance.setMarginType('BTCUSDT', 'ISOLATED');
await binance.modifyIsolatedMargin('BTCUSDT', 100, 'ADD');
await binance.modifyIsolatedMargin('BTCUSDT', 50, 'REDUCE');

// 仓位模式
await binance.getPositionMode();
await binance.setPositionMode(true);  // 对冲模式
await binance.setPositionMode(false); // 单向模式

// 多资产模式
await binance.getMultiAssetMode();
await binance.setMultiAssetMode(true);

分析

// 市场分析
await binance.getLongShortRatio('BTCUSDT', '1h');
await binance.getTopTraderLongShortRatio('BTCUSDT', '1h');
await binance.getTopTraderPositions('BTCUSDT', '1h');
await binance.getGlobalLongShortRatio('BTCUSDT', '1h');
await binance.getTakerBuySellVolume('BTCUSDT', '1h');

质押与赚取

// 质押
await binance.getStakingProducts();
await binance.stake('BNB', 10);
await binance.unstake('BNB', 5);
await binance.getStakingHistory();
await binance.getStakingPositions();

转换

// 资产转换
await binance.getConvertPairs('USDT', 'BTC');
await binance.sendQuote('USDT', 'BTC', 100);
await binance.acceptQuote(quoteId);
await binance.getConvertHistory();

组合保证金

await binance.getPortfolioMarginAccount();
await binance.getPortfolioMarginBankruptcyLoan();
await binance.repayPortfolioMarginLoan();

Bybit API(50+方法)

市场数据

await bybit.getTickers('linear');
await bybit.getTickers('linear', 'BTCUSDT');
await bybit.getOrderbook('BTCUSDT', 'linear');
await bybit.getKline('BTCUSDT', '1h', 'linear');
await bybit.getMarkPriceKline('BTCUSDT', '1h', 'linear');
await bybit.getIndexPriceKline('BTCUSDT', '1h', 'linear');
await bybit.getPremiumIndexPriceKline('BTCUSDT', '1h', 'linear');
await bybit.getInstrumentsInfo('linear');
await bybit.getFundingHistory('BTCUSDT', 'linear');
await bybit.getPublicTradingHistory('BTCUSDT', 'linear');
await bybit.getOpenInterest('BTCUSDT', 'linear', '1h');
await bybit.getHistoricalVolatility();
await bybit.getInsurance();
await bybit.getRiskLimit('linear');

交易

// 下单
await bybit.placeOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  side: 'Buy',
  orderType: 'Market',
  qty: '0.01',
});

await bybit.placeOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  side: 'Buy',
  orderType: 'Limit',
  qty: '0.01',
  price: '95000',
  timeInForce: 'GTC',
});

// 批量下单
await bybit.placeBatchOrders('linear', [
  { symbol: 'BTCUSDT', side: 'Buy', orderType: 'Limit', qty: '0.01', price: '94000' },
  { symbol: 'BTCUSDT', side: 'Buy', orderType: 'Limit', qty: '0.01', price: '93000' },
]);

// 修改与撤销
await bybit.amendOrder({ category: 'linear', symbol: 'BTCUSDT', orderId, qty: '0.02' });
await bybit.cancelOrder({ category: 'linear', symbol: 'BTCUSDT', orderId });
await bybit.cancelAllOrders({ category: 'linear', symbol: 'BTCUSDT' });
await bybit.cancelBatchOrders('linear', [{ symbol: 'BTCUSDT', orderId }]);

账户与仓位

await bybit.getWalletBalance('UNIFIED');
await bybit.getPositionInfo('linear');
await bybit.getPositionInfo('linear', 'BTCUSDT');
await bybit.getOpenOrders('linear');
await bybit.getOrderHistory('linear');
await bybit.getExecutionList('linear');
await bybit.getClosedPnl('linear');
await bybit.getBorrowHistory();
await bybit.getCollateralInfo();
await bybit.getCoinGreeks();
await bybit.getFeeRate('linear', 'BTCUSDT');
await bybit.getAccountInfo();
await bybit.getTransactionLog();
await bybit.getMMPState('linear');
await bybit.setMMP({ baseCoin: 'BTC', window: '5000', frozenPeriod: '100', qtyLimit: '10', deltaLimit: '100' });
await bybit.resetMMP('BTC');

风险管理

await bybit.setLeverage({ category: 'linear', symbol: 'BTCUSDT', buyLeverage: '10', sellLeverage: '10' });
await bybit.setMarginMode('ISOLATED_MARGIN');
await bybit.setPositionMode({ category: 'linear', mode: 0 });  // 0=单向,3=对冲
await bybit.setRiskLimit({ category: 'linear', symbol: 'BTCUSDT', riskId: 1 });
await bybit.setTradingStop({ category: 'linear', symbol: 'BTCUSDT', takeProfit: '105000', stopLoss: '95000' });
await bybit.setTpSlMode({ category: 'linear', symbol: 'BTCUSDT', tpSlMode: 'Full' });
await bybit.addOrReduceMargin({ category: 'linear', symbol: 'BTCUSDT', margin: '100' });
await bybit.switchCrossIsolatedMargin({ category: 'linear', symbol: 'BTCUSDT', tradeMode: 1, buyLeverage: '10', sellLeverage: '10' });

跟单交易

await bybit.getCopyTradingLeaders();
await bybit.followLeader(leaderId);
await bybit.unfollowLeader(leaderId);
await bybit.getCopyPositions();
await bybit.closeCopyPosition(symbol);

借贷与赚取

await bybit.getLendingProducts();
await bybit.depositToLending(productId, amount);
await bybit.redeemFromLending(productId, amount);
await bybit.getLendingOrders();
await bybit.getEarnProducts();
await bybit.getEarnOrders();

Hyperliquid API(60+方法)

市场数据

await hyperliquid.getMeta();
await hyperliquid.getMetaAndAssetCtxs();
await hyperliquid.getAssetCtxs();
await hyperliquid.getAllMids();
await hyperliquid.getCandleSnapshot('BTC', '1h', startTime, endTime);
await hyperliquid.getL2Snapshot('BTC');
await hyperliquid.getFundingHistory('BTC', startTime, endTime);
await hyperliquid.getRecentTrades('BTC');
await hyperliquid.getPredictedFunding();

交易

// 下单
await hyperliquid.placeOrder({
  asset: 'BTC',
  isBuy: true,
  sz: 0.01,
  limitPx: 95000,
  orderType: { limit: { tif: 'Gtc' } },
  reduceOnly: false,
});

// 市价单
await hyperliquid.placeOrder({
  asset: 'BTC',
  isBuy: true,
  sz: 0.01,
  limitPx: null,
  orderType: { market: {} },
});

// TWAP订单
await hyperliquid.placeTwapOrder({
  asset: 'BTC',
  isBuy: true,
  sz: 1.0,
  duration: 3600,  // 1小时
  randomize: true,
});

// 修改与撤销
await hyperliquid.modifyOrder(orderId, { sz: 0.02 });
await hyperliquid.cancelOrder('BTC', orderId);
await hyperliquid.cancelAllOrders();
await hyperliquid.cancelOrdersByCloid(['cloid1', 'cloid2']);

// 批量操作
await hyperliquid.batchModifyOrders([{ oid: orderId1, sz: 0.02 }, { oid: orderId2, sz: 0.03 }]);

账户与仓位

await hyperliquid.getUserState(walletAddress);
await hyperliquid.getClearinghouseState(walletAddress);
await hyperliquid.getOpenOrders(walletAddress);
await hyperliquid.getFrontendOpenOrders(walletAddress);
await hyperliquid.getUserFills(walletAddress);
await hyperliquid.getUserFillsByTime(walletAddress, startTime, endTime);
await hyperliquid.getUserFunding(walletAddress);
await hyperliquid.getUserFundingHistory(walletAddress, startTime, endTime);
await hyperliquid.getHistoricalOrders(walletAddress);
await hyperliquid.getOrderStatus(walletAddress, orderId);
await hyperliquid.getTwapHistory(walletAddress);
await hyperliquid.getSubaccounts(walletAddress);

杠杆与保证金

await hyperliquid.updateLeverage('BTC', 10, false);  // false=全仓
await hyperliquid.updateLeverage('BTC', 10, true);   // true=逐仓
await hyperliquid.updateIsolatedMargin('BTC', 100);

转账

await hyperliquid.usdTransfer(toAddress, amount);
await hyperliquid.spotTransfer(toAddress, token, amount);
await hyperliquid.withdraw(amount);
await hyperliquid.classTransfer(amount, toPerp);

现货交易

await hyperliquid.getSpotMeta();
await hyperliquid.getSpotMetaAndAssetCtxs();
await hyperliquid.getSpotClearinghouseState(walletAddress);
await hyperliquid.placeSpotOrder({
  asset: 'HYPE',
  isBuy: true,
  sz: 10,
  limitPx: 25,
});

金库

await hyperliquid.getVaultDetails(vaultAddress);
await hyperliquid.getUserVaultEquities(walletAddress);
await hyperliquid.depositToVault(vaultAddress, amount);
await hyperliquid.withdrawFromVault(vaultAddress, amount);
await hyperliquid.getAllVaults();

质押

await hyperliquid.getValidatorSummaries();
await hyperliquid.getUserStakingSummary(walletAddress);
await hyperliquid.stakeHype(amount, validatorAddress);
await hyperliquid.unstakeHype(amount, validatorAddress);
await hyperliquid.claimStakingRewards();

委托

await hyperliquid.getDelegatorSummary(walletAddress);
await hyperliquid.getDelegatorHistory(walletAddress);
await hyperliquid.delegate(amount, agentAddress);
await hyperliquid.undelegate(amount, agentAddress);

推荐与分析

await hyperliquid.getReferralState(walletAddress);
await hyperliquid.createReferralCode(code);
await hyperliquid.getReferredUsers(walletAddress);
await hyperliquid.getUserAnalytics(walletAddress);
await hyperliquid.getLeaderboard();
await hyperliquid.getMaxBuilderFee();

MEXC API(35+方法)

市场数据

await mexc.getContractDetail('BTC_USDT');
await mexc.getAllContractDetails();
await mexc.getOrderbook('BTC_USDT');
await mexc.getKlines('BTC_USDT', '1h');
await mexc.getTicker('BTC_USDT');
await mexc.getAllTickers();
await mexc.getFundingRate('BTC_USDT');
await mexc.getFundingRateHistory('BTC_USDT');
await mexc.getOpenInterest('BTC_USDT');
await mexc.getRecentTrades('BTC_USDT');
await mexc.getIndexPrice('BTC_USDT');
await mexc.getFairPrice('BTC_USDT');

交易

// 下单
await mexc.placeOrder({
  symbol: 'BTC_USDT',
  side: 1,  // 1=开多,2=平空,3=开空,4=平多
  type: 5,  // 1=限价,2=后置,3=IOC,4=FOK,5=市价
  vol: 1,   // 合约
  leverage: 10,
});

// 带TP/SL
await mexc.placeOrder({
  symbol: 'BTC_USDT',
  side: 1,
  type: 5,
  vol: 1,
  leverage: 10,
  takeProfit: 105000,
  stopLoss: 95000,
});

// 批量下单
await mexc.placeBatchOrders([
  { symbol: 'BTC_USDT', side: 1, type: 1, vol: 1, price: 94000, leverage: 10 },
  { symbol: 'BTC_USDT', side: 1, type: 1, vol: 1, price: 93000, leverage: 10 },
]);

// 触发订单
await mexc.placeTriggerOrder({
  symbol: 'BTC_USDT',
  side: 1,
  type: 1,
  vol: 1,
  triggerPrice: 96000,
  triggerType: 1,  // 1=最新价,2=公平价,3=指数价
  executionPrice: 96100,
  leverage: 10,
});

// 撤销
await mexc.cancelOrder('BTC_USDT', orderId);
await mexc.cancelAllOrders('BTC_USDT');
await mexc.cancelBatchOrders([orderId1, orderId2]);

账户与仓位

await mexc.getAccountInfo();
await mexc.getPositions();
await mexc.getPositions('BTC_USDT');
await mexc.getOpenOrders();
await mexc.getOpenOrders('BTC_USDT');
await mexc.getOrderHistory('BTC_USDT');
await mexc.getTradeHistory('BTC_USDT');
await mexc.getTriggerOrders();
await mexc.getStopOrders();
await mexc.getRiskLimit('BTC_USDT');
await mexc.getAssets();
await mexc.getAssetRecords();

风险管理

await mexc.setLeverage('BTC_USDT', 10);
await mexc.changeMarginMode('BTC_USDT', 1);  // 1=逐仓,2=全仓
await mexc.changePositionMode(1);  // 1=对冲,2=单向
await mexc.autoAddMargin('BTC_USDT', true);

数据库跟踪

初始化数据库

import { FuturesDatabase } from 'clodds/trading/futures';

const db = new FuturesDatabase(process.env.DATABASE_URL!);
await db.initialize();  // 如果不存在则创建表

记录交易

await db.logTrade({
  exchange: 'binance',
  symbol: 'BTCUSDT',
  orderId: '12345',
  side: 'BUY',
  price: 95000,
  quantity: 0.01,
  realizedPnl: 50.25,
  commission: 0.95,
  commissionAsset: 'USDT',
  timestamp: Date.now(),
  isMaker: false,
  strategy: 'momentum',
  variant: 'aggressive',
});

查询交易

// 获取交易
const trades = await db.getTrades({ exchange: 'binance' });
const btcTrades = await db.getTrades({ exchange: 'binance', symbol: 'BTCUSDT' });
const recentTrades = await db.getTrades({ limit: 100 });

// 获取统计
const stats = await db.getTradeStats('binance');
// { totalTrades, winRate, totalPnl, avgPnl, bestTrade, worstTrade }

// 获取变体性能
const results = await db.getVariantPerformance('momentum');
// { aggressive: { trades, pnl, winRate }, conservative: { ... } }

自定义策略

策略接口

import { FuturesStrategy, StrategySignal } from 'clodds/trading/futures';

interface FuturesStrategy {
  name: string;
  analyze(data: MarketData): Promise<StrategySignal | null>;
}

interface StrategySignal {
  action: 'BUY' | 'SELL' | 'CLOSE';
  symbol: string;
  confidence: number;  // 0-1
  reason: string;
  metadata?: Record<string, unknown>;
}

示例策略

class RSIStrategy implements FuturesStrategy {
  name = 'rsi-strategy';

  constructor(private config: { period: number; oversold: number; overbought: number }) {}

  async analyze(data: MarketData): Promise<StrategySignal | null> {
    const rsi = calculateRSI(data.closes, this.config.period);

    if (rsi < this.config.oversold) {
      return {
        action: 'BUY',
        symbol: data.symbol,
        confidence: (this.config.oversold - rsi) / this.config.oversold,
        reason: `RSI超卖于${rsi.toFixed(1)}`,
        metadata: { rsi },
      };
    }

    if (rsi > this.config.overbought) {
      return {
        action: 'SELL',
        symbol: data.symbol,
        confidence: (rsi - this.config.overbought) / (100 - this.config.overbought),
        reason: `RSI超买于${rsi.toFixed(1)}`,
        metadata: { rsi },
      };
    }

    return null;
  }
}

注册与运行

const engine = new StrategyEngine(db);
engine.registerStrategy(new RSIStrategy({ period: 14, oversold: 30, overbought: 70 }));

// A/B测试变体
engine.registerVariant('rsi-strategy', 'aggressive', { oversold: 25, overbought: 75 });
engine.registerVariant('rsi-strategy', 'conservative', { oversold: 35, overbought: 65 });

内置策略

策略 逻辑 配置
MomentumStrategy 跟随价格趋势 lookbackPeriod, threshold
MeanReversionStrategy 逢低买入,逢高卖出 maPeriod, deviationMultiplier
GridStrategy 在区间内下单 gridSize, levels, spacing

错误处理

所有客户端抛出类型化错误:

import { FuturesError, InsufficientBalanceError, InvalidOrderError } from 'clodds/trading/futures';

try {
  await binance.placeOrder({ ... });
} catch (error) {
  if (error instanceof InsufficientBalanceError) {
    console.log('保证金不足');
  } else if (error instanceof InvalidOrderError) {
    console.log('订单参数无效:', error.message);
  } else if (error instanceof FuturesError) {
    console.log('交易所错误:', error.code, error.message);
  }
}

频率限制

交易所 限制 注释
Binance 2400/分钟 每个IP,权重基础
Bybit 120/分钟 每个端点
Hyperliquid 1200/分钟 每个钱包
MEXC 20/秒 每个IP

所有客户端自动处理频率限制,带有指数退避。