此文件为 Claude Code (claude.ai/code) 在此代码库中工作时提供指导。
系统已从WebSocket订阅模式完全回退到HTTP+代理模式
useWebSocket = false
(默认禁用WebSocket)主程序测试确认:8/8服务正常运行,HTTP+代理模式稳定,交易功能正常。
src/modules/trading/BidirectionalProfitMakingStrategy.ts
)src/modules/trading/SuccessRateMonitor.ts
)src/examples/bidirectional_profit_trading_demo.ts
)# 配置双账户环境变量
PACIFICA_ACCOUNT_1=your_account_1
PACIFICA_PRIVATE_KEY_1=your_key_1
PACIFICA_ACCOUNT_2=your_account_2
PACIFICA_PRIVATE_KEY_2=your_key_2
# 启动双向盈利策略演示
npx tsx src/examples/bidirectional_profit_trading_demo.ts
不要重新启用WebSocket功能,因为WebSocket通过代理连接存在稳定性问题。当前HTTP+代理架构已经过验证且稳定运行。
SYSTEM_STATUS_UPDATE.md
BIDIRECTIONAL_STRATEGY_STATUS.md
BIDIRECTIONAL_PROFIT_MAKING_GUIDE.md
TRADING_STRATEGY_IMPROVEMENT.md
yarn build
- 编译 TypeScript 并生成类型别名yarn build:watch
- 监视模式编译yarn test
- 使用 Jest 运行所有测试yarn test:watch
- 交互式测试监视模式yarn test:coverage
- 生成测试覆盖率报告yarn test:ci
- 适合 CI 的测试运行(含覆盖率)yarn lint
- 使用 ESLint 检查 TypeScript 文件yarn prettier
- 使用 Prettier 格式化代码yarn test:unit
- 运行单元测试(连接器模式)yarn test:integration
- 运行集成测试yarn test:performance
- 运行性能基准测试yarn test:build
- 构建并运行 tester.jsyarn test:pacifica
- 测试 Pacifica DEX 集成yarn test:pacifica:ws
- 测试 Pacifica WebSocket 连接yarn test:aster:ws
- 测试 Aster DEX WebSocketyarn test:aster:order
- 测试 Aster DEX 订单执行yarn test:accounts:smoke
- 测试账户管理器功能yarn test:integration:full
- 运行完整的端到端集成测试yarn test:integration:verbose
- 运行详细输出的集成测试yarn test:real-trading
- 安全模式下单测试 (DRY RUN)yarn test:real-trading-help
- 查看实际交易测试帮助yarn trade:pacifica
- 执行实际Pacifica交易 (谨慎使用)yarn demo:same-platform-hedge
- 同一平台对冲演示yarn demo:proxy
- 代理配置测试演示npx tsx src/examples/bidirectional_profit_trading_demo.ts
- 双向盈利挂单策略演示yarn trading:bidirectional:stats
- 查看双向策略统计yarn trading:success-rate
- 成功率监控报告yarn trading:performance-report
- 策略性能分析系统使用统一的 ExchangeAdapter
接口来集成多个加密货币交易所:
src/exchanges/pacifica/
) - 基于 Solana 的永续 DEXsrc/exchanges/aster/
) - 基于以太坊的衍生品平台src/exchanges/binance/
) - 中心化交易所集成所有适配器都实现了通用方法:balances()
、positions()
、placeOrder()
、depth()
、ws()
用于统一的交易操作。
通过 AccountManager
(src/accounts/accountManager.ts
) 实现多交易所账户管理:
(exchange, accountId)
键进行跨交易所统一账户注册核心交易系统组件:
src/core/market/
) - 聚合多个来源的价格数据(Chainlink、CCXT、Uniswap V3)src/core/hedging/SamePlatformHedgingManager.ts
) - 在同一交易所内执行多账户对冲src/core/hedging/UnifiedHedgingExecutor.ts
) - 跨现货和永续市场对冲交易src/core/hedging/router.ts
) - 将交易路由到最优执行场所src/risk/riskAssessor.ts
) - 实时风险监控和仓位限制完整的下单和风险控制系统:
src/exchanges/pacifica/PacificaProxyClient.ts
) - 支持市价单、限价单、止损单src/exchanges/pacifica/OrdersAdapter.ts
) - 处理订单签名、批量执行和取消maxPositionSize
)maxTotalExposure
)minAccountBalance
)emergencyStopLoss
)maxSlippage
)src/modules/trading/BidirectionalProfitMakingStrategy.ts
) - 智能挂单算法:
环境驱动的配置系统:
src/config/asterConfig.ts
- Aster DEX WebSocket 和认证配置env.example
- 显示必需环境变量的模板# Aster DEX
ASTER_WS_URL=wss://fstream.asterdex.com
ASTER_ORDER_USER=0x...
ASTER_ORDER_SIGNER=0x...
PRIVATE_KEY=0x...
# Pacifica DEX
PACIFICA_BASE_URL=https://api.pacifica.fi
PACIFICA_WS_URL=wss://ws.pacifica.fi
PACIFICA_PRIVATE_KEY=...
# 币安(如果使用 CEX 功能)
BINANCE_API_KEY=...
BINANCE_SECRET_KEY=...
# 全局代理
PROXY_ENABLED=true
PROXY_PROTOCOL=http
PROXY_HOST=your-proxy-server.com
PROXY_PORT=8080
PROXY_USERNAME=your_username
PROXY_PASSWORD=your_password
# 交易所专用代理(优先级更高)
ASTER_PROXY_PROTOCOL=http
ASTER_PROXY_HOST=geo.iproyal.com
ASTER_PROXY_PORT=12321
ASTER_PROXY_USER=tuxla
# 会话管理
ASTER_PROXY_SESSION_PREFIX=test123456_country-jp,sg_session-
ASTER_PROXY_SESSION_SUFFIX=_lifetime-59m
# 同一平台多账户配置
PACIFICA_ACCOUNT_1=account_1_id
PACIFICA_PRIVATE_KEY_1=private_key_1
PACIFICA_ACCOUNT_2=account_2_id # 用于对冲
PACIFICA_PRIVATE_KEY_2=private_key_2
LOG_LEVEL=info
ASTER_SUBSCRIBE_SYMBOLS=BTCUSDT,ETHUSDT
PACIFICA_ENABLE_TEST_ORDER=0 # 测试交易的安全标志
__tests__/connector/
- 交易所适配器单元测试__tests__/integration/
- 端到端交易所集成__tests__/performance/
- 延迟和吞吐量基准测试ts-jest/presets/default-esm
支持 ESM 模块main.ts
和 tester.ts
入口点__tests__/setup.ts
完整的端到端测试涵盖以下功能模块:
多平台多账户管理
HTTP+代理数据更新 ⚠️已更新
跨账户对冲下单
# 运行完整集成测试
yarn test:integration:full
# 运行详细输出模式
yarn test:integration:verbose
# 查看测试覆盖率
yarn test:coverage
集成测试需要以下环境变量:
# Pacifica DEX (可选)
PACIFICA_ACCOUNT=your_account_id
PACIFICA_ACCOUNT_PRIVATE_KEY=your_private_key
# Aster DEX (可选)
ASTER_ORDER_USER=your_user_address
ASTER_API_KEY=your_api_key
ASTER_API_SECRET=your_api_secret
如果未配置环境变量,测试将以模拟模式运行。
创建 accounts.config.json
文件:
{
"accounts": [
{
"name": "pacifica-main",
"exchange": "pacifica",
"accountId": "main-account-1",
"alias": "Pacifica主账户",
"enabled": true,
"priority": 1,
"tradingEnabled": true,
"hedgingEnabled": true,
"maxPositionUsd": 10000,
"maxDailyVolumeUsd": 100000,
"auth": {
"privateKeyEnv": "PACIFICA_PRIVATE_KEY_1",
"accountIdEnv": "PACIFICA_ACCOUNT_1"
}
}
],
"hedgingGroups": [
{
"name": "cross-dex-hedge",
"strategy": "delta-neutral",
"accounts": ["pacifica-main", "aster-main"],
"maxExposureUsd": 50000,
"enabled": true
}
]
}
# 基本账户注入
yarn start:dev --exchange pacifica --account main-1 --priority 1
# 完整参数注入
yarn start:dev \
--exchange pacifica \
--account main-account \
--alias "我的Pacifica账户" \
--priority 1 \
--trading true \
--hedging true \
--max-position 5000 \
--config ./custom-accounts.json
# 演示模式
yarn demo:config-accounts --help # 查看帮助信息
yarn demo:config-accounts # 配置文件演示
yarn demo:fluent-accounts # 流畅式 API 演示
yarn demo:cli-accounts # 命令行注入帮助
yarn demo:elegant-accounts # 优雅账户注入演示
更优雅的链式 API 设计:
import { FluentAccountManager } from '../examples/fluent_account_injection'
// 1. 创建管理器并添加账户
const manager = new FluentAccountManager()
.add(builder =>
builder
.for('pacifica')
.account('trading-main')
.alias('Pacifica 主交易账户')
.priority(1)
.withTrading()
.withHedging()
.maxPosition(25000)
.tagged('main', 'production'),
)
.add(builder =>
builder
.for('aster')
.account('hedge-account')
.alias('Aster 对冲账户')
.withRisk({ maxDrawdown: 8 })
.tagged('hedge', 'production'),
)
// 2. 自动发现环境变量账户
manager.discoverFromEnv()
// 3. 创建对冲组
manager.createHedgeGroup('main-hedge', 'delta-neutral', 'Pacifica 主交易账户', 'Aster 对冲账户')
// 4. 智能查询
const enabledAccounts = manager.getEnabled()
const pacificaAccounts = manager.getByExchange('pacifica')
const productionAccounts = manager.getByTag('production')
"type": "module"
)tsc-alias
进行路径解析的 TypeScript 编译noImplicitAny: false
)EventEmitter
用于实时更新ticker
、trade
、depth
、kline
src/utils/logger.ts
)具有可配置级别注意: WebSocket功能已在Pacifica集成中完全禁用,因为代理连接不稳定。当前使用HTTP+代理轮询模式确保连接稳定性。
docs/PACIFICA_API_REFERENCE.md
主要端点:
/api/v1/info
, /api/v1/prices
, /api/v1/book
✅ HTTP轮询/api/v1/account/info
, /api/v1/account/positions
✅ HTTP轮询/api/v1/order/market
, /api/v1/order/limit
✅ HTTP+代理wss://ws.pacifica.fi/ws
当前工作模式:
PriceManager.ts
AccountManager.ts
项目包含详细的 API 集成文档:
docs/api/PACIFICA_API_REFERENCE.md
- Pacifica DEX 完整 API 参考
EXAMPLES_GUIDE.md
- 示例代码使用指南
文档会定期与官方 API 文档同步更新:
# 查看 Pacifica API 文档
cat docs/PACIFICA_API_REFERENCE.md
# 测试 Pacifica 集成
yarn test:pacifica
# 运行完整集成测试
yarn test:integration:full
配置多个账户:
# 在 .env 中配置多个Pacifica账户
PACIFICA_ACCOUNT_1=your_main_account
PACIFICA_PRIVATE_KEY_1=your_main_private_key
PACIFICA_ACCOUNT_2=your_hedge_account
PACIFICA_PRIVATE_KEY_2=your_hedge_private_key
# 配置代理(所有HTTP请求都通过代理)
PROXY_ENABLED=true
PROXY_HOST=your-proxy-server.com
PROXY_PORT=8080
测试对冲系统(安全模式):
yarn test:real-trading # DRY RUN 模式,不执行实际交易
执行实际对冲交易(谨慎使用):
yarn trade:pacifica # 执行真实交易,请谨慎使用!
系统内置多重风险保护:
import { SamePlatformHedgingManager } from './src/core/hedging/SamePlatformHedgingManager'
// 创建对冲管理器(带风险控制)
const manager = new SamePlatformHedgingManager('pacifica', {
maxPositionSize: 0.01, // 最大仓位 0.01 BTC
maxTotalExposure: 0.02, // 总敞口限制 0.02 BTC
emergencyStopLoss: 0.03, // 3%紧急止损
minAccountBalance: 10, // 最低账户余额要求
})
// 添加账户(自动创建代理客户端)
manager.addAccount('main', {
account: 'pacifica_account_1',
privateKey: 'private_key_1',
})
manager.addAccount('hedge', {
account: 'pacifica_account_2',
privateKey: 'private_key_2',
})
// 创建对冲对
manager.createHedgePair('btc-hedge', 'main', 'hedge', 'BTC-USD', 1.0)
// 执行自动对冲再平衡
await manager.rebalanceHedgePair('btc-hedge', 0.01)
// 批量执行对冲交易
const orders = [
{ accountId: 'main', symbol: 'BTC-USD', amount: 0.001, side: 'bid' },
{ accountId: 'hedge', symbol: 'BTC-USD', amount: 0.001, side: 'ask' },
]
await manager.executeBatchHedge(orders)
问题:代理连接失败
# 检查代理配置
yarn demo:proxy
# 查看代理状态和测试连接
问题:风险控制拒绝交易
# 检查风险参数设置,适当调整限制
const riskLimits = {
maxPositionSize: 0.1, // 增加最大仓位
maxTotalExposure: 0.5, // 增加总敞口限制
minAccountBalance: 5 // 降低余额要求
}
问题:订单执行失败
.env.full-example
docs/PACIFICA_API_REFERENCE.md
examples/
目录package.json
中的测试命令TradingEngine (src/modules/trading/TradingEngine.ts)
// Line 989: 移除ETH交易对
const symbols = ['BTC-USD', 'BTCUSDT'] // 专注BTC
// Line 927-947: 优化价格获取
if (cached && Date.now() - cached.timestamp < 120 * 1000) {
// 2分钟缓存
const midPrice = (cached.bid + cached.ask) / 2
return midPrice
}
// BTC价格估算fallback
if (symbol.includes('BTC')) {
console.log(`🔄 [估算价格] ${symbol}: $65000 (缓存过期)`)
return 65000
}
// Line 394-400: 订单金额验证
console.log(`🔍 [订单调试] signal.amount="${signal.amount}", parseFloat=${parseFloat(signal.amount)}`)
const amount = parseFloat(signal.amount)
if (!amount || amount <= 0 || !isFinite(amount)) {
console.log(`❌ [订单跳过] 无效金额: ${signal.amount} → ${amount}`)
return
}
HTTP客户端 (src/utils/httpClient.ts)
// Line 136-149: 精简代理日志
if (proxyUrl) {
const proxyAgent = new HttpsProxyAgent(proxyUrl)
;(fetchOptions as any).agent = proxyAgent
// 移除冗余的console.log调试信息
}
# 运行优化后的系统测试
yarn test:modular
# 预期结果:
# ✅ 简洁的日志输出(无ETH噪音)
# ✅ 正确的BTC价格获取($65,000+)
# ✅ 有效的订单金额计算(>= 0.000092 BTC)
# ✅ 稳定的70-80%使用率控制
问题描述:WebSocket账户连接频繁断开重连(每60秒),缺乏心跳机制和智能重连策略。
解决方案:
src/modules/hedging/AdvancedHedgingManager.ts
)// 新增WebSocket心跳管理
private pingIntervals: Map<string, NodeJS.Timeout> = new Map()
// 启动30秒心跳
private startPing(account: string, ws: WebSocket): void {
const pingInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }))
}
}, 30000)
this.pingIntervals.set(account, pingInterval)
}
// 智能重连:1s → 2s → 4s → 8s → ... 最大30s
const backoffDelay = Math.min(1000 * Math.pow(2, attempts), 30000)
const jitter = Math.random() * 1000 // 防止雷群重连
// 重连频率限制:最少间隔1秒
if (now - lastAttempt < 1000) {
logger.debug(`账户${account}重连过于频繁,跳过此次连接`)
return
}
// 新增状态跟踪字段
private reconnectAttempts: Map<string, number> = new Map()
private connectingAccounts: Set<string> = new Set()
private lastConnectAttempt: Map<string, number> = new Map()
// 防止重复连接
if (this.connectingAccounts.has(account) ||
(this.wsConnections.has(account) && ws?.readyState === WebSocket.OPEN)) {
return
}
public async stop(): Promise<void> {
// 停止所有心跳
for (const account of this.accounts) {
this.stopPing(account)
}
// 关闭所有WebSocket连接
for (const [account, ws] of this.wsConnections) {
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
ws.close(1000, 'Service stopped')
}
}
// 清理所有状态
this.wsConnections.clear()
this.connectingAccounts.clear()
this.reconnectAttempts.clear()
}
问题描述:仓位信息缺少entryPrice日志,没有基于entryPrice的敞口平衡逻辑。
解决方案:
src/modules/types.ts
)export interface AccountState {
// 原有字段...
// 新增仓位详细信息
entryPrice?: number // 入场价格
unrealizedPnl?: number // 未实现盈亏
currentPrice?: number // 当前价格
positionValue?: number // 仓位价值
leverage?: number // 杠杆倍数
}
src/modules/account/AccountManager.ts
)// Line 205-283: 新增updateAccountPosition详细信息收集
result.data.forEach((position: any) => {
const entryPrice = parseFloat(position.entry_price || position.entryPrice || '0')
const unrealizedPnl = parseFloat(position.funding || position.unrealizedPnL || '0')
// 累加P&L和仓位价值
totalUnrealizedPnl += unrealizedPnl
if (entryPrice > 0 && amount > 0) {
totalPositionValue += Math.abs(amount) * entryPrice
averageEntryPrice = (averageEntryPrice * positionCount + entryPrice) / (positionCount + 1)
}
})
// 更新账户状态包含详细信息
this.updateAccountState(accountId, {
netPosition: totalNetPosition,
entryPrice: averageEntryPrice > 0 ? averageEntryPrice : undefined,
unrealizedPnl: totalUnrealizedPnl,
currentPrice: currentPrice,
positionValue: totalPositionValue,
leverage: positionCount > 0 ? Math.round(totalPositionValue / (totalPositionValue / positionCount)) : undefined,
})
src/modules/dashboard/DashboardService.ts
)// Line 217-227: 新增entryPrice和P&L显示
const entryPriceStr = account.entryPrice ? `@$${account.entryPrice.toFixed(2)}` : ''
const pnlStr = account.unrealizedPnl
? `PnL: ${account.unrealizedPnl >= 0 ? '+' : ''}$${account.unrealizedPnl.toFixed(2)}`
: ''
const leverageStr = account.leverage ? `${account.leverage}x` : ''
console.log(
`📊 仓位: ${positionStr} BTC ${entryPriceStr} ${leverageStr} | ${pnlStr} | 使用率: ${utilizationRate.toFixed(1)}%`,
)
src/modules/trading/TradingEngine.ts
)// 新增executeAdvancedExposureBalancing方法
private async executeAdvancedExposureBalancing(): Promise<void> {
// 计算基于entryPrice的真实敞口风险
accounts.forEach(([accountId, state]) => {
if (state.netPosition !== 0 && state.entryPrice && currentPrice) {
const priceMovement = Math.abs(currentPrice - state.entryPrice)
const exposureRisk = Math.abs(state.netPosition) * priceMovement
// 风险分级:CRITICAL >$1000, HIGH >$500, MEDIUM >$200, LOW
const riskLevel = exposureRisk > 1000 ? 'CRITICAL' :
exposureRisk > 500 ? 'HIGH' :
exposureRisk > 200 ? 'MEDIUM' : 'LOW'
logger.info(`🎯 账户${accountId}敞口风险: ${riskLevel} ($${exposureRisk.toFixed(2)})`, {
position: state.netPosition.toFixed(4),
entryPrice: state.entryPrice.toFixed(2),
currentPrice: currentPrice.toFixed(2),
unrealizedPnl: state.unrealizedPnl?.toFixed(2)
})
}
})
}
# 验证WebSocket连接稳定性
yarn test:modular | grep -E "WebSocket.*连接|已连接|重连"
# 验证entryPrice信息显示
yarn test:modular | grep -E "entryPrice|PnL|仓位.*BTC.*@|敞口.*风险"
# 完整系统测试
yarn test:modular