t032_strategy_module_demo.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /**
  2. * T032 演示:策略模块桥接服务
  3. * 演示如何集成现有的 TradingEngineV2 与新的 StrategyModuleService
  4. */
  5. import { logger } from '../src/utils/logger.js'
  6. // 模拟现有的 TradingEngineV2
  7. class MockTradingEngineV2 {
  8. private isRunning = false
  9. async initialize(): Promise<void> {
  10. logger.info('模拟 TradingEngineV2 初始化')
  11. }
  12. async start(): Promise<void> {
  13. logger.info('模拟 TradingEngineV2 启动')
  14. this.isRunning = true
  15. }
  16. async stop(): Promise<void> {
  17. logger.info('模拟 TradingEngineV2 停止')
  18. this.isRunning = false
  19. }
  20. getStatus(): any {
  21. return {
  22. name: 'TradingEngineV2',
  23. status: this.isRunning ? 'running' : 'stopped',
  24. lastUpdate: Date.now(),
  25. details: {
  26. totalTrades: 150,
  27. successfulTrades: 145,
  28. failedTrades: 5,
  29. totalVolume: 12500.50
  30. }
  31. }
  32. }
  33. // 模拟生成交易信号
  34. generateTradingSignals(): any[] {
  35. return [
  36. {
  37. symbol: 'BTC-USD',
  38. action: 'buy',
  39. side: 'buy',
  40. amount: '0.01',
  41. confidence: 0.85,
  42. reason: 'Delta neutral rebalancing'
  43. },
  44. {
  45. symbol: 'ETH-USD',
  46. action: 'sell',
  47. side: 'sell',
  48. amount: '0.5',
  49. confidence: 0.78,
  50. reason: 'Volume boost signal'
  51. }
  52. ]
  53. }
  54. }
  55. // 模拟 StrategyModuleService
  56. class MockStrategyModuleService {
  57. async validateModule(module: any): Promise<any> {
  58. logger.info(`验证策略模块: ${module.moduleId}`)
  59. // 模拟验证过程
  60. await new Promise(resolve => setTimeout(resolve, 100))
  61. return {
  62. isValid: true,
  63. errors: []
  64. }
  65. }
  66. async runSandboxTest(module: any): Promise<any> {
  67. logger.info(`运行沙箱测试: ${module.moduleId}`)
  68. // 模拟沙箱测试
  69. await new Promise(resolve => setTimeout(resolve, 200))
  70. return {
  71. success: true,
  72. result: {
  73. simulatedTrades: Math.floor(Math.random() * 5),
  74. simulatedVolume: Math.random() * 1000,
  75. testDuration: 200
  76. },
  77. errors: []
  78. }
  79. }
  80. }
  81. // 模拟其他管理器
  82. class MockStrategyModuleManager {
  83. private modules = new Map<string, any>()
  84. addModule(module: any): void {
  85. this.modules.set(module.moduleId, module)
  86. logger.info(`添加策略模块: ${module.moduleId}`)
  87. }
  88. updateModule(module: any): void {
  89. this.modules.set(module.moduleId, module)
  90. logger.info(`更新策略模块: ${module.moduleId}`)
  91. }
  92. getAllModules(): any[] {
  93. return Array.from(this.modules.values())
  94. }
  95. }
  96. class MockExchangeAccountManager {
  97. private accounts = new Map<string, any>()
  98. getAllAccounts(): any[] {
  99. return Array.from(this.accounts.values())
  100. }
  101. addAccount(account: any): void {
  102. this.accounts.set(account.accountId, account)
  103. }
  104. }
  105. class MockMonitoringEventManager {
  106. private events: any[] = []
  107. addEvent(event: any): void {
  108. this.events.push(event)
  109. logger.info(`添加监控事件: ${event.type}`)
  110. }
  111. getAllEvents(): any[] {
  112. return this.events
  113. }
  114. }
  115. // 简化的策略模块桥接器实现
  116. class SimpleStrategyModuleBridge {
  117. private isRunning = false
  118. private executionStats = {
  119. totalExecutions: 0,
  120. successfulExecutions: 0,
  121. failedExecutions: 0,
  122. lastExecutionTime: 0,
  123. lastError: null as string | null
  124. }
  125. private registeredModules = new Map<string, any>()
  126. private activeModules = new Set<string>()
  127. constructor(
  128. private tradingEngineV2: MockTradingEngineV2,
  129. private strategyModuleService: MockStrategyModuleService,
  130. private strategyModuleManager: MockStrategyModuleManager,
  131. private exchangeAccountManager: MockExchangeAccountManager,
  132. private monitoringManager: MockMonitoringEventManager
  133. ) {}
  134. async start(): Promise<void> {
  135. logger.info('启动简化策略模块桥接器')
  136. try {
  137. await this.initializeStrategyModules()
  138. await this.registerLegacyStrategies()
  139. this.setupModuleExecutionMonitoring()
  140. this.isRunning = true
  141. logger.info('简化策略模块桥接器启动成功')
  142. } catch (error: any) {
  143. logger.error(`启动失败: ${error.message}`)
  144. throw error
  145. }
  146. }
  147. async stop(): Promise<void> {
  148. logger.info('停止简化策略模块桥接器')
  149. this.isRunning = false
  150. }
  151. private async initializeStrategyModules(): Promise<void> {
  152. logger.info('初始化策略模块')
  153. // 创建基础策略模块
  154. const deltaNeutralModule = {
  155. moduleId: 'delta-neutral-strategy',
  156. name: 'Delta Neutral Strategy',
  157. version: '1.0.0',
  158. type: 'hedging',
  159. status: 'active',
  160. config: {
  161. deltaThreshold: 0.0005,
  162. rebalanceInterval: 30000,
  163. maxPositionSize: 0.01,
  164. enableAutoRebalance: true
  165. },
  166. metadata: {
  167. author: 'System',
  168. description: 'Delta neutral hedging strategy for risk management',
  169. tags: ['hedging', 'risk-management', 'delta-neutral']
  170. },
  171. createdAt: new Date(),
  172. updatedAt: new Date()
  173. }
  174. this.strategyModuleManager.addModule(deltaNeutralModule)
  175. this.registeredModules.set(deltaNeutralModule.moduleId, deltaNeutralModule)
  176. const utilizationModule = {
  177. moduleId: 'utilization-management-strategy',
  178. name: 'Capital Utilization Management',
  179. version: '1.0.0',
  180. type: 'allocation',
  181. status: 'active',
  182. config: {
  183. targetUtilizationMin: 0.5,
  184. targetUtilizationMax: 0.8,
  185. rebalanceThreshold: 0.1,
  186. enableAutoRebalance: true
  187. },
  188. metadata: {
  189. author: 'System',
  190. description: 'Capital utilization management strategy',
  191. tags: ['allocation', 'utilization', 'rebalancing']
  192. },
  193. createdAt: new Date(),
  194. updatedAt: new Date()
  195. }
  196. this.strategyModuleManager.addModule(utilizationModule)
  197. this.registeredModules.set(utilizationModule.moduleId, utilizationModule)
  198. logger.info(`创建了 ${this.registeredModules.size} 个基础策略模块`)
  199. }
  200. private async registerLegacyStrategies(): Promise<void> {
  201. logger.info('注册现有交易策略')
  202. const signalGenerationModule = {
  203. moduleId: 'legacy-signal-generation',
  204. name: 'Legacy Signal Generation',
  205. version: '1.0.0',
  206. type: 'signal',
  207. status: 'active',
  208. config: {
  209. signalInterval: 15000,
  210. confidenceThreshold: 0.7,
  211. enableVolumeBoost: true,
  212. volumeBoostInterval: 8000
  213. },
  214. metadata: {
  215. author: 'Legacy',
  216. description: 'Legacy signal generation strategy from TradingEngineV2',
  217. tags: ['legacy', 'signal-generation', 'volume-boost']
  218. },
  219. createdAt: new Date(),
  220. updatedAt: new Date()
  221. }
  222. this.strategyModuleManager.addModule(signalGenerationModule)
  223. this.registeredModules.set(signalGenerationModule.moduleId, signalGenerationModule)
  224. logger.info('现有策略注册完成')
  225. }
  226. private setupModuleExecutionMonitoring(): void {
  227. logger.info('设置策略模块执行监控')
  228. this.monitoringManager.addEvent({
  229. eventId: `strategy-bridge-start-${Date.now()}`,
  230. type: 'strategy-bridge-start',
  231. payload: {
  232. registeredModules: this.registeredModules.size,
  233. bridgeMode: true
  234. },
  235. severity: 'INFO',
  236. createdAt: new Date()
  237. })
  238. logger.info('策略模块执行监控设置完成')
  239. }
  240. async executeModule(moduleId: string, context?: any): Promise<{
  241. success: boolean
  242. result?: any
  243. error?: string
  244. }> {
  245. try {
  246. const module = this.registeredModules.get(moduleId)
  247. if (!module) {
  248. return {
  249. success: false,
  250. error: `模块未找到: ${moduleId}`
  251. }
  252. }
  253. if (module.status !== 'active') {
  254. return {
  255. success: false,
  256. error: `模块未激活: ${moduleId}`
  257. }
  258. }
  259. this.activeModules.add(moduleId)
  260. this.executionStats.totalExecutions++
  261. logger.info(`执行策略模块: ${moduleId}`)
  262. // 模拟模块执行
  263. const mockResult = {
  264. moduleId: module.moduleId,
  265. executionMode: 'dry-run',
  266. simulatedTrades: Math.floor(Math.random() * 3),
  267. simulatedVolume: Math.random() * 1000,
  268. executionTime: Date.now(),
  269. success: true
  270. }
  271. this.executionStats.successfulExecutions++
  272. this.executionStats.lastExecutionTime = Date.now()
  273. this.executionStats.lastError = null
  274. this.activeModules.delete(moduleId)
  275. // 记录执行结果
  276. this.monitoringManager.addEvent({
  277. eventId: `module-execution-${Date.now()}`,
  278. type: 'module-execution',
  279. payload: {
  280. moduleId: module.moduleId,
  281. result: mockResult
  282. },
  283. severity: 'INFO',
  284. createdAt: new Date()
  285. })
  286. return {
  287. success: true,
  288. result: mockResult
  289. }
  290. } catch (error: any) {
  291. this.activeModules.delete(moduleId)
  292. this.executionStats.failedExecutions++
  293. this.executionStats.lastError = error.message
  294. logger.error(`策略模块执行失败: ${moduleId}`, { error: error.message })
  295. return {
  296. success: false,
  297. error: error.message
  298. }
  299. }
  300. }
  301. async startModule(moduleId: string): Promise<{
  302. success: boolean
  303. message: string
  304. }> {
  305. try {
  306. const module = this.registeredModules.get(moduleId)
  307. if (!module) {
  308. return {
  309. success: false,
  310. message: `模块未找到: ${moduleId}`
  311. }
  312. }
  313. module.status = 'active'
  314. this.strategyModuleManager.updateModule(module)
  315. logger.info(`启动策略模块: ${moduleId}`)
  316. return {
  317. success: true,
  318. message: `模块启动成功: ${moduleId}`
  319. }
  320. } catch (error: any) {
  321. return {
  322. success: false,
  323. message: `模块启动失败: ${error.message}`
  324. }
  325. }
  326. }
  327. async stopModule(moduleId: string): Promise<{
  328. success: boolean
  329. message: string
  330. }> {
  331. try {
  332. const module = this.registeredModules.get(moduleId)
  333. if (!module) {
  334. return {
  335. success: false,
  336. message: `模块未找到: ${moduleId}`
  337. }
  338. }
  339. module.status = 'stopped'
  340. this.strategyModuleManager.updateModule(module)
  341. this.activeModules.delete(moduleId)
  342. logger.info(`停止策略模块: ${moduleId}`)
  343. return {
  344. success: true,
  345. message: `模块停止成功: ${moduleId}`
  346. }
  347. } catch (error: any) {
  348. return {
  349. success: false,
  350. message: `模块停止失败: ${error.message}`
  351. }
  352. }
  353. }
  354. getBridgeStats(): any {
  355. return {
  356. registeredModules: this.registeredModules.size,
  357. activeModules: Array.from(this.registeredModules.values()).filter((m: any) => m.status === 'active').length,
  358. totalExecutions: this.executionStats.totalExecutions,
  359. successfulExecutions: this.executionStats.successfulExecutions,
  360. failedExecutions: this.executionStats.failedExecutions,
  361. sandboxTests: 0,
  362. lastExecutionTime: this.executionStats.lastExecutionTime,
  363. bridgeMode: true
  364. }
  365. }
  366. getRegisteredModules(): any[] {
  367. return Array.from(this.registeredModules.values())
  368. }
  369. getActiveModules(): any[] {
  370. return Array.from(this.registeredModules.values()).filter((m: any) => m.status === 'active')
  371. }
  372. }
  373. async function main() {
  374. logger.info('=== T032 策略模块桥接演示 ===')
  375. try {
  376. // 1. 创建模拟组件
  377. const mockTradingEngine = new MockTradingEngineV2()
  378. const mockStrategyService = new MockStrategyModuleService()
  379. const mockModuleManager = new MockStrategyModuleManager()
  380. const mockAccountManager = new MockExchangeAccountManager()
  381. const mockMonitoringManager = new MockMonitoringEventManager()
  382. // 2. 初始化交易引擎
  383. await mockTradingEngine.initialize()
  384. await mockTradingEngine.start()
  385. // 3. 创建策略模块桥接器
  386. const strategyBridge = new SimpleStrategyModuleBridge(
  387. mockTradingEngine,
  388. mockStrategyService,
  389. mockModuleManager,
  390. mockAccountManager,
  391. mockMonitoringManager
  392. )
  393. // 4. 启动策略模块桥接器
  394. logger.info('启动策略模块桥接器...')
  395. await strategyBridge.start()
  396. // 5. 检查初始状态
  397. const initialStats = strategyBridge.getBridgeStats()
  398. logger.info('初始策略模块桥接统计:', initialStats)
  399. // 6. 获取注册的模块列表
  400. const registeredModules = strategyBridge.getRegisteredModules()
  401. logger.info(`注册的模块数量: ${registeredModules.length}`)
  402. registeredModules.forEach(module => {
  403. logger.info(`- ${module.moduleId}: ${module.name} (${module.type})`)
  404. })
  405. // 7. 执行策略模块测试
  406. logger.info('执行策略模块测试...')
  407. for (const module of registeredModules.slice(0, 2)) { // 只测试前两个模块
  408. const executionResult = await strategyBridge.executeModule(module.moduleId)
  409. logger.info(`模块 ${module.moduleId} 执行结果:`, executionResult)
  410. }
  411. // 8. 测试模块启动/停止
  412. logger.info('测试模块启动/停止...')
  413. const firstModule = registeredModules[0]
  414. if (firstModule) {
  415. const stopResult = await strategyBridge.stopModule(firstModule.moduleId)
  416. logger.info(`停止模块结果:`, stopResult)
  417. const startResult = await strategyBridge.startModule(firstModule.moduleId)
  418. logger.info(`启动模块结果:`, startResult)
  419. }
  420. // 9. 检查最终状态
  421. const finalStats = strategyBridge.getBridgeStats()
  422. logger.info('最终策略模块桥接统计:', finalStats)
  423. // 10. 验证数据一致性
  424. logger.info('验证数据一致性...')
  425. const allModules = mockModuleManager.getAllModules()
  426. const monitoringEvents = mockMonitoringManager.getAllEvents()
  427. logger.info(`验证结果:`)
  428. logger.info(`- 策略模块: ${allModules.length}`)
  429. logger.info(`- 监控事件: ${monitoringEvents.length}`)
  430. logger.info(`- 总执行次数: ${finalStats.totalExecutions}`)
  431. logger.info(`- 成功执行次数: ${finalStats.successfulExecutions}`)
  432. logger.info(`- 失败执行次数: ${finalStats.failedExecutions}`)
  433. logger.info(`- 桥接模式: ${finalStats.bridgeMode ? '✅' : '❌'}`)
  434. logger.info(`- 数据一致性: ${allModules.length > 0 && monitoringEvents.length > 0 ? '✅' : '❌'}`)
  435. // 11. 停止桥接器
  436. await strategyBridge.stop()
  437. logger.info('=== T032 策略模块桥接演示完成 ===')
  438. } catch (error: any) {
  439. logger.error('T032 演示失败:', { error: error.message, stack: error.stack })
  440. process.exit(1)
  441. }
  442. }
  443. // 运行演示
  444. if (import.meta.url === `file://${process.argv[1]}`) {
  445. main().catch(error => {
  446. logger.error('演示运行失败:', error)
  447. process.exit(1)
  448. })
  449. }