| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 |
- /**
- * T032 演示:策略模块桥接服务
- * 演示如何集成现有的 TradingEngineV2 与新的 StrategyModuleService
- */
- import { logger } from '../src/utils/logger.js'
- // 模拟现有的 TradingEngineV2
- class MockTradingEngineV2 {
- private isRunning = false
- async initialize(): Promise<void> {
- logger.info('模拟 TradingEngineV2 初始化')
- }
- async start(): Promise<void> {
- logger.info('模拟 TradingEngineV2 启动')
- this.isRunning = true
- }
- async stop(): Promise<void> {
- logger.info('模拟 TradingEngineV2 停止')
- this.isRunning = false
- }
- getStatus(): any {
- return {
- name: 'TradingEngineV2',
- status: this.isRunning ? 'running' : 'stopped',
- lastUpdate: Date.now(),
- details: {
- totalTrades: 150,
- successfulTrades: 145,
- failedTrades: 5,
- totalVolume: 12500.50
- }
- }
- }
- // 模拟生成交易信号
- generateTradingSignals(): any[] {
- return [
- {
- symbol: 'BTC-USD',
- action: 'buy',
- side: 'buy',
- amount: '0.01',
- confidence: 0.85,
- reason: 'Delta neutral rebalancing'
- },
- {
- symbol: 'ETH-USD',
- action: 'sell',
- side: 'sell',
- amount: '0.5',
- confidence: 0.78,
- reason: 'Volume boost signal'
- }
- ]
- }
- }
- // 模拟 StrategyModuleService
- class MockStrategyModuleService {
- async validateModule(module: any): Promise<any> {
- logger.info(`验证策略模块: ${module.moduleId}`)
-
- // 模拟验证过程
- await new Promise(resolve => setTimeout(resolve, 100))
-
- return {
- isValid: true,
- errors: []
- }
- }
- async runSandboxTest(module: any): Promise<any> {
- logger.info(`运行沙箱测试: ${module.moduleId}`)
-
- // 模拟沙箱测试
- await new Promise(resolve => setTimeout(resolve, 200))
-
- return {
- success: true,
- result: {
- simulatedTrades: Math.floor(Math.random() * 5),
- simulatedVolume: Math.random() * 1000,
- testDuration: 200
- },
- errors: []
- }
- }
- }
- // 模拟其他管理器
- class MockStrategyModuleManager {
- private modules = new Map<string, any>()
- addModule(module: any): void {
- this.modules.set(module.moduleId, module)
- logger.info(`添加策略模块: ${module.moduleId}`)
- }
- updateModule(module: any): void {
- this.modules.set(module.moduleId, module)
- logger.info(`更新策略模块: ${module.moduleId}`)
- }
- getAllModules(): any[] {
- return Array.from(this.modules.values())
- }
- }
- class MockExchangeAccountManager {
- private accounts = new Map<string, any>()
- getAllAccounts(): any[] {
- return Array.from(this.accounts.values())
- }
- addAccount(account: any): void {
- this.accounts.set(account.accountId, account)
- }
- }
- class MockMonitoringEventManager {
- private events: any[] = []
- addEvent(event: any): void {
- this.events.push(event)
- logger.info(`添加监控事件: ${event.type}`)
- }
- getAllEvents(): any[] {
- return this.events
- }
- }
- // 简化的策略模块桥接器实现
- class SimpleStrategyModuleBridge {
- private isRunning = false
- private executionStats = {
- totalExecutions: 0,
- successfulExecutions: 0,
- failedExecutions: 0,
- lastExecutionTime: 0,
- lastError: null as string | null
- }
- private registeredModules = new Map<string, any>()
- private activeModules = new Set<string>()
- constructor(
- private tradingEngineV2: MockTradingEngineV2,
- private strategyModuleService: MockStrategyModuleService,
- private strategyModuleManager: MockStrategyModuleManager,
- private exchangeAccountManager: MockExchangeAccountManager,
- private monitoringManager: MockMonitoringEventManager
- ) {}
- async start(): Promise<void> {
- logger.info('启动简化策略模块桥接器')
-
- try {
- await this.initializeStrategyModules()
- await this.registerLegacyStrategies()
- this.setupModuleExecutionMonitoring()
- this.isRunning = true
- logger.info('简化策略模块桥接器启动成功')
- } catch (error: any) {
- logger.error(`启动失败: ${error.message}`)
- throw error
- }
- }
- async stop(): Promise<void> {
- logger.info('停止简化策略模块桥接器')
- this.isRunning = false
- }
- private async initializeStrategyModules(): Promise<void> {
- logger.info('初始化策略模块')
- // 创建基础策略模块
- const deltaNeutralModule = {
- moduleId: 'delta-neutral-strategy',
- name: 'Delta Neutral Strategy',
- version: '1.0.0',
- type: 'hedging',
- status: 'active',
- config: {
- deltaThreshold: 0.0005,
- rebalanceInterval: 30000,
- maxPositionSize: 0.01,
- enableAutoRebalance: true
- },
- metadata: {
- author: 'System',
- description: 'Delta neutral hedging strategy for risk management',
- tags: ['hedging', 'risk-management', 'delta-neutral']
- },
- createdAt: new Date(),
- updatedAt: new Date()
- }
- this.strategyModuleManager.addModule(deltaNeutralModule)
- this.registeredModules.set(deltaNeutralModule.moduleId, deltaNeutralModule)
- const utilizationModule = {
- moduleId: 'utilization-management-strategy',
- name: 'Capital Utilization Management',
- version: '1.0.0',
- type: 'allocation',
- status: 'active',
- config: {
- targetUtilizationMin: 0.5,
- targetUtilizationMax: 0.8,
- rebalanceThreshold: 0.1,
- enableAutoRebalance: true
- },
- metadata: {
- author: 'System',
- description: 'Capital utilization management strategy',
- tags: ['allocation', 'utilization', 'rebalancing']
- },
- createdAt: new Date(),
- updatedAt: new Date()
- }
- this.strategyModuleManager.addModule(utilizationModule)
- this.registeredModules.set(utilizationModule.moduleId, utilizationModule)
- logger.info(`创建了 ${this.registeredModules.size} 个基础策略模块`)
- }
- private async registerLegacyStrategies(): Promise<void> {
- logger.info('注册现有交易策略')
- const signalGenerationModule = {
- moduleId: 'legacy-signal-generation',
- name: 'Legacy Signal Generation',
- version: '1.0.0',
- type: 'signal',
- status: 'active',
- config: {
- signalInterval: 15000,
- confidenceThreshold: 0.7,
- enableVolumeBoost: true,
- volumeBoostInterval: 8000
- },
- metadata: {
- author: 'Legacy',
- description: 'Legacy signal generation strategy from TradingEngineV2',
- tags: ['legacy', 'signal-generation', 'volume-boost']
- },
- createdAt: new Date(),
- updatedAt: new Date()
- }
- this.strategyModuleManager.addModule(signalGenerationModule)
- this.registeredModules.set(signalGenerationModule.moduleId, signalGenerationModule)
- logger.info('现有策略注册完成')
- }
- private setupModuleExecutionMonitoring(): void {
- logger.info('设置策略模块执行监控')
- this.monitoringManager.addEvent({
- eventId: `strategy-bridge-start-${Date.now()}`,
- type: 'strategy-bridge-start',
- payload: {
- registeredModules: this.registeredModules.size,
- bridgeMode: true
- },
- severity: 'INFO',
- createdAt: new Date()
- })
- logger.info('策略模块执行监控设置完成')
- }
- async executeModule(moduleId: string, context?: any): Promise<{
- success: boolean
- result?: any
- error?: string
- }> {
- try {
- const module = this.registeredModules.get(moduleId)
- if (!module) {
- return {
- success: false,
- error: `模块未找到: ${moduleId}`
- }
- }
- if (module.status !== 'active') {
- return {
- success: false,
- error: `模块未激活: ${moduleId}`
- }
- }
- this.activeModules.add(moduleId)
- this.executionStats.totalExecutions++
- logger.info(`执行策略模块: ${moduleId}`)
- // 模拟模块执行
- const mockResult = {
- moduleId: module.moduleId,
- executionMode: 'dry-run',
- simulatedTrades: Math.floor(Math.random() * 3),
- simulatedVolume: Math.random() * 1000,
- executionTime: Date.now(),
- success: true
- }
- this.executionStats.successfulExecutions++
- this.executionStats.lastExecutionTime = Date.now()
- this.executionStats.lastError = null
- this.activeModules.delete(moduleId)
- // 记录执行结果
- this.monitoringManager.addEvent({
- eventId: `module-execution-${Date.now()}`,
- type: 'module-execution',
- payload: {
- moduleId: module.moduleId,
- result: mockResult
- },
- severity: 'INFO',
- createdAt: new Date()
- })
- return {
- success: true,
- result: mockResult
- }
- } catch (error: any) {
- this.activeModules.delete(moduleId)
- this.executionStats.failedExecutions++
- this.executionStats.lastError = error.message
-
- logger.error(`策略模块执行失败: ${moduleId}`, { error: error.message })
-
- return {
- success: false,
- error: error.message
- }
- }
- }
- async startModule(moduleId: string): Promise<{
- success: boolean
- message: string
- }> {
- try {
- const module = this.registeredModules.get(moduleId)
- if (!module) {
- return {
- success: false,
- message: `模块未找到: ${moduleId}`
- }
- }
- module.status = 'active'
- this.strategyModuleManager.updateModule(module)
-
- logger.info(`启动策略模块: ${moduleId}`)
-
- return {
- success: true,
- message: `模块启动成功: ${moduleId}`
- }
- } catch (error: any) {
- return {
- success: false,
- message: `模块启动失败: ${error.message}`
- }
- }
- }
- async stopModule(moduleId: string): Promise<{
- success: boolean
- message: string
- }> {
- try {
- const module = this.registeredModules.get(moduleId)
- if (!module) {
- return {
- success: false,
- message: `模块未找到: ${moduleId}`
- }
- }
- module.status = 'stopped'
- this.strategyModuleManager.updateModule(module)
-
- this.activeModules.delete(moduleId)
-
- logger.info(`停止策略模块: ${moduleId}`)
-
- return {
- success: true,
- message: `模块停止成功: ${moduleId}`
- }
- } catch (error: any) {
- return {
- success: false,
- message: `模块停止失败: ${error.message}`
- }
- }
- }
- getBridgeStats(): any {
- return {
- registeredModules: this.registeredModules.size,
- activeModules: Array.from(this.registeredModules.values()).filter((m: any) => m.status === 'active').length,
- totalExecutions: this.executionStats.totalExecutions,
- successfulExecutions: this.executionStats.successfulExecutions,
- failedExecutions: this.executionStats.failedExecutions,
- sandboxTests: 0,
- lastExecutionTime: this.executionStats.lastExecutionTime,
- bridgeMode: true
- }
- }
- getRegisteredModules(): any[] {
- return Array.from(this.registeredModules.values())
- }
- getActiveModules(): any[] {
- return Array.from(this.registeredModules.values()).filter((m: any) => m.status === 'active')
- }
- }
- async function main() {
- logger.info('=== T032 策略模块桥接演示 ===')
- try {
- // 1. 创建模拟组件
- const mockTradingEngine = new MockTradingEngineV2()
- const mockStrategyService = new MockStrategyModuleService()
- const mockModuleManager = new MockStrategyModuleManager()
- const mockAccountManager = new MockExchangeAccountManager()
- const mockMonitoringManager = new MockMonitoringEventManager()
- // 2. 初始化交易引擎
- await mockTradingEngine.initialize()
- await mockTradingEngine.start()
- // 3. 创建策略模块桥接器
- const strategyBridge = new SimpleStrategyModuleBridge(
- mockTradingEngine,
- mockStrategyService,
- mockModuleManager,
- mockAccountManager,
- mockMonitoringManager
- )
- // 4. 启动策略模块桥接器
- logger.info('启动策略模块桥接器...')
- await strategyBridge.start()
- // 5. 检查初始状态
- const initialStats = strategyBridge.getBridgeStats()
- logger.info('初始策略模块桥接统计:', initialStats)
- // 6. 获取注册的模块列表
- const registeredModules = strategyBridge.getRegisteredModules()
- logger.info(`注册的模块数量: ${registeredModules.length}`)
-
- registeredModules.forEach(module => {
- logger.info(`- ${module.moduleId}: ${module.name} (${module.type})`)
- })
- // 7. 执行策略模块测试
- logger.info('执行策略模块测试...')
-
- for (const module of registeredModules.slice(0, 2)) { // 只测试前两个模块
- const executionResult = await strategyBridge.executeModule(module.moduleId)
- logger.info(`模块 ${module.moduleId} 执行结果:`, executionResult)
- }
- // 8. 测试模块启动/停止
- logger.info('测试模块启动/停止...')
-
- const firstModule = registeredModules[0]
- if (firstModule) {
- const stopResult = await strategyBridge.stopModule(firstModule.moduleId)
- logger.info(`停止模块结果:`, stopResult)
- const startResult = await strategyBridge.startModule(firstModule.moduleId)
- logger.info(`启动模块结果:`, startResult)
- }
- // 9. 检查最终状态
- const finalStats = strategyBridge.getBridgeStats()
- logger.info('最终策略模块桥接统计:', finalStats)
- // 10. 验证数据一致性
- logger.info('验证数据一致性...')
- const allModules = mockModuleManager.getAllModules()
- const monitoringEvents = mockMonitoringManager.getAllEvents()
- logger.info(`验证结果:`)
- logger.info(`- 策略模块: ${allModules.length}`)
- logger.info(`- 监控事件: ${monitoringEvents.length}`)
- logger.info(`- 总执行次数: ${finalStats.totalExecutions}`)
- logger.info(`- 成功执行次数: ${finalStats.successfulExecutions}`)
- logger.info(`- 失败执行次数: ${finalStats.failedExecutions}`)
- logger.info(`- 桥接模式: ${finalStats.bridgeMode ? '✅' : '❌'}`)
- logger.info(`- 数据一致性: ${allModules.length > 0 && monitoringEvents.length > 0 ? '✅' : '❌'}`)
- // 11. 停止桥接器
- await strategyBridge.stop()
- logger.info('=== T032 策略模块桥接演示完成 ===')
- } catch (error: any) {
- logger.error('T032 演示失败:', { error: error.message, stack: error.stack })
- process.exit(1)
- }
- }
- // 运行演示
- if (import.meta.url === `file://${process.argv[1]}`) {
- main().catch(error => {
- logger.error('演示运行失败:', error)
- process.exit(1)
- })
- }
|