test_order_pair_execution.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /**
  2. * Integration test for order pair execution
  3. * Tests the complete flow of executing coordinated buy/sell order pairs
  4. */
  5. import { describe, it, expect, beforeAll, afterAll, beforeEach } from '@jest/globals';
  6. import { HedgingManager } from '../../src/core/HedgingManager';
  7. import { OrderCoordinator } from '../../src/core/OrderCoordinator';
  8. import { HedgingOrder, OrderDetails } from '../../src/types/hedging';
  9. describe('Order Pair Execution Integration', () => {
  10. let hedgingManager: HedgingManager;
  11. let orderCoordinator: OrderCoordinator;
  12. let testSessionId: string;
  13. beforeAll(async () => {
  14. // Initialize hedging manager
  15. hedgingManager = new HedgingManager({
  16. accounts: './config/accounts.json',
  17. hedging: './config/hedging-config.json',
  18. marketData: './config/market-data-config.json'
  19. });
  20. // Initialize order coordinator
  21. orderCoordinator = new OrderCoordinator({
  22. maxConcurrentOrders: 20,
  23. orderTimeout: 30000,
  24. retryAttempts: 3,
  25. retryDelay: 1000,
  26. atomicExecution: true
  27. });
  28. await hedgingManager.initialize();
  29. await orderCoordinator.initialize();
  30. });
  31. afterAll(async () => {
  32. if (hedgingManager) {
  33. await hedgingManager.shutdown();
  34. }
  35. if (orderCoordinator) {
  36. await orderCoordinator.shutdown();
  37. }
  38. });
  39. beforeEach(async () => {
  40. // Create a test session for each test
  41. const sessionRequest = {
  42. name: 'Order Pair Test Session',
  43. accountIds: ['account-1', 'account-2'],
  44. volumeTarget: 10000,
  45. strategy: {
  46. symbol: 'ETH/USD',
  47. volumeDistribution: 'equal' as const,
  48. priceRange: { min: 0.001, max: 0.01 },
  49. timing: { minInterval: 30, maxInterval: 120, orderSize: { min: 100, max: 500 } },
  50. riskLimits: { maxPositionSize: 0.1, stopLossThreshold: 0.05, maxSlippage: 0.02 },
  51. orderTypes: { primary: 'limit' as const, fallback: 'market' as const }
  52. }
  53. };
  54. try {
  55. const session = await hedgingManager.createSession(sessionRequest);
  56. testSessionId = session.id;
  57. } catch (error) {
  58. testSessionId = 'mock-session-id';
  59. }
  60. });
  61. describe('Order Pair Creation', () => {
  62. it('should create a coordinated buy/sell order pair', async () => {
  63. const orderPairRequest = {
  64. sessionId: testSessionId,
  65. buyAccountId: 'account-1',
  66. sellAccountId: 'account-2',
  67. symbol: 'ETH/USD',
  68. size: 100,
  69. price: 2500,
  70. orderType: 'limit' as const
  71. };
  72. try {
  73. const orderPair = await orderCoordinator.createOrderPair(orderPairRequest);
  74. expect(orderPair).toBeDefined();
  75. expect(orderPair.id).toBeDefined();
  76. expect(orderPair.sessionId).toBe(testSessionId);
  77. expect(orderPair.status).toBe('pending');
  78. expect(orderPair.volume).toBe(100);
  79. expect(orderPair.price).toBe(2500);
  80. // Verify order pair structure
  81. expect(orderPair.orderPair).toBeDefined();
  82. expect(orderPair.orderPair.buyOrder).toBeDefined();
  83. expect(orderPair.orderPair.sellOrder).toBeDefined();
  84. // Verify buy order
  85. const buyOrder: OrderDetails = orderPair.orderPair.buyOrder;
  86. expect(buyOrder.accountId).toBe('account-1');
  87. expect(buyOrder.side).toBe('buy');
  88. expect(buyOrder.type).toBe('limit');
  89. expect(buyOrder.size).toBe(100);
  90. expect(buyOrder.price).toBe(2500);
  91. expect(buyOrder.status).toBe('pending');
  92. // Verify sell order
  93. const sellOrder: OrderDetails = orderPair.orderPair.sellOrder;
  94. expect(sellOrder.accountId).toBe('account-2');
  95. expect(sellOrder.side).toBe('sell');
  96. expect(sellOrder.type).toBe('limit');
  97. expect(sellOrder.size).toBe(100);
  98. expect(sellOrder.price).toBe(2500);
  99. expect(sellOrder.status).toBe('pending');
  100. } catch (error) {
  101. // This test should fail initially since OrderCoordinator doesn't exist yet
  102. expect(error.message).toContain('OrderCoordinator');
  103. }
  104. });
  105. it('should validate order pair neutrality', async () => {
  106. const orderPairRequest = {
  107. sessionId: testSessionId,
  108. buyAccountId: 'account-1',
  109. sellAccountId: 'account-2',
  110. symbol: 'ETH/USD',
  111. size: 100,
  112. price: 2500,
  113. orderType: 'limit' as const
  114. };
  115. try {
  116. const orderPair = await orderCoordinator.createOrderPair(orderPairRequest);
  117. // Verify position neutrality
  118. expect(orderPair.orderPair.buyOrder.size).toBe(orderPair.orderPair.sellOrder.size);
  119. expect(orderPair.orderPair.buyOrder.price).toBe(orderPair.orderPair.sellOrder.price);
  120. expect(orderPair.orderPair.buyOrder.side).not.toBe(orderPair.orderPair.sellOrder.side);
  121. } catch (error) {
  122. // This test should fail initially since OrderCoordinator doesn't exist yet
  123. expect(error.message).toContain('OrderCoordinator');
  124. }
  125. });
  126. it('should reject order pair with same account for buy and sell', async () => {
  127. const invalidOrderPairRequest = {
  128. sessionId: testSessionId,
  129. buyAccountId: 'account-1',
  130. sellAccountId: 'account-1', // Same account for both sides
  131. symbol: 'ETH/USD',
  132. size: 100,
  133. price: 2500,
  134. orderType: 'limit' as const
  135. };
  136. try {
  137. await orderCoordinator.createOrderPair(invalidOrderPairRequest);
  138. fail('Should have rejected order pair with same account');
  139. } catch (error) {
  140. expect(error.message).toContain('same account');
  141. }
  142. });
  143. it('should reject order pair with different sizes', async () => {
  144. const invalidOrderPairRequest = {
  145. sessionId: testSessionId,
  146. buyAccountId: 'account-1',
  147. sellAccountId: 'account-2',
  148. symbol: 'ETH/USD',
  149. buySize: 100,
  150. sellSize: 150, // Different sizes
  151. price: 2500,
  152. orderType: 'limit' as const
  153. };
  154. try {
  155. await orderCoordinator.createOrderPair(invalidOrderPairRequest);
  156. fail('Should have rejected order pair with different sizes');
  157. } catch (error) {
  158. expect(error.message).toContain('size');
  159. }
  160. });
  161. });
  162. describe('Order Pair Execution', () => {
  163. let testOrderPairId: string;
  164. beforeEach(async () => {
  165. const orderPairRequest = {
  166. sessionId: testSessionId,
  167. buyAccountId: 'account-1',
  168. sellAccountId: 'account-2',
  169. symbol: 'ETH/USD',
  170. size: 100,
  171. price: 2500,
  172. orderType: 'limit' as const
  173. };
  174. try {
  175. const orderPair = await orderCoordinator.createOrderPair(orderPairRequest);
  176. testOrderPairId = orderPair.id;
  177. } catch (error) {
  178. testOrderPairId = 'mock-order-pair-id';
  179. }
  180. });
  181. it('should execute order pair atomically', async () => {
  182. try {
  183. const result = await orderCoordinator.executeOrderPair(testOrderPairId);
  184. expect(result).toBeDefined();
  185. expect(result.success).toBe(true);
  186. expect(result.orderPairId).toBe(testOrderPairId);
  187. expect(result.executionTime).toBeDefined();
  188. expect(result.executionTime).toBeGreaterThan(0);
  189. // Verify both orders were executed
  190. const orderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  191. expect(orderPair.status).toBe('filled');
  192. expect(orderPair.orderPair.buyOrder.status).toBe('filled');
  193. expect(orderPair.orderPair.sellOrder.status).toBe('filled');
  194. expect(orderPair.executedAt).toBeDefined();
  195. expect(orderPair.completedAt).toBeDefined();
  196. } catch (error) {
  197. // This test should fail initially since OrderCoordinator doesn't exist yet
  198. expect(error.message).toContain('OrderCoordinator');
  199. }
  200. });
  201. it('should handle partial fills correctly', async () => {
  202. try {
  203. // Mock partial fill scenario
  204. const result = await orderCoordinator.executeOrderPair(testOrderPairId);
  205. if (result.partialFill) {
  206. const orderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  207. expect(orderPair.status).toBe('partial');
  208. expect(orderPair.orderPair.buyOrder.fillSize).toBeLessThan(orderPair.orderPair.buyOrder.size);
  209. expect(orderPair.orderPair.sellOrder.fillSize).toBeLessThan(orderPair.orderPair.sellOrder.size);
  210. }
  211. } catch (error) {
  212. // This test should fail initially since OrderCoordinator doesn't exist yet
  213. expect(error.message).toContain('OrderCoordinator');
  214. }
  215. });
  216. it('should handle execution failures gracefully', async () => {
  217. try {
  218. // Mock execution failure scenario
  219. const result = await orderCoordinator.executeOrderPair(testOrderPairId);
  220. if (!result.success) {
  221. const orderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  222. expect(orderPair.status).toBe('failed');
  223. expect(result.error).toBeDefined();
  224. expect(result.error.message).toBeDefined();
  225. }
  226. } catch (error) {
  227. // This test should fail initially since OrderCoordinator doesn't exist yet
  228. expect(error.message).toContain('OrderCoordinator');
  229. }
  230. });
  231. it('should retry failed orders according to configuration', async () => {
  232. try {
  233. const result = await orderCoordinator.executeOrderPair(testOrderPairId);
  234. if (!result.success && result.retryCount) {
  235. expect(result.retryCount).toBeGreaterThan(0);
  236. expect(result.retryCount).toBeLessThanOrEqual(3); // Max retry attempts
  237. }
  238. } catch (error) {
  239. // This test should fail initially since OrderCoordinator doesn't exist yet
  240. expect(error.message).toContain('OrderCoordinator');
  241. }
  242. });
  243. });
  244. describe('Order Pair Monitoring', () => {
  245. let testOrderPairId: string;
  246. beforeEach(async () => {
  247. const orderPairRequest = {
  248. sessionId: testSessionId,
  249. buyAccountId: 'account-1',
  250. sellAccountId: 'account-2',
  251. symbol: 'ETH/USD',
  252. size: 100,
  253. price: 2500,
  254. orderType: 'limit' as const
  255. };
  256. try {
  257. const orderPair = await orderCoordinator.createOrderPair(orderPairRequest);
  258. testOrderPairId = orderPair.id;
  259. } catch (error) {
  260. testOrderPairId = 'mock-order-pair-id';
  261. }
  262. });
  263. it('should track order pair status changes', async () => {
  264. try {
  265. const initialOrderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  266. expect(initialOrderPair.status).toBe('pending');
  267. // Execute the order pair
  268. await orderCoordinator.executeOrderPair(testOrderPairId);
  269. const executedOrderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  270. expect(executedOrderPair.status).toBe('submitted');
  271. // Wait for execution to complete
  272. await new Promise(resolve => setTimeout(resolve, 100));
  273. const completedOrderPair = await orderCoordinator.getOrderPair(testOrderPairId);
  274. expect(['filled', 'failed', 'partial']).toContain(completedOrderPair.status);
  275. } catch (error) {
  276. // This test should fail initially since OrderCoordinator doesn't exist yet
  277. expect(error.message).toContain('OrderCoordinator');
  278. }
  279. });
  280. it('should calculate execution metrics', async () => {
  281. try {
  282. const result = await orderCoordinator.executeOrderPair(testOrderPairId);
  283. if (result.success) {
  284. expect(result.executionTime).toBeDefined();
  285. expect(result.slippage).toBeDefined();
  286. expect(result.fees).toBeDefined();
  287. expect(result.executionTime).toBeGreaterThan(0);
  288. }
  289. } catch (error) {
  290. // This test should fail initially since OrderCoordinator doesn't exist yet
  291. expect(error.message).toContain('OrderCoordinator');
  292. }
  293. });
  294. it('should emit order pair events', async () => {
  295. const events: string[] = [];
  296. try {
  297. orderCoordinator.on('orderPairCreated', (orderPair) => {
  298. events.push('orderPairCreated');
  299. expect(orderPair.id).toBe(testOrderPairId);
  300. });
  301. orderCoordinator.on('orderPairExecuted', (orderPair) => {
  302. events.push('orderPairExecuted');
  303. expect(orderPair.id).toBe(testOrderPairId);
  304. });
  305. orderCoordinator.on('orderPairCompleted', (orderPair) => {
  306. events.push('orderPairCompleted');
  307. expect(orderPair.id).toBe(testOrderPairId);
  308. });
  309. await orderCoordinator.executeOrderPair(testOrderPairId);
  310. expect(events).toContain('orderPairCreated');
  311. expect(events).toContain('orderPairExecuted');
  312. expect(events).toContain('orderPairCompleted');
  313. } catch (error) {
  314. // This test should fail initially since OrderCoordinator doesn't exist yet
  315. expect(error.message).toContain('OrderCoordinator');
  316. }
  317. });
  318. });
  319. describe('Concurrent Order Execution', () => {
  320. it('should handle multiple concurrent order pairs', async () => {
  321. const orderPairRequests = [
  322. {
  323. sessionId: testSessionId,
  324. buyAccountId: 'account-1',
  325. sellAccountId: 'account-2',
  326. symbol: 'ETH/USD',
  327. size: 100,
  328. price: 2500,
  329. orderType: 'limit' as const
  330. },
  331. {
  332. sessionId: testSessionId,
  333. buyAccountId: 'account-2',
  334. sellAccountId: 'account-1',
  335. symbol: 'ETH/USD',
  336. size: 150,
  337. price: 2501,
  338. orderType: 'limit' as const
  339. }
  340. ];
  341. try {
  342. const orderPairs = await Promise.all(
  343. orderPairRequests.map(request => orderCoordinator.createOrderPair(request))
  344. );
  345. expect(orderPairs).toHaveLength(2);
  346. expect(orderPairs[0].id).not.toBe(orderPairs[1].id);
  347. // Execute both order pairs concurrently
  348. const results = await Promise.all(
  349. orderPairs.map(orderPair => orderCoordinator.executeOrderPair(orderPair.id))
  350. );
  351. expect(results).toHaveLength(2);
  352. results.forEach(result => {
  353. expect(result).toBeDefined();
  354. expect(result.orderPairId).toBeDefined();
  355. });
  356. } catch (error) {
  357. // This test should fail initially since OrderCoordinator doesn't exist yet
  358. expect(error.message).toContain('OrderCoordinator');
  359. }
  360. });
  361. it('should respect maximum concurrent orders limit', async () => {
  362. const orderPairRequests = Array(25).fill(null).map((_, index) => ({
  363. sessionId: testSessionId,
  364. buyAccountId: 'account-1',
  365. sellAccountId: 'account-2',
  366. symbol: 'ETH/USD',
  367. size: 100,
  368. price: 2500 + index,
  369. orderType: 'limit' as const
  370. }));
  371. try {
  372. const orderPairs = await Promise.all(
  373. orderPairRequests.map(request => orderCoordinator.createOrderPair(request))
  374. );
  375. // Try to execute all order pairs
  376. const results = await Promise.allSettled(
  377. orderPairs.map(orderPair => orderCoordinator.executeOrderPair(orderPair.id))
  378. );
  379. // Some should succeed, some should be rejected due to concurrency limit
  380. const successful = results.filter(r => r.status === 'fulfilled');
  381. const rejected = results.filter(r => r.status === 'rejected');
  382. expect(successful.length + rejected.length).toBe(25);
  383. expect(successful.length).toBeLessThanOrEqual(20); // Max concurrent orders
  384. } catch (error) {
  385. // This test should fail initially since OrderCoordinator doesn't exist yet
  386. expect(error.message).toContain('OrderCoordinator');
  387. }
  388. });
  389. });
  390. describe('Error Handling', () => {
  391. it('should handle non-existent order pair operations gracefully', async () => {
  392. const nonExistentOrderPairId = 'non-existent-order-pair-id';
  393. try {
  394. await orderCoordinator.getOrderPair(nonExistentOrderPairId);
  395. fail('Should have thrown error for non-existent order pair');
  396. } catch (error) {
  397. expect(error.message).toContain('not found');
  398. }
  399. });
  400. it('should handle execution timeout', async () => {
  401. const orderPairRequest = {
  402. sessionId: testSessionId,
  403. buyAccountId: 'account-1',
  404. sellAccountId: 'account-2',
  405. symbol: 'ETH/USD',
  406. size: 100,
  407. price: 2500,
  408. orderType: 'limit' as const
  409. };
  410. try {
  411. const orderPair = await orderCoordinator.createOrderPair(orderPairRequest);
  412. // Mock timeout scenario
  413. const result = await orderCoordinator.executeOrderPair(orderPair.id);
  414. if (!result.success && result.timeout) {
  415. expect(result.error.message).toContain('timeout');
  416. }
  417. } catch (error) {
  418. // This test should fail initially since OrderCoordinator doesn't exist yet
  419. expect(error.message).toContain('OrderCoordinator');
  420. }
  421. });
  422. });
  423. });