@yuants/app-virtual-exchange 0.8.0 → 0.9.0
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/credential.js +61 -40
- package/dist/credential.js.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/position.js +11 -4
- package/dist/position.js.map +1 -1
- package/dist/quote/benchmark/ForkedQuoteStateComparisonTest.js +356 -0
- package/dist/quote/benchmark/ForkedQuoteStateComparisonTest.js.map +1 -0
- package/dist/quote/benchmark/PerformanceTester.js +131 -0
- package/dist/quote/benchmark/PerformanceTester.js.map +1 -0
- package/dist/quote/benchmark/QuoteStateComparisonTest.js +261 -0
- package/dist/quote/benchmark/QuoteStateComparisonTest.js.map +1 -0
- package/dist/quote/benchmark/QuoteStateTestRunner.js +313 -0
- package/dist/quote/benchmark/QuoteStateTestRunner.js.map +1 -0
- package/dist/quote/benchmark/index.js +43 -0
- package/dist/quote/benchmark/index.js.map +1 -0
- package/dist/quote/benchmark/test-helpers.js +66 -0
- package/dist/quote/benchmark/test-helpers.js.map +1 -0
- package/dist/quote/benchmark/worker.js +263 -0
- package/dist/quote/benchmark/worker.js.map +1 -0
- package/dist/quote/implementations/index.js +13 -0
- package/dist/quote/implementations/index.js.map +1 -0
- package/dist/quote/implementations/v0.js +64 -0
- package/dist/quote/implementations/v0.js.map +1 -0
- package/dist/quote/implementations/v1.js +107 -0
- package/dist/quote/implementations/v1.js.map +1 -0
- package/dist/quote/implementations/v2.js +107 -0
- package/dist/quote/implementations/v2.js.map +1 -0
- package/dist/quote/implementations/v3.js +211 -0
- package/dist/quote/implementations/v3.js.map +1 -0
- package/dist/quote/service.js +45 -0
- package/dist/quote/service.js.map +1 -0
- package/dist/quote/state.benchmark.js +32 -0
- package/dist/quote/state.benchmark.js.map +1 -0
- package/dist/quote/state.js +4 -0
- package/dist/quote/state.js.map +1 -0
- package/dist/quote/types.js +2 -0
- package/dist/quote/types.js.map +1 -0
- package/lib/credential.d.ts +14 -11
- package/lib/credential.d.ts.map +1 -1
- package/lib/credential.js +61 -42
- package/lib/credential.js.map +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/position.d.ts.map +1 -1
- package/lib/position.js +11 -4
- package/lib/position.js.map +1 -1
- package/lib/quote/benchmark/ForkedQuoteStateComparisonTest.d.ts +62 -0
- package/lib/quote/benchmark/ForkedQuoteStateComparisonTest.d.ts.map +1 -0
- package/lib/quote/benchmark/ForkedQuoteStateComparisonTest.js +360 -0
- package/lib/quote/benchmark/ForkedQuoteStateComparisonTest.js.map +1 -0
- package/lib/quote/benchmark/PerformanceTester.d.ts +53 -0
- package/lib/quote/benchmark/PerformanceTester.d.ts.map +1 -0
- package/lib/quote/benchmark/PerformanceTester.js +135 -0
- package/lib/quote/benchmark/PerformanceTester.js.map +1 -0
- package/lib/quote/benchmark/QuoteStateComparisonTest.d.ts +25 -0
- package/lib/quote/benchmark/QuoteStateComparisonTest.d.ts.map +1 -0
- package/lib/quote/benchmark/QuoteStateComparisonTest.js +265 -0
- package/lib/quote/benchmark/QuoteStateComparisonTest.js.map +1 -0
- package/lib/quote/benchmark/QuoteStateTestRunner.d.ts +61 -0
- package/lib/quote/benchmark/QuoteStateTestRunner.d.ts.map +1 -0
- package/lib/quote/benchmark/QuoteStateTestRunner.js +317 -0
- package/lib/quote/benchmark/QuoteStateTestRunner.js.map +1 -0
- package/lib/quote/benchmark/index.d.ts +13 -0
- package/lib/quote/benchmark/index.d.ts.map +1 -0
- package/lib/quote/benchmark/index.js +53 -0
- package/lib/quote/benchmark/index.js.map +1 -0
- package/lib/quote/benchmark/test-helpers.d.ts +18 -0
- package/lib/quote/benchmark/test-helpers.d.ts.map +1 -0
- package/lib/quote/benchmark/test-helpers.js +73 -0
- package/lib/quote/benchmark/test-helpers.js.map +1 -0
- package/lib/quote/benchmark/worker.d.ts +3 -0
- package/lib/quote/benchmark/worker.d.ts.map +1 -0
- package/lib/quote/benchmark/worker.js +265 -0
- package/lib/quote/benchmark/worker.js.map +1 -0
- package/lib/quote/implementations/index.d.ts +10 -0
- package/lib/quote/implementations/index.d.ts.map +1 -0
- package/lib/quote/implementations/index.js +16 -0
- package/lib/quote/implementations/index.js.map +1 -0
- package/lib/quote/implementations/v0.d.ts +7 -0
- package/lib/quote/implementations/v0.d.ts.map +1 -0
- package/lib/quote/implementations/v0.js +68 -0
- package/lib/quote/implementations/v0.js.map +1 -0
- package/lib/quote/implementations/v1.d.ts +8 -0
- package/lib/quote/implementations/v1.d.ts.map +1 -0
- package/lib/quote/implementations/v1.js +111 -0
- package/lib/quote/implementations/v1.js.map +1 -0
- package/lib/quote/implementations/v2.d.ts +7 -0
- package/lib/quote/implementations/v2.d.ts.map +1 -0
- package/lib/quote/implementations/v2.js +111 -0
- package/lib/quote/implementations/v2.js.map +1 -0
- package/lib/quote/implementations/v3.d.ts +8 -0
- package/lib/quote/implementations/v3.d.ts.map +1 -0
- package/lib/quote/implementations/v3.js +215 -0
- package/lib/quote/implementations/v3.js.map +1 -0
- package/lib/quote/service.d.ts +2 -0
- package/lib/quote/service.d.ts.map +1 -0
- package/lib/quote/service.js +47 -0
- package/lib/quote/service.js.map +1 -0
- package/lib/quote/state.benchmark.d.ts +2 -0
- package/lib/quote/state.benchmark.d.ts.map +1 -0
- package/lib/quote/state.benchmark.js +34 -0
- package/lib/quote/state.benchmark.js.map +1 -0
- package/lib/quote/state.d.ts +2 -0
- package/lib/quote/state.d.ts.map +1 -0
- package/lib/quote/state.js +7 -0
- package/lib/quote/state.js.map +1 -0
- package/lib/quote/types.d.ts +30 -0
- package/lib/quote/types.d.ts.map +1 -0
- package/lib/quote/types.js +3 -0
- package/lib/quote/types.js.map +1 -0
- package/package.json +2 -2
- package/temp/package-deps.json +25 -7
package/dist/credential.js
CHANGED
|
@@ -1,35 +1,61 @@
|
|
|
1
1
|
import { createCache } from '@yuants/cache';
|
|
2
2
|
import { getCredentialId } from '@yuants/exchange';
|
|
3
3
|
import { Terminal } from '@yuants/protocol';
|
|
4
|
-
import { readSecret, writeSecret } from '@yuants/secret';
|
|
4
|
+
import { listSecrets, readSecret, writeSecret } from '@yuants/secret';
|
|
5
5
|
import { escapeSQL, requestSQL } from '@yuants/sql';
|
|
6
6
|
import { newError } from '@yuants/utils';
|
|
7
7
|
import { defer, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';
|
|
8
8
|
const terminal = Terminal.fromNodeEnv();
|
|
9
9
|
const credentialReader = process.env.NODE_UNIT_PUBLIC_KEY || terminal.keyPair.public_key;
|
|
10
|
+
/**
|
|
11
|
+
* 根据 secret sign 解析出对应的 exchange credential
|
|
12
|
+
* 此处可以做缓存,因为同一个 secret sign 对应的 credential 信息永远不会变化,可以节约解密和后续 SQL 查询的开销
|
|
13
|
+
* 得到 credential 后,此 credential 不一定是有效的,因为可能凭证信息已经过期或被撤销
|
|
14
|
+
*/
|
|
15
|
+
const secretSignToCredentialIdCache = createCache(async (sign) => {
|
|
16
|
+
const sql = `SELECT * FROM secret WHERE sign = ${escapeSQL(sign)} LIMIT 1;`;
|
|
17
|
+
const res = await requestSQL(terminal, sql);
|
|
18
|
+
if (res.length === 0)
|
|
19
|
+
throw newError('SECRET_NOT_FOUND', { sign });
|
|
20
|
+
const secret = res[0];
|
|
21
|
+
const decrypted = await readSecret(terminal, secret);
|
|
22
|
+
const credential = JSON.parse(new TextDecoder().decode(decrypted));
|
|
23
|
+
return credential;
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* 根据 credential 信息解析出对应的 credential ID
|
|
27
|
+
* 此处可以做缓存,因为同一个 credential 永远对应同一个 credential ID,可以节约后续 SQL 查询的开销
|
|
28
|
+
* 但是需要注意的是,credential ID 可能会因为凭证被撤销而失效,但是可以在下游调用其他服务时感知到,因此可以永久缓存
|
|
29
|
+
*/
|
|
10
30
|
const credentialIdCache = createCache(async (credentialKey) => {
|
|
11
31
|
const credential = JSON.parse(credentialKey);
|
|
12
32
|
const res = await getCredentialId(terminal, credential);
|
|
13
33
|
return res.data;
|
|
14
34
|
});
|
|
15
|
-
|
|
16
|
-
const secrets = await
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
result.
|
|
26
|
-
|
|
35
|
+
const listAllCredentials = async () => {
|
|
36
|
+
const secrets = await listSecrets(terminal, {
|
|
37
|
+
reader: credentialReader,
|
|
38
|
+
tags: { type: 'exchange_credential' },
|
|
39
|
+
});
|
|
40
|
+
const results = await Promise.allSettled(secrets.map((secret) => getCredentialBySecretId(secret.sign)));
|
|
41
|
+
return results.map((result, index) => {
|
|
42
|
+
if (result.status === 'fulfilled') {
|
|
43
|
+
return {
|
|
44
|
+
sign: secrets[index].sign,
|
|
45
|
+
credential: result.value.credential,
|
|
46
|
+
credentialId: result.value.credentialId,
|
|
47
|
+
error: null,
|
|
48
|
+
};
|
|
27
49
|
}
|
|
28
|
-
|
|
29
|
-
|
|
50
|
+
else {
|
|
51
|
+
return {
|
|
52
|
+
sign: secrets[index].sign,
|
|
53
|
+
credential: null,
|
|
54
|
+
credentialId: null,
|
|
55
|
+
error: `${result.reason}`,
|
|
56
|
+
};
|
|
30
57
|
}
|
|
31
|
-
})
|
|
32
|
-
return results;
|
|
58
|
+
});
|
|
33
59
|
};
|
|
34
60
|
terminal.server.provideService('VEX/RegisterExchangeCredential', {
|
|
35
61
|
type: 'object',
|
|
@@ -44,6 +70,7 @@ terminal.server.provideService('VEX/RegisterExchangeCredential', {
|
|
|
44
70
|
const secret = await writeSecret(terminal, credentialReader, { type: 'exchange_credential' }, secretData);
|
|
45
71
|
return { res: { code: 0, message: 'OK', data: secret } };
|
|
46
72
|
});
|
|
73
|
+
// For Debugging Purpose
|
|
47
74
|
terminal.server.provideService('VEX/ListExchangeCredential', {}, async () => {
|
|
48
75
|
return { res: { code: 0, message: 'OK', data: await listAllCredentials() } };
|
|
49
76
|
});
|
|
@@ -51,8 +78,7 @@ terminal.server.provideService('VEX/ListCredentials', {}, async () => {
|
|
|
51
78
|
const credentials = await firstValueFrom(validCredentials$);
|
|
52
79
|
return { res: { code: 0, message: 'OK', data: [...credentials.keys()] } };
|
|
53
80
|
});
|
|
54
|
-
const
|
|
55
|
-
export const validCredentials$ = defer(() => credentialCache.query('')).pipe(map((x) => {
|
|
81
|
+
export const validCredentials$ = defer(() => listAllCredentials()).pipe(map((x) => {
|
|
56
82
|
const map = new Map();
|
|
57
83
|
if (!x)
|
|
58
84
|
return map;
|
|
@@ -70,26 +96,21 @@ export const validCredentialTypes$ = validCredentials$.pipe(map((credentials) =>
|
|
|
70
96
|
});
|
|
71
97
|
return Array.from(types);
|
|
72
98
|
}));
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (!
|
|
84
|
-
throw newError('CREDENTIAL_NOT_RESOLVED', {
|
|
85
|
-
|
|
86
|
-
if (!
|
|
87
|
-
throw newError('CREDENTIAL_ID_NOT_RESOLVED', {
|
|
88
|
-
}
|
|
89
|
-
return {
|
|
90
|
-
secret: theCredential.secret,
|
|
91
|
-
credential: theCredential.credential,
|
|
92
|
-
credentialId: theCredential.credentialId,
|
|
93
|
-
};
|
|
99
|
+
/**
|
|
100
|
+
* 根据 secret sign 解析出对应的 credential 以及 credential ID
|
|
101
|
+
* @param sign - secret sign
|
|
102
|
+
* @returns 解析得到的 credential 以及对应的 credential ID
|
|
103
|
+
* @throws 如果无法解析出对应的 credential 或 credential ID,则抛出异常
|
|
104
|
+
*
|
|
105
|
+
* 不依赖 List Credential 服务,可以及时感知凭证的新增和变更
|
|
106
|
+
*/
|
|
107
|
+
export const getCredentialBySecretId = async (sign) => {
|
|
108
|
+
const credential = await secretSignToCredentialIdCache.query(sign);
|
|
109
|
+
if (!credential)
|
|
110
|
+
throw newError('CREDENTIAL_NOT_RESOLVED', { sign });
|
|
111
|
+
const credentialId = await credentialIdCache.query(JSON.stringify(credential));
|
|
112
|
+
if (!credentialId)
|
|
113
|
+
throw newError('CREDENTIAL_ID_NOT_RESOLVED', { sign });
|
|
114
|
+
return { sign, credential, credentialId };
|
|
94
115
|
};
|
|
95
116
|
//# sourceMappingURL=credential.js.map
|
package/dist/credential.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credential.js","sourceRoot":"","sources":["../src/credential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAW,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"credential.js","sourceRoot":"","sources":["../src/credential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAW,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AAO9E,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,gBAAgB,GAAG,OAAO,CAAC,GAAG,CAAC,oBAAoB,I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E,KAAK,EAAE,CAAC,EACxB,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,WAAW,CAAC,CAAC,CAAC,CACf,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,iBAAiB,CAAC,IAAI,CACzD,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE;IAClB,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE;QACjC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC,CAAC,CACH,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,IAAY,EAAE,EAAE;IAC5D,MAAM,UAAU,GAAG,MAAM,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,IAAI,CAAC,UAAU;QAAE,MAAM,QAAQ,CAAC,yBAAyB,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACrE,MAAM,YAAY,GAAG,MAAM,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IAC/E,IAAI,CAAC,YAAY;QAAE,MAAM,QAAQ,CAAC,4BAA4B,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1E,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;AAC5C,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { getCredentialId } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { ISecret, listSecrets, readSecret, writeSecret } from '@yuants/secret';\nimport { escapeSQL, requestSQL } from '@yuants/sql';\nimport { newError } from '@yuants/utils';\nimport { defer, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';\n\ninterface IExchangeCredential {\n type: string;\n payload: any;\n}\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst credentialReader = process.env.NODE_UNIT_PUBLIC_KEY || terminal.keyPair.public_key;\n\n/**\n * 根据 secret sign 解析出对应的 exchange credential\n * 此处可以做缓存,因为同一个 secret sign 对应的 credential 信息永远不会变化,可以节约解密和后续 SQL 查询的开销\n * 得到 credential 后,此 credential 不一定是有效的,因为可能凭证信息已经过期或被撤销\n */\nconst secretSignToCredentialIdCache = createCache(async (sign: string) => {\n const sql = `SELECT * FROM secret WHERE sign = ${escapeSQL(sign)} LIMIT 1;`;\n const res = await requestSQL<ISecret[]>(terminal, sql);\n if (res.length === 0) throw newError('SECRET_NOT_FOUND', { sign });\n const secret = res[0];\n const decrypted = await readSecret(terminal, secret);\n const credential = JSON.parse(new TextDecoder().decode(decrypted)) as IExchangeCredential;\n return credential;\n});\n\n/**\n * 根据 credential 信息解析出对应的 credential ID\n * 此处可以做缓存,因为同一个 credential 永远对应同一个 credential ID,可以节约后续 SQL 查询的开销\n * 但是需要注意的是,credential ID 可能会因为凭证被撤销而失效,但是可以在下游调用其他服务时感知到,因此可以永久缓存\n */\nconst credentialIdCache = createCache(async (credentialKey: string) => {\n const credential = JSON.parse(credentialKey) as IExchangeCredential;\n const res = await getCredentialId(terminal, credential);\n return res.data;\n});\n\nconst listAllCredentials = async () => {\n const secrets = await listSecrets(terminal, {\n reader: credentialReader,\n tags: { type: 'exchange_credential' },\n });\n\n const results = await Promise.allSettled(secrets.map((secret) => getCredentialBySecretId(secret.sign)));\n return results.map(\n (\n result,\n index,\n ): {\n sign: string;\n credential: IExchangeCredential | null;\n credentialId: string | null;\n error: any;\n } => {\n if (result.status === 'fulfilled') {\n return {\n sign: secrets[index].sign,\n credential: result.value.credential,\n credentialId: result.value.credentialId,\n error: null,\n };\n } else {\n return {\n sign: secrets[index].sign,\n credential: null,\n credentialId: null,\n error: `${result.reason}`,\n };\n }\n },\n );\n};\n\nterminal.server.provideService<IExchangeCredential, ISecret>(\n 'VEX/RegisterExchangeCredential',\n {\n type: 'object',\n required: ['type', 'payload'],\n properties: {\n type: { type: 'string' },\n payload: { type: 'object' },\n },\n },\n async (msg) => {\n const credential = msg.req;\n const secretData = new TextEncoder().encode(JSON.stringify(credential));\n const secret = await writeSecret(terminal, credentialReader, { type: 'exchange_credential' }, secretData);\n return { res: { code: 0, message: 'OK', data: secret } };\n },\n);\n\n// For Debugging Purpose\nterminal.server.provideService('VEX/ListExchangeCredential', {}, async () => {\n return { res: { code: 0, message: 'OK', data: await listAllCredentials() } };\n});\n\nterminal.server.provideService<void, string[]>('VEX/ListCredentials', {}, async () => {\n const credentials = await firstValueFrom(validCredentials$);\n return { res: { code: 0, message: 'OK', data: [...credentials.keys()] } };\n});\n\nexport const validCredentials$ = defer(() => listAllCredentials()).pipe(\n map((x) => {\n const map = new Map<string, IExchangeCredential>();\n if (!x) return map;\n for (const xx of x) {\n if (xx.credentialId && xx.credential) {\n map.set(xx.credentialId, xx.credential);\n }\n }\n return map;\n }),\n repeat({ delay: 10000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const validCredentialTypes$ = validCredentials$.pipe(\n map((credentials) => {\n const types = new Set<string>();\n credentials.forEach((credential) => {\n types.add(credential.type);\n });\n return Array.from(types);\n }),\n);\n\n/**\n * 根据 secret sign 解析出对应的 credential 以及 credential ID\n * @param sign - secret sign\n * @returns 解析得到的 credential 以及对应的 credential ID\n * @throws 如果无法解析出对应的 credential 或 credential ID,则抛出异常\n *\n * 不依赖 List Credential 服务,可以及时感知凭证的新增和变更\n */\nexport const getCredentialBySecretId = async (sign: string) => {\n const credential = await secretSignToCredentialIdCache.query(sign);\n if (!credential) throw newError('CREDENTIAL_NOT_RESOLVED', { sign });\n const credentialId = await credentialIdCache.query(JSON.stringify(credential));\n if (!credentialId) throw newError('CREDENTIAL_ID_NOT_RESOLVED', { sign });\n return { sign, credential, credentialId };\n};\n"]}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,CAAC;AACtB,OAAO,WAAW,CAAC;AACnB,OAAO,mBAAmB,CAAC;AAC3B,OAAO,qBAAqB,CAAC","sourcesContent":["import './credential';\nimport './general';\nimport './legacy-services';\nimport './product-collector';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,CAAC;AACtB,OAAO,WAAW,CAAC;AACnB,OAAO,mBAAmB,CAAC;AAC3B,OAAO,qBAAqB,CAAC;AAC7B,OAAO,iBAAiB,CAAC","sourcesContent":["import './credential';\nimport './general';\nimport './legacy-services';\nimport './product-collector';\nimport './quote/service';\n"]}
|
package/dist/position.js
CHANGED
|
@@ -52,8 +52,14 @@ export const polyfillPosition = async (positions) => {
|
|
|
52
52
|
// 利率相关信息的追加
|
|
53
53
|
if (quote) {
|
|
54
54
|
if (quote.interest_rate_next_settled_at !== null) {
|
|
55
|
+
const nextSettledAt = new Date(quote.interest_rate_next_settled_at).getTime();
|
|
55
56
|
// 优先使用行情数据中的下一个结算时间
|
|
56
|
-
pos.settlement_scheduled_at =
|
|
57
|
+
pos.settlement_scheduled_at = nextSettledAt;
|
|
58
|
+
// 优先使用下一个结算时间推算结算间隔
|
|
59
|
+
if (interestRateInterval !== undefined) {
|
|
60
|
+
const interval = nextSettledAt - interestRateInterval.prev;
|
|
61
|
+
pos.settlement_interval = interval;
|
|
62
|
+
}
|
|
57
63
|
}
|
|
58
64
|
else if (quote.interest_rate_next_settled_at === null && interestRateInterval !== undefined) {
|
|
59
65
|
// 估算下一个结算时间
|
|
@@ -61,6 +67,10 @@ export const polyfillPosition = async (positions) => {
|
|
|
61
67
|
const k = Math.ceil((Date.now() - interestRateInterval.prev) / interestRateInterval.interval);
|
|
62
68
|
pos.settlement_scheduled_at = interestRateInterval.prev + k * interestRateInterval.interval;
|
|
63
69
|
}
|
|
70
|
+
// 如果还没有结算间隔,则使用 interest rate 表的时间间隔作为结算间隔
|
|
71
|
+
if (pos.settlement_interval === undefined && interestRateInterval) {
|
|
72
|
+
pos.settlement_interval = interestRateInterval.interval;
|
|
73
|
+
}
|
|
64
74
|
if (pos.direction === 'LONG') {
|
|
65
75
|
if (quote.interest_rate_long !== null) {
|
|
66
76
|
pos.interest_to_settle = +quote.interest_rate_long * pos.valuation;
|
|
@@ -72,9 +82,6 @@ export const polyfillPosition = async (positions) => {
|
|
|
72
82
|
}
|
|
73
83
|
}
|
|
74
84
|
}
|
|
75
|
-
if (interestRateInterval) {
|
|
76
|
-
pos.settlement_interval = interestRateInterval.interval;
|
|
77
|
-
}
|
|
78
85
|
}
|
|
79
86
|
return positions;
|
|
80
87
|
};
|
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,0CAA0C,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;IAC9E,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,UAAU,CAAW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AAS,EAAE;gBAC5B,MAAM,OAAO,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;gBAC5B,MAAM,QAAQ,GAAG,UAAU,CAAC,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC;gBACjE,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC;oBAAE,MAAM,QAAQ,CAAC,mBAAmB,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC;gBAC5F,qCAAqC;gBACrC,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,QAAQ,CAAC,GAAG,QAAQ,CAAC,GAAG,KAAK,EAAE;oBACzE,MAAM,QAAQ,CAAC,8CAA8C,EAAE;wBAC7D,KAAK;wBACL,QAAQ;wBACR,OAAO;wBACP,OAAO,EAAE,UAAU;qBACpB,CAAC,CAAC;iBACJ;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: 3600_000, expire: 8 * 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 // 优先使用行情数据中的下一个结算时间\n pos.settlement_scheduled_at = new Date(quote.interest_rate_next_settled_at).getTime();\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 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 if (interestRateInterval) {\n pos.settlement_interval = interestRateInterval.interval;\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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AC7D,KAAK;wBACL,QAAQ;wBACR,OAAO;wBACP,OAAO,EAAE,UAAU;qBACpB,CAAC,CAAC;iBACJ;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: 3600_000, expire: 8 * 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"]}
|