gridMaker.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import { describe, it, expect, beforeEach, vi } from 'vitest';
  2. import pino from 'pino';
  3. import { GridMaker, type AdaptiveGridConfig } from '../src/gridMaker';
  4. import type { Order, Fill, OrderBook } from '../../domain/src/types';
  5. import type { OrderRouter } from '../../execution/src/orderRouter';
  6. import type { HedgeEngine } from '../../hedge/src/hedgeEngine';
  7. import type { ShadowBook } from '../../utils/src/shadowBook';
  8. import pino from 'pino';
  9. describe('GridMaker', () => {
  10. let gridMaker: GridMaker;
  11. let mockRouter: OrderRouter;
  12. let mockHedgeEngine: HedgeEngine;
  13. let mockShadowBook: ShadowBook;
  14. const testConfig = {
  15. symbol: 'BTC',
  16. gridStepBps: 100, // 1%
  17. gridRangeBps: 400, // 4%
  18. baseClipUsd: 500,
  19. maxLayers: 4,
  20. hedgeThresholdBase: 0.3,
  21. accountId: 'maker'
  22. };
  23. const mockMidPrice = 50000;
  24. beforeEach(() => {
  25. // Mock OrderRouter
  26. mockRouter = {
  27. sendLimitChild: vi.fn(async (order: Order) => {
  28. return `order-${order.clientId}`;
  29. })
  30. } as any;
  31. // Mock HedgeEngine
  32. mockHedgeEngine = {
  33. maybeHedge: vi.fn(async () => ({ hedged: 0, clientId: undefined, orderId: undefined }))
  34. } as any;
  35. // Mock ShadowBook
  36. mockShadowBook = {
  37. mid: vi.fn(() => mockMidPrice),
  38. snapshot: vi.fn(() => ({
  39. bids: [{ px: 49900, sz: 1 }],
  40. asks: [{ px: 50100, sz: 1 }],
  41. ts: Date.now()
  42. } as OrderBook))
  43. } as any;
  44. const mockLogger = pino({ level: 'silent' });
  45. gridMaker = new GridMaker(
  46. testConfig,
  47. mockRouter,
  48. mockHedgeEngine,
  49. mockShadowBook,
  50. mockLogger,
  51. undefined,
  52. async () => {},
  53. () => {}
  54. );
  55. });
  56. describe('initialize', () => {
  57. it('should initialize grid orders correctly', async () => {
  58. await gridMaker.initialize();
  59. // 应该创建 4 层买单 + 4 层卖单 = 8 个订单
  60. expect(mockRouter.sendLimitChild).toHaveBeenCalledTimes(8);
  61. const status = gridMaker.getStatus();
  62. expect(status.isInitialized).toBe(true);
  63. expect(status.totalGrids).toBe(8);
  64. expect(status.activeOrders).toBe(8);
  65. });
  66. it('should place buy orders below mid price', async () => {
  67. await gridMaker.initialize();
  68. const calls = (mockRouter.sendLimitChild as any).mock.calls;
  69. const buyOrders = calls.filter((call: any) => call[0].side === 'buy');
  70. // 所有买单价格应该低于 mid
  71. buyOrders.forEach((call: any) => {
  72. const order = call[0] as Order;
  73. expect(order.px).toBeLessThan(mockMidPrice);
  74. expect(order.postOnly).toBe(true);
  75. expect(order.tif).toBe('GTC');
  76. });
  77. });
  78. it('should place sell orders above mid price', async () => {
  79. await gridMaker.initialize();
  80. const calls = (mockRouter.sendLimitChild as any).mock.calls;
  81. const sellOrders = calls.filter((call: any) => call[0].side === 'sell');
  82. // 所有卖单价格应该高于 mid
  83. sellOrders.forEach((call: any) => {
  84. const order = call[0] as Order;
  85. expect(order.px).toBeGreaterThan(mockMidPrice);
  86. expect(order.postOnly).toBe(true);
  87. });
  88. });
  89. it('should throw error if no mid price available', async () => {
  90. (mockShadowBook.mid as any).mockReturnValue(undefined);
  91. await expect(gridMaker.initialize()).rejects.toThrow(
  92. 'Cannot initialize grid: no mid price available'
  93. );
  94. });
  95. });
  96. describe('onFill', () => {
  97. beforeEach(async () => {
  98. await gridMaker.initialize();
  99. vi.clearAllMocks();
  100. });
  101. it('should place opposite order when buy order filled', async () => {
  102. const buyFill: Fill = {
  103. orderId: 'order-grid-BTC--1-' + Date.now(),
  104. tradeId: 'trade-1',
  105. symbol: 'BTC',
  106. side: 'buy',
  107. px: 49500, // 买单在 -1% 成交
  108. sz: 0.01,
  109. fee: 0.00001,
  110. liquidity: 'maker',
  111. ts: Date.now()
  112. };
  113. await gridMaker.onFill(buyFill);
  114. // 应该挂一个卖单在更高价
  115. expect(mockRouter.sendLimitChild).toHaveBeenCalledTimes(1);
  116. const call = (mockRouter.sendLimitChild as any).mock.calls[0];
  117. const oppositeOrder = call[0] as Order;
  118. expect(oppositeOrder.side).toBe('sell');
  119. expect(oppositeOrder.px).toBeGreaterThan(buyFill.px);
  120. // 应该在 buyFill.px * (1 + 1%) 附近
  121. expect(oppositeOrder.px).toBeCloseTo(buyFill.px * 1.01, 0);
  122. expect(oppositeOrder.accountId).toBe('maker');
  123. });
  124. it('should place opposite order when sell order filled', async () => {
  125. const sellFill: Fill = {
  126. orderId: 'order-grid-BTC-1-' + Date.now(),
  127. tradeId: 'trade-2',
  128. symbol: 'BTC',
  129. side: 'sell',
  130. px: 50500, // 卖单在 +1% 成交
  131. sz: 0.01,
  132. fee: 0.00001,
  133. liquidity: 'maker',
  134. ts: Date.now()
  135. };
  136. await gridMaker.onFill(sellFill);
  137. // 应该挂一个买单在更低价
  138. expect(mockRouter.sendLimitChild).toHaveBeenCalledTimes(1);
  139. const call = (mockRouter.sendLimitChild as any).mock.calls[0];
  140. const oppositeOrder = call[0] as Order;
  141. expect(oppositeOrder.side).toBe('buy');
  142. expect(oppositeOrder.px).toBeLessThan(sellFill.px);
  143. // 应该在 sellFill.px * (1 - 1%) 附近
  144. expect(oppositeOrder.px).toBeCloseTo(sellFill.px * 0.99, 0);
  145. expect(oppositeOrder.accountId).toBe('maker');
  146. });
  147. it('should update delta correctly', async () => {
  148. const buyFill: Fill = {
  149. orderId: 'order-grid-BTC--1-' + Date.now(),
  150. tradeId: 'trade-1',
  151. symbol: 'BTC',
  152. side: 'buy',
  153. px: 49500,
  154. sz: 0.1, // 买入 0.1 BTC
  155. fee: 0.0001,
  156. liquidity: 'maker',
  157. ts: Date.now()
  158. };
  159. await gridMaker.onFill(buyFill);
  160. const status = gridMaker.getStatus();
  161. expect(status.currentDelta).toBe(0.1); // Delta 应该增加 0.1
  162. });
  163. it('should trigger hedge when threshold reached', async () => {
  164. // 连续成交 3 笔买单,累积 Delta = 0.3(达到阈值)
  165. (mockHedgeEngine.maybeHedge as any).mockResolvedValueOnce({
  166. hedged: 0.3,
  167. orderId: 'hedge-order-1',
  168. clientId: 'hedge-1'
  169. });
  170. for (let i = 0; i < 3; i++) {
  171. const buyFill: Fill = {
  172. orderId: `order-grid-BTC--${i + 1}-` + (Date.now() + i),
  173. tradeId: `trade-${i}`,
  174. symbol: 'BTC',
  175. side: 'buy',
  176. px: 49500 - i * 100,
  177. sz: 0.1,
  178. fee: 0.0001,
  179. liquidity: 'maker',
  180. ts: Date.now() + i
  181. };
  182. await gridMaker.onFill(buyFill);
  183. }
  184. const status = gridMaker.getStatus();
  185. expect(status.currentDelta).toBe(0.3);
  186. expect(status.pendingHedges).toBe(1);
  187. // 应该触发对冲
  188. expect(mockHedgeEngine.maybeHedge).toHaveBeenCalled();
  189. expect(mockHedgeEngine.maybeHedge).toHaveBeenCalledWith('BTC', 0.3);
  190. });
  191. it('should ignore fill from non-grid orders', async () => {
  192. const externalFill: Fill = {
  193. orderId: 'external-order-123', // 非网格订单
  194. tradeId: 'trade-ext',
  195. symbol: 'BTC',
  196. side: 'buy',
  197. px: 50000,
  198. sz: 0.5,
  199. fee: 0.0005,
  200. liquidity: 'taker',
  201. ts: Date.now()
  202. };
  203. await gridMaker.onFill(externalFill);
  204. // 不应该挂对手单
  205. expect(mockRouter.sendLimitChild).not.toHaveBeenCalled();
  206. // Delta 不应该更新
  207. const status = gridMaker.getStatus();
  208. expect(status.currentDelta).toBe(0);
  209. });
  210. });
  211. describe('getStatus', () => {
  212. it('should return correct status before initialization', () => {
  213. const status = gridMaker.getStatus();
  214. expect(status.isInitialized).toBe(false);
  215. expect(status.totalGrids).toBe(0);
  216. expect(status.activeOrders).toBe(0);
  217. expect(status.filledGrids).toBe(0);
  218. expect(status.pendingHedges).toBe(0);
  219. });
  220. it('should return correct status after initialization', async () => {
  221. await gridMaker.initialize();
  222. const status = gridMaker.getStatus();
  223. expect(status.isInitialized).toBe(true);
  224. expect(status.gridCenter).toBe(mockMidPrice);
  225. expect(status.totalGrids).toBe(8);
  226. expect(status.activeOrders).toBe(8);
  227. expect(status.filledGrids).toBe(0);
  228. expect(status.pendingHedges).toBe(0);
  229. });
  230. it('should correct delta when hedge fill arrives', async () => {
  231. await gridMaker.initialize();
  232. (mockHedgeEngine.maybeHedge as any).mockResolvedValue({
  233. hedged: 0.3,
  234. orderId: 'hedge-order-1',
  235. clientId: 'hedge-1'
  236. });
  237. // 累积 delta 触发对冲
  238. for (let i = 0; i < 3; i++) {
  239. const fill: Fill = {
  240. orderId: `order-grid-BTC-${i}-` + (Date.now() + i),
  241. tradeId: `trade-${i}`,
  242. symbol: 'BTC',
  243. side: 'buy',
  244. px: 49500,
  245. sz: 0.1,
  246. fee: 0,
  247. liquidity: 'maker',
  248. ts: Date.now() + i
  249. };
  250. await gridMaker.onFill(fill);
  251. }
  252. const before = gridMaker.getStatus();
  253. expect(before.currentDelta).toBe(0.3);
  254. expect(before.pendingHedges).toBe(1);
  255. const hedgeFill: Fill = {
  256. orderId: 'hedge-order-1',
  257. tradeId: 'hedge-trade-1',
  258. symbol: 'BTC',
  259. side: 'sell',
  260. px: 49600,
  261. sz: 0.3,
  262. fee: 0,
  263. liquidity: 'taker',
  264. ts: Date.now() + 10
  265. };
  266. await gridMaker.onHedgeFill(hedgeFill);
  267. const after = gridMaker.getStatus();
  268. expect(after.currentDelta).toBeCloseTo(0.0, 5);
  269. expect(after.pendingHedges).toBe(0);
  270. });
  271. });
  272. describe('adaptive grid behaviour', () => {
  273. it('adjusts grid step and triggers reset when volatility jumps', async () => {
  274. const adaptiveConfig: AdaptiveGridConfig = {
  275. enabled: true,
  276. volatilityWindowMinutes: 1,
  277. minVolatilityBps: 20,
  278. maxVolatilityBps: 400,
  279. minGridStepBps: 20,
  280. maxGridStepBps: 200,
  281. recenterEnabled: true,
  282. recenterThresholdBps: 150,
  283. recenterCooldownMs: 60_000,
  284. minStepChangeRatio: 0.1,
  285. minSamples: 2
  286. };
  287. let currentMid = mockMidPrice;
  288. (mockShadowBook.mid as any).mockImplementation(() => currentMid);
  289. const mockLogger = pino({ level: 'silent' });
  290. const adaptiveMaker = new GridMaker(
  291. { ...testConfig },
  292. mockRouter,
  293. mockHedgeEngine,
  294. mockShadowBook,
  295. mockLogger,
  296. adaptiveConfig,
  297. async () => {},
  298. () => {}
  299. );
  300. await adaptiveMaker.initialize();
  301. const resetSpy = vi.spyOn(adaptiveMaker as any, 'reset').mockResolvedValue(undefined);
  302. await adaptiveMaker.onTick(); // baseline
  303. currentMid = mockMidPrice * 1.12; // ~12% move
  304. await adaptiveMaker.onTick();
  305. const status = adaptiveMaker.getStatus();
  306. expect(status.adaptive?.currentGridStepBps).toBeGreaterThan(testConfig.gridStepBps);
  307. expect(resetSpy).toHaveBeenCalled();
  308. resetSpy.mockRestore();
  309. });
  310. });
  311. });