@yuants/app-virtual-exchange 0.9.4 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/position.js +17 -0
- package/dist/position.js.map +1 -1
- package/dist/quote/__tests__/implementations.test.js +218 -0
- package/dist/quote/__tests__/implementations.test.js.map +1 -0
- package/dist/quote/implementations/v0.js +7 -9
- package/dist/quote/implementations/v0.js.map +1 -1
- package/dist/quote/implementations/v1.js +10 -4
- package/dist/quote/implementations/v1.js.map +1 -1
- package/dist/quote/service.js +103 -30
- package/dist/quote/service.js.map +1 -1
- package/dist/quote/types.js.map +1 -1
- package/dist/quote/upstream/executor.js +98 -0
- package/dist/quote/upstream/executor.js.map +1 -0
- package/dist/quote/upstream/index.js +2 -0
- package/dist/quote/upstream/index.js.map +1 -0
- package/dist/quote/upstream/prefix-matcher.js.map +1 -0
- package/dist/quote/upstream/registry.js +116 -0
- package/dist/quote/upstream/registry.js.map +1 -0
- package/dist/quote/upstream/router.js +119 -0
- package/dist/quote/upstream/router.js.map +1 -0
- package/lib/position.d.ts.map +1 -1
- package/lib/position.js +17 -0
- package/lib/position.js.map +1 -1
- package/lib/quote/__tests__/implementations.test.d.ts +2 -0
- package/lib/quote/__tests__/implementations.test.d.ts.map +1 -0
- package/lib/quote/__tests__/implementations.test.js +220 -0
- package/lib/quote/__tests__/implementations.test.js.map +1 -0
- package/lib/quote/implementations/v0.d.ts.map +1 -1
- package/lib/quote/implementations/v0.js +7 -9
- package/lib/quote/implementations/v0.js.map +1 -1
- package/lib/quote/implementations/v1.d.ts.map +1 -1
- package/lib/quote/implementations/v1.js +10 -4
- package/lib/quote/implementations/v1.js.map +1 -1
- package/lib/quote/service.js +102 -29
- package/lib/quote/service.js.map +1 -1
- package/lib/quote/types.d.ts +18 -0
- package/lib/quote/types.d.ts.map +1 -1
- package/lib/quote/types.js.map +1 -1
- package/lib/quote/upstream/executor.d.ts +8 -0
- package/lib/quote/upstream/executor.d.ts.map +1 -0
- package/lib/quote/upstream/executor.js +102 -0
- package/lib/quote/upstream/executor.js.map +1 -0
- package/lib/quote/upstream/index.d.ts +3 -0
- package/lib/quote/upstream/index.d.ts.map +1 -0
- package/lib/quote/upstream/index.js +6 -0
- package/lib/quote/upstream/index.js.map +1 -0
- package/lib/quote/upstream/prefix-matcher.d.ts.map +1 -0
- package/lib/quote/upstream/prefix-matcher.js.map +1 -0
- package/lib/quote/upstream/registry.d.ts +18 -0
- package/lib/quote/upstream/registry.d.ts.map +1 -0
- package/lib/quote/upstream/registry.js +120 -0
- package/lib/quote/upstream/registry.js.map +1 -0
- package/lib/quote/upstream/router.d.ts +27 -0
- package/lib/quote/upstream/router.d.ts.map +1 -0
- package/lib/quote/upstream/router.js +124 -0
- package/lib/quote/upstream/router.js.map +1 -0
- package/package.json +3 -3
- package/temp/package-deps.json +17 -13
- package/dist/quote/prefix-matcher.js.map +0 -1
- package/dist/quote/request-key.js +0 -20
- package/dist/quote/request-key.js.map +0 -1
- package/dist/quote/upstream-routing.js +0 -300
- package/dist/quote/upstream-routing.js.map +0 -1
- package/lib/quote/prefix-matcher.d.ts.map +0 -1
- package/lib/quote/prefix-matcher.js.map +0 -1
- package/lib/quote/request-key.d.ts +0 -2
- package/lib/quote/request-key.d.ts.map +0 -1
- package/lib/quote/request-key.js +0 -24
- package/lib/quote/request-key.js.map +0 -1
- package/lib/quote/upstream-routing.d.ts +0 -15
- package/lib/quote/upstream-routing.d.ts.map +0 -1
- package/lib/quote/upstream-routing.js +0 -304
- package/lib/quote/upstream-routing.js.map +0 -1
- /package/dist/quote/{prefix-matcher.js → upstream/prefix-matcher.js} +0 -0
- /package/lib/quote/{prefix-matcher.d.ts → upstream/prefix-matcher.d.ts} +0 -0
- /package/lib/quote/{prefix-matcher.js → upstream/prefix-matcher.js} +0 -0
package/dist/position.js
CHANGED
|
@@ -49,6 +49,23 @@ export const polyfillPosition = async (positions) => {
|
|
|
49
49
|
}
|
|
50
50
|
pos.valuation = Math.abs((theProduct.value_scale || 1) * pos.volume * pos.closable_price);
|
|
51
51
|
}
|
|
52
|
+
if (quote && pos.size) {
|
|
53
|
+
const sizeNum = +pos.size;
|
|
54
|
+
if (pos.current_price === undefined) {
|
|
55
|
+
if (sizeNum > 0) {
|
|
56
|
+
// 多头头寸使用买一价作为可平仓价格,如果没有买一价则使用最新价
|
|
57
|
+
pos.current_price = (quote.ask_price || quote.last_price) + '';
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
// 空头头寸使用卖一价作为可平仓价格,如果没有卖一价则使用最新价
|
|
61
|
+
pos.current_price = (quote.bid_price || quote.last_price) + '';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// 计算名义价值
|
|
65
|
+
if (pos.notional === undefined) {
|
|
66
|
+
pos.notional = sizeNum * (+pos.current_price || 0) + '';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
52
69
|
// 利率相关信息的追加
|
|
53
70
|
if (quote) {
|
|
54
71
|
if (quote.interest_rate_next_settled_at !== null) {
|
package/dist/position.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"position.js","sourceRoot":"","sources":["../src/position.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AACxC,MAAM,YAAY,GAAG,wBAAwB,CAAC,QAAQ,CAAC,CAAC;AACxD,MAAM,UAAU,GAAG,WAAW,CAC5B,KAAK,EAAE,UAAU,EAAE,EAAE;IACnB,MAAM,GAAG,GAAG,0CAA0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AG,CAAC,OAAO,CAAC,GAAG,UAAU,CAAC,WAAW,CAAC;aAC3D;SACF;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition } from '@yuants/data-account';\nimport { IOrder } from '@yuants/data-order';\nimport { createClientProductCache } from '@yuants/data-product';\nimport { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { escapeSQL, requestSQL } from '@yuants/sql';\nimport { newError } from '@yuants/utils';\n\nconst terminal = Terminal.fromNodeEnv();\nconst productCache = createClientProductCache(terminal);\nconst quoteCache = createCache<IQuote>(\n async (product_id) => {\n const sql = `select * from quote where product_id = ${escapeSQL(product_id)}`;\n const [quote] = await requestSQL<IQuote[]>(terminal, sql);\n return quote;\n },\n { expire: 30_000 },\n);\n\nconst interestRateIntervalCache = createCache(\n async (product_id: string) => {\n const sql = `select created_at from interest_rate where series_id = ${escapeSQL(\n product_id,\n )} order by created_at desc limit 2`;\n const rates = await requestSQL<{ created_at: string }[]>(terminal, sql);\n if (rates.length < 2) return undefined;\n const prev = new Date(rates[0].created_at).getTime();\n const prevOfPrev = new Date(rates[1].created_at).getTime();\n const interval = prev - prevOfPrev;\n return {\n prev,\n prevOfPrev,\n interval,\n };\n },\n { swrAfter: 60_000, expire: 3600_000 },\n);\n\nexport const polyfillPosition = async (positions: IPosition[]): Promise<IPosition[]> => {\n // TODO: 使用 batch query SQL 优化 product / quote 查询性能\n for (const pos of positions) {\n const [theProduct, quote, interestRateInterval] = await Promise.all([\n productCache.query(pos.product_id),\n quoteCache.query(pos.product_id),\n interestRateIntervalCache.query(pos.product_id),\n ]);\n\n // 估值 = value_scale * volume * closable_price\n if (theProduct) {\n if (theProduct.base_currency) {\n pos.base_currency = theProduct.base_currency;\n }\n if (theProduct.quote_currency) {\n pos.quote_currency = theProduct.quote_currency;\n }\n if (pos.size === undefined && pos.volume !== undefined && pos.direction !== undefined) {\n pos.size = (pos.direction === 'LONG' ? 1 : -1) * pos.volume * (theProduct.value_scale || 1) + '';\n }\n if (pos.free_size === undefined && pos.free_volume !== undefined && pos.direction !== undefined) {\n pos.free_size =\n (pos.direction === 'LONG' ? 1 : -1) * pos.free_volume * (theProduct.value_scale || 1) + '';\n }\n pos.valuation = Math.abs((theProduct.value_scale || 1) * pos.volume * pos.closable_price);\n }\n\n // 利率相关信息的追加\n if (quote) {\n if (quote.interest_rate_next_settled_at !== null) {\n const nextSettledAt = new Date(quote.interest_rate_next_settled_at).getTime();\n // 优先使用行情数据中的下一个结算时间\n pos.settlement_scheduled_at = nextSettledAt;\n // 优先使用下一个结算时间推算结算间隔\n if (interestRateInterval !== undefined) {\n const interval = nextSettledAt - interestRateInterval.prev;\n pos.settlement_interval = interval;\n }\n } else if (quote.interest_rate_next_settled_at === null && interestRateInterval !== undefined) {\n // 估算下一个结算时间\n // 找到 prev + k * interval > now 的最小 k,则下一个结算时间为 prev + k * interval\n const k = Math.ceil((Date.now() - interestRateInterval.prev) / interestRateInterval.interval);\n pos.settlement_scheduled_at = interestRateInterval.prev + k * interestRateInterval.interval;\n }\n\n // 如果还没有结算间隔,则使用 interest rate 表的时间间隔作为结算间隔\n if (pos.settlement_interval === undefined && interestRateInterval) {\n pos.settlement_interval = interestRateInterval.interval;\n }\n\n if (pos.direction === 'LONG') {\n if (quote.interest_rate_long !== null) {\n pos.interest_to_settle = +quote.interest_rate_long * pos.valuation;\n }\n }\n if (pos.direction === 'SHORT') {\n if (quote.interest_rate_short !== null) {\n pos.interest_to_settle = +quote.interest_rate_short * pos.valuation;\n }\n }\n }\n }\n return positions;\n};\n\nexport const polyfillOrders = async (orders: IOrder[]): Promise<IOrder[]> => {\n for (const order of orders) {\n const theProduct = await productCache.query(order.product_id);\n if (theProduct) {\n if (order.size !== undefined) {\n const sizeNum = +order.size;\n const sizeStep = theProduct.volume_step * theProduct.value_scale;\n if (!(sizeStep > 0)) throw newError('INVALID_SIZE_STEP', { product: theProduct, sizeStep });\n // check size is multiple of sizeStep\n if (Math.abs(sizeNum - Math.round(sizeNum / sizeStep) * sizeStep) > 1e-16) {\n throw newError('INVALID_ORDER_SIZE_NOT_MULTIPLE_OF_SIZE_STEP', {\n order,\n sizeStep,\n sizeNum,\n product: theProduct,\n });\n }\n\n if (sizeNum >= 0) {\n order.order_direction = order.is_close ? 'CLOSE_SHORT' : 'OPEN_LONG';\n } else {\n order.order_direction = order.is_close ? 'CLOSE_LONG' : 'OPEN_SHORT';\n }\n order.volume = Math.abs(sizeNum) / theProduct.value_scale;\n }\n }\n }\n return orders;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"position.js","sourceRoot":"","sources":["../src/position.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAG5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEhE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AACxC,MAAM,YAAY,GAAG,wBAAwB,CAAC,QAAQ,CAAC,CAAC;AACxD,MAAM,UAAU,GAAG,WAAW,CAC5B,KAAK,EAAE,UAAU,EAAE,EAAE;IACnB,MAAM,GAAG,GAAG,0CAA0C,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;IAC9E,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,UAAU,CAAW,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,KAAK,CAAC;AACf,CAAC,EACD,EAAE,MAAM,EAAE,KAAM,EAAE,CACnB,CAAC;AAEF,MAAM,yBAAyB,GAAG,WAAW,CAC3C,KAAK,EAAE,UAAkB,EAAE,EAAE;IAC3B,MAAM,GAAG,GAAG,0DAA0D,SAAS,CA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gBAED,IAAI,OAAO,IAAI,CAAC,EAAE;oBAChB,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,WAAW,CAAC;iBACtE;qBAAM;oBACL,KAAK,CAAC,eAAe,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC;iBACtE;gBACD,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,UAAU,CAAC,WAAW,CAAC;aAC3D;SACF;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition } from '@yuants/data-account';\nimport { IOrder } from '@yuants/data-order';\nimport { createClientProductCache } from '@yuants/data-product';\nimport { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { escapeSQL, requestSQL } from '@yuants/sql';\nimport { newError } from '@yuants/utils';\n\nconst terminal = Terminal.fromNodeEnv();\nconst productCache = createClientProductCache(terminal);\nconst quoteCache = createCache<IQuote>(\n async (product_id) => {\n const sql = `select * from quote where product_id = ${escapeSQL(product_id)}`;\n const [quote] = await requestSQL<IQuote[]>(terminal, sql);\n return quote;\n },\n { expire: 30_000 },\n);\n\nconst interestRateIntervalCache = createCache(\n async (product_id: string) => {\n const sql = `select created_at from interest_rate where series_id = ${escapeSQL(\n product_id,\n )} order by created_at desc limit 2`;\n const rates = await requestSQL<{ created_at: string }[]>(terminal, sql);\n if (rates.length < 2) return undefined;\n const prev = new Date(rates[0].created_at).getTime();\n const prevOfPrev = new Date(rates[1].created_at).getTime();\n const interval = prev - prevOfPrev;\n return {\n prev,\n prevOfPrev,\n interval,\n };\n },\n { swrAfter: 60_000, expire: 3600_000 },\n);\n\nexport const polyfillPosition = async (positions: IPosition[]): Promise<IPosition[]> => {\n // TODO: 使用 batch query SQL 优化 product / quote 查询性能\n for (const pos of positions) {\n const [theProduct, quote, interestRateInterval] = await Promise.all([\n productCache.query(pos.product_id),\n quoteCache.query(pos.product_id),\n interestRateIntervalCache.query(pos.product_id),\n ]);\n\n // 估值 = value_scale * volume * closable_price\n if (theProduct) {\n if (theProduct.base_currency) {\n pos.base_currency = theProduct.base_currency;\n }\n if (theProduct.quote_currency) {\n pos.quote_currency = theProduct.quote_currency;\n }\n if (pos.size === undefined && pos.volume !== undefined && pos.direction !== undefined) {\n pos.size = (pos.direction === 'LONG' ? 1 : -1) * pos.volume * (theProduct.value_scale || 1) + '';\n }\n if (pos.free_size === undefined && pos.free_volume !== undefined && pos.direction !== undefined) {\n pos.free_size =\n (pos.direction === 'LONG' ? 1 : -1) * pos.free_volume * (theProduct.value_scale || 1) + '';\n }\n pos.valuation = Math.abs((theProduct.value_scale || 1) * pos.volume * pos.closable_price);\n }\n\n if (quote && pos.size) {\n const sizeNum = +pos.size;\n if (pos.current_price === undefined) {\n if (sizeNum > 0) {\n // 多头头寸使用买一价作为可平仓价格,如果没有买一价则使用最新价\n pos.current_price = (quote.ask_price || quote.last_price) + '';\n } else {\n // 空头头寸使用卖一价作为可平仓价格,如果没有卖一价则使用最新价\n pos.current_price = (quote.bid_price || quote.last_price) + '';\n }\n }\n\n // 计算名义价值\n if (pos.notional === undefined) {\n pos.notional = sizeNum * (+pos.current_price || 0) + '';\n }\n }\n\n // 利率相关信息的追加\n if (quote) {\n if (quote.interest_rate_next_settled_at !== null) {\n const nextSettledAt = new Date(quote.interest_rate_next_settled_at).getTime();\n // 优先使用行情数据中的下一个结算时间\n pos.settlement_scheduled_at = nextSettledAt;\n // 优先使用下一个结算时间推算结算间隔\n if (interestRateInterval !== undefined) {\n const interval = nextSettledAt - interestRateInterval.prev;\n pos.settlement_interval = interval;\n }\n } else if (quote.interest_rate_next_settled_at === null && interestRateInterval !== undefined) {\n // 估算下一个结算时间\n // 找到 prev + k * interval > now 的最小 k,则下一个结算时间为 prev + k * interval\n const k = Math.ceil((Date.now() - interestRateInterval.prev) / interestRateInterval.interval);\n pos.settlement_scheduled_at = interestRateInterval.prev + k * interestRateInterval.interval;\n }\n\n // 如果还没有结算间隔,则使用 interest rate 表的时间间隔作为结算间隔\n if (pos.settlement_interval === undefined && interestRateInterval) {\n pos.settlement_interval = interestRateInterval.interval;\n }\n\n if (pos.direction === 'LONG') {\n if (quote.interest_rate_long !== null) {\n pos.interest_to_settle = +quote.interest_rate_long * pos.valuation;\n }\n }\n if (pos.direction === 'SHORT') {\n if (quote.interest_rate_short !== null) {\n pos.interest_to_settle = +quote.interest_rate_short * pos.valuation;\n }\n }\n }\n }\n return positions;\n};\n\nexport const polyfillOrders = async (orders: IOrder[]): Promise<IOrder[]> => {\n for (const order of orders) {\n const theProduct = await productCache.query(order.product_id);\n if (theProduct) {\n if (order.size !== undefined) {\n const sizeNum = +order.size;\n const sizeStep = theProduct.volume_step * theProduct.value_scale;\n if (!(sizeStep > 0)) throw newError('INVALID_SIZE_STEP', { product: theProduct, sizeStep });\n // check size is multiple of sizeStep\n if (Math.abs(sizeNum - Math.round(sizeNum / sizeStep) * sizeStep) > 1e-16) {\n throw newError('INVALID_ORDER_SIZE_NOT_MULTIPLE_OF_SIZE_STEP', {\n order,\n sizeStep,\n sizeNum,\n product: theProduct,\n });\n }\n\n if (sizeNum >= 0) {\n order.order_direction = order.is_close ? 'CLOSE_SHORT' : 'OPEN_LONG';\n } else {\n order.order_direction = order.is_close ? 'CLOSE_LONG' : 'OPEN_SHORT';\n }\n order.volume = Math.abs(sizeNum) / theProduct.value_scale;\n }\n }\n }\n return orders;\n};\n"]}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { implementations } from '../implementations';
|
|
2
|
+
// 测试所有实现的通用测试套件
|
|
3
|
+
describe('IQuoteState implementations', () => {
|
|
4
|
+
// 测试每个实现
|
|
5
|
+
Object.entries(implementations).forEach(([name, createQuoteState]) => {
|
|
6
|
+
describe(`${name} implementation`, () => {
|
|
7
|
+
let quoteState;
|
|
8
|
+
beforeEach(() => {
|
|
9
|
+
quoteState = createQuoteState();
|
|
10
|
+
});
|
|
11
|
+
// 测试 1: 初始状态应该是空的
|
|
12
|
+
it('should have empty initial state', () => {
|
|
13
|
+
const dumped = quoteState.dumpAsObject();
|
|
14
|
+
expect(dumped).toEqual({});
|
|
15
|
+
});
|
|
16
|
+
// 测试 2: 更新单个产品的单个字段
|
|
17
|
+
it('should update single field for single product', () => {
|
|
18
|
+
const updateAction = {
|
|
19
|
+
product_001: {
|
|
20
|
+
last_price: ['100.5', 1000],
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
quoteState.update(updateAction);
|
|
24
|
+
// 验证通过 getValueTuple 获取
|
|
25
|
+
const tuple = quoteState.getValueTuple('product_001', 'last_price');
|
|
26
|
+
expect(tuple).toEqual(['100.5', 1000]);
|
|
27
|
+
// 验证 dumpAsObject
|
|
28
|
+
const dumped = quoteState.dumpAsObject();
|
|
29
|
+
expect(dumped).toEqual(updateAction);
|
|
30
|
+
});
|
|
31
|
+
// 测试 3: 更新多个产品和多个字段
|
|
32
|
+
it('should update multiple fields for multiple products', () => {
|
|
33
|
+
const updateAction = {
|
|
34
|
+
product_001: {
|
|
35
|
+
last_price: ['100.5', 1000],
|
|
36
|
+
ask_price: ['101.0', 1001],
|
|
37
|
+
},
|
|
38
|
+
product_002: {
|
|
39
|
+
bid_price: ['99.0', 1002],
|
|
40
|
+
ask_volume: ['500', 1003],
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
quoteState.update(updateAction);
|
|
44
|
+
// 验证所有字段
|
|
45
|
+
expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['100.5', 1000]);
|
|
46
|
+
expect(quoteState.getValueTuple('product_001', 'ask_price')).toEqual(['101.0', 1001]);
|
|
47
|
+
expect(quoteState.getValueTuple('product_002', 'bid_price')).toEqual(['99.0', 1002]);
|
|
48
|
+
expect(quoteState.getValueTuple('product_002', 'ask_volume')).toEqual(['500', 1003]);
|
|
49
|
+
// 验证 dumpAsObject
|
|
50
|
+
const dumped = quoteState.dumpAsObject();
|
|
51
|
+
expect(dumped).toEqual(updateAction);
|
|
52
|
+
});
|
|
53
|
+
// 测试 4: 更新应该覆盖旧的时间戳,但忽略更旧的时间戳
|
|
54
|
+
it('should overwrite with newer timestamp, ignore older timestamp', () => {
|
|
55
|
+
// 初始更新
|
|
56
|
+
quoteState.update({
|
|
57
|
+
product_001: {
|
|
58
|
+
last_price: ['100.0', 1000],
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
// 用更新的时间戳覆盖
|
|
62
|
+
quoteState.update({
|
|
63
|
+
product_001: {
|
|
64
|
+
last_price: ['200.0', 2000],
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);
|
|
68
|
+
// 用更旧的时间戳尝试覆盖(应该被忽略)
|
|
69
|
+
quoteState.update({
|
|
70
|
+
product_001: {
|
|
71
|
+
last_price: ['300.0', 1500], // 时间戳 1500 比 2000 旧
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
// 应该仍然是旧的值
|
|
75
|
+
expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);
|
|
76
|
+
});
|
|
77
|
+
// 测试 5: 获取不存在的产品或字段应该返回 undefined
|
|
78
|
+
it('should return undefined for non-existent product or field', () => {
|
|
79
|
+
expect(quoteState.getValueTuple('non_existent', 'last_price')).toBeUndefined();
|
|
80
|
+
// 添加一个产品但不包含该字段
|
|
81
|
+
quoteState.update({
|
|
82
|
+
product_001: {
|
|
83
|
+
ask_price: ['101.0', 1000],
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
expect(quoteState.getValueTuple('product_001', 'last_price')).toBeUndefined();
|
|
87
|
+
expect(quoteState.getValueTuple('product_002', 'last_price')).toBeUndefined();
|
|
88
|
+
});
|
|
89
|
+
// 测试 6: filter 方法应该返回符合条件的数据
|
|
90
|
+
it('should filter data by product_ids, fields, and updated_at', () => {
|
|
91
|
+
// 设置测试数据
|
|
92
|
+
quoteState.update({
|
|
93
|
+
product_001: {
|
|
94
|
+
last_price: ['100.0', 1000],
|
|
95
|
+
ask_price: ['101.0', 2000],
|
|
96
|
+
bid_price: ['99.0', 500], // 较旧的时间戳
|
|
97
|
+
},
|
|
98
|
+
product_002: {
|
|
99
|
+
last_price: ['200.0', 1500],
|
|
100
|
+
ask_price: ['201.0', 2500],
|
|
101
|
+
},
|
|
102
|
+
product_003: {
|
|
103
|
+
last_price: ['300.0', 1200],
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
// 测试 1: 过滤特定产品和字段,时间阈值 1000
|
|
107
|
+
const result1 = quoteState.filter(['product_001', 'product_002'], ['last_price', 'ask_price'], 1000);
|
|
108
|
+
expect(result1).toEqual({
|
|
109
|
+
product_001: {
|
|
110
|
+
last_price: ['100.0', 1000],
|
|
111
|
+
ask_price: ['101.0', 2000],
|
|
112
|
+
},
|
|
113
|
+
product_002: {
|
|
114
|
+
last_price: ['200.0', 1500],
|
|
115
|
+
ask_price: ['201.0', 2500],
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
// 测试 2: 过滤时间阈值 1500(排除较旧的数据)
|
|
119
|
+
const result2 = quoteState.filter(['product_001', 'product_002', 'product_003'], ['last_price', 'bid_price'], 1500);
|
|
120
|
+
expect(result2).toEqual({
|
|
121
|
+
product_001: {
|
|
122
|
+
// last_price 时间戳 1000 < 1500,应该被排除
|
|
123
|
+
// bid_price 时间戳 500 < 1500,应该被排除
|
|
124
|
+
},
|
|
125
|
+
product_002: {
|
|
126
|
+
last_price: ['200.0', 1500],
|
|
127
|
+
},
|
|
128
|
+
product_003: {
|
|
129
|
+
// last_price 时间戳 1200 < 1500,应该被排除
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
// 测试 3: 过滤不存在的产品应该返回空对象
|
|
133
|
+
const result3 = quoteState.filter(['non_existent'], ['last_price'], 0);
|
|
134
|
+
expect(result3).toEqual({
|
|
135
|
+
non_existent: {},
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
// 测试 7: 空更新不应该改变状态
|
|
139
|
+
it('should handle empty update action', () => {
|
|
140
|
+
// 先添加一些数据
|
|
141
|
+
quoteState.update({
|
|
142
|
+
product_001: {
|
|
143
|
+
last_price: ['100.0', 1000],
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
const beforeDump = quoteState.dumpAsObject();
|
|
147
|
+
// 空更新
|
|
148
|
+
quoteState.update({});
|
|
149
|
+
const afterDump = quoteState.dumpAsObject();
|
|
150
|
+
expect(afterDump).toEqual(beforeDump);
|
|
151
|
+
});
|
|
152
|
+
// 测试 8: 更新时只提供部分字段,不应影响其他字段
|
|
153
|
+
it('should not affect other fields when updating partial fields', () => {
|
|
154
|
+
// 初始设置两个字段
|
|
155
|
+
quoteState.update({
|
|
156
|
+
product_001: {
|
|
157
|
+
last_price: ['100.0', 1000],
|
|
158
|
+
ask_price: ['101.0', 1001],
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
// 只更新一个字段
|
|
162
|
+
quoteState.update({
|
|
163
|
+
product_001: {
|
|
164
|
+
last_price: ['200.0', 2000],
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
// last_price 应该更新,ask_price 应该保持不变
|
|
168
|
+
expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);
|
|
169
|
+
expect(quoteState.getValueTuple('product_001', 'ask_price')).toEqual(['101.0', 1001]);
|
|
170
|
+
});
|
|
171
|
+
// 测试 9: 重复的更新应该保持幂等性
|
|
172
|
+
it('should be idempotent for duplicate updates', () => {
|
|
173
|
+
const updateAction = {
|
|
174
|
+
product_001: {
|
|
175
|
+
last_price: ['100.0', 1000],
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
// 多次执行相同的更新
|
|
179
|
+
quoteState.update(updateAction);
|
|
180
|
+
quoteState.update(updateAction);
|
|
181
|
+
quoteState.update(updateAction);
|
|
182
|
+
// 状态应该与单次更新相同
|
|
183
|
+
expect(quoteState.dumpAsObject()).toEqual(updateAction);
|
|
184
|
+
});
|
|
185
|
+
// 测试 10: 字段名称应该是 IQuoteKey 类型
|
|
186
|
+
it('should handle all IQuoteKey field types', () => {
|
|
187
|
+
const allFields = [
|
|
188
|
+
'last_price',
|
|
189
|
+
'ask_price',
|
|
190
|
+
'ask_volume',
|
|
191
|
+
'bid_volume',
|
|
192
|
+
'bid_price',
|
|
193
|
+
'interest_rate_short',
|
|
194
|
+
'open_interest',
|
|
195
|
+
'interest_rate_prev_settled_at',
|
|
196
|
+
'interest_rate_next_settled_at',
|
|
197
|
+
'interest_rate_long',
|
|
198
|
+
];
|
|
199
|
+
const updateAction = {
|
|
200
|
+
product_001: {},
|
|
201
|
+
};
|
|
202
|
+
// 为每个字段设置值
|
|
203
|
+
allFields.forEach((field, index) => {
|
|
204
|
+
updateAction['product_001'][field] = [`value_${index}`, 1000 + index];
|
|
205
|
+
});
|
|
206
|
+
quoteState.update(updateAction);
|
|
207
|
+
// 验证每个字段
|
|
208
|
+
allFields.forEach((field, index) => {
|
|
209
|
+
expect(quoteState.getValueTuple('product_001', field)).toEqual([`value_${index}`, 1000 + index]);
|
|
210
|
+
});
|
|
211
|
+
// 验证 dumpAsObject
|
|
212
|
+
const dumped = quoteState.dumpAsObject();
|
|
213
|
+
expect(dumped).toEqual(updateAction);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
//# sourceMappingURL=implementations.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"implementations.test.js","sourceRoot":"","sources":["../../../src/quote/__tests__/implementations.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAGrD,gBAAgB;AAChB,QAAQ,CAAC,6BAA6B,EAAE,GAAG,EAAE;IAC3C,SAAS;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AE,EAAE;oBACjC,MAAM,CAAC,UAAU,CAAC,aAAa,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS,KAAK,EAAE,EAAE,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC;gBACnG,CAAC,CAAC,CAAC;gBAEH,kBAAkB;gBAClB,MAAM,MAAM,GAAG,UAAU,CAAC,YAAY,EAAE,CAAC;gBACzC,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YACvC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { implementations } from '../implementations';\nimport { IQuoteKey, IQuoteUpdateAction } from '../types';\n\n// 测试所有实现的通用测试套件\ndescribe('IQuoteState implementations', () => {\n // 测试每个实现\n Object.entries(implementations).forEach(([name, createQuoteState]) => {\n describe(`${name} implementation`, () => {\n let quoteState: ReturnType<typeof createQuoteState>;\n\n beforeEach(() => {\n quoteState = createQuoteState();\n });\n\n // 测试 1: 初始状态应该是空的\n it('should have empty initial state', () => {\n const dumped = quoteState.dumpAsObject();\n expect(dumped).toEqual({});\n });\n\n // 测试 2: 更新单个产品的单个字段\n it('should update single field for single product', () => {\n const updateAction: IQuoteUpdateAction = {\n product_001: {\n last_price: ['100.5', 1000],\n },\n };\n\n quoteState.update(updateAction);\n\n // 验证通过 getValueTuple 获取\n const tuple = quoteState.getValueTuple('product_001', 'last_price');\n expect(tuple).toEqual(['100.5', 1000]);\n\n // 验证 dumpAsObject\n const dumped = quoteState.dumpAsObject();\n expect(dumped).toEqual(updateAction);\n });\n\n // 测试 3: 更新多个产品和多个字段\n it('should update multiple fields for multiple products', () => {\n const updateAction: IQuoteUpdateAction = {\n product_001: {\n last_price: ['100.5', 1000],\n ask_price: ['101.0', 1001],\n },\n product_002: {\n bid_price: ['99.0', 1002],\n ask_volume: ['500', 1003],\n },\n };\n\n quoteState.update(updateAction);\n\n // 验证所有字段\n expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['100.5', 1000]);\n expect(quoteState.getValueTuple('product_001', 'ask_price')).toEqual(['101.0', 1001]);\n expect(quoteState.getValueTuple('product_002', 'bid_price')).toEqual(['99.0', 1002]);\n expect(quoteState.getValueTuple('product_002', 'ask_volume')).toEqual(['500', 1003]);\n\n // 验证 dumpAsObject\n const dumped = quoteState.dumpAsObject();\n expect(dumped).toEqual(updateAction);\n });\n\n // 测试 4: 更新应该覆盖旧的时间戳,但忽略更旧的时间戳\n it('should overwrite with newer timestamp, ignore older timestamp', () => {\n // 初始更新\n quoteState.update({\n product_001: {\n last_price: ['100.0', 1000],\n },\n });\n\n // 用更新的时间戳覆盖\n quoteState.update({\n product_001: {\n last_price: ['200.0', 2000],\n },\n });\n\n expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);\n\n // 用更旧的时间戳尝试覆盖(应该被忽略)\n quoteState.update({\n product_001: {\n last_price: ['300.0', 1500], // 时间戳 1500 比 2000 旧\n },\n });\n\n // 应该仍然是旧的值\n expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);\n });\n\n // 测试 5: 获取不存在的产品或字段应该返回 undefined\n it('should return undefined for non-existent product or field', () => {\n expect(quoteState.getValueTuple('non_existent', 'last_price')).toBeUndefined();\n\n // 添加一个产品但不包含该字段\n quoteState.update({\n product_001: {\n ask_price: ['101.0', 1000],\n },\n });\n\n expect(quoteState.getValueTuple('product_001', 'last_price')).toBeUndefined();\n expect(quoteState.getValueTuple('product_002', 'last_price')).toBeUndefined();\n });\n\n // 测试 6: filter 方法应该返回符合条件的数据\n it('should filter data by product_ids, fields, and updated_at', () => {\n // 设置测试数据\n quoteState.update({\n product_001: {\n last_price: ['100.0', 1000],\n ask_price: ['101.0', 2000], // 较新的时间戳\n bid_price: ['99.0', 500], // 较旧的时间戳\n },\n product_002: {\n last_price: ['200.0', 1500],\n ask_price: ['201.0', 2500],\n },\n product_003: {\n last_price: ['300.0', 1200],\n },\n });\n\n // 测试 1: 过滤特定产品和字段,时间阈值 1000\n const result1 = quoteState.filter(['product_001', 'product_002'], ['last_price', 'ask_price'], 1000);\n\n expect(result1).toEqual({\n product_001: {\n last_price: ['100.0', 1000],\n ask_price: ['101.0', 2000],\n },\n product_002: {\n last_price: ['200.0', 1500],\n ask_price: ['201.0', 2500],\n },\n });\n\n // 测试 2: 过滤时间阈值 1500(排除较旧的数据)\n const result2 = quoteState.filter(\n ['product_001', 'product_002', 'product_003'],\n ['last_price', 'bid_price'],\n 1500,\n );\n\n expect(result2).toEqual({\n product_001: {\n // last_price 时间戳 1000 < 1500,应该被排除\n // bid_price 时间戳 500 < 1500,应该被排除\n },\n product_002: {\n last_price: ['200.0', 1500],\n },\n product_003: {\n // last_price 时间戳 1200 < 1500,应该被排除\n },\n });\n\n // 测试 3: 过滤不存在的产品应该返回空对象\n const result3 = quoteState.filter(['non_existent'], ['last_price'], 0);\n\n expect(result3).toEqual({\n non_existent: {},\n });\n });\n\n // 测试 7: 空更新不应该改变状态\n it('should handle empty update action', () => {\n // 先添加一些数据\n quoteState.update({\n product_001: {\n last_price: ['100.0', 1000],\n },\n });\n\n const beforeDump = quoteState.dumpAsObject();\n\n // 空更新\n quoteState.update({});\n\n const afterDump = quoteState.dumpAsObject();\n expect(afterDump).toEqual(beforeDump);\n });\n\n // 测试 8: 更新时只提供部分字段,不应影响其他字段\n it('should not affect other fields when updating partial fields', () => {\n // 初始设置两个字段\n quoteState.update({\n product_001: {\n last_price: ['100.0', 1000],\n ask_price: ['101.0', 1001],\n },\n });\n\n // 只更新一个字段\n quoteState.update({\n product_001: {\n last_price: ['200.0', 2000],\n },\n });\n\n // last_price 应该更新,ask_price 应该保持不变\n expect(quoteState.getValueTuple('product_001', 'last_price')).toEqual(['200.0', 2000]);\n expect(quoteState.getValueTuple('product_001', 'ask_price')).toEqual(['101.0', 1001]);\n });\n\n // 测试 9: 重复的更新应该保持幂等性\n it('should be idempotent for duplicate updates', () => {\n const updateAction: IQuoteUpdateAction = {\n product_001: {\n last_price: ['100.0', 1000],\n },\n };\n\n // 多次执行相同的更新\n quoteState.update(updateAction);\n quoteState.update(updateAction);\n quoteState.update(updateAction);\n\n // 状态应该与单次更新相同\n expect(quoteState.dumpAsObject()).toEqual(updateAction);\n });\n\n // 测试 10: 字段名称应该是 IQuoteKey 类型\n it('should handle all IQuoteKey field types', () => {\n const allFields: IQuoteKey[] = [\n 'last_price',\n 'ask_price',\n 'ask_volume',\n 'bid_volume',\n 'bid_price',\n 'interest_rate_short',\n 'open_interest',\n 'interest_rate_prev_settled_at',\n 'interest_rate_next_settled_at',\n 'interest_rate_long',\n ];\n\n const updateAction: IQuoteUpdateAction = {\n product_001: {},\n };\n\n // 为每个字段设置值\n allFields.forEach((field, index) => {\n updateAction['product_001'][field] = [`value_${index}`, 1000 + index];\n });\n\n quoteState.update(updateAction);\n\n // 验证每个字段\n allFields.forEach((field, index) => {\n expect(quoteState.getValueTuple('product_001', field)).toEqual([`value_${index}`, 1000 + index]);\n });\n\n // 验证 dumpAsObject\n const dumped = quoteState.dumpAsObject();\n expect(dumped).toEqual(updateAction);\n });\n });\n });\n});\n"]}
|
|
@@ -44,18 +44,16 @@ export function createQuoteStateV0() {
|
|
|
44
44
|
const result = {};
|
|
45
45
|
for (const product_id of product_ids) {
|
|
46
46
|
const productMap = data.get(product_id);
|
|
47
|
-
if (!productMap)
|
|
48
|
-
continue;
|
|
49
47
|
const productData = {};
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
48
|
+
if (productMap) {
|
|
49
|
+
for (const field of fields) {
|
|
50
|
+
const tuple = productMap.get(field);
|
|
51
|
+
if (tuple && tuple[1] >= updated_at) {
|
|
52
|
+
productData[field] = tuple;
|
|
53
|
+
}
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
|
|
57
|
-
result[product_id] = productData;
|
|
58
|
-
}
|
|
56
|
+
result[product_id] = productData;
|
|
59
57
|
}
|
|
60
58
|
return result;
|
|
61
59
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"v0.js","sourceRoot":"","sources":["../../../src/quote/implementations/v0.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,kBAAkB;IAChC,sDAAsD;IACtD,MAAM,IAAI,GAAG,IAAI,GAAG,EAA4C,CAAC;IAEjE,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE;QAC5C,KAAK,MAAM,UAAU,IAAI,MAAM,EAAE;YAC/B,IAAI,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACtC,IAAI,CAAC,UAAU,EAAE;gBACf,UAAU,GAAG,IAAI,GAAG,EAAE,CAAC;gBACvB,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;aAClC;YAED,MAAM,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;YAClC,KAAK,MAAM,UAAU,IAAI,MAAM,EAAE;gBAC/B,MAAM,KAAK,GAAG,UAAuB,CAAC;gBACtC,MAAM,CAAC,KAAK,EAAE,UAAU,CAAC,GAAG,MAAM,CAAC,KAAK,CAAE,CAAC;gBAC3C,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;gBACvC,IAAI,CAAC,QAAQ,IAAI,UAAU,IAAI,QAAQ,CAAC,CAAC,CAAC,EAAE;oBAC1C,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;iBAC5C;aACF;SACF;IACH,CAAC,CAAC;IAEF,MAAM,YAAY,GAAG,GAAuB,EAAE;QAC5C,MAAM,MAAM,GAAuB,EAAE,CAAC;QACtC,IAAI,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE;YACtC,MAAM,WAAW,GAAiD,EAAE,CAAC;YACrE,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MAAM,MAAM,GAAuB,EAAE,CAAC;QACtC,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE;YACpC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YACxC,MAAM,WAAW,GAAiD,EAAE,CAAC;YAErE,IAAI,UAAU,EAAE;gBACd,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE;oBAC1B,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;oBACpC,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE;wBACnC,WAAW,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;qBAC5B;iBACF;aACF;YAED,MAAM,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;SAClC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;AACzD,CAAC","sourcesContent":["import { IQuoteKey, IQuoteState, IQuoteUpdateAction } from '../types';\n\n/**\n * 创建一个简单的基于 Map 的实现,用于对比测试\n * 这个实现使用嵌套 Map 结构,作为性能对比的基准\n */\nexport function createQuoteStateV0(): IQuoteState {\n // 使用三层嵌套结构:product_id -> field -> [value, updated_at]\n const data = new Map<string, Map<IQuoteKey, [string, number]>>();\n\n const update = (action: IQuoteUpdateAction) => {\n for (const product_id in action) {\n let productMap = data.get(product_id);\n if (!productMap) {\n productMap = new Map();\n data.set(product_id, productMap);\n }\n\n const fields = action[product_id];\n for (const field_name in fields) {\n const field = field_name as IQuoteKey;\n const [value, updated_at] = fields[field]!;\n const existing = productMap.get(field);\n if (!existing || updated_at >= existing[1]) {\n productMap.set(field, [value, updated_at]);\n }\n }\n }\n };\n\n const dumpAsObject = (): IQuoteUpdateAction => {\n const result: IQuoteUpdateAction = {};\n data.forEach((productMap, product_id) => {\n const productData: Partial<Record<IQuoteKey, [string, number]>> = {};\n productMap.forEach((tuple, field) => {\n productData[field] = tuple;\n });\n result[product_id] = productData;\n });\n return result;\n };\n\n const getValueTuple = (product_id: string, field: IQuoteKey): [string, number] | undefined => {\n const productMap = data.get(product_id);\n if (!productMap) return undefined;\n return productMap.get(field);\n };\n\n const filter = (product_ids: string[], fields: IQuoteKey[], updated_at: number): IQuoteUpdateAction => {\n const result: IQuoteUpdateAction = {};\n for (const product_id of product_ids) {\n const productMap = data.get(product_id);\n const productData: Partial<Record<IQuoteKey, [string, number]>> = {};\n\n if (productMap) {\n for (const field of fields) {\n const tuple = productMap.get(field);\n if (tuple && tuple[1] >= updated_at) {\n productData[field] = tuple;\n }\n }\n }\n\n result[product_id] = productData;\n }\n return result;\n };\n\n return { update, dumpAsObject, getValueTuple, filter };\n}\n"]}
|
|
@@ -29,9 +29,7 @@ export const createQuoteStateV1 = () => {
|
|
|
29
29
|
const getFieldOffset = (product_id, field) => {
|
|
30
30
|
let baseIndex = mapProductIdToIndex.get(product_id);
|
|
31
31
|
if (baseIndex === undefined) {
|
|
32
|
-
|
|
33
|
-
products.push(product_id);
|
|
34
|
-
mapProductIdToIndex.set(product_id, baseIndex);
|
|
32
|
+
return undefined;
|
|
35
33
|
}
|
|
36
34
|
const fieldOffset = mapFieldNameToOffset[field];
|
|
37
35
|
if (fieldOffset === undefined)
|
|
@@ -40,6 +38,8 @@ export const createQuoteStateV1 = () => {
|
|
|
40
38
|
};
|
|
41
39
|
const getValueTuple = (product_id, field) => {
|
|
42
40
|
const offset = getFieldOffset(product_id, field);
|
|
41
|
+
if (offset === undefined)
|
|
42
|
+
return undefined;
|
|
43
43
|
const value = data[offset];
|
|
44
44
|
if (value === undefined)
|
|
45
45
|
return undefined;
|
|
@@ -47,7 +47,13 @@ export const createQuoteStateV1 = () => {
|
|
|
47
47
|
return [value, updated_at];
|
|
48
48
|
};
|
|
49
49
|
const setValueTuple = (product_id, field, value, updated_at) => {
|
|
50
|
-
|
|
50
|
+
let offset = getFieldOffset(product_id, field);
|
|
51
|
+
if (offset === undefined) {
|
|
52
|
+
const baseIndex = mapProductIdToIndex.size * FIELD_COUNT * 2;
|
|
53
|
+
products.push(product_id);
|
|
54
|
+
mapProductIdToIndex.set(product_id, baseIndex);
|
|
55
|
+
offset = baseIndex + mapFieldNameToOffset[field];
|
|
56
|
+
}
|
|
51
57
|
data[offset] = value;
|
|
52
58
|
data[offset + 1] = updated_at;
|
|
53
59
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"v1.js","sourceRoot":"","sources":["../../../src/quote/implementations/v1.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzC,wBAAwB;AACxB,MAAM,MAAM,GAAG,CAAC,CAAC,CAAiC,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAiB,CAAC,CAAC;IAC3F,mDAAmD;IACnD,UAAU,EAAE,CAAC;IACb,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,SAAS,EAAE,CAAC;IACZ,mBAAmB,EAAE,CAAC;IACtB,aAAa,EAAE,CAAC;IAChB,6BAA6B,EAAE,CAAC;IAChC,6BAA6B,EAAE,CAAC;IAChC,kBAAkB,EAAE,CAAC;CACtB,CAAC,CAAC;AAEH,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CAAC;AAClC,MAAM,oBAAoB,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAElG;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAgB,EAAE;IAClD,+BAA+B;IAC/B,MAAM,IAAI,GAAwB,EAAE,CAAC;IACrC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9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AAQ,CAAC,YAAY,CAAC,CAAC;YAE1C,MAAM,UAAU,GAAG,CAAC,CAAC,GAAG,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;YAC/C,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;YAEtC,MAAM,CAAC,UAAU,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;SACtD;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF;;;;;;OAMG;IACH,MAAM,MAAM,GAAG,CAAC,WAAqB,EAAE,MAAmB,EAAE,UAAkB,EAAsB,EAAE;QACpG,MAAM,MAAM,GAAuB,EAAE,CAAC;QACtC,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE;YACpC,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC;YACxB,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE;gBAC1B,MAAM,KAAK,GAAG,aAAa,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;gBAC/C,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,EAAE;oBACnC,MAAM,CAAC,UAAU,CAAE,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;iBACpC;aACF;SACF;QACD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;AACzD,CAAC,CAAC","sourcesContent":["import { newError } from '@yuants/utils';\nimport { IQuoteKey, IQuoteState, IQuoteUpdateAction } from '../types';\n\n// TRICK: 固定字段顺序,方便计算偏移量\nconst FIELDS = ((x: { [key in IQuoteKey]: number }) => Object.keys(x).sort() as IQuoteKey[])({\n // TS TRICK: 强制运行时数组具有 IQuoteKey 的所有字段。不重不漏,味道真是好极了\n last_price: 0,\n ask_price: 0,\n ask_volume: 0,\n bid_volume: 0,\n bid_price: 0,\n interest_rate_short: 0,\n open_interest: 0,\n interest_rate_prev_settled_at: 0,\n interest_rate_next_settled_at: 0,\n interest_rate_long: 0,\n});\n\nconst FIELD_COUNT = FIELDS.length;\nconst mapFieldNameToOffset = Object.fromEntries(FIELDS.map((field, index) => [field, index * 2]));\n\n/**\n * 高效的行情状态管理器\n * 内部使用扁平化数组存储数据,避免内存碎片化和过多的 Map/对象开销\n * 提供高效的读写接口,支持按需更新和查询\n */\nexport const createQuoteStateV1 = (): IQuoteState => {\n // 内部数据结构的设计需要考虑高效的读写性能,防止内存碎片化\n const data: (string | number)[] = [];\n const products: string[] = [];\n const mapProductIdToIndex = new Map<string, number>();\n // 0~20 (10 fields * 2 (value, updated_at))\n const getFieldOffset = (product_id: string, field: string): number | undefined => {\n let baseIndex = mapProductIdToIndex.get(product_id);\n if (baseIndex === undefined) {\n return undefined;\n }\n const fieldOffset = mapFieldNameToOffset[field];\n if (fieldOffset === undefined) throw newError('INVALID_FIELD_NAME', { field, available_fields: FIELDS });\n return baseIndex + fieldOffset;\n };\n\n const getValueTuple = (product_id: string, field: IQuoteKey): [string, number] | undefined => {\n const offset = getFieldOffset(product_id, field);\n if (offset === undefined) return undefined;\n const value = data[offset] as string;\n if (value === undefined) return undefined;\n const updated_at = data[offset + 1] as number;\n return [value, updated_at];\n };\n\n const setValueTuple = (product_id: string, field: IQuoteKey, value: string, updated_at: number) => {\n let offset = getFieldOffset(product_id, field);\n if (offset === undefined) {\n const baseIndex = mapProductIdToIndex.size * FIELD_COUNT * 2;\n products.push(product_id);\n mapProductIdToIndex.set(product_id, baseIndex);\n offset = baseIndex + mapFieldNameToOffset[field];\n }\n data[offset] = value;\n data[offset + 1] = updated_at;\n };\n\n const update = (action: IQuoteUpdateAction) => {\n for (const product_id in action) {\n const fields = action[product_id];\n for (const field_name in fields) {\n const field = field_name as IQuoteKey;\n const [value, updated_at] = fields[field]!;\n const oldTuple = getValueTuple(product_id, field);\n if (oldTuple === undefined || updated_at >= oldTuple[1]) {\n setValueTuple(product_id, field, value, updated_at);\n }\n }\n }\n };\n\n const dumpAsObject = (): IQuoteUpdateAction => {\n const result: IQuoteUpdateAction = {};\n for (const product_id of products) {\n result[product_id] = {};\n }\n for (let i = 0; i < data.length; i += 2) {\n const value = data[i] as string;\n if (value === undefined) continue;\n const updated_at = data[i + 1] as number;\n\n const productIndex = Math.floor(i / (FIELD_COUNT * 2));\n const product_id = products[productIndex];\n\n const fieldIndex = (i % (FIELD_COUNT * 2)) / 2;\n const field_name = FIELDS[fieldIndex];\n\n result[product_id][field_name] = [value, updated_at];\n }\n return result;\n };\n\n /**\n * 过滤状态,返回指定 product_id 列表和字段列表中,且更新时间不早于指定时间的字段数据\n * @param product_ids - 需要过滤的 product_id 列表\n * @param fields - 需要过滤的字段列表\n * @param updated_at - 需要过滤的更新时间阈值 (仅返回更新时间不早于该值的字段)\n * @returns 过滤后的数据\n */\n const filter = (product_ids: string[], fields: IQuoteKey[], updated_at: number): IQuoteUpdateAction => {\n const result: IQuoteUpdateAction = {};\n for (const product_id of product_ids) {\n result[product_id] = {};\n for (const field of fields) {\n const tuple = getValueTuple(product_id, field);\n if (tuple && tuple[1] >= updated_at) {\n result[product_id]![field] = tuple;\n }\n }\n }\n return result;\n };\n\n return { update, dumpAsObject, getValueTuple, filter };\n};\n"]}
|
package/dist/quote/service.js
CHANGED
|
@@ -1,29 +1,107 @@
|
|
|
1
1
|
import { Terminal } from '@yuants/protocol';
|
|
2
|
-
import { newError } from '@yuants/utils';
|
|
2
|
+
import { formatTime, newError } from '@yuants/utils';
|
|
3
|
+
import { Subject, concatMap, defer } from 'rxjs';
|
|
3
4
|
import { createQuoteState } from './state';
|
|
4
|
-
import {
|
|
5
|
+
import { createQuoteProviderRegistry } from './upstream';
|
|
5
6
|
const terminal = Terminal.fromNodeEnv();
|
|
6
7
|
const quoteState = createQuoteState();
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
8
|
+
const quoteProviderRegistry = createQuoteProviderRegistry(terminal);
|
|
9
|
+
const normalizeStrings = (values) => [...new Set(values)].sort();
|
|
10
|
+
const normalizeFields = (values) => [...new Set(values)].sort();
|
|
11
|
+
const analyzeRequestedQuotes = (quoteState, product_ids, fields, updated_at) => {
|
|
12
|
+
const missing = [];
|
|
13
|
+
const needUpdate = [];
|
|
12
14
|
for (const product_id of product_ids) {
|
|
13
15
|
for (const field of fields) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
const tuple = quoteState.getValueTuple(product_id, field);
|
|
17
|
+
if (tuple === undefined) {
|
|
18
|
+
missing.push({ product_id, field });
|
|
19
|
+
needUpdate.push({ product_id, field });
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (tuple[1] < updated_at) {
|
|
23
|
+
needUpdate.push({ product_id, field });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return { missing, needUpdate };
|
|
28
|
+
};
|
|
29
|
+
const filterLatest = (quoteState, product_ids, fields) => {
|
|
30
|
+
const result = {};
|
|
31
|
+
for (const product_id of product_ids) {
|
|
32
|
+
result[product_id] = {};
|
|
33
|
+
for (const field of fields) {
|
|
34
|
+
const tuple = quoteState.getValueTuple(product_id, field);
|
|
35
|
+
if (tuple) {
|
|
36
|
+
result[product_id][field] = tuple;
|
|
16
37
|
}
|
|
17
38
|
}
|
|
18
39
|
}
|
|
19
|
-
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
const assertNotMissing = (missing, updated_at) => {
|
|
43
|
+
if (missing.length > 0) {
|
|
20
44
|
throw newError('VEX_QUOTE_FRESHNESS_NOT_SATISFIED', {
|
|
21
45
|
updated_at,
|
|
22
|
-
missed:
|
|
23
|
-
missed_total:
|
|
46
|
+
missed: missing.slice(0, 200),
|
|
47
|
+
missed_total: missing.length,
|
|
24
48
|
});
|
|
25
49
|
}
|
|
26
50
|
};
|
|
51
|
+
const updateQueue$ = new Subject();
|
|
52
|
+
const updateQueueStats = {
|
|
53
|
+
queued_total: 0,
|
|
54
|
+
started_total: 0,
|
|
55
|
+
processed_total: 0,
|
|
56
|
+
};
|
|
57
|
+
const getQueueStatus = () => {
|
|
58
|
+
const pending = updateQueueStats.queued_total - updateQueueStats.started_total;
|
|
59
|
+
const in_flight = updateQueueStats.started_total - updateQueueStats.processed_total;
|
|
60
|
+
return Object.assign({ pending,
|
|
61
|
+
in_flight }, updateQueueStats);
|
|
62
|
+
};
|
|
63
|
+
const enqueueUpdateTask = (task) => {
|
|
64
|
+
updateQueueStats.queued_total++;
|
|
65
|
+
updateQueueStats.last_enqueued_at = Date.now();
|
|
66
|
+
updateQueue$.next(task);
|
|
67
|
+
};
|
|
68
|
+
const summarizeError = (error) => {
|
|
69
|
+
if (typeof error === 'object' && error !== null) {
|
|
70
|
+
const code = 'code' in error ? error.code : undefined;
|
|
71
|
+
const message = 'message' in error ? error.message : undefined;
|
|
72
|
+
return {
|
|
73
|
+
code: typeof code === 'string' ? code : undefined,
|
|
74
|
+
message: typeof message === 'string' ? message : undefined,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return {};
|
|
78
|
+
};
|
|
79
|
+
const processUpdateTask = async (task) => {
|
|
80
|
+
const { needUpdate } = analyzeRequestedQuotes(quoteState, task.product_ids, task.fields, task.updated_at);
|
|
81
|
+
await quoteProviderRegistry.fillQuoteStateFromUpstream({
|
|
82
|
+
quoteState,
|
|
83
|
+
cacheMissed: needUpdate,
|
|
84
|
+
updated_at: task.updated_at,
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
updateQueue$
|
|
88
|
+
.pipe(concatMap((task) => defer(async () => {
|
|
89
|
+
updateQueueStats.started_total++;
|
|
90
|
+
updateQueueStats.last_started_at = Date.now();
|
|
91
|
+
try {
|
|
92
|
+
await processUpdateTask(task);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
const summary = summarizeError(error);
|
|
96
|
+
updateQueueStats.last_error = Object.assign({ at: Date.now() }, summary);
|
|
97
|
+
console.info(formatTime(Date.now()), `[VEX][Quote]UpdateQueueTaskFailed`, `product_ids=${task.product_ids.length} fields=${task.fields.length} updated_at=${task.updated_at}`, JSON.stringify(summary));
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
updateQueueStats.processed_total++;
|
|
101
|
+
updateQueueStats.last_processed_at = Date.now();
|
|
102
|
+
}
|
|
103
|
+
})))
|
|
104
|
+
.subscribe();
|
|
27
105
|
terminal.server.provideService('VEX/UpdateQuotes', {}, async (msg) => {
|
|
28
106
|
quoteState.update(msg.req);
|
|
29
107
|
return { res: { code: 0, message: 'OK' } };
|
|
@@ -31,19 +109,7 @@ terminal.server.provideService('VEX/UpdateQuotes', {}, async (msg) => {
|
|
|
31
109
|
terminal.server.provideService('VEX/DumpQuoteState', {}, async () => {
|
|
32
110
|
return { res: { code: 0, message: 'OK', data: quoteState.dumpAsObject() } };
|
|
33
111
|
});
|
|
34
|
-
|
|
35
|
-
const cacheMissed = [];
|
|
36
|
-
for (const product_id of product_ids) {
|
|
37
|
-
for (const field of fields) {
|
|
38
|
-
const tuple = quoteState.getValueTuple(product_id, field);
|
|
39
|
-
if (tuple === undefined || tuple[1] < updated_at) {
|
|
40
|
-
cacheMissed.push({ product_id, field });
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return cacheMissed;
|
|
45
|
-
};
|
|
46
|
-
terminal.server.provideService('VEX/QueryQuotes', {
|
|
112
|
+
terminal.server.provideService('VEX/QueryQuotes/C1', {
|
|
47
113
|
type: 'object',
|
|
48
114
|
required: ['product_ids', 'fields', 'updated_at'],
|
|
49
115
|
properties: {
|
|
@@ -58,11 +124,18 @@ terminal.server.provideService('VEX/QueryQuotes', {
|
|
|
58
124
|
updated_at: { type: 'number' },
|
|
59
125
|
},
|
|
60
126
|
}, async (msg) => {
|
|
61
|
-
const
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
127
|
+
const product_ids = normalizeStrings(msg.req.product_ids);
|
|
128
|
+
const fields = normalizeFields(msg.req.fields);
|
|
129
|
+
const { updated_at } = msg.req;
|
|
130
|
+
const { missing, needUpdate } = analyzeRequestedQuotes(quoteState, product_ids, fields, updated_at);
|
|
131
|
+
if (needUpdate.length > 0) {
|
|
132
|
+
enqueueUpdateTask({ product_ids, fields, updated_at });
|
|
133
|
+
}
|
|
134
|
+
const data = filterLatest(quoteState, product_ids, fields);
|
|
135
|
+
assertNotMissing(missing, updated_at);
|
|
66
136
|
return { res: { code: 0, message: 'OK', data } };
|
|
67
137
|
});
|
|
138
|
+
terminal.server.provideService('VEX/QuoteUpdateQueueStatus', {}, async () => {
|
|
139
|
+
return { res: { code: 0, message: 'OK', data: getQueueStatus() } };
|
|
140
|
+
});
|
|
68
141
|
//# sourceMappingURL=service.js.map
|