t030_hedge_bridge_demo.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /**
  2. * T030 演示:对冲协调器桥接服务
  3. * 演示如何集成现有的 HedgingCoordinator 与新的 HedgeExecutionService
  4. */
  5. import { logger } from '../src/utils/logger.js'
  6. // 模拟现有的 HedgingCoordinator
  7. class MockHedgingCoordinator {
  8. private isActive = false
  9. private hedgePairs = new Map<string, any>()
  10. async initialize(): Promise<void> {
  11. logger.info('模拟 HedgingCoordinator 初始化')
  12. }
  13. async start(): Promise<void> {
  14. logger.info('模拟 HedgingCoordinator 启动')
  15. this.isActive = true
  16. }
  17. async stop(): Promise<void> {
  18. logger.info('模拟 HedgingCoordinator 停止')
  19. this.isActive = false
  20. }
  21. getStatus(): any {
  22. return {
  23. name: 'HedgingCoordinator',
  24. status: this.isActive ? 'running' : 'stopped',
  25. lastUpdate: Date.now(),
  26. details: {
  27. hedgePairs: this.hedgePairs.size,
  28. autoHedgingEnabled: true
  29. }
  30. }
  31. }
  32. // 模拟创建对冲对
  33. createHedgePair(id: string, primaryAccount: string, hedgeAccount: string, symbol: string, ratio: number): void {
  34. this.hedgePairs.set(id, {
  35. primaryAccount,
  36. hedgeAccount,
  37. symbol,
  38. rebalanceRatio: ratio
  39. })
  40. logger.info(`创建对冲对: ${id}`)
  41. }
  42. }
  43. // 模拟 HedgeExecutionService
  44. class MockHedgeExecutionService {
  45. async executeHedge(request: any): Promise<any> {
  46. logger.info(`执行对冲请求: ${request.executionId}`)
  47. // 模拟对冲执行
  48. await new Promise(resolve => setTimeout(resolve, 100))
  49. return {
  50. executionId: request.executionId,
  51. status: 'completed',
  52. deltaAfter: 0.001,
  53. executionDetails: {
  54. orders: [
  55. {
  56. orderId: `order-${Date.now()}-1`,
  57. accountId: request.primaryAccountId,
  58. symbol: request.symbol,
  59. side: 'sell',
  60. quantity: 0.01,
  61. price: 108000,
  62. status: 'filled'
  63. },
  64. {
  65. orderId: `order-${Date.now()}-2`,
  66. accountId: request.hedgeAccountId,
  67. symbol: request.symbol,
  68. side: 'buy',
  69. quantity: 0.01,
  70. price: 108000,
  71. status: 'filled'
  72. }
  73. ]
  74. },
  75. durationMs: 100,
  76. alerts: [],
  77. completedAt: new Date()
  78. }
  79. }
  80. }
  81. // 模拟 HedgeExecutionManager
  82. class MockHedgeExecutionManager {
  83. private executions = new Map<string, any>()
  84. addExecution(execution: any): void {
  85. this.executions.set(execution.executionId, execution)
  86. logger.info(`添加对冲执行记录: ${execution.executionId}`)
  87. }
  88. getAllExecutions(): any[] {
  89. return Array.from(this.executions.values())
  90. }
  91. }
  92. // 模拟其他管理器
  93. class MockExchangeAccountManager {
  94. private accounts = new Map<string, any>()
  95. getAllAccounts(): any[] {
  96. return Array.from(this.accounts.values())
  97. }
  98. addAccount(account: any): void {
  99. this.accounts.set(account.accountId, account)
  100. }
  101. }
  102. class MockRiskEnvelopeManager {
  103. private envelopes = new Map<string, any>()
  104. getEnvelopeByAccountId(accountId: string): any {
  105. return this.envelopes.get(`envelope-${accountId}`)
  106. }
  107. updateEnvelope(envelope: any): void {
  108. this.envelopes.set(envelope.envelopeId, envelope)
  109. }
  110. addEnvelope(envelope: any): void {
  111. this.envelopes.set(envelope.envelopeId, envelope)
  112. }
  113. }
  114. class MockMonitoringEventManager {
  115. private events: any[] = []
  116. addEvent(event: any): void {
  117. this.events.push(event)
  118. logger.info(`添加监控事件: ${event.type}`)
  119. }
  120. getAllEvents(): any[] {
  121. return this.events
  122. }
  123. }
  124. class MockAccountManager {
  125. private accountStates = new Map<string, any>()
  126. getAllAccountStates(): Map<string, any> {
  127. return this.accountStates
  128. }
  129. // 模拟设置账户状态
  130. setAccountStates(states: Map<string, any>): void {
  131. this.accountStates = states
  132. }
  133. }
  134. // 简化的对冲桥接器实现
  135. class SimpleHedgingCoordinatorBridge {
  136. private isRunning = false
  137. private hedgeExecutionStats = {
  138. totalExecutions: 0,
  139. successfulExecutions: 0,
  140. failedExecutions: 0,
  141. lastExecutionTime: 0,
  142. lastError: null as string | null
  143. }
  144. constructor(
  145. private legacyHedgingCoordinator: MockHedgingCoordinator,
  146. private hedgeExecutionService: MockHedgeExecutionService,
  147. private hedgeExecutionManager: MockHedgeExecutionManager,
  148. private exchangeAccountManager: MockExchangeAccountManager,
  149. private riskManager: MockRiskEnvelopeManager,
  150. private monitoringManager: MockMonitoringEventManager,
  151. private accountManager: MockAccountManager
  152. ) {}
  153. async start(): Promise<void> {
  154. logger.info('启动简化对冲协调器桥接器')
  155. try {
  156. await this.initializeBridgeMode()
  157. this.isRunning = true
  158. logger.info('简化对冲协调器桥接器启动成功')
  159. } catch (error: any) {
  160. logger.error(`启动失败: ${error.message}`)
  161. throw error
  162. }
  163. }
  164. async stop(): Promise<void> {
  165. logger.info('停止简化对冲协调器桥接器')
  166. this.isRunning = false
  167. }
  168. private async initializeBridgeMode(): Promise<void> {
  169. logger.info('初始化对冲桥接模式')
  170. // 1. 同步现有的对冲对
  171. await this.syncLegacyHedgePairs()
  172. // 2. 设置风险控制
  173. await this.setupRiskControls()
  174. // 3. 初始化监控事件
  175. this.setupMonitoringEvents()
  176. logger.info('对冲桥接模式初始化完成')
  177. }
  178. private async syncLegacyHedgePairs(): Promise<void> {
  179. logger.info('同步现有对冲对到新架构')
  180. // 模拟创建对冲对
  181. this.legacyHedgingCoordinator.createHedgePair('btc-main-hedge', 'pacifica-1', 'pacifica-2', 'BTC-USD', 1.0)
  182. // 创建示例对冲执行记录
  183. const sampleHedgeExecution = {
  184. executionId: `bridge-init-${Date.now()}`,
  185. primaryAccountId: 'pacifica-1',
  186. hedgeAccountId: 'pacifica-2',
  187. symbol: 'BTC-USD',
  188. deltaBefore: 0.005,
  189. deltaAfter: 0.001,
  190. hedgeQuantity: 0.01,
  191. executionPrice: 108000,
  192. executionMethod: 'limit',
  193. result: 'success',
  194. durationMs: 150,
  195. orders: [
  196. {
  197. orderId: `order-${Date.now()}-1`,
  198. accountId: 'pacifica-1',
  199. symbol: 'BTC-USD',
  200. side: 'sell',
  201. quantity: 0.01,
  202. price: 108000,
  203. status: 'filled',
  204. filledQuantity: 0.01,
  205. filledPrice: 108000
  206. },
  207. {
  208. orderId: `order-${Date.now()}-2`,
  209. accountId: 'pacifica-2',
  210. symbol: 'BTC-USD',
  211. side: 'buy',
  212. quantity: 0.01,
  213. price: 108000,
  214. status: 'filled',
  215. filledQuantity: 0.01,
  216. filledPrice: 108000
  217. }
  218. ],
  219. createdAt: new Date(),
  220. updatedAt: new Date()
  221. }
  222. this.hedgeExecutionManager.addExecution(sampleHedgeExecution)
  223. logger.info('现有对冲对同步完成')
  224. }
  225. private async setupRiskControls(): Promise<void> {
  226. logger.info('设置对冲风险控制')
  227. // 创建示例风险包络
  228. const riskEnvelope = {
  229. envelopeId: 'envelope-pacifica-1',
  230. accountId: 'pacifica-1',
  231. maxDrawdownPercent: 5.0,
  232. maxLeverage: 1.0,
  233. deltaThreshold: 0.01,
  234. slippageTolerance: 0.001,
  235. emergencyStopLossSeconds: 30,
  236. createdAt: new Date(),
  237. updatedAt: new Date()
  238. }
  239. this.riskManager.addEnvelope(riskEnvelope)
  240. logger.info('对冲风险控制设置完成')
  241. }
  242. private setupMonitoringEvents(): void {
  243. logger.info('设置对冲监控事件')
  244. this.monitoringManager.addEvent({
  245. eventId: `hedge-bridge-start-${Date.now()}`,
  246. type: 'hedge-bridge-start',
  247. payload: {
  248. bridgeMode: true,
  249. legacyHedgePairs: 1
  250. },
  251. severity: 'INFO',
  252. createdAt: new Date()
  253. })
  254. logger.info('对冲监控事件设置完成')
  255. }
  256. async triggerManualHedge(hedgeRequest: any): Promise<{
  257. success: boolean
  258. message: string
  259. executionId?: string
  260. }> {
  261. try {
  262. logger.info('执行手动对冲')
  263. this.hedgeExecutionStats.totalExecutions++
  264. const hedgeResponse = await this.hedgeExecutionService.executeHedge(hedgeRequest)
  265. if (hedgeResponse.status === 'completed') {
  266. this.hedgeExecutionStats.successfulExecutions++
  267. this.hedgeExecutionStats.lastError = null
  268. } else {
  269. this.hedgeExecutionStats.failedExecutions++
  270. this.hedgeExecutionStats.lastError = 'Hedge execution failed'
  271. }
  272. this.hedgeExecutionStats.lastExecutionTime = Date.now()
  273. return {
  274. success: hedgeResponse.status === 'completed',
  275. message: '手动对冲执行完成',
  276. executionId: hedgeResponse.executionId
  277. }
  278. } catch (error: any) {
  279. this.hedgeExecutionStats.failedExecutions++
  280. this.hedgeExecutionStats.lastError = error.message
  281. return {
  282. success: false,
  283. message: `手动对冲失败: ${error.message}`
  284. }
  285. }
  286. }
  287. getBridgeStats(): any {
  288. return {
  289. legacyHedgePairs: 1,
  290. newHedgeExecutions: this.hedgeExecutionManager.getAllExecutions().length,
  291. totalHedgesExecuted: this.hedgeExecutionStats.totalExecutions,
  292. successfulHedges: this.hedgeExecutionStats.successfulExecutions,
  293. failedHedges: this.hedgeExecutionStats.failedExecutions,
  294. lastHedgeTime: this.hedgeExecutionStats.lastExecutionTime,
  295. bridgeMode: true
  296. }
  297. }
  298. }
  299. async function main() {
  300. logger.info('=== T030 对冲协调器桥接演示 ===')
  301. try {
  302. // 1. 创建模拟组件
  303. const mockHedgingCoordinator = new MockHedgingCoordinator()
  304. const mockHedgeExecutionService = new MockHedgeExecutionService()
  305. const mockHedgeExecutionManager = new MockHedgeExecutionManager()
  306. const mockExchangeAccountManager = new MockExchangeAccountManager()
  307. const mockRiskManager = new MockRiskEnvelopeManager()
  308. const mockMonitoringManager = new MockMonitoringEventManager()
  309. const mockAccountManager = new MockAccountManager()
  310. // 2. 初始化现有对冲协调器
  311. await mockHedgingCoordinator.initialize()
  312. await mockHedgingCoordinator.start()
  313. // 3. 创建对冲桥接器
  314. const hedgeBridge = new SimpleHedgingCoordinatorBridge(
  315. mockHedgingCoordinator,
  316. mockHedgeExecutionService,
  317. mockHedgeExecutionManager,
  318. mockExchangeAccountManager,
  319. mockRiskManager,
  320. mockMonitoringManager,
  321. mockAccountManager
  322. )
  323. // 4. 启动对冲桥接器
  324. logger.info('启动对冲桥接器...')
  325. await hedgeBridge.start()
  326. // 5. 检查初始状态
  327. const initialStats = hedgeBridge.getBridgeStats()
  328. logger.info('初始对冲桥接统计:', initialStats)
  329. // 6. 执行手动对冲
  330. logger.info('执行手动对冲...')
  331. const hedgeRequest = {
  332. executionId: `manual-hedge-${Date.now()}`,
  333. primaryAccountId: 'pacifica-1',
  334. hedgeAccountId: 'pacifica-2',
  335. deltaBefore: 0.005,
  336. targetDelta: 0.001,
  337. symbol: 'BTC-USD',
  338. triggerReason: 'manual',
  339. proxyProfile: 'default'
  340. }
  341. const hedgeResult = await hedgeBridge.triggerManualHedge(hedgeRequest)
  342. logger.info('对冲结果:', hedgeResult)
  343. // 7. 检查对冲后状态
  344. const finalStats = hedgeBridge.getBridgeStats()
  345. logger.info('最终对冲桥接统计:', finalStats)
  346. // 8. 验证数据一致性
  347. logger.info('验证数据一致性...')
  348. const hedgeExecutions = mockHedgeExecutionManager.getAllExecutions()
  349. const monitoringEvents = mockMonitoringManager.getAllEvents()
  350. logger.info(`验证结果:`)
  351. logger.info(`- 对冲执行记录: ${hedgeExecutions.length}`)
  352. logger.info(`- 监控事件: ${monitoringEvents.length}`)
  353. logger.info(`- 桥接模式: ${finalStats.bridgeMode ? '✅' : '❌'}`)
  354. logger.info(`- 数据一致性: ${hedgeExecutions.length > 0 ? '✅' : '❌'}`)
  355. // 9. 停止桥接器
  356. await hedgeBridge.stop()
  357. logger.info('=== T030 对冲协调器桥接演示完成 ===')
  358. } catch (error: any) {
  359. logger.error('T030 演示失败:', { error: error.message, stack: error.stack })
  360. process.exit(1)
  361. }
  362. }
  363. // 运行演示
  364. if (import.meta.url === `file://${process.argv[1]}`) {
  365. main().catch(error => {
  366. logger.error('演示运行失败:', error)
  367. process.exit(1)
  368. })
  369. }