Browse Source

🧹 清理src目录中的过期组件

## 清理成果
📊 从120个文件减少到87个文件 (-33个文件)
🗂️ 删除重复目录和文件
🔧 修复main.ts的引用问题

## 删除的组件类别

### 1. 重复文件清理 ✅
- 删除 src/shared/utils/ 下所有重复工具类
- 删除 src/shared/types/、src/shared/config/ 重复目录
- 保留 src/ 下的原版本,确保一致性

### 2. 孤立文件清理 ✅
- core/: hedgingExecutor, orchestrator, credential-manager, positionStrategy
- exchanges/: unifiedEvents, orderBookManager, types.d.ts, RestAdapter
- utils/: math, StateManager, web3, proxyFetch
- accounts/: AutoDiscoveryProvider, CLIAccountInjector, AccountConfigLoader

### 3. 入口文件修复 ✅
- 修复 main.ts 引用不存在的文件问题
- 统一使用 main-modular.ts 作为唯一入口
- 移除对缺失文件的依赖

### 4. 目录结构优化 ✅
- 删除空目录
- 简化目录层次
- 保持功能模块清晰分离

## 当前目录结构

⚠️ 注意: 部分TypeScript编译错误需要在Feature开发阶段修复
🎯 结果: 更清洁、更易维护的代码结构
helium3@sina.com 1 week ago
parent
commit
5861c24832

+ 0 - 338
src/accounts/AccountConfigLoader.ts

@@ -1,338 +0,0 @@
-/**
- * 账户配置文件加载器
- * 支持从JSON/YAML文件动态加载账户配置
- */
-
-import { readFileSync, existsSync, watchFile } from 'fs'
-import { resolve } from 'path'
-import { EventEmitter } from 'events'
-
-export interface AccountAuthConfig {
-  // 环境变量引用方式
-  privateKeyEnv?: string
-  accountIdEnv?: string
-  apiKeyEnv?: string
-  apiSecretEnv?: string
-  userEnv?: string
-  signerEnv?: string
-
-  // 直接配置方式 (不推荐,仅用于开发)
-  privateKey?: string
-  accountId?: string
-  apiKey?: string
-  apiSecret?: string
-  user?: string
-  signer?: string
-}
-
-export interface FileAccountConfig {
-  name: string
-  exchange: string
-  accountId: string
-  alias?: string
-  enabled: boolean
-  priority: number
-  tradingEnabled: boolean
-  hedgingEnabled: boolean
-  maxPositionUsd: number
-  maxDailyVolumeUsd: number
-  auth: AccountAuthConfig
-  tags?: string[]
-  notes?: string
-}
-
-export interface AccountConfigFile {
-  accounts: FileAccountConfig[]
-  hedgingGroups?: Array<{
-    name: string
-    accounts: string[]
-    strategy: 'delta_neutral' | 'arbitrage' | 'funding_rate'
-    maxExposureUsd: number
-    enabled: boolean
-  }>
-  tradingRules?: Array<{
-    name: string
-    accounts: string[]
-    symbols: string[]
-    maxOrderSizeUsd: number
-    minOrderSizeUsd: number
-    maxSlippage: number
-    cooldownMs: number
-    enabled: boolean
-  }>
-  metadata?: {
-    version: string
-    lastUpdated: string
-    description: string
-  }
-}
-
-export class AccountConfigLoader extends EventEmitter {
-  private configFile: string
-  private lastConfig: AccountConfigFile | null = null
-  private isWatching = false
-
-  constructor(configFile = 'accounts.config.json') {
-    super()
-    this.configFile = resolve(process.cwd(), configFile)
-  }
-
-  /**
-   * 加载配置文件
-   */
-  load(): AccountConfigFile {
-    try {
-      if (!existsSync(this.configFile)) {
-        throw new Error(`配置文件不存在: ${this.configFile}`)
-      }
-
-      const content = readFileSync(this.configFile, 'utf-8')
-      let config: AccountConfigFile
-
-      if (this.configFile.endsWith('.json')) {
-        config = JSON.parse(content)
-      } else if (this.configFile.endsWith('.yaml') || this.configFile.endsWith('.yml')) {
-        // 如果需要YAML支持,需要安装yaml包
-        throw new Error('YAML支持需要安装yaml包')
-      } else {
-        throw new Error(`不支持的配置文件格式: ${this.configFile}`)
-      }
-
-      // 验证配置格式
-      this.validateConfig(config)
-
-      // 解析认证信息
-      this.resolveAuthConfig(config)
-
-      this.lastConfig = config
-      this.emit('config_loaded', config)
-
-      console.info(`✅ 账户配置加载成功: ${config.accounts.length} 个账户`)
-      return config
-    } catch (error) {
-      console.error('❌ 账户配置加载失败:', error)
-      throw error
-    }
-  }
-
-  /**
-   * 启用配置文件监听
-   */
-  startWatching(): void {
-    if (this.isWatching) return
-
-    watchFile(this.configFile, (curr, prev) => {
-      if (curr.mtime > prev.mtime) {
-        console.info('📁 检测到配置文件变更,重新加载...')
-        try {
-          const newConfig = this.load()
-          this.emit('config_changed', newConfig, this.lastConfig)
-        } catch (error) {
-          console.error('❌ 配置文件重新加载失败:', error)
-          this.emit('config_error', error)
-        }
-      }
-    })
-
-    this.isWatching = true
-    console.info(`👁️ 开始监听配置文件: ${this.configFile}`)
-  }
-
-  /**
-   * 停止配置文件监听
-   */
-  stopWatching(): void {
-    if (!this.isWatching) return
-    // unwatchFile(this.configFile) // Node.js API
-    this.isWatching = false
-    console.info('⏹️ 停止监听配置文件')
-  }
-
-  /**
-   * 获取启用的账户配置
-   */
-  getEnabledAccounts(): FileAccountConfig[] {
-    if (!this.lastConfig) {
-      throw new Error('配置尚未加载')
-    }
-    return this.lastConfig.accounts.filter(acc => acc.enabled)
-  }
-
-  /**
-   * 根据交易所筛选账户
-   */
-  getAccountsByExchange(exchange: string): FileAccountConfig[] {
-    if (!this.lastConfig) {
-      throw new Error('配置尚未加载')
-    }
-    return this.lastConfig.accounts.filter(acc => acc.exchange === exchange && acc.enabled)
-  }
-
-  /**
-   * 根据名称获取账户
-   */
-  getAccountByName(name: string): FileAccountConfig | undefined {
-    if (!this.lastConfig) {
-      throw new Error('配置尚未加载')
-    }
-    return this.lastConfig.accounts.find(acc => acc.name === name)
-  }
-
-  /**
-   * 验证配置格式
-   */
-  private validateConfig(config: any): void {
-    if (!config.accounts || !Array.isArray(config.accounts)) {
-      throw new Error('配置文件必须包含accounts数组')
-    }
-
-    for (const [index, account] of config.accounts.entries()) {
-      const required = ['name', 'exchange', 'accountId', 'enabled', 'priority']
-      for (const field of required) {
-        if (account[field] === undefined) {
-          throw new Error(`账户配置[${index}]缺少必需字段: ${field}`)
-        }
-      }
-
-      if (!account.auth || typeof account.auth !== 'object') {
-        throw new Error(`账户配置[${index}]缺少auth配置`)
-      }
-
-      // 检查重名
-      const duplicate = config.accounts.find(
-        (other: any, otherIndex: number) => otherIndex !== index && other.name === account.name,
-      )
-      if (duplicate) {
-        throw new Error(`账户名称重复: ${account.name}`)
-      }
-    }
-  }
-
-  /**
-   * 解析认证配置 - 从环境变量获取实际值
-   */
-  private resolveAuthConfig(config: AccountConfigFile): void {
-    for (const account of config.accounts) {
-      const auth = account.auth
-
-      // 从环境变量解析认证信息
-      if (auth.privateKeyEnv) {
-        auth.privateKey = process.env[auth.privateKeyEnv]
-        if (!auth.privateKey) {
-          console.warn(`⚠️ 环境变量 ${auth.privateKeyEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-
-      if (auth.accountIdEnv) {
-        auth.accountId = process.env[auth.accountIdEnv]
-        if (!auth.accountId) {
-          console.warn(`⚠️ 环境变量 ${auth.accountIdEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-
-      if (auth.apiKeyEnv) {
-        auth.apiKey = process.env[auth.apiKeyEnv]
-        if (!auth.apiKey) {
-          console.warn(`⚠️ 环境变量 ${auth.apiKeyEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-
-      if (auth.apiSecretEnv) {
-        auth.apiSecret = process.env[auth.apiSecretEnv]
-        if (!auth.apiSecret) {
-          console.warn(`⚠️ 环境变量 ${auth.apiSecretEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-
-      if (auth.userEnv) {
-        auth.user = process.env[auth.userEnv]
-        if (!auth.user) {
-          console.warn(`⚠️ 环境变量 ${auth.userEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-
-      if (auth.signerEnv) {
-        auth.signer = process.env[auth.signerEnv]
-        if (!auth.signer) {
-          console.warn(`⚠️ 环境变量 ${auth.signerEnv} 未设置 (账户: ${account.name})`)
-        }
-      }
-    }
-  }
-
-  /**
-   * 将文件配置转换为系统配置格式
-   */
-  convertToAccountConfigs(accounts?: FileAccountConfig[]): any[] {
-    const accountsToConvert = accounts || this.getEnabledAccounts()
-
-    return accountsToConvert.map(fileConfig => ({
-      exchange: fileConfig.exchange,
-      accountId: fileConfig.accountId,
-      alias: fileConfig.alias,
-      enabled: fileConfig.enabled,
-      priority: fileConfig.priority,
-      tradingEnabled: fileConfig.tradingEnabled,
-      hedgingEnabled: fileConfig.hedgingEnabled,
-      maxPositionUsd: fileConfig.maxPositionUsd,
-      maxDailyVolumeUsd: fileConfig.maxDailyVolumeUsd,
-
-      // 认证信息
-      privateKey: fileConfig.auth.privateKey,
-      apiKey: fileConfig.auth.apiKey,
-      apiSecret: fileConfig.auth.apiSecret,
-      user: fileConfig.auth.user,
-      signer: fileConfig.auth.signer,
-
-      // 元数据
-      name: fileConfig.name,
-      tags: fileConfig.tags,
-      notes: fileConfig.notes,
-    }))
-  }
-
-  /**
-   * 获取对冲组配置
-   */
-  getHedgingGroups() {
-    return this.lastConfig?.hedgingGroups || []
-  }
-
-  /**
-   * 获取交易规则配置
-   */
-  getTradingRules() {
-    return this.lastConfig?.tradingRules || []
-  }
-
-  /**
-   * 获取配置文件路径
-   */
-  getConfigPath(): string {
-    return this.configFile
-  }
-
-  /**
-   * 检查配置文件是否存在
-   */
-  exists(): boolean {
-    return existsSync(this.configFile)
-  }
-
-  /**
-   * 获取最后加载的配置
-   */
-  getLastConfig(): AccountConfigFile | null {
-    return this.lastConfig
-  }
-
-  /**
-   * 导出当前配置为JSON字符串
-   */
-  exportConfig(): string {
-    if (!this.lastConfig) {
-      throw new Error('配置尚未加载')
-    }
-    return JSON.stringify(this.lastConfig, null, 2)
-  }
-}

+ 0 - 98
src/accounts/CLIAccountInjector.ts

@@ -1,98 +0,0 @@
-/**
- * 命令行账户注入器
- * 支持通过命令行参数动态注入账户
- */
-
-export interface CLIAccountOptions {
-  exchange?: string
-  accountId?: string
-  alias?: string
-  priority?: number
-  tradingEnabled?: boolean
-  hedgingEnabled?: boolean
-  maxPositionUsd?: number
-  configFile?: string
-  dryRun?: boolean
-}
-
-export class CLIAccountInjector {
-  /**
-   * 解析命令行参数
-   */
-  static parseArgs(): CLIAccountOptions {
-    const args = process.argv.slice(2)
-    const options: CLIAccountOptions = {}
-
-    for (let i = 0; i < args.length; i++) {
-      const arg = args[i]
-      const value = args[i + 1]
-
-      switch (arg) {
-        case '--exchange':
-        case '-e':
-          options.exchange = value
-          i++
-          break
-        case '--account':
-        case '-a':
-          options.accountId = value
-          i++
-          break
-        case '--alias':
-          options.alias = value
-          i++
-          break
-        case '--priority':
-        case '-p':
-          options.priority = parseInt(value)
-          i++
-          break
-        case '--trading':
-          options.tradingEnabled = value === 'true'
-          i++
-          break
-        case '--hedging':
-          options.hedgingEnabled = value === 'true'
-          i++
-          break
-        case '--max-position':
-          options.maxPositionUsd = parseFloat(value)
-          i++
-          break
-        case '--config':
-        case '-c':
-          options.configFile = value
-          i++
-          break
-        case '--dry-run':
-          options.dryRun = true
-          break
-      }
-    }
-
-    return options
-  }
-
-  /**
-   * 从命令行快速注入单个账户
-   */
-  static createQuickAccount(): any {
-    const options = this.parseArgs()
-
-    if (!options.exchange) {
-      throw new Error('必须指定交易所: --exchange pacifica|aster|binance')
-    }
-
-    return {
-      exchange: options.exchange,
-      accountId: options.accountId || 'cli-account',
-      alias: options.alias || `CLI-${options.exchange}`,
-      enabled: true,
-      priority: options.priority || 999,
-      tradingEnabled: options.tradingEnabled !== false,
-      hedgingEnabled: options.hedgingEnabled !== false,
-      maxPositionUsd: options.maxPositionUsd || 1000,
-      maxDailyVolumeUsd: (options.maxPositionUsd || 1000) * 10,
-    }
-  }
-}

+ 0 - 276
src/accounts/providers/AutoDiscoveryProvider.ts

@@ -1,276 +0,0 @@
-/**
- * 智能账户自动发现提供者
- * 通过约定优于配置的方式自动发现可用账户
- */
-
-import { AccountProvider, AccountDescriptor } from '../AccountRegistry.js'
-
-export class AutoDiscoveryProvider implements AccountProvider {
-  name = 'auto-discovery'
-  priority = 0 // 最高优先级
-
-  async discover(): Promise<AccountDescriptor[]> {
-    const descriptors: AccountDescriptor[] = []
-
-    // 1. 环境变量模式发现
-    descriptors.push(...(await this.discoverFromEnvironment()))
-
-    // 2. 约定命名发现
-    descriptors.push(...(await this.discoverByConvention()))
-
-    // 3. 配置文件发现
-    descriptors.push(...(await this.discoverFromConfigFiles()))
-
-    return descriptors
-  }
-
-  async validate(descriptor: AccountDescriptor): Promise<boolean> {
-    try {
-      const credentials = await descriptor.credentials()
-      return this.hasRequiredCredentials(descriptor.exchange, credentials)
-    } catch {
-      return false
-    }
-  }
-
-  /**
-   * 从环境变量自动发现账户
-   * 支持多账户命名约定: EXCHANGE_FIELD_INDEX
-   */
-  private async discoverFromEnvironment(): Promise<AccountDescriptor[]> {
-    const descriptors: AccountDescriptor[] = []
-    const exchanges = ['PACIFICA', 'ASTER', 'BINANCE']
-
-    for (const exchange of exchanges) {
-      // 发现单账户模式
-      const singleAccount = await this.discoverSingleAccount(exchange)
-      if (singleAccount) {
-        descriptors.push(singleAccount)
-      }
-
-      // 发现多账户模式
-      const multiAccounts = await this.discoverMultiAccounts(exchange)
-      descriptors.push(...multiAccounts)
-    }
-
-    return descriptors
-  }
-
-  /**
-   * 发现单账户配置
-   * 例: PACIFICA_PRIVATE_KEY, ASTER_API_KEY
-   */
-  private async discoverSingleAccount(exchange: string): Promise<AccountDescriptor | null> {
-    const patterns = this.getCredentialPatterns(exchange)
-    const credentials = this.gatherCredentials(patterns)
-
-    if (Object.keys(credentials).length === 0) {
-      return null
-    }
-
-    return {
-      id: `${exchange.toLowerCase()}-main`,
-      name: `${exchange} Main Account`,
-      exchange: exchange.toLowerCase(),
-      credentials: async () => credentials,
-      config: {
-        enabled: true,
-        priority: 1,
-        trading: true,
-        hedging: true,
-        limits: {
-          maxPosition: parseFloat(process.env[`${exchange}_MAX_POSITION`] || '10000'),
-          maxDailyVolume: parseFloat(process.env[`${exchange}_MAX_DAILY_VOLUME`] || '100000'),
-        },
-      },
-      metadata: {
-        source: 'env-auto',
-        tags: ['main', 'auto-discovered'],
-        createdAt: new Date(),
-        updatedAt: new Date(),
-      },
-    }
-  }
-
-  /**
-   * 发现多账户配置
-   * 例: PACIFICA_PRIVATE_KEY_1, PACIFICA_PRIVATE_KEY_2
-   */
-  private async discoverMultiAccounts(exchange: string): Promise<AccountDescriptor[]> {
-    const descriptors: AccountDescriptor[] = []
-    const maxAccounts = 10 // 最多检查10个账户
-
-    for (let i = 1; i <= maxAccounts; i++) {
-      const patterns = this.getCredentialPatterns(exchange, i)
-      const credentials = this.gatherCredentials(patterns)
-
-      if (Object.keys(credentials).length > 0) {
-        descriptors.push({
-          id: `${exchange.toLowerCase()}-${i}`,
-          name: `${exchange} Account ${i}`,
-          exchange: exchange.toLowerCase(),
-          credentials: async () => credentials,
-          config: {
-            enabled: process.env[`${exchange}_ENABLED_${i}`] !== 'false',
-            priority: i,
-            trading: process.env[`${exchange}_TRADING_${i}`] !== 'false',
-            hedging: process.env[`${exchange}_HEDGING_${i}`] !== 'false',
-            limits: {
-              maxPosition: parseFloat(process.env[`${exchange}_MAX_POSITION_${i}`] || '5000'),
-              maxDailyVolume: parseFloat(process.env[`${exchange}_MAX_DAILY_VOLUME_${i}`] || '50000'),
-            },
-          },
-          metadata: {
-            source: 'env-auto-multi',
-            tags: ['multi-account', 'auto-discovered', `account-${i}`],
-            createdAt: new Date(),
-            updatedAt: new Date(),
-          },
-        })
-      }
-    }
-
-    return descriptors
-  }
-
-  /**
-   * 通过约定命名自动发现
-   * 支持角色约定: main, hedge, backup, test
-   */
-  private async discoverByConvention(): Promise<AccountDescriptor[]> {
-    const descriptors: AccountDescriptor[] = []
-    const exchanges = ['PACIFICA', 'ASTER', 'BINANCE']
-    const roles = ['MAIN', 'HEDGE', 'BACKUP', 'TEST']
-
-    for (const exchange of exchanges) {
-      for (const role of roles) {
-        const patterns = this.getCredentialPatterns(exchange, undefined, role)
-        const credentials = this.gatherCredentials(patterns)
-
-        if (Object.keys(credentials).length > 0) {
-          const priority = this.getRolePriority(role)
-          const enabled = role !== 'TEST' && process.env[`${exchange}_${role}_ENABLED`] !== 'false'
-
-          descriptors.push({
-            id: `${exchange.toLowerCase()}-${role.toLowerCase()}`,
-            name: `${exchange} ${role.charAt(0) + role.slice(1).toLowerCase()} Account`,
-            exchange: exchange.toLowerCase(),
-            credentials: async () => credentials,
-            config: {
-              enabled,
-              priority,
-              trading: role !== 'BACKUP',
-              hedging: role === 'HEDGE' || role === 'MAIN',
-              limits: {
-                maxPosition: this.getRoleLimit(role, 'POSITION'),
-                maxDailyVolume: this.getRoleLimit(role, 'VOLUME'),
-              },
-            },
-            metadata: {
-              source: 'convention',
-              tags: ['role-based', role.toLowerCase()],
-              createdAt: new Date(),
-              updatedAt: new Date(),
-            },
-          })
-        }
-      }
-    }
-
-    return descriptors
-  }
-
-  /**
-   * 从配置文件发现
-   */
-  private async discoverFromConfigFiles(): Promise<AccountDescriptor[]> {
-    // 这里可以集成现有的 ConfigFileProvider
-    return []
-  }
-
-  /**
-   * 获取交易所认证模式
-   */
-  private getCredentialPatterns(exchange: string, index?: number, role?: string): Record<string, string> {
-    const suffix = index ? `_${index}` : role ? `_${role}` : ''
-
-    const patterns: Record<string, Record<string, string>> = {
-      PACIFICA: {
-        privateKey: `${exchange}_PRIVATE_KEY${suffix}`,
-        accountId: `${exchange}_ACCOUNT${suffix}`,
-        agentWallet: `${exchange}_AGENT_WALLET${suffix}`,
-        agentPrivateKey: `${exchange}_AGENT_PRIVATE_KEY${suffix}`,
-      },
-      ASTER: {
-        user: `${exchange}_ORDER_USER${suffix}`,
-        signer: `${exchange}_ORDER_SIGNER${suffix}`,
-        privateKey: `PRIVATE_KEY${suffix}`,
-        apiKey: `${exchange}_API_KEY${suffix}`,
-        apiSecret: `${exchange}_API_SECRET${suffix}`,
-      },
-      BINANCE: {
-        apiKey: `${exchange}_API_KEY${suffix}`,
-        apiSecret: `${exchange}_SECRET_KEY${suffix}`,
-      },
-    }
-
-    return patterns[exchange] || {}
-  }
-
-  /**
-   * 收集凭证
-   */
-  private gatherCredentials(patterns: Record<string, string>): Record<string, string> {
-    const credentials: Record<string, string> = {}
-
-    for (const [key, envVar] of Object.entries(patterns)) {
-      const value = process.env[envVar]
-      if (value) {
-        credentials[key] = value
-      }
-    }
-
-    return credentials
-  }
-
-  /**
-   * 检查必需凭证
-   */
-  private hasRequiredCredentials(exchange: string, credentials: Record<string, any>): boolean {
-    const required: Record<string, string[]> = {
-      pacifica: ['privateKey', 'accountId'],
-      aster: ['user', 'signer', 'privateKey'],
-      binance: ['apiKey', 'apiSecret'],
-    }
-
-    const requiredFields = required[exchange] || []
-    return requiredFields.every(field => credentials[field])
-  }
-
-  /**
-   * 获取角色优先级
-   */
-  private getRolePriority(role: string): number {
-    const priorities: Record<string, number> = {
-      MAIN: 1,
-      HEDGE: 2,
-      BACKUP: 3,
-      TEST: 9,
-    }
-    return priorities[role] || 5
-  }
-
-  /**
-   * 获取角色限额
-   */
-  private getRoleLimit(role: string, type: 'POSITION' | 'VOLUME'): number {
-    const limits: Record<string, Record<string, number>> = {
-      MAIN: { POSITION: 20000, VOLUME: 200000 },
-      HEDGE: { POSITION: 15000, VOLUME: 150000 },
-      BACKUP: { POSITION: 5000, VOLUME: 50000 },
-      TEST: { POSITION: 1000, VOLUME: 10000 },
-    }
-
-    return limits[role]?.[type] || (type === 'POSITION' ? 5000 : 50000)
-  }
-}

+ 0 - 323
src/core/credential-manager.ts

@@ -1,323 +0,0 @@
-/**
- * 主凭据管理服务 - 专注于Pacifica平台
- * 单一职责:凭据分类管理和签名服务
- */
-
-import { EventEmitter } from 'events'
-import {
-  CredentialManager,
-  PlatformAccount,
-  SignatureResult,
-  ConfigStatus,
-  PacificaSignData,
-  ErrorCode,
-  BatchSignRequest,
-  BatchSignResponse,
-} from '../shared/credential-types'
-import { PERFORMANCE_LIMITS } from '../shared/credential-constants'
-import { createApiError, formatTimestamp, PerformanceTimer, sanitizePrivateKey } from '../shared/credential-utils'
-import { CredentialConfigLoader } from './config-loader'
-import { PacificaSignatureAdapter } from './signature-adapters/pacifica'
-
-/**
- * 主凭据管理器实现
- */
-export class PacificaCredentialManager extends EventEmitter implements CredentialManager {
-  private _configLoader: CredentialConfigLoader
-  private _pacificaAdapter: PacificaSignatureAdapter
-  private _initialized: boolean = false
-
-  constructor(configPath?: string) {
-    super()
-
-    this._configLoader = new CredentialConfigLoader(configPath)
-    this._pacificaAdapter = new PacificaSignatureAdapter()
-
-    // 转发配置加载器事件
-    this._configLoader.on('config:loaded', event => this.emit('config:loaded', event))
-    this._configLoader.on('config:reloaded', event => this.emit('config:reloaded', event))
-    this._configLoader.on('config:error', event => this.emit('config:error', event))
-
-    console.log(`🚀 [CredentialManager] 初始化完成 (专注Pacifica平台)`)
-  }
-
-  /**
-   * 初始化服务
-   */
-  async initialize(): Promise<void> {
-    if (this._initialized) {
-      console.log(`⚠️ [CredentialManager] 服务已初始化`)
-      return
-    }
-
-    try {
-      // 加载配置文件
-      await this._configLoader.loadConfig()
-
-      // 启动文件监控
-      this._configLoader.watchConfig()
-
-      this._initialized = true
-      console.log(`✅ [CredentialManager] 服务初始化成功`)
-
-      this.emit('service:initialized', {
-        timestamp: formatTimestamp(),
-        accountCount: this._configLoader.accounts.size,
-      })
-    } catch (error) {
-      console.error(`❌ [CredentialManager] 服务初始化失败:`, error)
-      throw error
-    }
-  }
-
-  /**
-   * 执行签名操作(核心功能)
-   */
-  async sign(platformId: string, accountId: string, data: PacificaSignData): Promise<SignatureResult> {
-    const timer = new PerformanceTimer()
-
-    try {
-      // 检查服务初始化状态
-      if (!this._initialized) {
-        throw createApiError(ErrorCode.SIGNATURE_FAILED, {
-          reason: 'Service not initialized',
-        })
-      }
-
-      // 验证平台支持
-      if (platformId !== 'pacifica') {
-        throw createApiError(ErrorCode.PLATFORM_NOT_SUPPORTED, {
-          platformId,
-          supportedPlatforms: ['pacifica'],
-        })
-      }
-
-      // 获取账户信息
-      const account = this.getAccount(platformId, accountId)
-      if (!account) {
-        throw createApiError(ErrorCode.ACCOUNT_NOT_FOUND, {
-          platformId,
-          accountId,
-        })
-      }
-
-      // 检查账户状态
-      if (account.status !== 'active') {
-        throw createApiError(ErrorCode.ACCOUNT_INACTIVE, {
-          platformId,
-          accountId,
-          status: account.status,
-        })
-      }
-
-      // 执行Pacifica签名
-      const result = await this._pacificaAdapter.sign(data, {
-        privateKey: account.credentials.privateKey!,
-      })
-
-      const elapsedMs = timer.elapsed()
-
-      // 更新账户使用统计
-      await this._updateAccountUsage(account, true, elapsedMs)
-
-      console.log(`✅ [CredentialManager] 签名完成: ${accountId} (${elapsedMs.toFixed(1)}ms)`)
-
-      this.emit('signature:success', {
-        platformId,
-        accountId,
-        algorithm: result.algorithm,
-        executionTimeMs: elapsedMs,
-        timestamp: formatTimestamp(),
-      })
-
-      return result
-    } catch (error) {
-      const elapsedMs = timer.elapsed()
-
-      // 更新账户错误统计
-      const account = this.getAccount(platformId, accountId)
-      if (account) {
-        await this._updateAccountUsage(account, false, elapsedMs)
-      }
-
-      console.error(`❌ [CredentialManager] 签名失败: ${accountId} (${elapsedMs.toFixed(1)}ms)`, error)
-
-      this.emit('signature:error', {
-        platformId,
-        accountId,
-        error: error instanceof Error ? error.message : String(error),
-        executionTimeMs: elapsedMs,
-        timestamp: formatTimestamp(),
-      })
-
-      throw error
-    }
-  }
-
-  /**
-   * 批量签名操作
-   */
-  async signBatch(batchRequest: BatchSignRequest): Promise<BatchSignResponse> {
-    const timer = new PerformanceTimer()
-    const results: BatchSignResponse['results'] = []
-
-    console.log(`🔄 [CredentialManager] 开始批量签名: ${batchRequest.requests.length}个请求`)
-
-    for (const request of batchRequest.requests) {
-      try {
-        const signature = await this.sign(request.platformId, request.accountId, request.data)
-
-        results.push({
-          requestId: request.requestId,
-          status: 'success',
-          signature: signature.signature,
-          algorithm: signature.algorithm,
-        })
-      } catch (error) {
-        results.push({
-          requestId: request.requestId,
-          status: 'error',
-          error: error instanceof Error ? error.message : String(error),
-        })
-      }
-    }
-
-    const elapsedMs = timer.elapsed()
-    const successful = results.filter(r => r.status === 'success').length
-    const failed = results.length - successful
-
-    console.log(`✅ [CredentialManager] 批量签名完成: ${successful}成功/${failed}失败 (${elapsedMs.toFixed(1)}ms)`)
-
-    return {
-      results,
-      summary: {
-        total: results.length,
-        successful,
-        failed,
-      },
-    }
-  }
-
-  /**
-   * 获取指定账户
-   */
-  getAccount(platformId: string, accountId: string): PlatformAccount | null {
-    return this._configLoader.getAccount(platformId, accountId)
-  }
-
-  /**
-   * 列出账户
-   */
-  listAccounts(platformId?: string): PlatformAccount[] {
-    if (platformId) {
-      return this._configLoader.getAccountsByPlatform(platformId)
-    }
-
-    // 返回所有账户
-    return Array.from(this._configLoader.accounts.values())
-  }
-
-  /**
-   * 重新加载配置
-   */
-  async reloadConfig(): Promise<void> {
-    console.log(`🔄 [CredentialManager] 重新加载配置`)
-    await this._configLoader.reloadConfig()
-  }
-
-  /**
-   * 获取服务状态
-   */
-  getStatus(): ConfigStatus {
-    const stats = this._configLoader.getStats()
-
-    return {
-      configPath: stats.configPath,
-      lastLoaded: stats.lastLoaded,
-      accountCount: stats.totalAccounts,
-      platformCount: Object.keys(stats.platformStats).length,
-      isWatching: stats.isWatching,
-    }
-  }
-
-  /**
-   * 获取详细统计信息
-   */
-  getDetailedStats() {
-    const baseStats = this._configLoader.getStats()
-    const pacificaAccounts = this.listAccounts('pacifica')
-
-    const accountUsageStats = pacificaAccounts.map(account => ({
-      accountId: account.accountId,
-      alias: account.alias,
-      totalSigns: account.usage.totalSigns,
-      errorCount: account.usage.errorCount,
-      lastUsed: account.usage.lastSignAt,
-      environment: account.environment,
-      status: account.status,
-    }))
-
-    return {
-      ...baseStats,
-      service: {
-        initialized: this._initialized,
-        uptime: this._initialized ? Date.now() - this._configLoader.lastLoaded.getTime() : 0,
-      },
-      performance: {
-        maxSignatureTimeMs: PERFORMANCE_LIMITS.MAX_SIGNATURE_TIME_MS,
-        maxBatchTimeMs: PERFORMANCE_LIMITS.MAX_BATCH_SIGNATURE_TIME_MS,
-        maxQPS: PERFORMANCE_LIMITS.MAX_QPS,
-      },
-      accounts: accountUsageStats,
-    }
-  }
-
-  /**
-   * 私有方法:更新账户使用统计
-   */
-  private async _updateAccountUsage(
-    account: PlatformAccount,
-    success: boolean,
-    executionTimeMs: number,
-  ): Promise<void> {
-    try {
-      if (success) {
-        account.usage.totalSigns++
-        account.usage.lastSignAt = new Date()
-      } else {
-        account.usage.errorCount++
-      }
-
-      account.updatedAt = new Date()
-
-      // 性能警告
-      if (executionTimeMs > PERFORMANCE_LIMITS.MAX_SIGNATURE_TIME_MS) {
-        console.warn(
-          `⚠️ [CredentialManager] 签名性能超出目标: ${executionTimeMs.toFixed(1)}ms > ${
-            PERFORMANCE_LIMITS.MAX_SIGNATURE_TIME_MS
-          }ms`,
-        )
-      }
-    } catch (error) {
-      console.error(`❌ [CredentialManager] 更新账户统计失败:`, error)
-    }
-  }
-
-  /**
-   * 优雅关闭服务
-   */
-  async shutdown(): Promise<void> {
-    console.log(`🛑 [CredentialManager] 开始关闭服务`)
-
-    try {
-      await this._configLoader.shutdown()
-      this.removeAllListeners()
-      this._initialized = false
-
-      console.log(`✅ [CredentialManager] 服务已关闭`)
-    } catch (error) {
-      console.error(`❌ [CredentialManager] 关闭服务时出错:`, error)
-      throw error
-    }
-  }
-}

+ 0 - 39
src/core/hedging/hedgingExecutor.ts

@@ -1,39 +0,0 @@
-import { hedgeCalculator } from './hedgeCalculator'
-import { tradeRouter } from './router'
-import { HedgeRequest, ExecutionPlan, ExecutionResult } from './types'
-
-export class HedgingExecutor {
-  async execute(req: HedgeRequest): Promise<ExecutionResult> {
-    // 1) 计算对冲决策
-    const decision = hedgeCalculator.decide(req)
-    if (!decision.shouldHedge) {
-      return { success: true, executedQuantity: 0, executedPrice: 0, orderId: undefined, txHash: undefined }
-    }
-
-    const side: 'buy' | 'sell' = decision.hedgeQuantity > 0 ? 'buy' : 'sell'
-    const absQty = Math.abs(decision.hedgeQuantity)
-
-    // 2) 路由报价(根据 method)
-    const quote =
-      decision.method === 'spot'
-        ? await tradeRouter.quoteSpot(req.symbol, absQty)
-        : await tradeRouter.quotePerp(req.symbol, absQty)
-
-    // 3) 滑点检查(占位:总是通过)。实际应根据 req.config.thresholds.maxSlippage 与 quote 对比
-
-    // 4) 生成执行计划
-    const plan: ExecutionPlan = {
-      method: decision.method,
-      symbol: req.symbol,
-      quantity: absQty,
-      side,
-      quote,
-    }
-
-    // 5) 执行
-    const result = await tradeRouter.execute(plan)
-    return result as ExecutionResult
-  }
-}
-
-export const hedgingExecutor = new HedgingExecutor()

+ 0 - 584
src/core/orchestration/orchestrator.ts

@@ -1,584 +0,0 @@
-/**
- * 🎯 统一系统协调器 v2.0 - Delta中性控制平面系统协调器
- *
- * 基于tasks规范重构的系统协调器,支持:
- * - Delta中性控制平面完整架构
- * - 统一账户管理系统集成
- * - 企业级风险包络管理
- * - 多平台认证和代理管理
- * - 实时监控和性能报告
- * - 优雅启动和关闭流程
- */
-
-import { TradingService, ServiceStatus } from '../../shared/types/index'
-import UnifiedAccountManager, { UnifiedAccountConfig } from '../accounts/manager'
-import { RiskEnvelopeManager, RiskEnvelopeConfig } from '../risk/envelope'
-import { DeltaNeutralController } from '../risk/controller'
-import DeltaNeutralTradingEngine from '../trading/engine'
-import { DashboardService } from '../../services/dashboard'
-import { CacheManager } from '../../adapters/data/cache/manager'
-import { RiskManager } from '../../services/risk-manager'
-import { logger } from '../../shared/utils/logger'
-
-/**
- * 系统初始化配置
- */
-export interface UnifiedSystemConfig {
-  // 账户配置
-  accounts: UnifiedAccountConfig[]
-
-  // 功能开关
-  enableTrading: boolean
-  enableDashboard: boolean
-  enableDeltaControl: boolean
-  enableRiskMonitoring: boolean
-
-  // Delta中性控制配置
-  deltaControl?: {
-    deltaThreshold: number // Delta阈值
-    utilizationTargetMin: number // 最小利用率目标
-    utilizationTargetMax: number // 最大利用率目标
-    controlCycleInterval: number // 控制循环间隔
-    emergencyResponseTime: number // 紧急响应时间
-  }
-
-  // 风险管理配置
-  riskManagement?: {
-    globalMaxDrawdown: number // 全局最大回撤
-    accountMaxLeverage: number // 账户最大杠杆
-    emergencyStopLoss: number // 紧急止损
-    riskCheckInterval: number // 风险检查间隔
-  }
-
-  // 显示配置
-  displayConfig?: {
-    showPrices: boolean
-    showPositions: boolean
-    showRiskMetrics: boolean
-    refreshInterval: number
-  }
-
-  // 环境配置
-  environment: 'development' | 'production' | 'testing'
-  logLevel: 'debug' | 'info' | 'warn' | 'error'
-}
-
-/**
- * 系统状态信息
- */
-export interface SystemStatus {
-  status: 'stopped' | 'initializing' | 'running' | 'stopping' | 'error'
-  environment: string
-  startTime?: Date
-  uptime?: number
-  services: Record<string, ServiceStatus>
-
-  // Delta中性状态
-  deltaControl: {
-    enabled: boolean
-    globalDelta: number
-    accountsMonitored: number
-    lastControlCycle?: Date
-    controlCycleSuccess: number
-    controlCycleFailures: number
-  }
-
-  // 风险状态
-  riskManagement: {
-    enabled: boolean
-    totalViolations: number
-    emergencyAccounts: number
-    lastRiskCheck?: Date
-  }
-
-  // 性能指标
-  performance: {
-    totalAccounts: number
-    activeAccounts: number
-    totalTrades: number
-    avgExecutionTime: number
-    systemLoad: number
-  }
-}
-
-/**
- * 统一系统协调器
- */
-export class UnifiedSystemOrchestrator implements TradingService {
-  private status: 'stopped' | 'initializing' | 'running' | 'stopping' | 'error' = 'stopped'
-  private lastStatusChange = Date.now()
-  private startTime?: Date
-  private config?: UnifiedSystemConfig
-
-  // 核心服务实例
-  private services: Map<string, TradingService> = new Map()
-  private unifiedAccountManager!: UnifiedAccountManager
-  private riskEnvelopeManager!: RiskEnvelopeManager
-  private deltaNeutralController!: DeltaNeutralController
-  private tradingEngine!: DeltaNeutralTradingEngine
-  private dashboardService!: DashboardService
-  private cacheManager!: CacheManager
-  private riskManager!: RiskManager
-
-  // 服务初始化顺序
-  private readonly initializationOrder: string[] = [
-    'CacheManager',
-    'RiskEnvelopeManager',
-    'UnifiedAccountManager',
-    'DeltaNeutralController',
-    'RiskManager',
-    'DeltaNeutralTradingEngine',
-    'DashboardService',
-  ]
-
-  constructor() {
-    logger.info('🎯 UnifiedSystemOrchestrator v2.0 创建')
-  }
-
-  /**
-   * 初始化统一系统
-   */
-  async initialize(config: UnifiedSystemConfig): Promise<void> {
-    logger.info('🚀 UnifiedSystemOrchestrator v2.0 初始化开始')
-    this.status = 'initializing'
-    this.lastStatusChange = Date.now()
-    this.config = config
-
-    try {
-      // 1. 验证配置
-      this.validateConfig(config)
-
-      // 2. 创建核心服务实例
-      await this.createCoreServices(config)
-
-      // 3. 按依赖顺序初始化服务
-      await this.initializeServicesInOrder()
-
-      // 4. 配置账户
-      await this.configureAccounts(config.accounts)
-
-      // 5. 设置Delta中性控制
-      if (config.enableDeltaControl) {
-        await this.setupDeltaNeutralControl(config.deltaControl)
-      }
-
-      // 6. 设置风险管理
-      if (config.enableRiskMonitoring) {
-        await this.setupRiskManagement(config.riskManagement)
-      }
-
-      this.status = 'running'
-      this.lastStatusChange = Date.now()
-
-      logger.info('✅ UnifiedSystemOrchestrator v2.0 初始化完成')
-      logger.info(`🏗️ 环境: ${config.environment}`)
-      logger.info(`📊 账户数: ${config.accounts.length}`)
-      logger.info(`🎯 Delta控制: ${config.enableDeltaControl ? '启用' : '禁用'}`)
-      logger.info(`🛡️ 风险监控: ${config.enableRiskMonitoring ? '启用' : '禁用'}`)
-      logger.info(`📈 交易功能: ${config.enableTrading ? '启用' : '禁用'}`)
-    } catch (error) {
-      this.status = 'error'
-      this.lastStatusChange = Date.now()
-      logger.error('❌ UnifiedSystemOrchestrator 初始化失败:', error)
-      throw error
-    }
-  }
-
-  /**
-   * 启动系统
-   */
-  async start(): Promise<void> {
-    if (this.status !== 'running') {
-      throw new Error('系统必须先完成初始化')
-    }
-
-    logger.info('🚀 UnifiedSystemOrchestrator v2.0 启动中')
-    this.startTime = new Date()
-
-    try {
-      // 按顺序启动所有服务
-      for (const serviceName of this.initializationOrder) {
-        const service = this.services.get(serviceName)
-        if (service) {
-          logger.info(`▶️ 启动服务: ${serviceName}`)
-          await service.start()
-        }
-      }
-
-      // 执行启动后检查
-      await this.performPostStartupChecks()
-
-      logger.info('✅ UnifiedSystemOrchestrator v2.0 启动完成')
-      logger.info(`⏰ 启动时间: ${new Date().toISOString()}`)
-      logger.info('🎯 Delta中性控制平面已激活')
-    } catch (error) {
-      this.status = 'error'
-      this.lastStatusChange = Date.now()
-      logger.error('❌ UnifiedSystemOrchestrator 启动失败:', error)
-      throw error
-    }
-  }
-
-  /**
-   * 停止系统
-   */
-  async stop(): Promise<void> {
-    logger.info('🛑 UnifiedSystemOrchestrator v2.0 停止中')
-    this.status = 'stopping'
-    this.lastStatusChange = Date.now()
-
-    try {
-      // 逆序停止所有服务
-      const stopOrder = [...this.initializationOrder].reverse()
-
-      for (const serviceName of stopOrder) {
-        const service = this.services.get(serviceName)
-        if (service) {
-          try {
-            logger.info(`⏹️ 停止服务: ${serviceName}`)
-            await service.stop()
-          } catch (error) {
-            logger.error(`❌ 停止服务 ${serviceName} 失败:`, error)
-          }
-        }
-      }
-
-      // 清理资源
-      this.cleanup()
-
-      this.status = 'stopped'
-      this.lastStatusChange = Date.now()
-
-      const uptime = this.startTime ? Date.now() - this.startTime.getTime() : 0
-      logger.info('✅ UnifiedSystemOrchestrator v2.0 已安全停止')
-      logger.info(`⏱️ 运行时长: ${Math.round(uptime / 1000)}秒`)
-    } catch (error) {
-      this.status = 'error'
-      this.lastStatusChange = Date.now()
-      logger.error('❌ UnifiedSystemOrchestrator 停止失败:', error)
-      throw error
-    }
-  }
-
-  /**
-   * 获取系统状态
-   */
-  async getSystemStatus(): Promise<SystemStatus> {
-    const serviceStatuses: Record<string, ServiceStatus> = {}
-
-    for (const [name, service] of this.services) {
-      try {
-        serviceStatuses[name] = service.getStatus()
-      } catch (error) {
-        serviceStatuses[name] = {
-          name,
-          status: 'error',
-          lastUpdate: Date.now(),
-        }
-      }
-    }
-
-    // 获取Delta中性控制状态
-    const deltaControlState = this.deltaNeutralController ? this.deltaNeutralController.getControlLoopState() : null
-
-    // 获取账户管理状态
-    const accountSummary = this.unifiedAccountManager ? this.unifiedAccountManager.getSystemSummary() : null
-
-    const uptime = this.startTime ? Date.now() - this.startTime.getTime() : 0
-
-    return {
-      status: this.status,
-      environment: this.config?.environment || 'unknown',
-      startTime: this.startTime,
-      uptime,
-      services: serviceStatuses,
-
-      deltaControl: {
-        enabled: this.config?.enableDeltaControl || false,
-        globalDelta: accountSummary?.globalDelta || 0,
-        accountsMonitored: accountSummary?.totalAccounts || 0,
-        lastControlCycle: deltaControlState?.lastExecution,
-        controlCycleSuccess: deltaControlState?.successfulCycles || 0,
-        controlCycleFailures: deltaControlState?.failedCycles || 0,
-      },
-
-      riskManagement: {
-        enabled: this.config?.enableRiskMonitoring || false,
-        totalViolations: 0, // 需要从RiskEnvelopeManager获取
-        emergencyAccounts: accountSummary?.accountsNeedingHedge || 0,
-        lastRiskCheck: new Date(),
-      },
-
-      performance: {
-        totalAccounts: accountSummary?.totalAccounts || 0,
-        activeAccounts: accountSummary?.activeAccounts || 0,
-        totalTrades: 0, // 需要从TradingEngine获取
-        avgExecutionTime: 0, // 需要计算
-        systemLoad: this.calculateSystemLoad(),
-      },
-    }
-  }
-
-  /**
-   * 获取服务状态
-   */
-  getStatus(): ServiceStatus {
-    return {
-      name: 'UnifiedSystemOrchestrator',
-      status: this.status === 'running' ? 'running' : this.status === 'error' ? 'error' : 'stopped',
-      lastUpdate: this.lastStatusChange,
-      details: {
-        serviceCount: this.services.size,
-        environment: this.config?.environment,
-        uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0,
-      },
-    }
-  }
-
-  getLastStatusChange(): number {
-    return this.lastStatusChange
-  }
-
-  /**
-   * 获取账户管理器
-   */
-  getAccountManager(): UnifiedAccountManager {
-    return this.unifiedAccountManager
-  }
-
-  /**
-   * 获取Delta中性控制器
-   */
-  getDeltaNeutralController(): DeltaNeutralController {
-    return this.deltaNeutralController
-  }
-
-  /**
-   * 获取风险包络管理器
-   */
-  getRiskEnvelopeManager(): RiskEnvelopeManager {
-    return this.riskEnvelopeManager
-  }
-
-  // ========== 私有方法 ==========
-
-  /**
-   * 验证配置
-   */
-  private validateConfig(config: UnifiedSystemConfig): void {
-    if (!config.accounts || config.accounts.length === 0) {
-      throw new Error('至少需要配置一个账户')
-    }
-
-    if (!config.environment) {
-      throw new Error('必须指定运行环境')
-    }
-
-    if (config.enableDeltaControl && !config.deltaControl) {
-      logger.warn('Delta控制已启用但未提供详细配置,将使用默认值')
-    }
-
-    logger.info('✅ 系统配置验证通过')
-  }
-
-  /**
-   * 创建核心服务实例
-   */
-  private async createCoreServices(config: UnifiedSystemConfig): Promise<void> {
-    logger.info('🔧 创建核心服务实例')
-
-    // 1. 创建缓存管理器
-    this.cacheManager = new CacheManager()
-    this.services.set('CacheManager', this.cacheManager)
-
-    // 2. 创建风险包络管理器
-    this.riskEnvelopeManager = new RiskEnvelopeManager()
-    this.services.set('RiskEnvelopeManager', this.riskEnvelopeManager)
-
-    // 3. 创建统一账户管理器
-    this.unifiedAccountManager = new UnifiedAccountManager()
-    this.services.set('UnifiedAccountManager', this.unifiedAccountManager)
-
-    // 4. 创建Delta中性控制器
-    this.deltaNeutralController = new DeltaNeutralController(this.unifiedAccountManager, this.riskEnvelopeManager)
-    this.services.set('DeltaNeutralController', this.deltaNeutralController)
-
-    // 5. 创建风险管理器
-    this.riskManager = new RiskManager()
-    this.services.set('RiskManager', this.riskManager)
-
-    // 6. 创建Delta中性交易引擎
-    if (config.enableTrading) {
-      this.tradingEngine = new DeltaNeutralTradingEngine(
-        this.unifiedAccountManager,
-        this.riskEnvelopeManager,
-        this.deltaNeutralController,
-        this.cacheManager,
-      )
-      this.services.set('DeltaNeutralTradingEngine', this.tradingEngine)
-    }
-
-    // 7. 创建仪表板服务
-    if (config.enableDashboard) {
-      this.dashboardService = new DashboardService(this.unifiedAccountManager, this.cacheManager, config.displayConfig)
-      this.services.set('DashboardService', this.dashboardService)
-    }
-
-    logger.info(`✅ 创建了 ${this.services.size} 个核心服务`)
-  }
-
-  /**
-   * 按依赖顺序初始化服务
-   */
-  private async initializeServicesInOrder(): Promise<void> {
-    logger.info('⚙️ 按依赖顺序初始化服务')
-
-    for (const serviceName of this.initializationOrder) {
-      const service = this.services.get(serviceName)
-      if (service) {
-        logger.info(`🔄 初始化服务: ${serviceName}`)
-        await service.initialize()
-      }
-    }
-
-    logger.info('✅ 所有服务初始化完成')
-  }
-
-  /**
-   * 配置账户
-   */
-  private async configureAccounts(accounts: UnifiedAccountConfig[]): Promise<void> {
-    logger.info(`📝 配置 ${accounts.length} 个账户`)
-
-    for (const accountConfig of accounts) {
-      try {
-        await this.unifiedAccountManager.addAccount(accountConfig)
-        logger.info(`✅ 账户 ${accountConfig.accountId} 配置成功`)
-      } catch (error) {
-        logger.error(`❌ 账户 ${accountConfig.accountId} 配置失败:`, error)
-        throw error
-      }
-    }
-
-    logger.info('✅ 所有账户配置完成')
-  }
-
-  /**
-   * 设置Delta中性控制
-   */
-  private async setupDeltaNeutralControl(deltaConfig?: any): Promise<void> {
-    logger.info('🎯 设置Delta中性控制')
-
-    // 应用Delta控制配置
-    if (deltaConfig) {
-      logger.info('📊 应用Delta控制配置', deltaConfig)
-    }
-
-    logger.info('✅ Delta中性控制设置完成')
-  }
-
-  /**
-   * 设置风险管理
-   */
-  private async setupRiskManagement(riskConfig?: any): Promise<void> {
-    logger.info('🛡️ 设置风险管理')
-
-    // 为每个账户创建风险包络
-    const accounts = this.unifiedAccountManager.getAllAccounts()
-    for (const account of accounts) {
-      const config = account.getConfig()
-
-      const riskEnvelopeConfig: RiskEnvelopeConfig = {
-        envelopeId: `risk-${config.accountId}`,
-        accountId: config.accountId,
-        maxDrawdownPercent: (riskConfig?.globalMaxDrawdown || 5.0) / 100, // 转换为小数
-        maxLeverage: riskConfig?.accountMaxLeverage || 10.0,
-        maxPositionSize: config.maxPositionValue,
-        stopLossPercent: (riskConfig?.emergencyStopLoss || 3.0) / 100, // 转换为小数
-        liquidationBuffer: 2.0,
-        riskBudgetUsd: config.maxPositionValue * 0.1,
-        enabled: true,
-      }
-
-      this.riskEnvelopeManager.createRiskEnvelope(riskEnvelopeConfig)
-    }
-
-    logger.info('✅ 风险管理设置完成')
-  }
-
-  /**
-   * 执行启动后检查
-   */
-  private async performPostStartupChecks(): Promise<void> {
-    logger.info('🔍 执行启动后检查')
-
-    // 1. 检查所有服务状态
-    let healthyServices = 0
-    let totalServices = 0
-
-    for (const [name, service] of this.services) {
-      totalServices++
-      try {
-        const status = service.getStatus()
-        if (status.status === 'running') {
-          healthyServices++
-        } else {
-          logger.warn(`⚠️ 服务 ${name} 状态异常: ${status.status}`)
-        }
-      } catch (error) {
-        logger.error(`❌ 服务 ${name} 状态检查失败:`, error)
-      }
-    }
-
-    logger.info(`💚 健康服务: ${healthyServices}/${totalServices}`)
-
-    // 2. 检查账户连接状态
-    if (this.unifiedAccountManager) {
-      const accountSummaries = this.unifiedAccountManager.getAllAccountSummaries()
-      const onlineAccounts = accountSummaries.filter(acc => acc.isOnline).length
-
-      logger.info(`🔗 在线账户: ${onlineAccounts}/${accountSummaries.length}`)
-    }
-
-    // 3. 检查Delta中性控制状态
-    if (this.deltaNeutralController && this.config?.enableDeltaControl) {
-      const globalDelta = this.unifiedAccountManager.calculateGlobalDelta()
-      logger.info(`🎯 全局Delta: ${globalDelta.toFixed(6)} BTC`)
-    }
-
-    logger.info('✅ 启动后检查完成')
-  }
-
-  /**
-   * 计算系统负载
-   */
-  private calculateSystemLoad(): number {
-    // 简化实现:基于服务状态计算负载
-    let totalServices = 0
-    let runningServices = 0
-
-    for (const service of this.services.values()) {
-      totalServices++
-      try {
-        if (service.getStatus().status === 'running') {
-          runningServices++
-        }
-      } catch (error) {
-        // 忽略错误
-      }
-    }
-
-    return totalServices > 0 ? runningServices / totalServices : 0
-  }
-
-  /**
-   * 清理资源
-   */
-  private cleanup(): void {
-    this.services.clear()
-    this.startTime = undefined
-    this.config = undefined
-  }
-}
-
-export default UnifiedSystemOrchestrator

+ 0 - 19
src/core/strategy/positionStrategy.ts

@@ -1,19 +0,0 @@
-import { TradingSignal } from '../../types/core'
-
-export class PositionStrategy {
-  generateSignals(symbols: string[]): TradingSignal[] {
-    const now = Date.now()
-    // TODO: 使用指标计算真实信号
-    return symbols.map(symbol => ({
-      symbol,
-      action: 'hedge',
-      confidence: 0.5,
-      quantity: 0,
-      reason: 'placeholder',
-      indicators: {},
-      timestamp: now,
-    }))
-  }
-}
-
-export const positionStrategy = new PositionStrategy()

+ 0 - 125
src/exchanges/aster/orderBookManager.ts

@@ -1,125 +0,0 @@
-import { EventEmitter } from 'events'
-import { AsterOrderBook, OrderBookSnapshot, DepthUpdate } from './orderBook'
-import { AsterWsClient, AsterWsConfig, AsterStreamArg } from './wsClient'
-
-export class AsterOrderBookManager extends EventEmitter {
-  private orderBooks: Map<string, AsterOrderBook> = new Map()
-  private wsClient: AsterWsClient
-  private httpBase: string
-  private isConnected: boolean = false
-
-  constructor(wsConfig: AsterWsConfig, httpBase: string = 'https://fapi.asterdex.com') {
-    super()
-    this.httpBase = httpBase
-    this.wsClient = new AsterWsClient(wsConfig)
-    this.setupWebSocketHandlers()
-  }
-
-  private setupWebSocketHandlers(): void {
-    this.wsClient.on('open', () => {
-      this.isConnected = true
-    })
-    this.wsClient.on('close', () => {
-      this.isConnected = false
-    })
-    this.wsClient.on('error', error => {
-      this.emit('error', 'ALL', error)
-    })
-    this.wsClient.on('raw', message => {
-      this.handleWebSocketMessage(message)
-    })
-  }
-
-  private handleWebSocketMessage(message: any): void {
-    if (message.stream && message.data) {
-      const data = message.data
-      if (String(message.stream).includes('@depth')) {
-        const update: DepthUpdate = {
-          symbol: data.s,
-          firstUpdateId: data.U,
-          finalUpdateId: data.u,
-          previousFinalUpdateId: data.pu,
-          bids: data.b || [],
-          asks: data.a || [],
-          timestamp: data.E || Date.now(),
-        }
-        this.updateOrderBook(update)
-      }
-      return
-    }
-    if (message.e === 'depthUpdate') {
-      const update: DepthUpdate = {
-        symbol: message.s,
-        firstUpdateId: message.U,
-        finalUpdateId: message.u,
-        previousFinalUpdateId: message.pu,
-        bids: message.b || [],
-        asks: message.a || [],
-        timestamp: message.E || Date.now(),
-      }
-      this.updateOrderBook(update)
-    }
-  }
-
-  async addSymbol(symbol: string): Promise<void> {
-    const normalizedSymbol = symbol.toUpperCase()
-    if (this.orderBooks.has(normalizedSymbol)) return
-    const orderBook = new AsterOrderBook(normalizedSymbol, this.httpBase)
-    orderBook.on('update', snapshot => {
-      this.emit('update', normalizedSymbol, snapshot)
-    })
-    orderBook.on('error', error => {
-      this.emit('error', normalizedSymbol, error)
-    })
-    orderBook.on('reconnect', () => {
-      this.emit('reconnect', normalizedSymbol)
-    })
-    await orderBook.initialize()
-    this.orderBooks.set(normalizedSymbol, orderBook)
-    if (this.isConnected) this.subscribeDepth(normalizedSymbol)
-  }
-
-  removeSymbol(symbol: string): void {
-    const normalizedSymbol = symbol.toUpperCase()
-    if (!this.orderBooks.has(normalizedSymbol)) return
-    if (this.isConnected) this.unsubscribeDepth(normalizedSymbol)
-    this.orderBooks.delete(normalizedSymbol)
-  }
-
-  private subscribeDepth(symbol: string): void {
-    const normalizedSymbol = symbol.toLowerCase()
-    const subscription: AsterStreamArg = { channel: 'depth', symbol: normalizedSymbol } as any
-    this.wsClient.subscribe(subscription)
-  }
-
-  private unsubscribeDepth(symbol: string): void {
-    const normalizedSymbol = symbol.toLowerCase()
-    const subscription: AsterStreamArg = { channel: 'depth', symbol: normalizedSymbol } as any
-    this.wsClient.unsubscribe(subscription)
-  }
-
-  private updateOrderBook(update: DepthUpdate): void {
-    const orderBook = this.orderBooks.get(update.symbol)
-    if (orderBook) orderBook.updateDepth(update)
-  }
-
-  connect(): void {
-    this.wsClient.connect()
-  }
-  disconnect(): void {
-    this.wsClient.disconnect()
-    this.isConnected = false
-  }
-  getOrderBook(symbol: string): OrderBookSnapshot | null {
-    const ob = this.orderBooks.get(symbol.toUpperCase())
-    return ob ? ob.getSnapshot() : null
-  }
-  getBestBid(symbol: string): number | null {
-    const ob = this.orderBooks.get(symbol.toUpperCase())
-    return ob ? ob.getBestBid() : null
-  }
-  getBestAsk(symbol: string): number | null {
-    const ob = this.orderBooks.get(symbol.toUpperCase())
-    return ob ? ob.getBestAsk() : null
-  }
-}

+ 0 - 52
src/exchanges/pacifica/RestAdapter.ts

@@ -1,52 +0,0 @@
-import { PacificaClient } from './PacificaClient'
-
-export class PacificaRestAdapter {
-  constructor(private client: PacificaClient) {}
-
-  async getPrices() {
-    const response = await this.client.getPublic<any>('/api/v1/info/prices')
-    const data = response?.data ?? response
-    return Array.isArray(data) ? data : []
-  }
-
-  async getFundingHistory(params: { symbol: string; limit?: number; offset?: number }) {
-    const { symbol, limit, offset } = params
-    const qs = [`symbol=${symbol}`]
-    if (limit !== undefined) qs.push(`limit=${limit}`)
-    if (offset !== undefined) qs.push(`offset=${offset}`)
-    const response = await this.client.getPublic<any>(`/api/v1/funding_rate/history?${qs.join('&')}`)
-    const data = response?.data ?? response
-    return Array.isArray(data) ? data : []
-  }
-
-  async getMarketInfo(symbol?: string) {
-    const response = await this.client.getPublic<any>(this.client.endpoints.symbols)
-    const data = response?.data ?? response
-    if (!Array.isArray(data)) return data
-    return symbol ? data.find(item => String(item.symbol) === symbol) : data
-  }
-
-  async getOrderBook(params: { symbol: string; aggLevel?: number }) {
-    const url = `${this.client.endpoints.depth}?symbol=${params.symbol}&agg_level=${params.aggLevel ?? 1}`
-    const response = await this.client.getPublic<any>(url)
-    const payload = response?.data ?? response
-    return {
-      symbol: payload?.s,
-      bids: Array.isArray(payload?.l?.[0])
-        ? payload.l[0].map((lvl: any) => ({
-            price: String(lvl?.p ?? ''),
-            amount: String(lvl?.a ?? ''),
-            count: lvl?.n ?? 0,
-          }))
-        : [],
-      asks: Array.isArray(payload?.l?.[1])
-        ? payload.l[1].map((lvl: any) => ({
-            price: String(lvl?.p ?? ''),
-            amount: String(lvl?.a ?? ''),
-            count: lvl?.n ?? 0,
-          }))
-        : [],
-      timestamp: Number(payload?.t ?? Date.now()),
-    }
-  }
-}

+ 0 - 4
src/exchanges/pacifica/types.d.ts

@@ -1,4 +0,0 @@
-declare module 'tweetnacl'
-declare module 'bs58'
-
-

+ 0 - 149
src/exchanges/unifiedEvents.ts

@@ -1,149 +0,0 @@
-// 统一账户类 WS 事件与归一化工具(Aster → Unified)
-
-export interface UnifiedBalanceItem {
-  asset: string // 资产代码,如 USDT
-  total: string // 总额(字符串避免精度问题)
-  free: string // 可用(若无法区分,则等同 total)
-}
-
-export interface UnifiedBalancesEvent {
-  channel: 'account_balance'
-  data: UnifiedBalanceItem[]
-  ts?: number
-}
-
-export interface UnifiedPositionItem {
-  symbol: string // 交易对,如 BTCUSDT
-  side: 'LONG' | 'SHORT' // 方向
-  qty: string // 持仓数量
-  entryPrice?: string // 开仓均价
-  unrealizedPnl?: string // 未实现盈亏
-  leverage?: string // 杠杆(若可用)
-  marginType?: 'cross' | 'isolated' // 保证金模式(若可用)
-}
-
-export interface UnifiedPositionsEvent {
-  channel: 'account_positions'
-  data: UnifiedPositionItem[]
-  ts?: number
-}
-
-export interface UnifiedAccountInfoData {
-  ae?: string // accountEquity
-  mu?: string // marginUsed
-  pc?: number // position count
-  oc?: number // open order count
-  sc?: number // stop count
-  as?: string // assets remark/aggregation
-  aw?: string // alert warning / ratio
-  t: number // timestamp (ms)
-}
-
-export interface UnifiedAccountInfoEvent {
-  channel: 'account_info'
-  data: UnifiedAccountInfoData
-  ts?: number
-}
-
-export interface UnifiedOrderEventData {
-  id: string // 订单 ID
-  symbol: string
-  side: 'BUY' | 'SELL'
-  type: string // MARKET / LIMIT / ...
-  status: string // NEW / FILLED / CANCELED ...
-  price?: string // 报价
-  avgPrice?: string // 成交均价
-  origQty?: string // 原始数量
-  executedQty?: string // 已成交数量
-  updateTime?: number // 更新时间(毫秒)
-  positionSide?: 'LONG' | 'SHORT' | 'BOTH'
-  reduceOnly?: boolean
-  raw?: any // 保留原始字段
-}
-
-export interface UnifiedOrdersEvent {
-  channel: 'orders'
-  data: UnifiedOrderEventData
-  ts?: number
-}
-
-export type UnifiedAccountWsEvent =
-  | UnifiedBalancesEvent
-  | UnifiedPositionsEvent
-  | UnifiedAccountInfoEvent
-  | UnifiedOrdersEvent
-
-// ===== Aster → Unified =====
-
-// Aster balance: 来自 ACCOUNT_UPDATE 的 a.B 项:{ a, wb, cw, bc }
-export function normalizeAsterBalanceEvent(ev: any): UnifiedBalancesEvent {
-  const ts = typeof ev?.ts === 'number' ? ev.ts : typeof ev?.E === 'number' ? ev.E : Date.now()
-  const arr = Array.isArray(ev?.data) ? ev.data : Array.isArray(ev) ? ev : []
-  const items: UnifiedBalanceItem[] = arr.map((b: any) => {
-    const asset = String(b?.a ?? b?.asset ?? '').toUpperCase()
-    const total = String(b?.wb ?? b?.total ?? b?.balance ?? '0')
-    const free = String(b?.cw ?? b?.free ?? total)
-    return { asset, total, free }
-  })
-  return { channel: 'account_balance', data: items, ts }
-}
-
-// Aster positions: 来自 ACCOUNT_UPDATE 的 a.P 项,形如 { s, pa, ep, up, mt, ps }
-export function normalizeAsterPositionsEvent(ev: any): UnifiedPositionsEvent {
-  const ts = typeof ev?.ts === 'number' ? ev.ts : typeof ev?.E === 'number' ? ev.E : Date.now()
-  const arr = Array.isArray(ev?.data) ? ev.data : Array.isArray(ev) ? ev : []
-  const items: UnifiedPositionItem[] = []
-  for (const p of arr) {
-    const symbol = String(p?.s ?? p?.symbol ?? '').toUpperCase()
-    const side = String(p?.ps ?? p?.positionSide ?? '').toUpperCase()
-    if (!symbol) continue
-    if (side !== 'LONG' && side !== 'SHORT') continue // 过滤 BOTH 的记录
-    const qty = String(p?.pa ?? p?.positionAmt ?? p?.qty ?? '0')
-    const entryPrice = p?.ep != null ? String(p.ep) : p?.entryPrice != null ? String(p.entryPrice) : undefined
-    const unrealizedPnl = p?.up != null ? String(p.up) : p?.unrealizedPnl != null ? String(p.unrealizedPnl) : undefined
-    const marginType = p?.mt === 'cross' ? 'cross' : p?.mt === 'isolated' ? 'isolated' : undefined
-    items.push({ symbol, side: side as any, qty, entryPrice, unrealizedPnl, marginType })
-  }
-  return { channel: 'account_positions', data: items, ts }
-}
-
-// Aster account_info: 我们可能只有 pc/t,可按可用字段填充
-export function normalizeAsterAccountInfoEvent(ev: any): UnifiedAccountInfoEvent {
-  const ts = typeof ev?.ts === 'number' ? ev.ts : typeof ev?.E === 'number' ? ev.E : Date.now()
-  const d = ev?.data !== undefined ? ev.data : ev || {}
-  const out: UnifiedAccountInfoData = {
-    ae: d?.ae != null ? String(d.ae) : undefined,
-    mu: d?.mu != null ? String(d.mu) : undefined,
-    pc: d?.pc != null ? Number(d.pc) : undefined,
-    oc: d?.oc != null ? Number(d.oc) : undefined,
-    sc: d?.sc != null ? Number(d.sc) : undefined,
-    as: d?.as != null ? String(d.as) : undefined,
-    aw: d?.aw != null ? String(d.aw) : undefined,
-    t: d?.t != null ? Number(d.t) : ts,
-  }
-  return { channel: 'account_info', data: out, ts }
-}
-
-// Aster orders: 来自 ORDER_TRADE_UPDATE 的 o 字段
-export function normalizeAsterOrdersEvent(ev: any): UnifiedOrdersEvent {
-  const ts = typeof ev?.ts === 'number' ? ev.ts : typeof ev?.E === 'number' ? ev.E : Date.now()
-  const o = ev?.data !== undefined ? ev.data : (ev?.o ?? ev) || {}
-  const data: UnifiedOrderEventData = {
-    id: String(o?.i ?? o?.orderId ?? ''),
-    symbol: String(o?.s ?? o?.symbol ?? '').toUpperCase(),
-    side: (o?.S ?? o?.side ?? '').toUpperCase(),
-    type: o?.o ?? o?.type ?? '',
-    status: o?.X ?? o?.status ?? '',
-    price: o?.p != null ? String(o.p) : o?.price != null ? String(o.price) : undefined,
-    avgPrice: o?.ap != null ? String(o.ap) : o?.avgPrice != null ? String(o.avgPrice) : undefined,
-    origQty: o?.q != null ? String(o.q) : o?.origQty != null ? String(o.origQty) : undefined,
-    executedQty: o?.z != null ? String(o.z) : o?.executedQty != null ? String(o.executedQty) : undefined,
-    updateTime: o?.T != null ? Number(o.T) : o?.updateTime != null ? Number(o.updateTime) : undefined,
-    positionSide: o?.ps as any,
-    reduceOnly: Boolean(o?.R),
-    raw: o,
-  } as UnifiedOrderEventData
-  return { channel: 'orders', data, ts }
-}
-
-

+ 4 - 4
src/main.ts

@@ -16,15 +16,15 @@ import process from 'process'
 
 // 根据环境选择启动方式
 if (process.env.NODE_ENV === 'production') {
-  // 生产环境使用完整的生产入口
-  import('./main-production.js')
+  // 生产环境使用模块化入口
+  import('./main-modular.js')
     .then(module => {
       console.log('🚀 启动生产环境对冲交易系统')
     })
     .catch(console.error)
 } else {
-  // 开发环境使用简化入口
-  import('./core/app.js')
+  // 开发环境也使用模块化入口
+  import('./main-modular.js')
     .then(module => {
       console.log('🔧 启动开发环境对冲交易系统')
     })

+ 0 - 97
src/shared/config/asterConfig.ts

@@ -1,97 +0,0 @@
-import { AsterWsConfig, AsterAuthConfig } from '../adapters/exchanges/aster/types'
-
-export interface AsterConfig {
-  // WebSocket 配置
-  ws: {
-    url: string
-    pingInterval: number
-    pongTimeout: number
-    reconnectInterval: number
-    maxReconnectAttempts: number
-  }
-
-  // HTTP API 配置
-  http: {
-    baseUrl: string
-  }
-
-  // 鉴权配置
-  auth: {
-    user: string
-    signer: string
-    privateKey: string
-  }
-
-  // 订阅配置
-  subscribe: {
-    symbols: string[]
-  }
-
-  // 日志配置
-  log: {
-    level: string
-  }
-}
-
-/**
- * 从环境变量读取 Aster DEX 配置
- */
-export function loadAsterConfig(): AsterConfig {
-  const required = ['ASTER_WS_URL', 'ASTER_ORDER_USER', 'ASTER_ORDER_SIGNER', 'PRIVATE_KEY']
-
-  for (const key of required) {
-    if (!process.env[key]) {
-      throw new Error(`缺少必需的环境变量: ${key}`)
-    }
-  }
-
-  return {
-    ws: {
-      url: process.env.ASTER_WS_URL!,
-      pingInterval: parseInt(process.env.ASTER_WS_PING_INTERVAL || '30000'),
-      pongTimeout: parseInt(process.env.ASTER_WS_PONG_TIMEOUT || '10000'),
-      reconnectInterval: parseInt(process.env.ASTER_WS_RECONNECT_INTERVAL || '5000'),
-      maxReconnectAttempts: parseInt(process.env.ASTER_WS_MAX_RECONNECT_ATTEMPTS || '10'),
-    },
-    http: {
-      baseUrl: process.env.ASTER_HTTP_BASE || 'https://fapi.asterdex.com',
-    },
-    auth: {
-      user: process.env.ASTER_ORDER_USER!,
-      signer: process.env.ASTER_ORDER_SIGNER!,
-      privateKey: process.env.PRIVATE_KEY!,
-    },
-    subscribe: {
-      symbols: (process.env.ASTER_SUBSCRIBE_SYMBOLS || 'BTCUSDT,ETHUSDT').split(',').map(s => s.trim()),
-    },
-    log: {
-      level: process.env.LOG_LEVEL || 'info',
-    },
-  }
-}
-
-/**
- * 转换为 AsterWsConfig
- */
-export function toAsterWsConfig(config: AsterConfig): AsterWsConfig {
-  return {
-    wsUrl: config.ws.url,
-    pingIntervalMs: config.ws.pingInterval,
-    pongTimeoutMs: config.ws.pongTimeout,
-    autoReconnect: true,
-    reconnectIntervalMs: config.ws.reconnectInterval,
-  }
-}
-
-/**
- * 转换为 AsterAuthConfig
- */
-export function toAsterAuthConfig(config: AsterConfig): AsterAuthConfig {
-  return {
-    type: 'signer',
-    user: config.auth.user,
-    signer: config.auth.signer,
-    privateKey: config.auth.privateKey,
-    loginMethod: 'login',
-  }
-}

+ 0 - 210
src/shared/config/controlPlaneConfig.ts

@@ -1,210 +0,0 @@
-import { SimpleEnv, EnvKeys } from './simpleEnv'
-
-/**
- * 多平台 Delta 中性控制平面配置
- * 基于 data-model.md 中的实体定义
- */
-export const ControlPlaneEnvKeys = {
-  // 控制平面基础配置
-  CONTROL_PLANE_ENABLED: 'CONTROL_PLANE_ENABLED',
-  CONTROL_PLANE_MODE: 'CONTROL_PLANE_MODE', // 'production' | 'sandbox' | 'dry-run'
-
-  // Delta 中性配置
-  DELTA_THRESHOLD_BTC: 'DELTA_THRESHOLD_BTC', // 默认 0.0005
-  DELTA_CHECK_INTERVAL_MS: 'DELTA_CHECK_INTERVAL_MS', // 默认 8000
-
-  // 资金利用率配置
-  UTILIZATION_TARGET_MIN: 'UTILIZATION_TARGET_MIN', // 默认 0.5 (50%)
-  UTILIZATION_TARGET_MAX: 'UTILIZATION_TARGET_MAX', // 默认 0.8 (80%)
-  UTILIZATION_CHECK_INTERVAL_MS: 'UTILIZATION_CHECK_INTERVAL_MS', // 默认 8000
-
-  // 行情数据源配置
-  MARKET_DATA_PRIMARY_TIMEOUT_MS: 'MARKET_DATA_PRIMARY_TIMEOUT_MS', // 默认 2000
-  MARKET_DATA_FAILOVER_DEADLINE_MS: 'MARKET_DATA_FAILOVER_DEADLINE_MS', // 默认 10000
-
-  // 风险控制配置
-  MAX_LEVERAGE: 'MAX_LEVERAGE', // 默认 1.0
-  MAX_DRAWDOWN_PERCENT: 'MAX_DRAWDOWN_PERCENT', // 默认 5.0
-  SLIPPAGE_TOLERANCE: 'SLIPPAGE_TOLERANCE', // 默认 0.001 (0.1%)
-  EMERGENCY_STOP_LOSS_SECONDS: 'EMERGENCY_STOP_LOSS_SECONDS', // 默认 30
-
-  // 策略模块配置
-  STRATEGY_MODULE_ENABLED: 'STRATEGY_MODULE_ENABLED',
-  STRATEGY_MODULE_MAX_CONCURRENT: 'STRATEGY_MODULE_MAX_CONCURRENT', // 默认 3
-  STRATEGY_MODULE_PROFIT_TARGET: 'STRATEGY_MODULE_PROFIT_TARGET', // 默认 0.001 (0.1%)
-
-  // 监控与日志配置
-  MONITORING_ENABLED: 'MONITORING_ENABLED',
-  AUDIT_LOG_RETENTION_DAYS: 'AUDIT_LOG_RETENTION_DAYS', // 默认 90
-
-  // 账户同步配置
-  ACCOUNT_SYNC_INTERVAL_MS: 'ACCOUNT_SYNC_INTERVAL_MS', // 默认 30000
-  ACCOUNT_SYNC_TIMEOUT_MS: 'ACCOUNT_SYNC_TIMEOUT_MS', // 默认 10000
-
-  // 对冲执行配置
-  HEDGE_EXECUTION_TIMEOUT_MS: 'HEDGE_EXECUTION_TIMEOUT_MS', // 默认 30000
-  HEDGE_EXECUTION_MAX_RETRIES: 'HEDGE_EXECUTION_MAX_RETRIES', // 默认 3
-} as const
-
-/**
- * 控制平面配置对象
- */
-export const ControlPlaneConfig = {
-  // 基础配置
-  enabled: () => SimpleEnv.bool(ControlPlaneEnvKeys.CONTROL_PLANE_ENABLED, true),
-  mode: () => SimpleEnv.get(ControlPlaneEnvKeys.CONTROL_PLANE_MODE, 'sandbox') as 'production' | 'sandbox' | 'dry-run',
-  isProduction: () => ControlPlaneConfig.mode() === 'production',
-  isSandbox: () => ControlPlaneConfig.mode() === 'sandbox',
-  isDryRun: () => ControlPlaneConfig.mode() === 'dry-run',
-
-  // Delta 中性配置
-  delta: {
-    thresholdBtc: () => SimpleEnv.number(ControlPlaneEnvKeys.DELTA_THRESHOLD_BTC, 0.0005),
-    checkIntervalMs: () => SimpleEnv.number(ControlPlaneEnvKeys.DELTA_CHECK_INTERVAL_MS, 8000),
-    tolerancePercent: () => 0.05, // ±5% 容忍度
-  },
-
-  // 资金利用率配置
-  utilization: {
-    targetMin: () => SimpleEnv.number(ControlPlaneEnvKeys.UTILIZATION_TARGET_MIN, 0.5),
-    targetMax: () => SimpleEnv.number(ControlPlaneEnvKeys.UTILIZATION_TARGET_MAX, 0.8),
-    checkIntervalMs: () => SimpleEnv.number(ControlPlaneEnvKeys.UTILIZATION_CHECK_INTERVAL_MS, 8000),
-    rebalanceThreshold: () => 0.05, // 5% 偏差触发再平衡
-  },
-
-  // 行情数据源配置
-  marketData: {
-    primaryTimeoutMs: () => SimpleEnv.number(ControlPlaneEnvKeys.MARKET_DATA_PRIMARY_TIMEOUT_MS, 2000),
-    failoverDeadlineMs: () => SimpleEnv.number(ControlPlaneEnvKeys.MARKET_DATA_FAILOVER_DEADLINE_MS, 10000),
-    heartbeatIntervalMs: () => 5000,
-    reconnectIntervalMs: () => 5000,
-    maxReconnectAttempts: () => 10,
-  },
-
-  // 风险控制配置
-  risk: {
-    maxLeverage: () => SimpleEnv.number(ControlPlaneEnvKeys.MAX_LEVERAGE, 1.0),
-    maxDrawdownPercent: () => SimpleEnv.number(ControlPlaneEnvKeys.MAX_DRAWDOWN_PERCENT, 5.0),
-    slippageTolerance: () => SimpleEnv.number(ControlPlaneEnvKeys.SLIPPAGE_TOLERANCE, 0.001),
-    emergencyStopLossSeconds: () => SimpleEnv.number(ControlPlaneEnvKeys.EMERGENCY_STOP_LOSS_SECONDS, 30),
-  },
-
-  // 策略模块配置
-  strategy: {
-    enabled: () => SimpleEnv.bool(ControlPlaneEnvKeys.STRATEGY_MODULE_ENABLED, true),
-    maxConcurrent: () => SimpleEnv.number(ControlPlaneEnvKeys.STRATEGY_MODULE_MAX_CONCURRENT, 3),
-    profitTarget: () => SimpleEnv.number(ControlPlaneEnvKeys.STRATEGY_MODULE_PROFIT_TARGET, 0.001),
-    sandboxEnabled: () => ControlPlaneConfig.isSandbox() || ControlPlaneConfig.isDryRun(),
-  },
-
-  // 监控与日志配置
-  monitoring: {
-    enabled: () => SimpleEnv.bool(ControlPlaneEnvKeys.MONITORING_ENABLED, true),
-    auditLogRetentionDays: () => SimpleEnv.number(ControlPlaneEnvKeys.AUDIT_LOG_RETENTION_DAYS, 90),
-    healthCheckIntervalMs: () => 10000,
-    metricsIntervalMs: () => 5000,
-  },
-
-  // 账户同步配置
-  accountSync: {
-    intervalMs: () => SimpleEnv.number(ControlPlaneEnvKeys.ACCOUNT_SYNC_INTERVAL_MS, 30000),
-    timeoutMs: () => SimpleEnv.number(ControlPlaneEnvKeys.ACCOUNT_SYNC_TIMEOUT_MS, 10000),
-    maxConcurrent: () => 3,
-    retryAttempts: () => 3,
-  },
-
-  // 对冲执行配置
-  hedgeExecution: {
-    timeoutMs: () => SimpleEnv.number(ControlPlaneEnvKeys.HEDGE_EXECUTION_TIMEOUT_MS, 30000),
-    maxRetries: () => SimpleEnv.number(ControlPlaneEnvKeys.HEDGE_EXECUTION_MAX_RETRIES, 3),
-    parallelExecution: () => true,
-    circuitBreakerThreshold: () => 5, // 连续失败5次触发熔断
-  },
-
-  // 获取完整配置(用于调试和验证)
-  getAll: () => ({
-    enabled: ControlPlaneConfig.enabled(),
-    mode: ControlPlaneConfig.mode(),
-    delta: {
-      thresholdBtc: ControlPlaneConfig.delta.thresholdBtc(),
-      checkIntervalMs: ControlPlaneConfig.delta.checkIntervalMs(),
-      tolerancePercent: ControlPlaneConfig.delta.tolerancePercent(),
-    },
-    utilization: {
-      targetMin: ControlPlaneConfig.utilization.targetMin(),
-      targetMax: ControlPlaneConfig.utilization.targetMax(),
-      checkIntervalMs: ControlPlaneConfig.utilization.checkIntervalMs(),
-      rebalanceThreshold: ControlPlaneConfig.utilization.rebalanceThreshold(),
-    },
-    marketData: {
-      primaryTimeoutMs: ControlPlaneConfig.marketData.primaryTimeoutMs(),
-      failoverDeadlineMs: ControlPlaneConfig.marketData.failoverDeadlineMs(),
-      heartbeatIntervalMs: ControlPlaneConfig.marketData.heartbeatIntervalMs(),
-    },
-    risk: {
-      maxLeverage: ControlPlaneConfig.risk.maxLeverage(),
-      maxDrawdownPercent: ControlPlaneConfig.risk.maxDrawdownPercent(),
-      slippageTolerance: ControlPlaneConfig.risk.slippageTolerance(),
-      emergencyStopLossSeconds: ControlPlaneConfig.risk.emergencyStopLossSeconds(),
-    },
-    strategy: {
-      enabled: ControlPlaneConfig.strategy.enabled(),
-      maxConcurrent: ControlPlaneConfig.strategy.maxConcurrent(),
-      profitTarget: ControlPlaneConfig.strategy.profitTarget(),
-      sandboxEnabled: ControlPlaneConfig.strategy.sandboxEnabled(),
-    },
-    monitoring: {
-      enabled: ControlPlaneConfig.monitoring.enabled(),
-      auditLogRetentionDays: ControlPlaneConfig.monitoring.auditLogRetentionDays(),
-    },
-    accountSync: {
-      intervalMs: ControlPlaneConfig.accountSync.intervalMs(),
-      timeoutMs: ControlPlaneConfig.accountSync.timeoutMs(),
-    },
-    hedgeExecution: {
-      timeoutMs: ControlPlaneConfig.hedgeExecution.timeoutMs(),
-      maxRetries: ControlPlaneConfig.hedgeExecution.maxRetries(),
-    },
-  }),
-
-  // 验证配置完整性
-  validate: (): { isValid: boolean; errors: string[] } => {
-    const errors: string[] = []
-
-    // 验证 Delta 配置
-    if (ControlPlaneConfig.delta.thresholdBtc() <= 0) {
-      errors.push('DELTA_THRESHOLD_BTC must be positive')
-    }
-
-    // 验证利用率配置
-    const minUtil = ControlPlaneConfig.utilization.targetMin()
-    const maxUtil = ControlPlaneConfig.utilization.targetMax()
-    if (minUtil >= maxUtil) {
-      errors.push('UTILIZATION_TARGET_MIN must be less than UTILIZATION_TARGET_MAX')
-    }
-    if (minUtil < 0 || minUtil > 1) {
-      errors.push('UTILIZATION_TARGET_MIN must be between 0 and 1')
-    }
-    if (maxUtil < 0 || maxUtil > 1) {
-      errors.push('UTILIZATION_TARGET_MAX must be between 0 and 1')
-    }
-
-    // 验证行情配置
-    if (ControlPlaneConfig.marketData.failoverDeadlineMs() <= ControlPlaneConfig.marketData.primaryTimeoutMs()) {
-      errors.push('MARKET_DATA_FAILOVER_DEADLINE_MS must be greater than MARKET_DATA_PRIMARY_TIMEOUT_MS')
-    }
-
-    // 验证风险配置
-    if (ControlPlaneConfig.risk.maxLeverage() <= 0) {
-      errors.push('MAX_LEVERAGE must be positive')
-    }
-    if (ControlPlaneConfig.risk.maxDrawdownPercent() <= 0 || ControlPlaneConfig.risk.maxDrawdownPercent() > 100) {
-      errors.push('MAX_DRAWDOWN_PERCENT must be between 0 and 100')
-    }
-
-    return {
-      isValid: errors.length === 0,
-      errors,
-    }
-  },
-}

+ 0 - 272
src/shared/config/riskTemplates.ts

@@ -1,272 +0,0 @@
-import { ControlPlaneConfig } from './controlPlaneConfig'
-
-/**
- * 风险包络配置模板
- * 基于 data-model.md 中的 RiskEnvelope 实体定义
- */
-
-export interface RiskEnvelopeTemplate {
-  templateId: string
-  name: string
-  description: string
-  maxDrawdownPercent: number
-  maxLeverage: number
-  deltaThreshold: number
-  slippageTolerance: number
-  emergencyStopLossSeconds: number
-  maxPositionValue: number
-  maxDailyLoss: number
-  maxConcurrentOrders: number
-  allowedExchanges: string[]
-  allowedSymbols: string[]
-  riskLevel: 'conservative' | 'moderate' | 'aggressive'
-  applicableAccountTypes: ('primary' | 'hedge' | 'backup')[]
-}
-
-/**
- * 预定义的风险包络模板
- */
-export const RiskEnvelopeTemplates: Record<string, RiskEnvelopeTemplate> = {
-  // 保守型配置 - 适合主要交易账户
-  CONSERVATIVE_PRIMARY: {
-    templateId: 'CONSERVATIVE_PRIMARY',
-    name: '保守型主要账户',
-    description: '低风险、低杠杆,适合主要交易账户的保守配置',
-    maxDrawdownPercent: 2.0,
-    maxLeverage: 1.0,
-    deltaThreshold: 0.0002, // ±0.0002 BTC
-    slippageTolerance: 0.0005, // 0.05%
-    emergencyStopLossSeconds: 15,
-    maxPositionValue: 1000, // $1000
-    maxDailyLoss: 50, // $50
-    maxConcurrentOrders: 2,
-    allowedExchanges: ['pacifica', 'aster'],
-    allowedSymbols: ['BTC', 'ETH'],
-    riskLevel: 'conservative',
-    applicableAccountTypes: ['primary'],
-  },
-
-  // 中等风险配置 - 适合对冲账户
-  MODERATE_HEDGE: {
-    templateId: 'MODERATE_HEDGE',
-    name: '中等风险对冲账户',
-    description: '中等风险,适合对冲操作的账户配置',
-    maxDrawdownPercent: 5.0,
-    maxLeverage: 2.0,
-    deltaThreshold: 0.0005, // ±0.0005 BTC
-    slippageTolerance: 0.001, // 0.1%
-    emergencyStopLossSeconds: 30,
-    maxPositionValue: 5000, // $5000
-    maxDailyLoss: 200, // $200
-    maxConcurrentOrders: 5,
-    allowedExchanges: ['pacifica', 'aster', 'binance'],
-    allowedSymbols: ['BTC', 'ETH', 'SOL'],
-    riskLevel: 'moderate',
-    applicableAccountTypes: ['hedge'],
-  },
-
-  // 激进型配置 - 适合备用账户
-  AGGRESSIVE_BACKUP: {
-    templateId: 'AGGRESSIVE_BACKUP',
-    name: '激进型备用账户',
-    description: '高风险、高杠杆,适合备用账户的激进配置',
-    maxDrawdownPercent: 10.0,
-    maxLeverage: 5.0,
-    deltaThreshold: 0.001, // ±0.001 BTC
-    slippageTolerance: 0.002, // 0.2%
-    emergencyStopLossSeconds: 60,
-    maxPositionValue: 10000, // $10000
-    maxDailyLoss: 500, // $500
-    maxConcurrentOrders: 10,
-    allowedExchanges: ['pacifica', 'aster', 'binance'],
-    allowedSymbols: ['BTC', 'ETH', 'SOL', 'ADA', 'DOT'],
-    riskLevel: 'aggressive',
-    applicableAccountTypes: ['backup'],
-  },
-
-  // 测试配置 - 适合沙箱环境
-  TEST_SANDBOX: {
-    templateId: 'TEST_SANDBOX',
-    name: '测试沙箱配置',
-    description: '用于测试和开发的沙箱环境配置',
-    maxDrawdownPercent: 50.0,
-    maxLeverage: 10.0,
-    deltaThreshold: 0.01, // ±0.01 BTC
-    slippageTolerance: 0.005, // 0.5%
-    emergencyStopLossSeconds: 120,
-    maxPositionValue: 100, // $100
-    maxDailyLoss: 10, // $10
-    maxConcurrentOrders: 20,
-    allowedExchanges: ['pacifica', 'aster', 'binance'],
-    allowedSymbols: ['BTC', 'ETH', 'SOL', 'ADA', 'DOT', 'MATIC', 'AVAX'],
-    riskLevel: 'conservative',
-    applicableAccountTypes: ['primary', 'hedge', 'backup'],
-  },
-
-  // 自定义配置 - 基于全局配置
-  CUSTOM_GLOBAL: {
-    templateId: 'CUSTOM_GLOBAL',
-    name: '自定义全局配置',
-    description: '基于控制平面全局配置的自定义风险包络',
-    maxDrawdownPercent: ControlPlaneConfig.risk.maxDrawdownPercent(),
-    maxLeverage: ControlPlaneConfig.risk.maxLeverage(),
-    deltaThreshold: ControlPlaneConfig.delta.thresholdBtc(),
-    slippageTolerance: ControlPlaneConfig.risk.slippageTolerance(),
-    emergencyStopLossSeconds: ControlPlaneConfig.risk.emergencyStopLossSeconds(),
-    maxPositionValue: 10000, // 默认值
-    maxDailyLoss: 500, // 默认值
-    maxConcurrentOrders: 5, // 默认值
-    allowedExchanges: ['pacifica', 'aster', 'binance'],
-    allowedSymbols: ['BTC', 'ETH', 'SOL'],
-    riskLevel: 'moderate',
-    applicableAccountTypes: ['primary', 'hedge', 'backup'],
-  },
-}
-
-/**
- * 风险包络管理器
- */
-export class RiskEnvelopeManager {
-  /**
-   * 根据账户类型和风险偏好获取合适的模板
-   */
-  static getTemplate(
-    accountType: 'primary' | 'hedge' | 'backup',
-    riskPreference?: 'conservative' | 'moderate' | 'aggressive',
-  ): RiskEnvelopeTemplate {
-    // 如果是沙箱模式,使用测试配置
-    if (ControlPlaneConfig.isSandbox() || ControlPlaneConfig.isDryRun()) {
-      return RiskEnvelopeTemplates.TEST_SANDBOX
-    }
-
-    // 根据账户类型选择默认模板
-    switch (accountType) {
-      case 'primary':
-        return riskPreference === 'aggressive'
-          ? RiskEnvelopeTemplates.MODERATE_HEDGE
-          : RiskEnvelopeTemplates.CONSERVATIVE_PRIMARY
-      case 'hedge':
-        return riskPreference === 'conservative'
-          ? RiskEnvelopeTemplates.CONSERVATIVE_PRIMARY
-          : RiskEnvelopeTemplates.MODERATE_HEDGE
-      case 'backup':
-        return riskPreference === 'conservative'
-          ? RiskEnvelopeTemplates.MODERATE_HEDGE
-          : RiskEnvelopeTemplates.AGGRESSIVE_BACKUP
-      default:
-        return RiskEnvelopeTemplates.CUSTOM_GLOBAL
-    }
-  }
-
-  /**
-   * 创建自定义风险包络
-   */
-  static createCustom(baseTemplate: string, overrides: Partial<RiskEnvelopeTemplate>): RiskEnvelopeTemplate {
-    const template = RiskEnvelopeTemplates[baseTemplate]
-    if (!template) {
-      throw new Error(`Template ${baseTemplate} not found`)
-    }
-
-    return {
-      ...template,
-      ...overrides,
-      templateId: `${baseTemplate}_CUSTOM_${Date.now()}`,
-      name: overrides.name || `${template.name} (自定义)`,
-    }
-  }
-
-  /**
-   * 验证风险包络配置
-   */
-  static validate(template: RiskEnvelopeTemplate): { isValid: boolean; errors: string[] } {
-    const errors: string[] = []
-
-    // 验证数值范围
-    if (template.maxDrawdownPercent <= 0 || template.maxDrawdownPercent > 100) {
-      errors.push('maxDrawdownPercent must be between 0 and 100')
-    }
-
-    if (template.maxLeverage <= 0) {
-      errors.push('maxLeverage must be positive')
-    }
-
-    if (template.deltaThreshold <= 0) {
-      errors.push('deltaThreshold must be positive')
-    }
-
-    if (template.slippageTolerance <= 0 || template.slippageTolerance > 1) {
-      errors.push('slippageTolerance must be between 0 and 1')
-    }
-
-    if (template.emergencyStopLossSeconds <= 0) {
-      errors.push('emergencyStopLossSeconds must be positive')
-    }
-
-    if (template.maxPositionValue <= 0) {
-      errors.push('maxPositionValue must be positive')
-    }
-
-    if (template.maxDailyLoss <= 0) {
-      errors.push('maxDailyLoss must be positive')
-    }
-
-    if (template.maxConcurrentOrders <= 0) {
-      errors.push('maxConcurrentOrders must be positive')
-    }
-
-    // 验证数组内容
-    if (template.allowedExchanges.length === 0) {
-      errors.push('allowedExchanges cannot be empty')
-    }
-
-    if (template.allowedSymbols.length === 0) {
-      errors.push('allowedSymbols cannot be empty')
-    }
-
-    if (template.applicableAccountTypes.length === 0) {
-      errors.push('applicableAccountTypes cannot be empty')
-    }
-
-    // 验证风险等级一致性
-    const riskLevelThresholds = {
-      conservative: { maxDrawdown: 5, maxLeverage: 2 },
-      moderate: { maxDrawdown: 10, maxLeverage: 5 },
-      aggressive: { maxDrawdown: 20, maxLeverage: 10 },
-    }
-
-    const threshold = riskLevelThresholds[template.riskLevel]
-    if (template.maxDrawdownPercent > threshold.maxDrawdown) {
-      errors.push(`${template.riskLevel} risk level should have maxDrawdownPercent <= ${threshold.maxDrawdown}`)
-    }
-
-    if (template.maxLeverage > threshold.maxLeverage) {
-      errors.push(`${template.riskLevel} risk level should have maxLeverage <= ${threshold.maxLeverage}`)
-    }
-
-    return {
-      isValid: errors.length === 0,
-      errors,
-    }
-  }
-
-  /**
-   * 获取所有可用模板
-   */
-  static getAllTemplates(): RiskEnvelopeTemplate[] {
-    return Object.values(RiskEnvelopeTemplates)
-  }
-
-  /**
-   * 根据风险等级筛选模板
-   */
-  static getTemplatesByRiskLevel(riskLevel: 'conservative' | 'moderate' | 'aggressive'): RiskEnvelopeTemplate[] {
-    return this.getAllTemplates().filter(template => template.riskLevel === riskLevel)
-  }
-
-  /**
-   * 根据账户类型筛选模板
-   */
-  static getTemplatesByAccountType(accountType: 'primary' | 'hedge' | 'backup'): RiskEnvelopeTemplate[] {
-    return this.getAllTemplates().filter(template => template.applicableAccountTypes.includes(accountType))
-  }
-}

+ 0 - 657
src/shared/config/simpleEnv.ts

@@ -1,657 +0,0 @@
-import 'dotenv/config'
-
-/**
- * 简化的环境变量管理器
- * 统一处理所有环境变量读取,避免重复的 process.env 调用
- */
-export class SimpleEnv {
-  private static cache = new Map<string, string | undefined>()
-
-  /**
-   * 获取环境变量值
-   */
-  static get(key: string, defaultValue?: string): string | undefined {
-    if (this.cache.has(key)) {
-      return this.cache.get(key)
-    }
-
-    const value = process.env[key] || defaultValue
-    this.cache.set(key, value)
-    return value
-  }
-
-  /**
-   * 获取必需的环境变量值,如果不存在则抛出错误
-   */
-  static require(key: string): string {
-    const value = this.get(key)
-    if (!value) {
-      throw new Error(`Required environment variable ${key} is not set`)
-    }
-    return value
-  }
-
-  /**
-   * 获取布尔值环境变量
-   */
-  static bool(key: string, defaultValue: boolean = false): boolean {
-    const value = this.get(key)
-    if (!value) return defaultValue
-    return ['true', '1', 'yes', 'on'].includes(value.toLowerCase())
-  }
-
-  /**
-   * 获取数字环境变量
-   */
-  static number(key: string, defaultValue?: number): number | undefined {
-    const value = this.get(key)
-    if (!value) return defaultValue
-    const num = parseInt(value, 10)
-    return isNaN(num) ? defaultValue : num
-  }
-
-  /**
-   * 获取 JSON 环境变量
-   */
-  static json<T = any>(key: string, defaultValue?: T): T | undefined {
-    const value = this.get(key)
-    if (!value) return defaultValue
-    try {
-      return JSON.parse(value)
-    } catch {
-      return defaultValue
-    }
-  }
-
-  /**
-   * 获取数组环境变量(逗号分隔)
-   */
-  static array(key: string, defaultValue: string[] = []): string[] {
-    const value = this.get(key)
-    if (!value) return defaultValue
-    return value
-      .split(',')
-      .map(s => s.trim())
-      .filter(s => s.length > 0)
-  }
-
-  /**
-   * 清除缓存
-   */
-  static clearCache(): void {
-    this.cache.clear()
-  }
-
-  /**
-   * 批量获取带前缀的环境变量
-   */
-  static getPrefix(prefix: string): Record<string, string> {
-    const result: Record<string, string> = {}
-
-    Object.keys(process.env).forEach(key => {
-      if (key.startsWith(prefix)) {
-        const shortKey = key.slice(prefix.length)
-        const value = process.env[key]
-        if (value) {
-          result[shortKey] = value
-        }
-      }
-    })
-
-    return result
-  }
-}
-
-/**
- * 预定义的配置键,只包含需要从环境变量读取的配置
- */
-export const EnvKeys = {
-  // 基础配置 (可选,有默认值)
-  NODE_ENV: 'NODE_ENV',
-  LOG_LEVEL: 'LOG_LEVEL',
-
-  // Aster DEX 认证 (必需)
-  ASTER_ORDER_USER: 'ASTER_ORDER_USER',
-  ASTER_API_KEY: 'ASTER_API_KEY',
-  ASTER_API_SECRET: 'ASTER_API_SECRET',
-
-  // Aster 第二账户 (可选)
-  ASTER2_ORDER_USER: 'ASTER2_ORDER_USER',
-  ASTER2_ORDER_SIGNER: 'ASTER2_ORDER_SIGNER',
-  PRIVATE_KEY2: 'PRIVATE_KEY2',
-
-  // Pacifica DEX 认证 (必需)
-  PACIFICA_ACCOUNT: 'PACIFICA_ACCOUNT',
-  PACIFICA_ACCOUNT_PRIVATE_KEY: 'PACIFICA_ACCOUNT_PRIVATE_KEY',
-
-  // 测试配置 (可选)
-  PACIFICA_ENABLE_TEST_ORDER: 'PACIFICA_ENABLE_TEST_ORDER',
-  PACIFICA_TEST_QTY: 'PACIFICA_TEST_QTY',
-
-  // Binance (可选)
-  BINANCE_API_KEY: 'BINANCE_API_KEY',
-  BINANCE_SECRET_KEY: 'BINANCE_SECRET_KEY',
-
-  // Proxy 配置 (可选)
-  PROXY_ENABLED: 'PROXY_ENABLED',
-  PROXY_PROTOCOL: 'PROXY_PROTOCOL',
-  PROXY_HOST: 'PROXY_HOST',
-  PROXY_PORT: 'PROXY_PORT',
-  PROXY_USERNAME: 'PROXY_USERNAME',
-  PROXY_PASSWORD: 'PROXY_PASSWORD',
-
-  // 高级代理配置 (会话管理)
-  PROXY_SESSION_PREFIX: 'PROXY_SESSION_PREFIX',
-  PROXY_SESSION_SUFFIX: 'PROXY_SESSION_SUFFIX',
-  PROXY_SESSION_STATIC: 'PROXY_SESSION_STATIC',
-
-  // 交易所专用代理 (可选,优先级高于全局代理)
-  ASTER_PROXY_PROTOCOL: 'ASTER_PROXY_PROTOCOL',
-  ASTER_PROXY_HOST: 'ASTER_PROXY_HOST',
-  ASTER_PROXY_PORT: 'ASTER_PROXY_PORT',
-  ASTER_PROXY_USER: 'ASTER_PROXY_USER',
-  ASTER_PROXY_PASS: 'ASTER_PROXY_PASS',
-  ASTER_PROXY_SESSION_PREFIX: 'ASTER_PROXY_SESSION_PREFIX',
-  ASTER_PROXY_SESSION_SUFFIX: 'ASTER_PROXY_SESSION_SUFFIX',
-  ASTER_PROXY_SESSION_STATIC: 'ASTER_PROXY_SESSION_STATIC',
-
-  // Pacifica专用代理
-  PACIFICA_PROXY_PROTOCOL: 'PACIFICA_PROXY_PROTOCOL',
-  PACIFICA_PROXY_HOST: 'PACIFICA_PROXY_HOST',
-  PACIFICA_PROXY_PORT: 'PACIFICA_PROXY_PORT',
-  PACIFICA_PROXY_USER: 'PACIFICA_PROXY_USER',
-  PACIFICA_PROXY_PASS: 'PACIFICA_PROXY_PASS',
-  PACIFICA_PROXY_SESSION_PREFIX: 'PACIFICA_PROXY_SESSION_PREFIX',
-  PACIFICA_PROXY_SESSION_SUFFIX: 'PACIFICA_PROXY_SESSION_SUFFIX',
-  PACIFICA_PROXY_SESSION_STATIC: 'PACIFICA_PROXY_SESSION_STATIC',
-
-  // Binance专用代理
-  BINANCE_PROXY_PROTOCOL: 'BINANCE_PROXY_PROTOCOL',
-  BINANCE_PROXY_HOST: 'BINANCE_PROXY_HOST',
-  BINANCE_PROXY_PORT: 'BINANCE_PROXY_PORT',
-  BINANCE_PROXY_USER: 'BINANCE_PROXY_USER',
-  BINANCE_PROXY_PASS: 'BINANCE_PROXY_PASS',
-  BINANCE_PROXY_SESSION_PREFIX: 'BINANCE_PROXY_SESSION_PREFIX',
-  BINANCE_PROXY_SESSION_SUFFIX: 'BINANCE_PROXY_SESSION_SUFFIX',
-  BINANCE_PROXY_SESSION_STATIC: 'BINANCE_PROXY_SESSION_STATIC',
-} as const
-
-/**
- * 统一的配置对象 - 将固定配置写死,只有认证信息从环境变量读取
- */
-export const Config = {
-  // 基础配置
-  nodeEnv: () => SimpleEnv.get(EnvKeys.NODE_ENV, 'development'),
-  logLevel: () => SimpleEnv.get(EnvKeys.LOG_LEVEL, 'info'),
-  isDev: () => Config.nodeEnv() === 'development',
-  isProd: () => Config.nodeEnv() === 'production',
-
-  // Aster 配置 - 固定的服务端点,只有认证信息动态
-  aster: {
-    // 固定配置 - 不从环境变量读取
-    wsUrl: 'wss://fstream.asterdex.com',
-    httpBase: 'https://fapi.asterdex.com',
-    subscribeSymbols: ['BTCUSDT', 'ETHUSDT'], // 默认订阅交易对
-    wsPingInterval: 30000,
-    wsPongTimeout: 10000,
-    wsReconnectInterval: 5000,
-    wsMaxReconnectAttempts: 10,
-    recvWindow: 50000,
-
-    // 动态配置 - 从环境变量读取
-    orderUser: () => SimpleEnv.get(EnvKeys.ASTER_ORDER_USER),
-    apiKey: () => SimpleEnv.get(EnvKeys.ASTER_API_KEY),
-    apiSecret: () => SimpleEnv.get(EnvKeys.ASTER_API_SECRET),
-
-    // 第二账户
-    orderUser2: () => SimpleEnv.get(EnvKeys.ASTER2_ORDER_USER),
-    orderSigner2: () => SimpleEnv.get(EnvKeys.ASTER2_ORDER_SIGNER),
-    privateKey2: () => SimpleEnv.get(EnvKeys.PRIVATE_KEY2),
-  },
-
-  // Pacifica 配置 - 固定的服务端点,只有认证信息动态
-  pacifica: {
-    // 固定配置 - 不从环境变量读取
-    baseUrl: 'https://api.pacifica.fi',
-    wsUrl: 'wss://ws.pacifica.fi/ws',
-    symbol: 'BTC-USD', // 默认交易对
-    defaultQty: 0.001, // 默认交易数量
-
-    // 动态配置 - 从环境变量读取
-    account: () => SimpleEnv.get(EnvKeys.PACIFICA_ACCOUNT),
-    accountPrivateKey: () => SimpleEnv.get(EnvKeys.PACIFICA_ACCOUNT_PRIVATE_KEY),
-    enableTestOrder: () => SimpleEnv.bool(EnvKeys.PACIFICA_ENABLE_TEST_ORDER, false),
-    testQty: () => SimpleEnv.number(EnvKeys.PACIFICA_TEST_QTY, 0.001),
-  },
-
-  // Binance 配置 - 只有认证信息
-  binance: {
-    // 固定配置
-    baseUrl: 'https://api.binance.com',
-    wsUrl: 'wss://stream.binance.com:9443/ws',
-
-    // 动态配置
-    apiKey: () => SimpleEnv.get(EnvKeys.BINANCE_API_KEY),
-    secretKey: () => SimpleEnv.get(EnvKeys.BINANCE_SECRET_KEY),
-  },
-
-  // Proxy 配置 - 支持全局和交易所专用代理
-  proxy: {
-    // 全局代理配置
-    enabled: () => SimpleEnv.bool(EnvKeys.PROXY_ENABLED, false),
-    protocol: () => SimpleEnv.get(EnvKeys.PROXY_PROTOCOL, 'http'),
-    host: () => SimpleEnv.get(EnvKeys.PROXY_HOST),
-    port: () => SimpleEnv.number(EnvKeys.PROXY_PORT, 8080),
-    username: () => SimpleEnv.get(EnvKeys.PROXY_USERNAME),
-    password: () => SimpleEnv.get(EnvKeys.PROXY_PASSWORD),
-
-    // 会话管理 (高级功能)
-    sessionPrefix: () => SimpleEnv.get(EnvKeys.PROXY_SESSION_PREFIX),
-    sessionSuffix: () => SimpleEnv.get(EnvKeys.PROXY_SESSION_SUFFIX),
-    sessionStatic: () => SimpleEnv.get(EnvKeys.PROXY_SESSION_STATIC),
-
-    // 交易所专用代理配置
-    aster: {
-      protocol: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_PROTOCOL, 'http'),
-      host: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_HOST),
-      port: () => SimpleEnv.number(EnvKeys.ASTER_PROXY_PORT, 12321),
-      user: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_USER),
-      pass: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_PASS),
-      sessionPrefix: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_SESSION_PREFIX),
-      sessionSuffix: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_SESSION_SUFFIX),
-      sessionStatic: () => SimpleEnv.get(EnvKeys.ASTER_PROXY_SESSION_STATIC),
-
-      isConfigured: (): boolean => {
-        return !!Config.proxy.aster.host() && !!Config.proxy.aster.user()
-      },
-    },
-
-    pacifica: {
-      protocol: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_PROTOCOL, 'http'),
-      host: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_HOST),
-      port: () => SimpleEnv.number(EnvKeys.PACIFICA_PROXY_PORT, 8080),
-      user: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_USER),
-      pass: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_PASS),
-      sessionPrefix: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_SESSION_PREFIX),
-      sessionSuffix: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_SESSION_SUFFIX),
-      sessionStatic: () => SimpleEnv.get(EnvKeys.PACIFICA_PROXY_SESSION_STATIC),
-
-      isConfigured: (): boolean => {
-        return !!Config.proxy.pacifica.host() && !!Config.proxy.pacifica.user()
-      },
-    },
-
-    binance: {
-      protocol: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_PROTOCOL, 'http'),
-      host: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_HOST),
-      port: () => SimpleEnv.number(EnvKeys.BINANCE_PROXY_PORT, 8080),
-      user: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_USER),
-      pass: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_PASS),
-      sessionPrefix: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_SESSION_PREFIX),
-      sessionSuffix: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_SESSION_SUFFIX),
-      sessionStatic: () => SimpleEnv.get(EnvKeys.BINANCE_PROXY_SESSION_STATIC),
-
-      isConfigured: (): boolean => {
-        return !!Config.proxy.binance.host() && !!Config.proxy.binance.user()
-      },
-    },
-
-    // 生成随机会话ID (8位字符)
-    generateSessionId: (): string => {
-      const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
-      let result = ''
-      for (let i = 0; i < 8; i++) {
-        result += chars.charAt(Math.floor(Math.random() * chars.length))
-      }
-      return result
-    },
-
-    // 构建代理密码 (支持会话管理)
-    buildPassword: (exchange?: 'aster' | 'pacifica' | 'binance'): string | undefined => {
-      let config: any
-
-      // 优先使用交易所专用配置
-      if (exchange === 'aster' && Config.proxy.aster.isConfigured()) {
-        config = {
-          pass: Config.proxy.aster.pass(),
-          prefix: Config.proxy.aster.sessionPrefix(),
-          suffix: Config.proxy.aster.sessionSuffix(),
-          static: Config.proxy.aster.sessionStatic(),
-        }
-      } else if (exchange === 'pacifica' && Config.proxy.pacifica.isConfigured()) {
-        config = {
-          pass: Config.proxy.pacifica.pass(),
-          prefix: Config.proxy.pacifica.sessionPrefix(),
-          suffix: Config.proxy.pacifica.sessionSuffix(),
-          static: Config.proxy.pacifica.sessionStatic(),
-        }
-      } else if (exchange === 'binance' && Config.proxy.binance.isConfigured()) {
-        config = {
-          pass: Config.proxy.binance.pass(),
-          prefix: Config.proxy.binance.sessionPrefix(),
-          suffix: Config.proxy.binance.sessionSuffix(),
-          static: Config.proxy.binance.sessionStatic(),
-        }
-      } else {
-        // 使用全局配置,如果没有则尝试使用ASTER配置作为回退
-        config = {
-          pass: Config.proxy.password() || Config.proxy.aster.pass(),
-          prefix: Config.proxy.sessionPrefix() || Config.proxy.aster.sessionPrefix(),
-          suffix: Config.proxy.sessionSuffix() || Config.proxy.aster.sessionSuffix(),
-          static: Config.proxy.sessionStatic() || Config.proxy.aster.sessionStatic(),
-        }
-      }
-
-      // 方式一:直接使用完整密码
-      if (config.pass) {
-        return config.pass
-      }
-
-      // 方式二:使用前后缀+会话ID
-      if (config.prefix && config.suffix) {
-        const sessionId = config.static || Config.proxy.generateSessionId()
-        return `${config.prefix}${sessionId}${config.suffix}`
-      }
-
-      return undefined
-    },
-
-    // 获取代理URL (支持交易所专用配置)
-    getUrl: (exchange?: 'aster' | 'pacifica' | 'binance'): string | undefined => {
-      let proxyConfig: any
-
-      // 优先使用交易所专用代理
-      if (exchange === 'aster' && Config.proxy.aster.isConfigured()) {
-        proxyConfig = {
-          protocol: Config.proxy.aster.protocol(),
-          host: Config.proxy.aster.host(),
-          port: Config.proxy.aster.port(),
-          username: Config.proxy.aster.user(),
-          password: Config.proxy.buildPassword('aster'),
-        }
-      } else if (exchange === 'pacifica' && Config.proxy.pacifica.isConfigured()) {
-        proxyConfig = {
-          protocol: Config.proxy.pacifica.protocol(),
-          host: Config.proxy.pacifica.host(),
-          port: Config.proxy.pacifica.port(),
-          username: Config.proxy.pacifica.user(),
-          password: Config.proxy.buildPassword('pacifica'),
-        }
-      } else if (exchange === 'binance' && Config.proxy.binance.isConfigured()) {
-        proxyConfig = {
-          protocol: Config.proxy.binance.protocol(),
-          host: Config.proxy.binance.host(),
-          port: Config.proxy.binance.port(),
-          username: Config.proxy.binance.user(),
-          password: Config.proxy.buildPassword('binance'),
-        }
-      } else if (Config.proxy.enabled() && Config.proxy.host()) {
-        // 全局代理
-        proxyConfig = {
-          protocol: Config.proxy.protocol(),
-          host: Config.proxy.host(),
-          port: Config.proxy.port(),
-          username: Config.proxy.username() || Config.proxy.aster.user(),
-          password: Config.proxy.buildPassword(),
-        }
-      } else if (Config.proxy.aster.isConfigured()) {
-        // 回退使用ASTER代理配置作为全局代理
-        proxyConfig = {
-          protocol: Config.proxy.aster.protocol(),
-          host: Config.proxy.aster.host(),
-          port: Config.proxy.aster.port(),
-          username: Config.proxy.aster.user(),
-          password: Config.proxy.buildPassword(),
-        }
-      } else {
-        return undefined
-      }
-
-      const { protocol, host, port, username, password } = proxyConfig
-
-      if (username && password) {
-        return `${protocol}://${username}:${password}@${host}:${port}`
-      } else {
-        return `${protocol}://${host}:${port}`
-      }
-    },
-
-    // 检查代理是否配置 (全局或交易所专用)
-    isConfigured: (exchange?: 'aster' | 'pacifica' | 'binance'): boolean => {
-      if (exchange === 'aster') {
-        return Config.proxy.aster.isConfigured()
-      } else if (exchange === 'pacifica') {
-        return Config.proxy.pacifica.isConfigured()
-      } else if (exchange === 'binance') {
-        return Config.proxy.binance.isConfigured()
-      }
-      return Config.proxy.enabled() && !!Config.proxy.host()
-    },
-
-    // 检查任何代理是否配置
-    isAnyConfigured: (): boolean => {
-      return (
-        Config.proxy.isConfigured() ||
-        Config.proxy.aster.isConfigured() ||
-        Config.proxy.pacifica.isConfigured() ||
-        Config.proxy.binance.isConfigured()
-      )
-    },
-  },
-
-  // 获取所有配置(用于调试)
-  getAll: () => ({
-    nodeEnv: Config.nodeEnv(),
-    logLevel: Config.logLevel(),
-    aster: {
-      wsUrl: Config.aster.wsUrl,
-      httpBase: Config.aster.httpBase,
-      subscribeSymbols: Config.aster.subscribeSymbols,
-      orderUser: Config.aster.orderUser() ? '已设置' : '未设置',
-      apiKey: Config.aster.apiKey() ? '已设置' : '未设置',
-    },
-    pacifica: {
-      baseUrl: Config.pacifica.baseUrl,
-      wsUrl: Config.pacifica.wsUrl,
-      symbol: Config.pacifica.symbol,
-      account: Config.pacifica.account() ? '已设置' : '未设置',
-      enableTestOrder: Config.pacifica.enableTestOrder(),
-    },
-    binance: {
-      baseUrl: Config.binance.baseUrl,
-      wsUrl: Config.binance.wsUrl,
-      apiKey: Config.binance.apiKey() ? '已设置' : '未设置',
-    },
-    proxy: {
-      enabled: Config.proxy.enabled(),
-      configured: Config.proxy.isConfigured(),
-      url: Config.proxy.getUrl() ? '已配置' : '未配置',
-    },
-  }),
-}
-
-/**
- * 智能账户发现器 - 简化版
- */
-export class SmartAccountDiscovery {
-  /**
-   * 发现 Pacifica 账户
-   */
-  static discoverPacifica(): Array<{
-    name: string
-    account: string
-    privateKey: string
-    suffix: string
-  }> {
-    const accounts: Array<{
-      name: string
-      account: string
-      privateKey: string
-      suffix: string
-    }> = []
-
-    // 检查基础账户
-    const baseAccount = SimpleEnv.get('PACIFICA_ACCOUNT')
-    const baseKey = SimpleEnv.get('PACIFICA_ACCOUNT_PRIVATE_KEY')
-    if (baseAccount && baseKey) {
-      accounts.push({
-        name: 'Pacifica Main',
-        account: baseAccount,
-        privateKey: baseKey,
-        suffix: '',
-      })
-    }
-
-    // 检查编号账户 (1-5)
-    for (let i = 1; i <= 5; i++) {
-      const account = SimpleEnv.get(`PACIFICA_ACCOUNT_${i}`)
-      const key = SimpleEnv.get(`PACIFICA_PRIVATE_KEY_${i}`)
-      if (account && key) {
-        accounts.push({
-          name: `Pacifica ${i}`,
-          account,
-          privateKey: key,
-          suffix: `_${i}`,
-        })
-      }
-    }
-
-    // 检查角色账户
-    const roles = ['MAIN', 'HEDGE', 'BACKUP']
-    roles.forEach(role => {
-      const account = SimpleEnv.get(`PACIFICA_ACCOUNT_${role}`)
-      const key = SimpleEnv.get(`PACIFICA_PRIVATE_KEY_${role}`)
-      if (account && key) {
-        accounts.push({
-          name: `Pacifica ${role.toLowerCase()}`,
-          account,
-          privateKey: key,
-          suffix: `_${role}`,
-        })
-      }
-    })
-
-    return accounts
-  }
-
-  /**
-   * 发现 Aster 账户
-   */
-  static discoverAster(): Array<{
-    name: string
-    user: string
-    signer?: string
-    privateKey: string
-    suffix: string
-  }> {
-    const accounts: Array<{
-      name: string
-      user: string
-      signer?: string
-      privateKey: string
-      suffix: string
-    }> = []
-
-    // 检查基础账户
-    const baseUser = SimpleEnv.get('ASTER_ORDER_USER')
-    const baseSigner = SimpleEnv.get('ASTER_ORDER_SIGNER')
-    const baseKey = SimpleEnv.get('PRIVATE_KEY')
-    if (baseUser && baseKey) {
-      accounts.push({
-        name: 'Aster Main',
-        user: baseUser,
-        signer: baseSigner,
-        privateKey: baseKey,
-        suffix: '',
-      })
-    }
-
-    // 检查第二账户
-    const user2 = SimpleEnv.get('ASTER2_ORDER_USER')
-    const signer2 = SimpleEnv.get('ASTER2_ORDER_SIGNER')
-    const key2 = SimpleEnv.get('PRIVATE_KEY2')
-    if (user2 && key2) {
-      accounts.push({
-        name: 'Aster 2',
-        user: user2,
-        signer: signer2,
-        privateKey: key2,
-        suffix: '_2',
-      })
-    }
-
-    // 检查编号账户 (1-3)
-    for (let i = 1; i <= 3; i++) {
-      const user = SimpleEnv.get(`ASTER_ORDER_USER_${i}`)
-      const signer = SimpleEnv.get(`ASTER_ORDER_SIGNER_${i}`)
-      const key = SimpleEnv.get(`ASTER_PRIVATE_KEY_${i}`)
-      if (user && key) {
-        accounts.push({
-          name: `Aster ${i}`,
-          user,
-          signer,
-          privateKey: key,
-          suffix: `_${i}`,
-        })
-      }
-    }
-
-    return accounts
-  }
-
-  /**
-   * 发现 Binance 账户
-   */
-  static discoverBinance(): Array<{
-    name: string
-    apiKey: string
-    secretKey: string
-    suffix: string
-  }> {
-    const accounts: Array<{
-      name: string
-      apiKey: string
-      secretKey: string
-      suffix: string
-    }> = []
-
-    // 检查基础账户
-    const baseKey = SimpleEnv.get('BINANCE_API_KEY')
-    const baseSecret = SimpleEnv.get('BINANCE_SECRET_KEY')
-    if (baseKey && baseSecret) {
-      accounts.push({
-        name: 'Binance Main',
-        apiKey: baseKey,
-        secretKey: baseSecret,
-        suffix: '',
-      })
-    }
-
-    // 检查编号账户 (1-3)
-    for (let i = 1; i <= 3; i++) {
-      const key = SimpleEnv.get(`BINANCE_API_KEY_${i}`)
-      const secret = SimpleEnv.get(`BINANCE_SECRET_KEY_${i}`)
-      if (key && secret) {
-        accounts.push({
-          name: `Binance ${i}`,
-          apiKey: key,
-          secretKey: secret,
-          suffix: `_${i}`,
-        })
-      }
-    }
-
-    return accounts
-  }
-
-  /**
-   * 发现所有账户
-   */
-  static discoverAll() {
-    return {
-      pacifica: this.discoverPacifica(),
-      aster: this.discoverAster(),
-      binance: this.discoverBinance(),
-    }
-  }
-}

+ 0 - 41
src/shared/constants/index.ts

@@ -1,41 +0,0 @@
-// 常量与枚举
-
-export enum OrderSide {
-  BUY = 'buy',
-  SELL = 'sell',
-}
-
-export enum PositionSide {
-  LONG = 'long',
-  SHORT = 'short',
-}
-
-export enum OrderType {
-  MARKET = 'market',
-  LIMIT = 'limit',
-  STOP = 'stop',
-  STOP_MARKET = 'stop_market',
-}
-
-export enum Severity {
-  LOW = 'low',
-  MEDIUM = 'medium',
-  HIGH = 'high',
-  CRITICAL = 'critical',
-}
-
-export const DEFAULT_WS_URL = 'wss://fstream.binance.com/ws'
-
-export const DEFAULT_RECONNECT_MS = 5000
-export const DEFAULT_MAX_RECONNECT = 10
-
-export const SUPPORTED_INTERVALS = ['1m', '5m', '15m', '1h', '4h', '1d']
-
-export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
-
-export const CHAIN_IDS = {
-  ETHEREUM: 1,
-  ARBITRUM: 42161,
-  POLYGON: 137,
-  BSC: 56,
-}

+ 0 - 188
src/shared/types/core/index.ts

@@ -1,188 +0,0 @@
-// 核心交易模块的类型定义
-
-/**
- * 交易对信息
- */
-export interface TradingPair {
-  symbol: string // 交易对符号,如 "BTC-USDT"
-  baseAsset: string // 基础资产
-  quoteAsset: string // 计价资产
-  contractAddress?: string // 合约地址(Perp DEX)
-  decimals: number // 小数位数
-}
-
-/**
- * 市场数据接口
- */
-export interface MarketData {
-  symbol: string
-  price: number
-  timestamp: number
-  volume24h: number
-  change24h: number
-  high24h: number
-  low24h: number
-  bidPrice: number
-  askPrice: number
-  bidQty: number
-  askQty: number
-  fundingRate?: number // 资金费率(Perp DEX)
-}
-
-/**
- * 订单簿数据
- */
-export interface OrderBook {
-  symbol: string
-  timestamp: number
-  bids: Array<[number, number]> // [price, quantity]
-  asks: Array<[number, number]> // [price, quantity]
-  lastUpdateId: number
-}
-
-/**
- * K线数据
- */
-export interface KlineData {
-  symbol: string
-  interval: string
-  openTime: number
-  open: number
-  high: number
-  low: number
-  close: number
-  volume: number
-  closeTime: number
-  quoteVolume: number
-  trades: number
-}
-
-/**
- * 持仓信息
- */
-export interface Position {
-  id: string
-  symbol: string
-  side: 'long' | 'short'
-  size: number // 仓位大小
-  entryPrice: number // 入场价格
-  markPrice: number // 标记价格
-  leverage: number // 杠杆倍数
-  unrealizedPnL: number // 未实现盈亏
-  realizedPnL: number // 已实现盈亏
-  fundingFees: number // 资金费用
-  liquidationPrice: number // 强平价格
-  margin: number // 保证金
-  timestamp: number
-  isOpen: boolean // 是否为开仓
-}
-
-/**
- * 交易订单
- */
-export interface Order {
-  id: string
-  symbol: string
-  side: 'buy' | 'sell'
-  type: 'market' | 'limit' | 'stop' | 'stop_market'
-  quantity: number
-  price?: number
-  stopPrice?: number
-  status: 'pending' | 'filled' | 'cancelled' | 'rejected'
-  filledQuantity: number
-  remainingQuantity: number
-  timestamp: number
-  fee?: number
-  feeAsset?: string
-}
-
-/**
- * 交易信号
- */
-export interface TradingSignal {
-  symbol: string
-  action: 'open_long' | 'open_short' | 'close' | 'hedge'
-  confidence: number // 置信度 0-1
-  quantity: number // 建议数量
-  price?: number // 建议价格
-  leverage?: number // 建议杠杆
-  reason: string // 信号原因
-  indicators: Record<string, number> // 技术指标
-  timestamp: number
-}
-
-/**
- * 对冲配置
- */
-export interface HedgeConfig {
-  symbol: string
-  hedgeRatio: number // 对冲比例
-  hedgeMethod: 'spot' | 'perp' | 'options' // 对冲方式
-  maxSlippage: number // 最大滑点
-  rebalanceThreshold: number // 重新平衡阈值
-  minHedgeInterval: number // 最小对冲间隔
-}
-
-/**
- * 交易执行结果
- */
-export interface ExecutionResult {
-  success: boolean
-  orderId?: string
-  executedQuantity: number
-  executedPrice: number
-  fee: number
-  error?: string
-  txHash?: string // 链上交易哈希
-  gasUsed?: number // gas 使用量
-}
-
-/**
- * 市场数据源
- */
-export interface MarketDataSource {
-  name: string
-  type: 'cex' | 'dex' | 'oracle'
-  baseUrl: string
-  wsUrl?: string
-  apiKey?: string
-  secret?: string
-  chainId?: number // 链ID
-  rpcUrl?: string
-}
-
-/**
- * 价格数据
- */
-export interface PriceData {
-  symbol: string
-  price: number
-  source: string
-  timestamp: number
-  confidence: number // 数据置信度
-}
-
-/**
- * 资金费率数据
- */
-export interface FundingRateData {
-  symbol: string
-  fundingRate: number
-  markPrice: number
-  indexPrice: number
-  estimatedSettlePrice: number
-  nextFundingTime: number
-  timestamp: number
-}
-
-/**
- * 流动性数据
- */
-export interface LiquidityData {
-  symbol: string
-  poolAddress: string
-  reserve0: number
-  reserve1: number
-  fee: number
-  timestamp: number
-}

+ 0 - 168
src/shared/types/index.ts

@@ -1,168 +0,0 @@
-/**
- * 共享类型定义
- */
-
-export interface SystemStatus {
-  accounts: number
-  activeConnections: number
-  totalTrades: number
-  totalVolume: string
-  uptime: number
-  lastUpdate: number
-}
-
-export interface TradingSignal {
-  symbol: string
-  action: 'buy' | 'sell' | 'hedge' | 'volume_boost' | 'close_position' | 'balance_accounts'
-  side?: 'buy' | 'sell'
-  amount: string
-  price?: string
-  confidence: number
-  reason: string
-  reduceOnly?: boolean
-  targetAccount?: string
-  stopLoss?: number
-  takeProfit?: number
-  enableTrailing?: boolean
-}
-
-export interface AccountState {
-  totalTrades: number
-  netPosition: number
-  totalVolume: number
-  lastBalance: number
-  availableBalance: number
-  marginUsed: number
-  needsRebalance: boolean
-  // 新增仓位详细信息
-  entryPrice?: number
-  unrealizedPnl?: number
-  currentPrice?: number
-  positionValue?: number
-  leverage?: number
-}
-
-export interface BasisDataPoint {
-  spotPrice: number
-  futuresPrice: number
-  basis: number
-  basisPercent: number
-  timestamp: number
-}
-
-export interface BasisRiskAssessment {
-  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
-  currentBasis: number | null
-  confidence: number
-  message: string
-  timestamp: number
-}
-
-export interface StopLossOrder {
-  orderId: string
-  symbol: string
-  amount: string
-  stopPrice: number
-  side: 'buy' | 'sell'
-  accountId: string
-  timestamp: number
-  isActive: boolean
-}
-
-export interface TakeProfitOrder {
-  orderId: string
-  symbol: string
-  amount: string
-  targetPrice: number
-  side: 'buy' | 'sell'
-  accountId: string
-  timestamp: number
-  isActive: boolean
-}
-
-export interface RiskScore {
-  riskScore: number
-  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
-  riskFactors: string[]
-  recommendations: string[]
-}
-
-export interface CacheEntry {
-  data: any
-  timestamp: number
-  ttl: number
-}
-
-export interface ServiceConfig {
-  enabled: boolean
-  settings: Record<string, any>
-}
-
-export interface ServiceStatus {
-  name: string
-  status: 'running' | 'stopped' | 'error'
-  lastUpdate: number
-  details?: any
-}
-
-export interface DashboardData {
-  timestamp: number
-  accounts: {
-    total: number
-    totalBalance: number
-    totalNetPosition: number
-    accountDetails: Array<{
-      id: string
-      balance: number
-      available: number
-      position: number
-      marginUsed: number
-    }>
-  }
-  trading: {
-    totalTrades: number
-    successfulTrades: number
-    failedTrades: number
-    successRate: number
-    totalVolume: number
-    lastTradeTime: number
-  }
-  risk: {
-    riskScore: number
-    riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
-    riskFactors: string[]
-    recommendations: string[]
-    basisRisk: {
-      level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
-      currentBasis: number | null
-      message: string
-    }
-  }
-  stopLoss: {
-    activeStopLoss: number
-    activeTakeProfit: number
-    monitoringSymbols: number
-  }
-  hedging: {
-    hedgePairs: number
-    autoHedgingEnabled: boolean
-    totalNetExposure: number
-  }
-  cache: {
-    totalEntries: number
-    hitRate: number
-    memoryUsage: string
-  }
-  system: {
-    services: { [serviceName: string]: string }
-    uptime: number
-    version: string
-  }
-}
-
-export interface TradingService {
-  initialize(): Promise<void>
-  start(): Promise<void>
-  stop(): Promise<void>
-  getStatus(): ServiceStatus
-}

+ 0 - 367
src/shared/types/infrastructure/index.ts

@@ -1,367 +0,0 @@
-// 基础设施模块的类型定义
-
-/**
- * 钱包配置
- */
-export interface WalletConfig {
-  type: 'hd' | 'private_key' | 'mnemonic' | 'hardware'
-  chainId: number
-  rpcUrl: string
-  gasPrice?: number
-  gasLimit?: number
-
-  // HD 钱包配置
-  mnemonic?: string
-  derivationPath?: string
-  accountIndex?: number
-
-  // 私钥配置
-  privateKey?: string
-
-  // 硬件钱包配置
-  hardwareType?: 'ledger' | 'trezor'
-  hardwarePath?: string
-}
-
-/**
- * 账户信息
- */
-export interface AccountInfo {
-  address: string
-  chainId: number
-  balance: Record<string, number> // token -> balance
-  nonce: number
-  gasPrice: number
-
-  // 合约地址
-  contracts: {
-    perpContract?: string
-    spotRouter?: string
-    oracle?: string
-  }
-
-  // 权限
-  permissions: {
-    canTrade: boolean
-    canWithdraw: boolean
-    canManage: boolean
-  }
-}
-
-/**
- * 交易配置
- */
-export interface TransactionConfig {
-  gasPrice: number
-  gasLimit: number
-  maxSlippage: number
-  deadline: number
-  approveAmount?: number
-  useFlashbots?: boolean
-}
-
-/**
- * 系统配置
- */
-export interface SystemConfig {
-  // 网络配置
-  networks: Record<
-    string,
-    {
-      chainId: number
-      rpcUrl: string
-      wsUrl?: string
-      explorerUrl: string
-      gasPrice: number
-    }
-  >
-
-  // API 配置
-  apis: {
-    binance?: {
-      apiKey: string
-      secret: string
-      testnet: boolean
-    }
-    coingecko?: {
-      apiKey: string
-    }
-    chainlink?: {
-      feeds: Record<string, string> // symbol -> feed address
-    }
-  }
-
-  // 数据库配置
-  database: {
-    host: string
-    port: number
-    database: string
-    username: string
-    password: string
-    dialect: 'postgres' | 'mysql' | 'sqlite'
-    logging: boolean
-    pool: {
-      max: number
-      min: number
-      acquire: number
-      idle: number
-    }
-  }
-
-  // Redis 配置
-  redis: {
-    host: string
-    port: number
-    password?: string
-    db: number
-    keyPrefix: string
-  }
-
-  // 风险配置
-  risk: {
-    maxLeverage: number
-    maxPositionSize: number
-    maxDrawdown: number
-    minMarginRatio: number
-    maxSlippage: number
-  }
-
-  // 交易配置
-  trading: {
-    defaultSlippage: number
-    minOrderValue: number
-    maxOrderValue: number
-    rebalanceInterval: number
-    hedgeThreshold: number
-  }
-
-  // 监控配置
-  monitoring: {
-    alertCooldown: number
-    metricsInterval: number
-    healthCheckInterval: number
-    logLevel: 'debug' | 'info' | 'warn' | 'error'
-  }
-}
-
-/**
- * 数据库模型定义
- */
-export interface DatabaseSchema {
-  // 交易表
-  trades: {
-    id: string
-    symbol: string
-    side: 'buy' | 'sell'
-    type: string
-    quantity: number
-    price: number
-    fee: number
-    feeAsset: string
-    status: string
-    txHash?: string
-    timestamp: Date
-    metadata?: Record<string, any>
-  }
-
-  // 持仓表
-  positions: {
-    id: string
-    symbol: string
-    side: 'long' | 'short'
-    size: number
-    entryPrice: number
-    leverage: number
-    margin: number
-    unrealizedPnL: number
-    realizedPnL: number
-    liquidationPrice: number
-    status: 'open' | 'closed' | 'liquidated'
-    openedAt: Date
-    closedAt?: Date
-    metadata?: Record<string, any>
-  }
-
-  // 订单表
-  orders: {
-    id: string
-    symbol: string
-    side: 'buy' | 'sell'
-    type: string
-    quantity: number
-    price?: number
-    status: string
-    filledQuantity: number
-    remainingQuantity: number
-    fee?: number
-    txHash?: string
-    createdAt: Date
-    updatedAt: Date
-  }
-
-  // 警报表
-  alerts: {
-    id: string
-    type: string
-    severity: string
-    title: string
-    message: string
-    value: number
-    threshold: number
-    resolved: boolean
-    resolvedAt?: Date
-    createdAt: Date
-  }
-
-  // 性能指标表
-  metrics: {
-    id: string
-    name: string
-    value: number
-    labels?: Record<string, string>
-    timestamp: Date
-  }
-}
-
-/**
- * 任务调度配置
- */
-export interface JobConfig {
-  name: string
-  schedule: string // cron 表达式
-  enabled: boolean
-  retryCount: number
-  retryDelay: number
-  timeout: number
-  params?: Record<string, any>
-}
-
-/**
- * 日志配置
- */
-export interface LogConfig {
-  level: 'debug' | 'info' | 'warn' | 'error'
-  format: 'json' | 'simple' | 'detailed'
-  transports: {
-    console?: {
-      enabled: boolean
-      level: string
-      format: string
-    }
-    file?: {
-      enabled: boolean
-      level: string
-      filename: string
-      maxsize: number
-      maxFiles: number
-    }
-    telegram?: {
-      enabled: boolean
-      botToken: string
-      chatId: string
-      level: string
-    }
-  }
-}
-
-/**
- * 通知配置
- */
-export interface NotificationConfig {
-  telegram: {
-    botToken: string
-    chatId: string
-    enabled: boolean
-    templates: Record<string, string>
-  }
-
-  email: {
-    host: string
-    port: number
-    secure: boolean
-    auth: {
-      user: string
-      pass: string
-    }
-    from: string
-    to: string[]
-    enabled: boolean
-    templates: Record<string, string>
-  }
-
-  slack: {
-    webhook: string
-    channel: string
-    enabled: boolean
-    templates: Record<string, string>
-  }
-}
-
-/**
- * 健康检查配置
- */
-export interface HealthCheckConfig {
-  enabled: boolean
-  interval: number // 检查间隔(秒)
-  timeout: number // 超时时间(秒)
-
-  checks: {
-    database?: {
-      enabled: boolean
-      timeout: number
-    }
-    redis?: {
-      enabled: boolean
-      timeout: number
-    }
-    web3?: {
-      enabled: boolean
-      timeout: number
-      networks: number[]
-    }
-    exchange?: {
-      enabled: boolean
-      timeout: number
-      apis: string[]
-    }
-  }
-
-  alerts: {
-    enabled: boolean
-    thresholds: {
-      consecutiveFailures: number
-      uptime: number
-    }
-  }
-}
-
-/**
- * 备份配置
- */
-export interface BackupConfig {
-  enabled: boolean
-  schedule: string // cron 表达式
-  retention: number // 保留天数
-
-  targets: {
-    database?: {
-      enabled: boolean
-      type: 'full' | 'incremental'
-      compression: boolean
-    }
-    logs?: {
-      enabled: boolean
-      compression: boolean
-    }
-    config?: {
-      enabled: boolean
-    }
-  }
-
-  storage: {
-    type: 'local' | 's3' | 'ftp'
-    path?: string
-    bucket?: string
-    credentials?: Record<string, string>
-  }
-}

+ 0 - 271
src/shared/types/risk/index.ts

@@ -1,271 +0,0 @@
-// 风险与监控模块的类型定义
-
-/**
- * 风险指标
- */
-export interface RiskMetrics {
-  symbol: string
-  timestamp: number
-
-  // 基础风险指标
-  var: number // 价值-at-风险
-  cvar: number // 条件价值-at-风险
-  maxDrawdown: number // 最大回撤
-  sharpeRatio: number // 夏普比率
-  volatility: number // 波动率
-
-  // 持仓风险
-  leverageRatio: number // 杠杆比率
-  liquidationRisk: number // 强平风险
-  concentrationRisk: number // 集中度风险
-
-  // 流动性风险
-  slippageRisk: number // 滑点风险
-  liquidityRisk: number // 流动性风险
-  fundingRateRisk: number // 资金费率风险
-
-  // 市场风险
-  correlationRisk: number // 相关性风险
-  marketImpact: number // 市场冲击
-}
-
-/**
- * 持仓风险评估
- */
-export interface PositionRisk {
-  positionId: string
-  symbol: string
-  side: 'long' | 'short'
-
-  // 风险值
-  delta: number // Delta
-  gamma: number // Gamma
-  theta: number // Theta
-  vega: number // Vega
-  rho: number // Rho
-
-  // 风险指标
-  var: number // 价值-at-风险
-  cvar: number // 条件价值-at-风险
-  liquidationPrice: number // 强平价格
-  marginRatio: number // 保证金比率
-  unrealizedPnL: number // 未实现盈亏
-
-  // 压力测试
-  stressTestResults: {
-    scenario: string
-    pnl: number
-    liquidationPrice: number
-  }[]
-}
-
-/**
- * 投资组合风险
- */
-export interface PortfolioRisk {
-  totalValue: number
-  totalUnrealizedPnL: number
-  totalRealizedPnL: number
-
-  // 整体风险指标
-  portfolioVaR: number
-  portfolioCVaR: number
-  maxDrawdown: number
-  sharpeRatio: number
-  volatility: number
-
-  // 风险分解
-  marketRisk: number
-  creditRisk: number
-  liquidityRisk: number
-  operationalRisk: number
-
-  // 相关性矩阵
-  correlationMatrix: Record<string, Record<string, number>>
-
-  // 风险贡献度
-  riskContributions: Record<string, number> // symbol -> risk contribution
-
-  timestamp: number
-}
-
-/**
- * 警报配置
- */
-export interface AlertConfig {
-  id: string
-  name: string
-  symbol?: string // 特定交易对(可选)
-  type: 'price' | 'volume' | 'risk' | 'position' | 'system'
-
-  // 触发条件
-  conditions: {
-    metric: string // 监控指标
-    operator: '>' | '<' | '>=' | '<=' | '==' | '!='
-    threshold: number // 阈值
-    window?: number // 时间窗口(秒)
-  }[]
-
-  // 警报设置
-  severity: 'low' | 'medium' | 'high' | 'critical'
-  cooldown: number // 冷却时间(秒)
-  enabled: boolean
-
-  // 通知渠道
-  channels: {
-    telegram?: boolean
-    email?: boolean
-    slack?: boolean
-    webhook?: string
-  }
-
-  // 自动响应
-  autoActions?: {
-    type: 'stop_loss' | 'take_profit' | 'reduce_position' | 'close_position'
-    params: Record<string, any>
-  }[]
-}
-
-/**
- * 警报事件
- */
-export interface AlertEvent {
-  id: string
-  configId: string
-  symbol: string
-  type: string
-  severity: 'low' | 'medium' | 'high' | 'critical'
-  title: string
-  message: string
-  value: number // 当前值
-  threshold: number // 阈值
-  timestamp: number
-  resolved?: boolean
-  resolvedAt?: number
-
-  // 相关数据
-  context?: Record<string, any>
-}
-
-/**
- * 风险阈值配置
- */
-export interface RiskThresholds {
-  // 持仓风险阈值
-  maxLeverage: number // 最大杠杆
-  maxPositionSize: number // 最大仓位大小
-  maxDrawdown: number // 最大回撤
-  minMarginRatio: number // 最小保证金比率
-
-  // 流动性风险阈值
-  maxSlippage: number // 最大滑点
-  minLiquidity: number // 最小流动性
-  maxGasPrice: number // 最大gas价格
-
-  // 市场风险阈值
-  maxVolatility: number // 最大波动率
-  maxConcentration: number // 最大集中度
-
-  // 系统风险阈值
-  maxLatency: number // 最大延迟
-  minUptime: number // 最小运行时间
-}
-
-/**
- * 压力测试场景
- */
-export interface StressTestScenario {
-  id: string
-  name: string
-  description: string
-
-  // 市场冲击
-  priceShocks: Record<string, number> // symbol -> price change %
-  volatilityShocks: Record<string, number> // symbol -> volatility multiplier
-
-  // 流动性冲击
-  liquidityShocks: Record<string, number> // symbol -> liquidity reduction %
-
-  // 资金费率冲击
-  fundingRateShocks: Record<string, number> // symbol -> funding rate change
-
-  // 持续时间
-  duration: number // 场景持续时间(秒)
-  probability: number // 发生概率
-}
-
-/**
- * 压力测试结果
- */
-export interface StressTestResult {
-  scenarioId: string
-  symbol: string
-  timestamp: number
-
-  // 结果指标
-  portfolioValue: number
-  unrealizedPnL: number
-  realizedPnL: number
-  marginRatio: number
-  liquidationRisk: number
-
-  // 风险指标
-  var: number
-  cvar: number
-  maxDrawdown: number
-
-  // 持仓变化
-  positionChanges: Record<
-    string,
-    {
-      size: number
-      unrealizedPnL: number
-      liquidationPrice: number
-    }
-  >
-
-  // 是否触发强平
-  liquidations: string[] // 被强平的持仓ID列表
-}
-
-/**
- * 风险报告
- */
-export interface RiskReport {
-  id: string
-  timestamp: number
-  period: {
-    start: number
-    end: number
-  }
-
-  // 总体风险概览
-  overview: {
-    totalValue: number
-    totalPnL: number
-    sharpeRatio: number
-    maxDrawdown: number
-    winRate: number
-  }
-
-  // 风险分解
-  riskBreakdown: {
-    marketRisk: number
-    creditRisk: number
-    liquidityRisk: number
-    operationalRisk: number
-  }
-
-  // 持仓风险详情
-  positionRisks: Record<string, PositionRisk>
-
-  // 警报统计
-  alertStats: {
-    total: number
-    bySeverity: Record<string, number>
-    byType: Record<string, number>
-  }
-
-  // 建议
-  recommendations: string[]
-}

+ 0 - 451
src/shared/utils/ProductionLogger.ts

@@ -1,451 +0,0 @@
-import { createWriteStream, WriteStream, existsSync, mkdirSync } from 'fs'
-import { join, dirname } from 'path'
-import { fileURLToPath } from 'url'
-
-export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'critical'
-
-export interface LogEntry {
-  timestamp: string
-  level: LogLevel
-  module: string
-  message: string
-  metadata?: Record<string, any>
-  traceId?: string
-  userId?: string
-  exchange?: string
-  accountId?: string
-}
-
-export interface LoggerConfig {
-  level: LogLevel
-  enableConsole: boolean
-  enableFile: boolean
-  logDir?: string
-  maxFileSize?: number // MB
-  maxFiles?: number
-  enableRotation?: boolean
-  enableAudit?: boolean
-}
-
-export class ProductionLogger {
-  private config: LoggerConfig
-  private logStream?: WriteStream
-  private auditStream?: WriteStream
-  private currentLogFile?: string
-  private currentFileSize = 0
-  private static instance?: ProductionLogger
-
-  constructor(config: Partial<LoggerConfig> = {}) {
-    this.config = {
-      level: 'info',
-      enableConsole: true,
-      enableFile: true,
-      logDir: './logs',
-      maxFileSize: 100, // 100MB
-      maxFiles: 10,
-      enableRotation: true,
-      enableAudit: true,
-      ...config,
-    }
-
-    this.initializeLogDirectory()
-    this.initializeLogStreams()
-  }
-
-  /**
-   * 获取单例实例
-   */
-  static getInstance(config?: Partial<LoggerConfig>): ProductionLogger {
-    if (!ProductionLogger.instance) {
-      ProductionLogger.instance = new ProductionLogger(config)
-    }
-    return ProductionLogger.instance
-  }
-
-  /**
-   * 初始化日志目录
-   */
-  private initializeLogDirectory(): void {
-    if (this.config.enableFile && this.config.logDir) {
-      if (!existsSync(this.config.logDir)) {
-        mkdirSync(this.config.logDir, { recursive: true })
-      }
-    }
-  }
-
-  /**
-   * 初始化日志流
-   */
-  private initializeLogStreams(): void {
-    if (this.config.enableFile && this.config.logDir) {
-      const timestamp = new Date().toISOString().split('T')[0]
-
-      // 主日志文件
-      this.currentLogFile = join(this.config.logDir, `trading-system-${timestamp}.log`)
-      this.logStream = createWriteStream(this.currentLogFile, { flags: 'a' })
-
-      // 审计日志文件
-      if (this.config.enableAudit) {
-        const auditFile = join(this.config.logDir, `audit-${timestamp}.log`)
-        this.auditStream = createWriteStream(auditFile, { flags: 'a' })
-      }
-    }
-  }
-
-  /**
-   * 记录 Debug 级别日志
-   */
-  debug(message: string, metadata?: Record<string, any>, module = 'SYSTEM'): void {
-    this.log('debug', module, message, metadata)
-  }
-
-  /**
-   * 记录 Info 级别日志
-   */
-  info(message: string, metadata?: Record<string, any>, module = 'SYSTEM'): void {
-    this.log('info', module, message, metadata)
-  }
-
-  /**
-   * 记录 Warning 级别日志
-   */
-  warn(message: string, metadata?: Record<string, any>, module = 'SYSTEM'): void {
-    this.log('warn', module, message, metadata)
-  }
-
-  /**
-   * 记录 Error 级别日志
-   */
-  error(message: string, error?: Error | any, metadata?: Record<string, any>, module = 'SYSTEM'): void {
-    const errorMetadata = {
-      ...metadata,
-      ...(error && {
-        error: {
-          name: error.name,
-          message: error.message,
-          stack: error.stack,
-        },
-      }),
-    }
-    this.log('error', module, message, errorMetadata)
-  }
-
-  /**
-   * 记录 Critical 级别日志
-   */
-  critical(message: string, error?: Error | any, metadata?: Record<string, any>, module = 'SYSTEM'): void {
-    const errorMetadata = {
-      ...metadata,
-      ...(error && {
-        error: {
-          name: error.name,
-          message: error.message,
-          stack: error.stack,
-        },
-      }),
-    }
-    this.log('critical', module, message, errorMetadata)
-  }
-
-  /**
-   * 记录交易相关日志
-   */
-  trade(
-    action: string,
-    details: {
-      exchange: string
-      accountId?: string
-      symbol?: string
-      side?: string
-      quantity?: string
-      price?: string
-      orderId?: string
-      [key: string]: any
-    },
-  ): void {
-    this.log('info', 'TRADING', `交易操作: ${action}`, {
-      ...details,
-      category: 'trading',
-    })
-  }
-
-  /**
-   * 记录对冲相关日志
-   */
-  hedge(
-    action: string,
-    details: {
-      sourceExchange: string
-      targetExchange: string
-      symbol: string
-      quantity: string
-      reason: string
-      [key: string]: any
-    },
-  ): void {
-    this.log('info', 'HEDGING', `对冲操作: ${action}`, {
-      ...details,
-      category: 'hedging',
-    })
-  }
-
-  /**
-   * 记录账户相关日志
-   */
-  account(
-    action: string,
-    details: {
-      exchange: string
-      accountId: string
-      [key: string]: any
-    },
-  ): void {
-    this.log('info', 'ACCOUNT', `账户操作: ${action}`, {
-      ...details,
-      category: 'account',
-    })
-  }
-
-  /**
-   * 记录 WebSocket 相关日志
-   */
-  websocket(
-    action: string,
-    details: {
-      exchange: string
-      event?: string
-      symbol?: string
-      [key: string]: any
-    },
-  ): void {
-    this.log('info', 'WEBSOCKET', `WebSocket事件: ${action}`, {
-      ...details,
-      category: 'websocket',
-    })
-  }
-
-  /**
-   * 记录性能相关日志
-   */
-  performance(metric: string, value: number, details?: Record<string, any>): void {
-    this.log('info', 'PERFORMANCE', `性能指标: ${metric}`, {
-      metric,
-      value,
-      unit: 'ms',
-      ...details,
-      category: 'performance',
-    })
-  }
-
-  /**
-   * 记录审计日志
-   */
-  audit(
-    action: string,
-    details: {
-      userId?: string
-      exchange?: string
-      accountId?: string
-      resource: string
-      result: 'success' | 'failure'
-      [key: string]: any
-    },
-  ): void {
-    const auditEntry = {
-      timestamp: new Date().toISOString(),
-      action,
-      ...details,
-      category: 'audit',
-    }
-
-    // 同时写入主日志和审计日志
-    this.log('info', 'AUDIT', `审计操作: ${action}`, auditEntry)
-
-    if (this.auditStream) {
-      this.auditStream.write(JSON.stringify(auditEntry) + '\n')
-    }
-  }
-
-  /**
-   * 核心日志记录方法
-   */
-  private log(level: LogLevel, module: string, message: string, metadata?: Record<string, any>): void {
-    // 检查日志级别
-    if (!this.shouldLog(level)) {
-      return
-    }
-
-    const logEntry: LogEntry = {
-      timestamp: new Date().toISOString(),
-      level,
-      module,
-      message,
-      metadata,
-    }
-
-    // 控制台输出
-    if (this.config.enableConsole) {
-      this.outputToConsole(logEntry)
-    }
-
-    // 文件输出
-    if (this.config.enableFile && this.logStream) {
-      this.outputToFile(logEntry)
-    }
-
-    // 检查文件轮转
-    if (this.config.enableRotation && this.shouldRotate()) {
-      this.rotateLogFile()
-    }
-  }
-
-  /**
-   * 检查是否应该记录该级别的日志
-   */
-  private shouldLog(level: LogLevel): boolean {
-    const levels = ['debug', 'info', 'warn', 'error', 'critical']
-    const currentLevelIndex = levels.indexOf(this.config.level)
-    const messageLevelIndex = levels.indexOf(level)
-    return messageLevelIndex >= currentLevelIndex
-  }
-
-  /**
-   * 输出到控制台
-   */
-  private outputToConsole(entry: LogEntry): void {
-    const coloredLevel = this.getColoredLevel(entry.level)
-    const timestamp = entry.timestamp.split('T')[1].split('.')[0] // 只显示时间部分
-
-    let output = `${timestamp} ${coloredLevel} [${entry.module}] ${entry.message}`
-
-    if (entry.metadata) {
-      const metadataStr = JSON.stringify(entry.metadata, null, 2)
-        .split('\n')
-        .map(line => `  ${line}`)
-        .join('\n')
-      output += `\n${metadataStr}`
-    }
-
-    // 根据级别选择输出方式
-    switch (entry.level) {
-      case 'error':
-      case 'critical':
-        console.error(output)
-        break
-      case 'warn':
-        console.warn(output)
-        break
-      default:
-        console.log(output)
-    }
-  }
-
-  /**
-   * 输出到文件
-   */
-  private outputToFile(entry: LogEntry): void {
-    if (!this.logStream) return
-
-    const logLine = JSON.stringify(entry) + '\n'
-    this.logStream.write(logLine)
-    this.currentFileSize += Buffer.byteLength(logLine)
-  }
-
-  /**
-   * 获取带颜色的日志级别
-   */
-  private getColoredLevel(level: LogLevel): string {
-    const colors = {
-      debug: '\x1b[90m', // 灰色
-      info: '\x1b[32m', // 绿色
-      warn: '\x1b[33m', // 黄色
-      error: '\x1b[31m', // 红色
-      critical: '\x1b[41m', // 红色背景
-    }
-
-    const reset = '\x1b[0m'
-    return `${colors[level]}${level.toUpperCase().padEnd(8)}${reset}`
-  }
-
-  /**
-   * 检查是否需要轮转日志文件
-   */
-  private shouldRotate(): boolean {
-    const maxSizeBytes = (this.config.maxFileSize || 100) * 1024 * 1024
-    return this.currentFileSize > maxSizeBytes
-  }
-
-  /**
-   * 轮转日志文件
-   */
-  private rotateLogFile(): void {
-    if (this.logStream) {
-      this.logStream.end()
-    }
-
-    if (this.auditStream) {
-      this.auditStream.end()
-    }
-
-    this.currentFileSize = 0
-    this.initializeLogStreams()
-
-    this.info(
-      '日志文件已轮转',
-      {
-        newLogFile: this.currentLogFile,
-      },
-      'LOGGER',
-    )
-  }
-
-  /**
-   * 创建子日志器
-   */
-  child(module: string, baseMetadata?: Record<string, any>) {
-    return {
-      debug: (message: string, metadata?: Record<string, any>) =>
-        this.debug(message, { ...baseMetadata, ...metadata }, module),
-      info: (message: string, metadata?: Record<string, any>) =>
-        this.info(message, { ...baseMetadata, ...metadata }, module),
-      warn: (message: string, metadata?: Record<string, any>) =>
-        this.warn(message, { ...baseMetadata, ...metadata }, module),
-      error: (message: string, error?: Error, metadata?: Record<string, any>) =>
-        this.error(message, error, { ...baseMetadata, ...metadata }, module),
-      critical: (message: string, error?: Error, metadata?: Record<string, any>) =>
-        this.critical(message, error, { ...baseMetadata, ...metadata }, module),
-    }
-  }
-
-  /**
-   * 关闭日志器
-   */
-  close(): void {
-    if (this.logStream) {
-      this.logStream.end()
-    }
-    if (this.auditStream) {
-      this.auditStream.end()
-    }
-  }
-
-  /**
-   * 获取统计信息
-   */
-  getStats() {
-    return {
-      config: this.config,
-      currentLogFile: this.currentLogFile,
-      currentFileSize: this.currentFileSize,
-      streamActive: !!this.logStream && !this.logStream.destroyed,
-    }
-  }
-}
-
-// 创建默认的全局日志器实例
-export const logger = ProductionLogger.getInstance({
-  level: (process.env.LOG_LEVEL as LogLevel) || 'info',
-  enableConsole: process.env.NODE_ENV !== 'test',
-  enableFile: process.env.NODE_ENV === 'production',
-  logDir: process.env.LOG_DIR || './logs',
-})

+ 0 - 280
src/shared/utils/StateManager.ts

@@ -1,280 +0,0 @@
-import fs from 'fs'
-import path from 'path'
-import { logger } from './logger'
-
-/**
- * 系统状态管理器
- * 负责持久化和恢复系统状态,确保Delta中性连续性
- */
-export interface SystemState {
-  timestamp: number
-  accountStates: Record<
-    string,
-    {
-      totalTrades: number
-      netPosition: number
-      totalVolume: number
-      lastBalance: number
-      needsRebalance: boolean
-      lastUpdateTime: number
-    }
-  >
-  globalStats: {
-    totalTrades: number
-    successfulTrades: number
-    failedTrades: number
-    totalVolume: number
-    sessionStartTime: number
-  }
-  deltaMetrics: {
-    totalDelta: number
-    maxDelta: number
-    lastRebalanceTime: number
-    rebalanceCount: number
-  }
-  riskMetrics: {
-    dailyTrades: number
-    lastRiskCheck: number
-    emergencyStops: number
-  }
-}
-
-export class StateManager {
-  private stateFile: string
-  private backupDir: string
-
-  constructor(stateFile = '.system_state.json') {
-    this.stateFile = path.resolve(stateFile)
-    this.backupDir = path.resolve('.state_backups')
-    this.ensureBackupDirectory()
-  }
-
-  private ensureBackupDirectory(): void {
-    if (!fs.existsSync(this.backupDir)) {
-      fs.mkdirSync(this.backupDir, { recursive: true })
-    }
-  }
-
-  /**
-   * 保存系统状态
-   */
-  async saveState(state: SystemState): Promise<void> {
-    try {
-      // 创建状态快照
-      const stateSnapshot = {
-        ...state,
-        timestamp: Date.now(),
-        version: '1.0.0',
-        checksum: this.calculateChecksum(state),
-      }
-
-      // 备份当前状态文件
-      if (fs.existsSync(this.stateFile)) {
-        const backupFile = path.join(
-          this.backupDir,
-          `state_backup_${new Date().toISOString().replace(/[:.]/g, '-')}.json`,
-        )
-        fs.copyFileSync(this.stateFile, backupFile)
-      }
-
-      // 保存新状态
-      fs.writeFileSync(this.stateFile, JSON.stringify(stateSnapshot, null, 2))
-
-      logger.info('系统状态已保存', {
-        timestamp: stateSnapshot.timestamp,
-        accounts: Object.keys(state.accountStates).length,
-        totalDelta: state.deltaMetrics.totalDelta,
-      })
-
-      // 清理旧备份文件 (保留最近10个)
-      this.cleanupOldBackups()
-    } catch (error: any) {
-      logger.error('保存系统状态失败', { error: error.message })
-      throw error
-    }
-  }
-
-  /**
-   * 加载系统状态
-   */
-  async loadState(): Promise<SystemState | null> {
-    try {
-      if (!fs.existsSync(this.stateFile)) {
-        logger.info('未找到状态文件,将创建新的系统状态')
-        return null
-      }
-
-      const stateData = fs.readFileSync(this.stateFile, 'utf8')
-      const parsedState = JSON.parse(stateData)
-
-      // 验证状态完整性
-      if (!this.validateState(parsedState)) {
-        logger.warn('状态文件损坏,尝试从备份恢复')
-        return await this.loadFromBackup()
-      }
-
-      logger.info('系统状态加载成功', {
-        timestamp: parsedState.timestamp,
-        accounts: Object.keys(parsedState.accountStates || {}).length,
-        totalDelta: parsedState.deltaMetrics?.totalDelta || 0,
-        age: Date.now() - parsedState.timestamp,
-      })
-
-      return parsedState as SystemState
-    } catch (error: any) {
-      logger.error('加载系统状态失败', { error: error.message })
-      return await this.loadFromBackup()
-    }
-  }
-
-  /**
-   * 从备份恢复状态
-   */
-  private async loadFromBackup(): Promise<SystemState | null> {
-    try {
-      const backupFiles = fs
-        .readdirSync(this.backupDir)
-        .filter(file => file.startsWith('state_backup_'))
-        .sort()
-        .reverse()
-
-      for (const backupFile of backupFiles.slice(0, 3)) {
-        // 尝试最近3个备份
-        try {
-          const backupPath = path.join(this.backupDir, backupFile)
-          const backupData = fs.readFileSync(backupPath, 'utf8')
-          const parsedBackup = JSON.parse(backupData)
-
-          if (this.validateState(parsedBackup)) {
-            logger.info('从备份恢复系统状态成功', { backupFile })
-            return parsedBackup as SystemState
-          }
-        } catch (backupError) {
-          logger.warn('备份文件损坏', { backupFile })
-          continue
-        }
-      }
-
-      logger.warn('所有备份文件都无法使用,返回空状态')
-      return null
-    } catch (error: any) {
-      logger.error('从备份恢复失败', { error: error.message })
-      return null
-    }
-  }
-
-  /**
-   * 验证状态完整性
-   */
-  private validateState(state: any): boolean {
-    return (
-      state &&
-      typeof state.timestamp === 'number' &&
-      state.accountStates &&
-      typeof state.accountStates === 'object' &&
-      state.globalStats &&
-      state.deltaMetrics &&
-      state.riskMetrics
-    )
-  }
-
-  /**
-   * 计算状态校验和
-   */
-  private calculateChecksum(state: SystemState): string {
-    const stateString = JSON.stringify(state, Object.keys(state).sort())
-    return Buffer.from(stateString).toString('base64').slice(0, 16)
-  }
-
-  /**
-   * 清理旧备份文件
-   */
-  private cleanupOldBackups(): void {
-    try {
-      const backupFiles = fs
-        .readdirSync(this.backupDir)
-        .filter(file => file.startsWith('state_backup_'))
-        .sort()
-
-      if (backupFiles.length > 10) {
-        const filesToDelete = backupFiles.slice(0, backupFiles.length - 10)
-        filesToDelete.forEach(file => {
-          fs.unlinkSync(path.join(this.backupDir, file))
-        })
-        logger.info('清理旧备份文件', { deleted: filesToDelete.length })
-      }
-    } catch (error: any) {
-      logger.warn('清理备份文件失败', { error: error.message })
-    }
-  }
-
-  /**
-   * 创建默认状态
-   */
-  createDefaultState(): SystemState {
-    return {
-      timestamp: Date.now(),
-      accountStates: {},
-      globalStats: {
-        totalTrades: 0,
-        successfulTrades: 0,
-        failedTrades: 0,
-        totalVolume: 0,
-        sessionStartTime: Date.now(),
-      },
-      deltaMetrics: {
-        totalDelta: 0,
-        maxDelta: 0,
-        lastRebalanceTime: 0,
-        rebalanceCount: 0,
-      },
-      riskMetrics: {
-        dailyTrades: 0,
-        lastRiskCheck: Date.now(),
-        emergencyStops: 0,
-      },
-    }
-  }
-
-  /**
-   * 获取Delta中性报告
-   */
-  getDeltaNeutralityReport(state: SystemState): {
-    isDeltaNeutral: boolean
-    totalDelta: number
-    maxAllowedDelta: number
-    recommendation: string
-  } {
-    const totalDelta = Math.abs(state.deltaMetrics.totalDelta)
-    const maxAllowedDelta = 0.01 // 最大允许敞口 0.01 BTC
-
-    const isDeltaNeutral = totalDelta <= maxAllowedDelta
-
-    let recommendation = ''
-    if (!isDeltaNeutral) {
-      recommendation = `需要对冲平仓 ${totalDelta.toFixed(4)} BTC 敞口以保持Delta中性`
-    } else {
-      recommendation = 'Delta中性状态良好,可以安全退出'
-    }
-
-    return {
-      isDeltaNeutral,
-      totalDelta,
-      maxAllowedDelta,
-      recommendation,
-    }
-  }
-
-  /**
-   * 紧急状态保存 (进程退出时)
-   */
-  emergencySave(state: SystemState): void {
-    try {
-      const emergencyFile = `.emergency_state_${Date.now()}.json`
-      fs.writeFileSync(emergencyFile, JSON.stringify(state, null, 2))
-      logger.info('紧急状态保存完成', { file: emergencyFile })
-    } catch (error: any) {
-      logger.error('紧急状态保存失败', { error: error.message })
-    }
-  }
-}

+ 0 - 5
src/shared/utils/events.ts

@@ -1,5 +0,0 @@
-import { EventEmitter } from 'events'
-
-class EventBus extends EventEmitter {}
-
-export const eventBus = new EventBus()

+ 0 - 328
src/shared/utils/httpClient.ts

@@ -1,328 +0,0 @@
-import { HttpsProxyAgent } from 'https-proxy-agent'
-import { Config } from '../config/simpleEnv'
-import { logger } from './logger'
-
-/**
- * HTTP 请求选项
- */
-export interface HttpRequestOptions {
-  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
-  headers?: Record<string, string>
-  body?: any
-  timeout?: number
-  signal?: AbortSignal
-  retries?: number
-  retryDelay?: number
-  useProxy?: boolean
-  exchange?: 'aster' | 'pacifica' | 'binance' // 交易所标识,用于选择专用代理
-  accountId?: string // 账户标识,支持同一交易所多账户
-}
-
-/**
- * HTTP 响应接口
- */
-export interface HttpResponse<T = any> {
-  status: number
-  statusText: string
-  ok: boolean
-  data: T
-  headers: Headers
-}
-
-/**
- * 统一的HTTP客户端,支持proxy和重试
- */
-export class HttpClient {
-  private static instance: HttpClient
-  private proxyAgent: HttpsProxyAgent | undefined
-  private defaultTimeout = 30000
-  private defaultRetries = 3
-  private defaultRetryDelay = 1000
-
-  constructor() {
-    this.initializeProxy()
-  }
-
-  static getInstance(): HttpClient {
-    if (!HttpClient.instance) {
-      HttpClient.instance = new HttpClient()
-    }
-    return HttpClient.instance
-  }
-
-  private initializeProxy(): void {
-    if (Config.proxy.isAnyConfigured()) {
-      logger.info('HTTP代理系统已初始化')
-      if (Config.proxy.isConfigured()) {
-        logger.info(`全局代理: ${Config.proxy.protocol()}://${Config.proxy.host()}:${Config.proxy.port()}`)
-      }
-      if (Config.proxy.aster.isConfigured()) {
-        logger.info(
-          `Aster专用代理: ${Config.proxy.aster.protocol()}://${Config.proxy.aster.host()}:${Config.proxy.aster.port()}`,
-        )
-      }
-    } else {
-      logger.info('HTTP代理未配置,使用直连')
-    }
-  }
-
-  /**
-   * 重新初始化代理 (当环境变量发生变化时调用)
-   */
-  reinitializeProxy(): void {
-    this.proxyAgent = undefined
-    this.initializeProxy()
-  }
-
-  /**
-   * 检查HTTP状态码是否应该重试
-   */
-  private shouldRetry(status: number): boolean {
-    return status >= 500 || status === 429 || status === 408 || status === 0
-  }
-
-  /**
-   * 等待指定时间
-   */
-  private sleep(ms: number): Promise<void> {
-    return new Promise(resolve => setTimeout(resolve, ms))
-  }
-
-  /**
-   * 发送HTTP请求
-   */
-  async request<T = any>(url: string, options: HttpRequestOptions = {}): Promise<HttpResponse<T>> {
-    const {
-      method = 'GET',
-      headers = {},
-      body,
-      timeout = this.defaultTimeout,
-      signal,
-      retries = this.defaultRetries,
-      retryDelay = this.defaultRetryDelay,
-      useProxy = true,
-      exchange,
-    } = options
-
-    const maxRetries = Math.max(0, retries)
-    let lastError: Error
-
-    // 请求配置
-    const fetchOptions: RequestInit = {
-      method,
-      headers: {
-        'User-Agent': 'Binance-Multi-Exchange-Client/1.0',
-        ...headers,
-      },
-      signal,
-    }
-
-    // 添加请求体
-    if (body && method !== 'GET') {
-      if (typeof body === 'object') {
-        fetchOptions.body = JSON.stringify(body)
-        fetchOptions.headers = {
-          'Content-Type': 'application/json',
-          ...fetchOptions.headers,
-        }
-      } else {
-        fetchOptions.body = body
-      }
-    }
-
-    // 添加代理(仅在Node.js环境中)
-    if (useProxy && typeof global !== 'undefined') {
-      const proxyUrl = Config.proxy.getUrl(exchange as any)
-      if (proxyUrl) {
-        const proxyAgent = new HttpsProxyAgent(proxyUrl)
-        ;(fetchOptions as any).agent = proxyAgent
-
-        if (Config.isDev()) {
-          logger.debug(`使用代理发送HTTP请求`, {
-            exchange: exchange || 'global',
-            proxyHost: exchange === 'aster' ? Config.proxy.aster.host() : Config.proxy.host(),
-            method,
-            url: url.length > 100 ? url.substring(0, 100) + '...' : url,
-          })
-        }
-      }
-    }
-
-    for (let attempt = 0; attempt <= maxRetries; attempt++) {
-      try {
-        // 创建超时控制
-        const controller = new AbortController()
-        const timeoutId = setTimeout(() => controller.abort(), timeout)
-        const requestSignal = signal || controller.signal
-
-        const startTime = Date.now()
-        const response = await fetch(url, {
-          ...fetchOptions,
-          signal: requestSignal,
-        })
-
-        clearTimeout(timeoutId)
-        const duration = Date.now() - startTime
-
-        // 读取响应数据
-        const contentType = response.headers.get('content-type') || ''
-        let data: T
-
-        if (contentType.includes('application/json')) {
-          data = await response.json()
-        } else {
-          data = (await response.text()) as any
-        }
-
-        // 记录请求日志
-        if (Config.isDev()) {
-          logger.debug(`HTTP ${method} ${url}`, {
-            status: response.status,
-            duration: `${duration}ms`,
-            attempt: attempt + 1,
-            proxy: useProxy && this.proxyAgent ? 'enabled' : 'disabled',
-          })
-        }
-
-        // 检查是否需要重试
-        if (!response.ok && this.shouldRetry(response.status) && attempt < maxRetries) {
-          const jitter = Math.random() * 500 // 0-500ms随机延迟
-          const delay = retryDelay * Math.pow(2, attempt) + jitter
-
-          logger.warn(`HTTP请求失败,将在${Math.round(delay)}ms后重试`, {
-            url,
-            status: response.status,
-            attempt: attempt + 1,
-            maxRetries: maxRetries + 1,
-          })
-
-          await this.sleep(delay)
-          continue
-        }
-
-        return {
-          status: response.status,
-          statusText: response.statusText,
-          ok: response.ok,
-          data,
-          headers: response.headers,
-        }
-      } catch (error: any) {
-        lastError = error
-        const isTimeout = error.name === 'AbortError'
-        const isNetworkError = error.message?.includes('fetch')
-
-        // 记录错误日志
-        logger.error(`HTTP请求异常`, {
-          url,
-          method,
-          attempt: attempt + 1,
-          error: error.message,
-          isTimeout,
-          isNetworkError,
-        })
-
-        // 检查是否需要重试
-        if ((isTimeout || isNetworkError) && attempt < maxRetries) {
-          const jitter = Math.random() * 500
-          const delay = retryDelay * Math.pow(2, attempt) + jitter
-
-          logger.warn(`网络错误,将在${Math.round(delay)}ms后重试`, {
-            url,
-            attempt: attempt + 1,
-            maxRetries: maxRetries + 1,
-          })
-
-          await this.sleep(delay)
-          continue
-        }
-
-        // 不能重试,抛出错误
-        throw error
-      }
-    }
-
-    // 所有重试都失败了
-    throw lastError || new Error(`HTTP请求失败,已重试${maxRetries}次`)
-  }
-
-  /**
-   * GET 请求
-   */
-  async get<T = any>(url: string, options: Omit<HttpRequestOptions, 'method' | 'body'> = {}): Promise<HttpResponse<T>> {
-    return this.request<T>(url, { ...options, method: 'GET' })
-  }
-
-  /**
-   * POST 请求
-   */
-  async post<T = any>(
-    url: string,
-    body?: any,
-    options: Omit<HttpRequestOptions, 'method' | 'body'> = {},
-  ): Promise<HttpResponse<T>> {
-    return this.request<T>(url, { ...options, method: 'POST', body })
-  }
-
-  /**
-   * PUT 请求
-   */
-  async put<T = any>(
-    url: string,
-    body?: any,
-    options: Omit<HttpRequestOptions, 'method' | 'body'> = {},
-  ): Promise<HttpResponse<T>> {
-    return this.request<T>(url, { ...options, method: 'PUT', body })
-  }
-
-  /**
-   * DELETE 请求
-   */
-  async delete<T = any>(
-    url: string,
-    options: Omit<HttpRequestOptions, 'method' | 'body'> = {},
-  ): Promise<HttpResponse<T>> {
-    return this.request<T>(url, { ...options, method: 'DELETE' })
-  }
-}
-
-/**
- * 全局HTTP客户端实例
- */
-export const httpClient = HttpClient.getInstance()
-
-/**
- * 便捷方法:使用代理的fetch
- */
-export async function fetchWithProxy<T = any>(url: string, options: HttpRequestOptions = {}): Promise<HttpResponse<T>> {
-  return httpClient.request<T>(url, options)
-}
-
-/**
- * 便捷方法:GET请求with proxy
- */
-export async function getWithProxy<T = any>(
-  url: string,
-  options: Omit<HttpRequestOptions, 'method' | 'body'> = {},
-): Promise<T> {
-  const response = await httpClient.get<T>(url, options)
-  if (!response.ok) {
-    throw new Error(`HTTP ${response.status}: ${response.statusText}`)
-  }
-  return response.data
-}
-
-/**
- * 便捷方法:POST请求with proxy
- */
-export async function postWithProxy<T = any>(
-  url: string,
-  body?: any,
-  options: Omit<HttpRequestOptions, 'method' | 'body'> = {},
-): Promise<T> {
-  const response = await httpClient.post<T>(url, body, options)
-  if (!response.ok) {
-    throw new Error(`HTTP ${response.status}: ${response.statusText}`)
-  }
-  return response.data
-}

+ 0 - 51
src/shared/utils/logger.ts

@@ -1,51 +0,0 @@
-import winston from 'winston'
-import { ProductionLogger, logger as productionLogger } from './ProductionLogger'
-
-const { combine, timestamp, printf, colorize } = winston.format
-
-const logFormat = printf(({ level, message, timestamp }) => {
-  return `${timestamp} [${level}] ${message}`
-})
-
-// 保持向后兼容的 Winston logger,添加EPIPE错误处理
-const winstonLogger = winston.createLogger({
-  level: process.env.LOG_LEVEL || 'info',
-  format: combine(timestamp(), logFormat),
-  transports: [
-    new winston.transports.Console({
-      format: combine(colorize(), timestamp(), logFormat),
-      handleExceptions: false,
-      handleRejections: false,
-    }),
-  ],
-  exitOnError: false,
-})
-
-// 处理EPIPE错误,避免进程崩溃
-winstonLogger.on('error', error => {
-  if (error.code === 'EPIPE') {
-    // 静默处理EPIPE错误,不打印到控制台
-    return
-  }
-  // 其他错误仍然处理
-  console.error('Winston logger error:', error.message)
-})
-
-// 处理stdout/stderr的EPIPE错误
-process.stdout.on('error', error => {
-  if (error.code === 'EPIPE') {
-    process.exit(0)
-  }
-})
-
-process.stderr.on('error', error => {
-  if (error.code === 'EPIPE') {
-    process.exit(0)
-  }
-})
-
-// 生产环境使用新的 ProductionLogger,开发环境使用 Winston
-export const logger = process.env.NODE_ENV === 'production' ? productionLogger : winstonLogger
-
-// 导出新的生产日志器供直接使用
-export { ProductionLogger, productionLogger }

+ 0 - 20
src/shared/utils/math.ts

@@ -1,20 +0,0 @@
-export function toFixed(num: number, decimals: number = 8): number {
-  const factor = Math.pow(10, decimals)
-  return Math.round(num * factor) / factor
-}
-
-export function percentChange(from: number, to: number): number {
-  if (from === 0) return 0
-  return ((to - from) / from) * 100
-}
-
-// 简单移动平均
-export function sma(values: number[], period: number): number[] {
-  const result: number[] = []
-  for (let i = 0; i <= values.length - period; i++) {
-    const window = values.slice(i, i + period)
-    const avg = window.reduce((a, b) => a + b, 0) / period
-    result.push(avg)
-  }
-  return result
-}

+ 0 - 251
src/shared/utils/precision.ts

@@ -1,251 +0,0 @@
-/**
- * 统一精度和步进校验工具
- * 处理不同交易所的价格和数量精度要求
- */
-
-export interface PrecisionConfig {
-  tickSize: string // 价格步进
-  stepSize: string // 数量步进
-  minQty: string // 最小数量
-  maxQty: string // 最大数量
-  minNotional: string // 最小名义价值
-  maxNotional?: string // 最大名义价值
-  precision?: number // 精度位数
-}
-
-export interface ExchangeSymbolInfo {
-  symbol: string
-  status: string
-  baseAsset: string
-  quoteAsset: string
-  precision: PrecisionConfig
-}
-
-export class PrecisionValidator {
-  private static exchangeConfigs = new Map<string, Map<string, ExchangeSymbolInfo>>()
-
-  /**
-   * 更新交易所符号配置
-   */
-  static updateExchangeConfig(exchange: string, symbolsInfo: ExchangeSymbolInfo[]): void {
-    const exchangeMap = new Map<string, ExchangeSymbolInfo>()
-    symbolsInfo.forEach(info => {
-      exchangeMap.set(info.symbol, info)
-    })
-    this.exchangeConfigs.set(exchange, exchangeMap)
-  }
-
-  /**
-   * 获取符号精度配置
-   */
-  static getSymbolConfig(exchange: string, symbol: string): ExchangeSymbolInfo | null {
-    const exchangeMap = this.exchangeConfigs.get(exchange)
-    return exchangeMap?.get(symbol) || null
-  }
-
-  /**
-   * 格式化价格到正确精度
-   */
-  static formatPrice(price: number | string, tickSize: string): string {
-    const numPrice = Number(price)
-    const numTickSize = Number(tickSize)
-
-    if (numTickSize <= 0) return String(numPrice)
-
-    // 计算精度位数
-    const decimals = this.countDecimals(numTickSize)
-
-    // 舍入到最近的tick
-    const rounded = Math.floor(numPrice / numTickSize) * numTickSize
-
-    return rounded.toFixed(decimals)
-  }
-
-  /**
-   * 格式化数量到正确精度
-   */
-  static formatQuantity(quantity: number | string, stepSize: string): string {
-    const numQuantity = Number(quantity)
-    const numStepSize = Number(stepSize)
-
-    if (numStepSize <= 0) return String(numQuantity)
-
-    // 计算精度位数
-    const decimals = this.countDecimals(numStepSize)
-
-    // 舍入到最近的step
-    const rounded = Math.floor(numQuantity / numStepSize) * numStepSize
-
-    return rounded.toFixed(decimals)
-  }
-
-  /**
-   * 验证订单参数
-   */
-  static validateOrder(
-    exchange: string,
-    symbol: string,
-    price: string,
-    quantity: string,
-  ): { valid: boolean; errors: string[]; adjustedPrice?: string; adjustedQuantity?: string } {
-    const config = this.getSymbolConfig(exchange, symbol)
-    const errors: string[] = []
-
-    if (!config) {
-      return { valid: false, errors: [`未找到 ${exchange}:${symbol} 的配置信息`] }
-    }
-
-    const numPrice = Number(price)
-    const numQuantity = Number(quantity)
-    const numMinQty = Number(config.precision.minQty)
-    const numMaxQty = Number(config.precision.maxQty)
-    const numMinNotional = Number(config.precision.minNotional)
-
-    // 验证数量范围
-    if (numQuantity < numMinQty) {
-      errors.push(`数量 ${quantity} 小于最小值 ${config.precision.minQty}`)
-    }
-    if (numMaxQty > 0 && numQuantity > numMaxQty) {
-      errors.push(`数量 ${quantity} 超过最大值 ${config.precision.maxQty}`)
-    }
-
-    // 验证名义价值
-    const notional = numPrice * numQuantity
-    if (notional < numMinNotional) {
-      errors.push(`名义价值 ${notional} 小于最小值 ${config.precision.minNotional}`)
-    }
-
-    // 格式化价格和数量
-    const adjustedPrice = this.formatPrice(price, config.precision.tickSize)
-    const adjustedQuantity = this.formatQuantity(quantity, config.precision.stepSize)
-
-    // 检查是否需要调整
-    if (adjustedPrice !== price) {
-      errors.push(`价格已调整: ${price} -> ${adjustedPrice}`)
-    }
-    if (adjustedQuantity !== quantity) {
-      errors.push(`数量已调整: ${quantity} -> ${adjustedQuantity}`)
-    }
-
-    return {
-      valid: errors.length === 0,
-      errors,
-      adjustedPrice,
-      adjustedQuantity,
-    }
-  }
-
-  /**
-   * 自动调整订单参数使其符合精度要求
-   */
-  static adjustOrderParams(
-    exchange: string,
-    symbol: string,
-    price: number | string,
-    quantity: number | string,
-    direction: 'up' | 'down' = 'down',
-  ): { price: string; quantity: string; valid: boolean; warnings: string[] } {
-    const config = this.getSymbolConfig(exchange, symbol)
-    const warnings: string[] = []
-
-    if (!config) {
-      return {
-        price: String(price),
-        quantity: String(quantity),
-        valid: false,
-        warnings: [`未找到 ${exchange}:${symbol} 的配置`],
-      }
-    }
-
-    const adjustedPrice = this.formatPrice(price, config.precision.tickSize)
-    let adjustedQuantity = this.formatQuantity(quantity, config.precision.stepSize)
-
-    // 确保满足最小数量要求
-    const numAdjustedQuantity = Number(adjustedQuantity)
-    const numMinQty = Number(config.precision.minQty)
-
-    if (numAdjustedQuantity < numMinQty) {
-      adjustedQuantity = config.precision.minQty
-      warnings.push(`数量调整到最小值: ${adjustedQuantity}`)
-    }
-
-    // 确保满足最小名义价值要求
-    const notional = Number(adjustedPrice) * Number(adjustedQuantity)
-    const numMinNotional = Number(config.precision.minNotional)
-
-    if (notional < numMinNotional) {
-      if (direction === 'up') {
-        // 通过增加数量来满足最小名义价值
-        const minQuantityForNotional = numMinNotional / Number(adjustedPrice)
-        adjustedQuantity = this.formatQuantity(minQuantityForNotional, config.precision.stepSize)
-        warnings.push(`为满足最小名义价值,数量调整为: ${adjustedQuantity}`)
-      } else {
-        warnings.push(`名义价值 ${notional} 低于最小值 ${numMinNotional}`)
-      }
-    }
-
-    const validation = this.validateOrder(exchange, symbol, adjustedPrice, adjustedQuantity)
-
-    return {
-      price: adjustedPrice,
-      quantity: adjustedQuantity,
-      valid: validation.valid,
-      warnings,
-    }
-  }
-
-  /**
-   * 批量调整多个订单
-   */
-  static adjustBatchOrders(
-    exchange: string,
-    orders: Array<{ symbol: string; price: number | string; quantity: number | string }>,
-  ): Array<{ symbol: string; price: string; quantity: string; valid: boolean; warnings: string[] }> {
-    return orders.map(order => ({
-      symbol: order.symbol,
-      ...this.adjustOrderParams(exchange, order.symbol, order.price, order.quantity),
-    }))
-  }
-
-  /**
-   * 计算小数位数
-   */
-  private static countDecimals(value: number | string): number {
-    const str = String(value)
-    const decimalIndex = str.indexOf('.')
-    return decimalIndex >= 0 ? str.length - decimalIndex - 1 : 0
-  }
-
-  /**
-   * 获取建议的订单参数
-   */
-  static getSuggestedOrderSize(
-    exchange: string,
-    symbol: string,
-    targetNotional: number,
-    currentPrice: number,
-  ): { price: string; quantity: string; actualNotional: number } | null {
-    const config = this.getSymbolConfig(exchange, symbol)
-    if (!config) return null
-
-    const baseQuantity = targetNotional / currentPrice
-    const adjustedPrice = this.formatPrice(currentPrice, config.precision.tickSize)
-    const adjustedQuantity = this.formatQuantity(baseQuantity, config.precision.stepSize)
-
-    // 确保满足最小要求
-    const result = this.adjustOrderParams(exchange, symbol, adjustedPrice, adjustedQuantity, 'up')
-
-    return {
-      price: result.price,
-      quantity: result.quantity,
-      actualNotional: Number(result.price) * Number(result.quantity),
-    }
-  }
-
-  /**
-   * 清理配置缓存
-   */
-  static clearCache(): void {
-    this.exchangeConfigs.clear()
-  }
-}

+ 0 - 64
src/shared/utils/proxyFetch.ts

@@ -1,64 +0,0 @@
-import { httpClient } from './httpClient'
-import { logger } from './logger'
-
-/**
- * 代理增强的fetch函数
- * 完全兼容原生fetch API,但自动支持代理
- */
-export async function proxyFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
-  const url = typeof input === 'string' ? input : input.toString()
-  const options = init || {}
-
-  try {
-    const response = await httpClient.request(url, {
-      method: (options.method as any) || 'GET',
-      headers: options.headers as Record<string, string>,
-      body: options.body,
-      signal: options.signal,
-      retries: 2, // 默认重试2次
-      retryDelay: 1000,
-    })
-
-    // 创建兼容的Response对象
-    const responseInit: ResponseInit = {
-      status: response.status,
-      statusText: response.statusText,
-      headers: response.headers,
-    }
-
-    return new Response(typeof response.data === 'string' ? response.data : JSON.stringify(response.data), responseInit)
-  } catch (error: any) {
-    logger.error('ProxyFetch error:', { url, error: error.message })
-    throw error
-  }
-}
-
-/**
- * 全局替换fetch函数 (仅在Node.js环境)
- */
-export function installProxyFetch(): void {
-  if (typeof globalThis !== 'undefined') {
-    // 保存原始fetch
-    const originalFetch = globalThis.fetch
-
-    // 替换为代理版本
-    ;(globalThis as any).fetch = proxyFetch
-
-    // 提供还原方法
-    ;(globalThis as any).restoreOriginalFetch = () => {
-      ;(globalThis as any).fetch = originalFetch
-    }
-
-    logger.info('全局fetch已替换为代理版本')
-  }
-}
-
-/**
- * 还原原始fetch函数
- */
-export function restoreOriginalFetch(): void {
-  if (typeof globalThis !== 'undefined' && (globalThis as any).restoreOriginalFetch) {
-    ;(globalThis as any).restoreOriginalFetch()
-    logger.info('已还原原始fetch函数')
-  }
-}

+ 0 - 9
src/shared/utils/web3.ts

@@ -1,9 +0,0 @@
-import { ethers } from 'ethers'
-
-export function getProvider(rpcUrl: string): ethers.JsonRpcProvider {
-  return new ethers.JsonRpcProvider(rpcUrl)
-}
-
-export function getWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {
-  return new ethers.Wallet(privateKey, provider)
-}

+ 0 - 280
src/utils/StateManager.ts

@@ -1,280 +0,0 @@
-import fs from 'fs'
-import path from 'path'
-import { logger } from './logger.js'
-
-/**
- * 系统状态管理器
- * 负责持久化和恢复系统状态,确保Delta中性连续性
- */
-export interface SystemState {
-  timestamp: number
-  accountStates: Record<
-    string,
-    {
-      totalTrades: number
-      netPosition: number
-      totalVolume: number
-      lastBalance: number
-      needsRebalance: boolean
-      lastUpdateTime: number
-    }
-  >
-  globalStats: {
-    totalTrades: number
-    successfulTrades: number
-    failedTrades: number
-    totalVolume: number
-    sessionStartTime: number
-  }
-  deltaMetrics: {
-    totalDelta: number
-    maxDelta: number
-    lastRebalanceTime: number
-    rebalanceCount: number
-  }
-  riskMetrics: {
-    dailyTrades: number
-    lastRiskCheck: number
-    emergencyStops: number
-  }
-}
-
-export class StateManager {
-  private stateFile: string
-  private backupDir: string
-
-  constructor(stateFile = '.system_state.json') {
-    this.stateFile = path.resolve(stateFile)
-    this.backupDir = path.resolve('.state_backups')
-    this.ensureBackupDirectory()
-  }
-
-  private ensureBackupDirectory(): void {
-    if (!fs.existsSync(this.backupDir)) {
-      fs.mkdirSync(this.backupDir, { recursive: true })
-    }
-  }
-
-  /**
-   * 保存系统状态
-   */
-  async saveState(state: SystemState): Promise<void> {
-    try {
-      // 创建状态快照
-      const stateSnapshot = {
-        ...state,
-        timestamp: Date.now(),
-        version: '1.0.0',
-        checksum: this.calculateChecksum(state),
-      }
-
-      // 备份当前状态文件
-      if (fs.existsSync(this.stateFile)) {
-        const backupFile = path.join(
-          this.backupDir,
-          `state_backup_${new Date().toISOString().replace(/[:.]/g, '-')}.json`,
-        )
-        fs.copyFileSync(this.stateFile, backupFile)
-      }
-
-      // 保存新状态
-      fs.writeFileSync(this.stateFile, JSON.stringify(stateSnapshot, null, 2))
-
-      logger.info('系统状态已保存', {
-        timestamp: stateSnapshot.timestamp,
-        accounts: Object.keys(state.accountStates).length,
-        totalDelta: state.deltaMetrics.totalDelta,
-      })
-
-      // 清理旧备份文件 (保留最近10个)
-      this.cleanupOldBackups()
-    } catch (error: any) {
-      logger.error('保存系统状态失败', { error: error.message })
-      throw error
-    }
-  }
-
-  /**
-   * 加载系统状态
-   */
-  async loadState(): Promise<SystemState | null> {
-    try {
-      if (!fs.existsSync(this.stateFile)) {
-        logger.info('未找到状态文件,将创建新的系统状态')
-        return null
-      }
-
-      const stateData = fs.readFileSync(this.stateFile, 'utf8')
-      const parsedState = JSON.parse(stateData)
-
-      // 验证状态完整性
-      if (!this.validateState(parsedState)) {
-        logger.warn('状态文件损坏,尝试从备份恢复')
-        return await this.loadFromBackup()
-      }
-
-      logger.info('系统状态加载成功', {
-        timestamp: parsedState.timestamp,
-        accounts: Object.keys(parsedState.accountStates || {}).length,
-        totalDelta: parsedState.deltaMetrics?.totalDelta || 0,
-        age: Date.now() - parsedState.timestamp,
-      })
-
-      return parsedState as SystemState
-    } catch (error: any) {
-      logger.error('加载系统状态失败', { error: error.message })
-      return await this.loadFromBackup()
-    }
-  }
-
-  /**
-   * 从备份恢复状态
-   */
-  private async loadFromBackup(): Promise<SystemState | null> {
-    try {
-      const backupFiles = fs
-        .readdirSync(this.backupDir)
-        .filter(file => file.startsWith('state_backup_'))
-        .sort()
-        .reverse()
-
-      for (const backupFile of backupFiles.slice(0, 3)) {
-        // 尝试最近3个备份
-        try {
-          const backupPath = path.join(this.backupDir, backupFile)
-          const backupData = fs.readFileSync(backupPath, 'utf8')
-          const parsedBackup = JSON.parse(backupData)
-
-          if (this.validateState(parsedBackup)) {
-            logger.info('从备份恢复系统状态成功', { backupFile })
-            return parsedBackup as SystemState
-          }
-        } catch (backupError) {
-          logger.warn('备份文件损坏', { backupFile })
-          continue
-        }
-      }
-
-      logger.warn('所有备份文件都无法使用,返回空状态')
-      return null
-    } catch (error: any) {
-      logger.error('从备份恢复失败', { error: error.message })
-      return null
-    }
-  }
-
-  /**
-   * 验证状态完整性
-   */
-  private validateState(state: any): boolean {
-    return (
-      state &&
-      typeof state.timestamp === 'number' &&
-      state.accountStates &&
-      typeof state.accountStates === 'object' &&
-      state.globalStats &&
-      state.deltaMetrics &&
-      state.riskMetrics
-    )
-  }
-
-  /**
-   * 计算状态校验和
-   */
-  private calculateChecksum(state: SystemState): string {
-    const stateString = JSON.stringify(state, Object.keys(state).sort())
-    return Buffer.from(stateString).toString('base64').slice(0, 16)
-  }
-
-  /**
-   * 清理旧备份文件
-   */
-  private cleanupOldBackups(): void {
-    try {
-      const backupFiles = fs
-        .readdirSync(this.backupDir)
-        .filter(file => file.startsWith('state_backup_'))
-        .sort()
-
-      if (backupFiles.length > 10) {
-        const filesToDelete = backupFiles.slice(0, backupFiles.length - 10)
-        filesToDelete.forEach(file => {
-          fs.unlinkSync(path.join(this.backupDir, file))
-        })
-        logger.info('清理旧备份文件', { deleted: filesToDelete.length })
-      }
-    } catch (error: any) {
-      logger.warn('清理备份文件失败', { error: error.message })
-    }
-  }
-
-  /**
-   * 创建默认状态
-   */
-  createDefaultState(): SystemState {
-    return {
-      timestamp: Date.now(),
-      accountStates: {},
-      globalStats: {
-        totalTrades: 0,
-        successfulTrades: 0,
-        failedTrades: 0,
-        totalVolume: 0,
-        sessionStartTime: Date.now(),
-      },
-      deltaMetrics: {
-        totalDelta: 0,
-        maxDelta: 0,
-        lastRebalanceTime: 0,
-        rebalanceCount: 0,
-      },
-      riskMetrics: {
-        dailyTrades: 0,
-        lastRiskCheck: Date.now(),
-        emergencyStops: 0,
-      },
-    }
-  }
-
-  /**
-   * 获取Delta中性报告
-   */
-  getDeltaNeutralityReport(state: SystemState): {
-    isDeltaNeutral: boolean
-    totalDelta: number
-    maxAllowedDelta: number
-    recommendation: string
-  } {
-    const totalDelta = Math.abs(state.deltaMetrics.totalDelta)
-    const maxAllowedDelta = 0.01 // 最大允许敞口 0.01 BTC
-
-    const isDeltaNeutral = totalDelta <= maxAllowedDelta
-
-    let recommendation = ''
-    if (!isDeltaNeutral) {
-      recommendation = `需要对冲平仓 ${totalDelta.toFixed(4)} BTC 敞口以保持Delta中性`
-    } else {
-      recommendation = 'Delta中性状态良好,可以安全退出'
-    }
-
-    return {
-      isDeltaNeutral,
-      totalDelta,
-      maxAllowedDelta,
-      recommendation,
-    }
-  }
-
-  /**
-   * 紧急状态保存 (进程退出时)
-   */
-  emergencySave(state: SystemState): void {
-    try {
-      const emergencyFile = `.emergency_state_${Date.now()}.json`
-      fs.writeFileSync(emergencyFile, JSON.stringify(state, null, 2))
-      logger.info('紧急状态保存完成', { file: emergencyFile })
-    } catch (error: any) {
-      logger.error('紧急状态保存失败', { error: error.message })
-    }
-  }
-}

+ 0 - 20
src/utils/math.ts

@@ -1,20 +0,0 @@
-export function toFixed(num: number, decimals: number = 8): number {
-  const factor = Math.pow(10, decimals)
-  return Math.round(num * factor) / factor
-}
-
-export function percentChange(from: number, to: number): number {
-  if (from === 0) return 0
-  return ((to - from) / from) * 100
-}
-
-// 简单移动平均
-export function sma(values: number[], period: number): number[] {
-  const result: number[] = []
-  for (let i = 0; i <= values.length - period; i++) {
-    const window = values.slice(i, i + period)
-    const avg = window.reduce((a, b) => a + b, 0) / period
-    result.push(avg)
-  }
-  return result
-}

+ 0 - 64
src/utils/proxyFetch.ts

@@ -1,64 +0,0 @@
-import { httpClient } from './httpClient.js'
-import { logger } from './logger.js'
-
-/**
- * 代理增强的fetch函数
- * 完全兼容原生fetch API,但自动支持代理
- */
-export async function proxyFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
-  const url = typeof input === 'string' ? input : input.toString()
-  const options = init || {}
-
-  try {
-    const response = await httpClient.request(url, {
-      method: (options.method as any) || 'GET',
-      headers: options.headers as Record<string, string>,
-      body: options.body,
-      signal: options.signal,
-      retries: 2, // 默认重试2次
-      retryDelay: 1000,
-    })
-
-    // 创建兼容的Response对象
-    const responseInit: ResponseInit = {
-      status: response.status,
-      statusText: response.statusText,
-      headers: response.headers,
-    }
-
-    return new Response(typeof response.data === 'string' ? response.data : JSON.stringify(response.data), responseInit)
-  } catch (error: any) {
-    logger.error('ProxyFetch error:', { url, error: error.message })
-    throw error
-  }
-}
-
-/**
- * 全局替换fetch函数 (仅在Node.js环境)
- */
-export function installProxyFetch(): void {
-  if (typeof globalThis !== 'undefined') {
-    // 保存原始fetch
-    const originalFetch = globalThis.fetch
-
-    // 替换为代理版本
-    ;(globalThis as any).fetch = proxyFetch
-
-    // 提供还原方法
-    ;(globalThis as any).restoreOriginalFetch = () => {
-      ;(globalThis as any).fetch = originalFetch
-    }
-
-    logger.info('全局fetch已替换为代理版本')
-  }
-}
-
-/**
- * 还原原始fetch函数
- */
-export function restoreOriginalFetch(): void {
-  if (typeof globalThis !== 'undefined' && (globalThis as any).restoreOriginalFetch) {
-    ;(globalThis as any).restoreOriginalFetch()
-    logger.info('已还原原始fetch函数')
-  }
-}

+ 0 - 9
src/utils/web3.ts

@@ -1,9 +0,0 @@
-import { ethers } from 'ethers'
-
-export function getProvider(rpcUrl: string): ethers.JsonRpcProvider {
-  return new ethers.JsonRpcProvider(rpcUrl)
-}
-
-export function getWallet(privateKey: string, provider: ethers.JsonRpcProvider): ethers.Wallet {
-  return new ethers.Wallet(privateKey, provider)
-}