| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- #!/usr/bin/env tsx
- /**
- * 实际交易和对冲功能测试
- * ⚠️ 警告:这将执行真实的交易订单!
- * 请确保在测试环境中运行,或使用极小的金额
- */
- import { Config, SmartAccountDiscovery } from '../src/config/simpleEnv.js'
- import { PacificaProxyClient } from '../src/exchanges/pacifica/PacificaProxyClient.js'
- import { SamePlatformHedgingManager } from '../src/core/hedging/SamePlatformHedgingManager.js'
- import { logger } from '../src/utils/logger.js'
- async function realTradingTest() {
- console.log('🚨 实际交易和对冲功能测试')
- console.log('⚠️ 警告:这将执行真实的交易订单!')
- console.log('='.repeat(60))
- // 安全检查
- if (process.argv.includes('--dry-run')) {
- console.log('🔒 DRY RUN 模式 - 不会执行实际交易')
- } else {
- console.log('💰 实际交易模式 - 将执行真实订单')
- console.log('如果您不想执行实际交易,请添加 --dry-run 参数')
- console.log('按 Ctrl+C 取消,或等待5秒继续...')
- if (!process.argv.includes('--force')) {
- await new Promise(resolve => setTimeout(resolve, 5000))
- }
- }
- const isDryRun = process.argv.includes('--dry-run')
- try {
- // 1. 检查配置和账户
- console.log('\n📋 第一步: 检查配置和账户...')
- console.log(`代理状态: ${Config.proxy.isAnyConfigured() ? '✅ 启用' : '❌ 禁用'}`)
- const accounts = SmartAccountDiscovery.discoverPacifica()
- console.log(`发现 ${accounts.length} 个Pacifica账户`)
- if (accounts.length < 2) {
- console.log('❌ 需要至少2个账户进行对冲测试')
- return
- }
- // 2. 创建增强的对冲管理器(带风险控制)
- console.log('\n🛡️ 第二步: 创建带风险控制的对冲管理器...')
- const riskLimits = {
- maxPositionSize: 0.01, // 最大0.01个币的仓位
- maxTotalExposure: 0.02, // 总敞口不超过0.02
- maxAccountBalance: 1000, // 账户余额上限
- minAccountBalance: 10, // 账户余额下限
- maxDailyTrades: 20, // 每日最多20笔交易
- maxSlippage: 0.01, // 最大1%滑点
- emergencyStopLoss: 0.03, // 3%紧急止损
- enabled: true, // 启用风险控制
- }
- const hedgeManager = new SamePlatformHedgingManager('pacifica', riskLimits)
- // 3. 添加账户到对冲管理器
- console.log('\n🏦 第三步: 添加账户到对冲管理器...')
- const account1 = accounts[0]
- const account2 = accounts[1]
- hedgeManager.addAccount('pacifica-main', {
- account: account1.account,
- privateKey: account1.privateKey,
- })
- hedgeManager.addAccount('pacifica-hedge', {
- account: account2.account,
- privateKey: account2.privateKey,
- })
- console.log(`✅ 添加主账户: ${account1.account.substring(0, 8)}...`)
- console.log(`✅ 添加对冲账户: ${account2.account.substring(0, 8)}...`)
- // 4. 创建对冲对
- console.log('\n🔗 第四步: 创建BTC-USD对冲对...')
- hedgeManager.createHedgePair('btc-usd-hedge', 'pacifica-main', 'pacifica-hedge', 'BTC-USD', 1.0)
- console.log('✅ BTC-USD对冲对创建成功')
- // 5. 测试单笔小额交易
- console.log('\n💸 第五步: 测试小额交易...')
- const testAmount = 0.001 // 0.001 BTC
- const testSymbol = 'BTC-USD'
- console.log(`测试交易参数:`)
- console.log(` 交易对: ${testSymbol}`)
- console.log(` 数量: ${testAmount}`)
- console.log(` 账户: ${account1.account.substring(0, 8)}...`)
- console.log(` 实际执行: ${isDryRun ? '否 (DRY RUN)' : '是'}`)
- if (!isDryRun) {
- try {
- // 创建交易客户端
- const client1 = new PacificaProxyClient({
- account: account1.account,
- privateKey: account1.privateKey,
- })
- // 跳过余额和持仓检查,直接测试下单
- console.log('跳过余额和持仓检查,直接测试下单...')
- // 执行小额买单测试
- console.log('执行小额买单测试...')
- const buyOrderResult = await client1.createMarketOrder({
- account: account1.account,
- symbol: testSymbol,
- amount: testAmount.toString(),
- side: 'bid',
- reduceOnly: false,
- slippagePercent: '0.5',
- })
- console.log('✅ 买单执行成功:')
- console.log(JSON.stringify(buyOrderResult, null, 2))
- // 等待一秒后执行对冲卖单
- console.log('等待1秒后执行对冲...')
- await new Promise(resolve => setTimeout(resolve, 1000))
- const client2 = new PacificaProxyClient({
- account: account2.account,
- privateKey: account2.privateKey,
- })
- const sellOrderResult = await client2.createMarketOrder({
- account: account2.account,
- symbol: testSymbol,
- amount: testAmount.toString(),
- side: 'ask',
- reduceOnly: false,
- slippagePercent: '0.5',
- })
- console.log('✅ 对冲卖单执行成功:')
- console.log(JSON.stringify(sellOrderResult, null, 2))
- } catch (error: any) {
- console.log('❌ 交易执行失败:', error.message)
- logger.error('实际交易测试失败', { error: error.message })
- }
- } else {
- console.log('🔒 DRY RUN 模式 - 跳过实际交易')
- }
- // 6. 测试批量对冲功能
- console.log('\n🔄 第六步: 测试批量对冲功能...')
- const batchOrders = [
- {
- accountId: 'pacifica-main',
- symbol: 'BTC-USD',
- amount: 0.001,
- side: 'bid' as const,
- orderType: 'market' as const,
- },
- {
- accountId: 'pacifica-hedge',
- symbol: 'BTC-USD',
- amount: 0.001,
- side: 'ask' as const,
- orderType: 'market' as const,
- },
- ]
- console.log(`批量订单数量: ${batchOrders.length}`)
- console.log(`实际执行: ${isDryRun ? '否 (DRY RUN)' : '是'}`)
- if (!isDryRun) {
- const batchResults = await hedgeManager.executeBatchHedge(batchOrders)
- console.log('✅ 批量对冲执行完成:')
- batchResults.forEach((result, index) => {
- console.log(` 订单${index + 1}: ${result.success ? '成功' : '失败'}`)
- if (result.success) {
- console.log(` 订单ID: ${result.orderId}`)
- } else {
- console.log(` 错误: ${result.error}`)
- }
- })
- } else {
- console.log('🔒 DRY RUN 模式 - 跳过批量对冲执行')
- }
- // 7. 检查对冲状态
- console.log('\n📊 第七步: 检查对冲状态...')
- const hedgeStatuses = hedgeManager.getHedgePairStatuses()
- hedgeStatuses.forEach(status => {
- console.log(`对冲对: ${status.pairId}`)
- console.log(` 交易对: ${status.symbol}`)
- console.log(` 多头账户: ${status.longAccount}`)
- console.log(` 空头账户: ${status.shortAccount}`)
- console.log(` 净敞口: ${status.netExposure}`)
- console.log(` 状态: ${status.isActive ? '激活' : '停用'}`)
- })
- console.log('\n🎉 实际交易和对冲功能测试完成!')
- console.log('\n📋 测试总结:')
- console.log(` ✅ 发现账户: ${accounts.length} 个`)
- console.log(` ✅ 风险控制: 已启用`)
- console.log(` ✅ 代理配置: ${Config.proxy.isAnyConfigured() ? '已启用' : '未启用'}`)
- console.log(` ✅ 交易执行: ${isDryRun ? 'DRY RUN 模式' : '实际执行'}`)
- console.log(` ✅ 对冲功能: 已测试`)
- if (isDryRun) {
- console.log('\n💡 要执行实际交易,请运行:')
- console.log('tsx examples/real_trading_test.ts --force')
- } else {
- console.log('\n⚠️ 提醒: 已执行实际交易,请检查账户状态!')
- }
- } catch (error: any) {
- console.error('❌ 实际交易测试失败:', error)
- logger.error('实际交易测试失败', { error: error.message, stack: error.stack })
- }
- }
- /**
- * 显示使用帮助
- */
- function showTradingHelp() {
- console.log('\n💡 实际交易测试使用说明:')
- console.log(`
- # 使用方式:
- ## 安全测试 (推荐)
- tsx examples/real_trading_test.ts --dry-run
- ## 实际交易 (谨慎使用)
- tsx examples/real_trading_test.ts --force
- # 参数说明:
- --dry-run : 模拟模式,不执行实际交易
- --force : 强制执行实际交易
- --help : 显示此帮助信息
- # 风险提醒:
- ⚠️ 实际交易模式将执行真实订单并消耗资金
- ⚠️ 建议先在测试环境或极小金额下测试
- ⚠️ 确保账户有足够余额并了解交易风险
- ⚠️ 系统已内置风险控制,但仍需谨慎操作
- # 功能特性:
- ✅ 完整的风险控制系统
- ✅ 紧急止损机制
- ✅ 多账户代理隔离
- ✅ 批量对冲执行
- ✅ 实时仓位监控
- ✅ 详细交易日志
- `)
- }
- // 运行测试
- if (import.meta.url === `file://${process.argv[1]}`) {
- if (process.argv.includes('--help') || process.argv.includes('-h')) {
- showTradingHelp()
- } else {
- realTradingTest()
- }
- }
|