@yuants/vendor-hyperliquid 0.5.2 → 0.6.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.
Files changed (140) hide show
  1. package/dist/api/client.js +1 -1
  2. package/dist/api/client.js.map +1 -1
  3. package/dist/api/private-api.js +56 -0
  4. package/dist/api/private-api.js.map +1 -1
  5. package/dist/api/public-api.js +83 -1
  6. package/dist/api/public-api.js.map +1 -1
  7. package/dist/api/types.js +19 -2
  8. package/dist/api/types.js.map +1 -1
  9. package/dist/index.js +9 -4
  10. package/dist/index.js.map +1 -1
  11. package/dist/services/account-actions-with-credential.js +122 -0
  12. package/dist/services/account-actions-with-credential.js.map +1 -0
  13. package/dist/{account.js → services/accounts/perp.js} +6 -6
  14. package/dist/services/accounts/perp.js.map +1 -0
  15. package/dist/{public-data → services/markets}/interest-rate.js +1 -1
  16. package/dist/services/markets/interest-rate.js.map +1 -0
  17. package/dist/{public-data → services/markets}/ohlc.js +1 -1
  18. package/dist/services/markets/ohlc.js.map +1 -0
  19. package/dist/{public-data → services/markets}/product.js +1 -1
  20. package/dist/services/markets/product.js.map +1 -0
  21. package/dist/{public-data → services/markets}/quote.js +1 -1
  22. package/dist/services/markets/quote.js.map +1 -0
  23. package/dist/{order-actions-with-credential.js → services/order-actions-with-credential.js} +7 -4
  24. package/dist/services/order-actions-with-credential.js.map +1 -0
  25. package/dist/{order-actions → services/orders}/cancelOrder.js +2 -2
  26. package/dist/services/orders/cancelOrder.js.map +1 -0
  27. package/dist/services/orders/listOrders.js +87 -0
  28. package/dist/services/orders/listOrders.js.map +1 -0
  29. package/dist/services/orders/modifyOrder.js +53 -0
  30. package/dist/services/orders/modifyOrder.js.map +1 -0
  31. package/dist/{order-actions → services/orders}/submitOrder.js +2 -2
  32. package/dist/services/orders/submitOrder.js.map +1 -0
  33. package/dist/{order-utils.js → utils.js} +30 -46
  34. package/dist/utils.js.map +1 -0
  35. package/lib/api/client.d.ts.map +1 -1
  36. package/lib/api/client.js +1 -1
  37. package/lib/api/client.js.map +1 -1
  38. package/lib/api/private-api.d.ts +83 -0
  39. package/lib/api/private-api.d.ts.map +1 -1
  40. package/lib/api/private-api.js +59 -1
  41. package/lib/api/private-api.js.map +1 -1
  42. package/lib/api/public-api.d.ts +82 -0
  43. package/lib/api/public-api.d.ts.map +1 -1
  44. package/lib/api/public-api.js +83 -1
  45. package/lib/api/public-api.js.map +1 -1
  46. package/lib/api/types.d.ts +19 -1
  47. package/lib/api/types.d.ts.map +1 -1
  48. package/lib/api/types.js +21 -3
  49. package/lib/api/types.js.map +1 -1
  50. package/lib/index.d.ts +7 -4
  51. package/lib/index.d.ts.map +1 -1
  52. package/lib/index.js +9 -4
  53. package/lib/index.js.map +1 -1
  54. package/lib/services/account-actions-with-credential.d.ts +2 -0
  55. package/lib/services/account-actions-with-credential.d.ts.map +1 -0
  56. package/lib/services/account-actions-with-credential.js +124 -0
  57. package/lib/services/account-actions-with-credential.js.map +1 -0
  58. package/lib/{account.d.ts → services/accounts/perp.d.ts} +1 -1
  59. package/lib/services/accounts/perp.d.ts.map +1 -0
  60. package/lib/{account.js → services/accounts/perp.js} +6 -6
  61. package/lib/services/accounts/perp.js.map +1 -0
  62. package/lib/services/markets/interest-rate.d.ts.map +1 -0
  63. package/lib/{public-data → services/markets}/interest-rate.js +1 -1
  64. package/lib/services/markets/interest-rate.js.map +1 -0
  65. package/lib/{public-data → services/markets}/ohlc.d.ts.map +1 -1
  66. package/lib/{public-data → services/markets}/ohlc.js +1 -1
  67. package/lib/services/markets/ohlc.js.map +1 -0
  68. package/lib/services/markets/product.d.ts.map +1 -0
  69. package/lib/{public-data → services/markets}/product.js +1 -1
  70. package/lib/services/markets/product.js.map +1 -0
  71. package/lib/{public-data → services/markets}/quote.d.ts.map +1 -1
  72. package/lib/{public-data → services/markets}/quote.js +1 -1
  73. package/lib/services/markets/quote.js.map +1 -0
  74. package/lib/services/order-actions-with-credential.d.ts.map +1 -0
  75. package/lib/{order-actions-with-credential.js → services/order-actions-with-credential.js} +7 -4
  76. package/lib/services/order-actions-with-credential.js.map +1 -0
  77. package/lib/{order-actions → services/orders}/cancelOrder.d.ts +1 -1
  78. package/lib/services/orders/cancelOrder.d.ts.map +1 -0
  79. package/lib/{order-actions → services/orders}/cancelOrder.js +3 -3
  80. package/lib/services/orders/cancelOrder.js.map +1 -0
  81. package/lib/services/orders/listOrders.d.ts +7 -0
  82. package/lib/services/orders/listOrders.d.ts.map +1 -0
  83. package/lib/services/orders/listOrders.js +91 -0
  84. package/lib/services/orders/listOrders.js.map +1 -0
  85. package/lib/services/orders/modifyOrder.d.ts +15 -0
  86. package/lib/services/orders/modifyOrder.d.ts.map +1 -0
  87. package/lib/services/orders/modifyOrder.js +57 -0
  88. package/lib/services/orders/modifyOrder.js.map +1 -0
  89. package/lib/{order-actions → services/orders}/submitOrder.d.ts +1 -1
  90. package/lib/services/orders/submitOrder.d.ts.map +1 -0
  91. package/lib/{order-actions → services/orders}/submitOrder.js +3 -3
  92. package/lib/services/orders/submitOrder.js.map +1 -0
  93. package/lib/{order-utils.d.ts → utils.d.ts} +1 -1
  94. package/lib/utils.d.ts.map +1 -0
  95. package/lib/{order-utils.js → utils.js} +30 -46
  96. package/lib/utils.js.map +1 -0
  97. package/package.json +4 -3
  98. package/temp/package-deps.json +26 -24
  99. package/dist/account.js.map +0 -1
  100. package/dist/order-actions/cancelOrder.js.map +0 -1
  101. package/dist/order-actions/submitOrder.js.map +0 -1
  102. package/dist/order-actions-with-credential.js.map +0 -1
  103. package/dist/order-actions.js +0 -36
  104. package/dist/order-actions.js.map +0 -1
  105. package/dist/order-utils.js.map +0 -1
  106. package/dist/public-data/index.js +0 -5
  107. package/dist/public-data/index.js.map +0 -1
  108. package/dist/public-data/interest-rate.js.map +0 -1
  109. package/dist/public-data/ohlc.js.map +0 -1
  110. package/dist/public-data/product.js.map +0 -1
  111. package/dist/public-data/quote.js.map +0 -1
  112. package/lib/account.d.ts.map +0 -1
  113. package/lib/account.js.map +0 -1
  114. package/lib/order-actions/cancelOrder.d.ts.map +0 -1
  115. package/lib/order-actions/cancelOrder.js.map +0 -1
  116. package/lib/order-actions/submitOrder.d.ts.map +0 -1
  117. package/lib/order-actions/submitOrder.js.map +0 -1
  118. package/lib/order-actions-with-credential.d.ts.map +0 -1
  119. package/lib/order-actions-with-credential.js.map +0 -1
  120. package/lib/order-actions.d.ts +0 -2
  121. package/lib/order-actions.d.ts.map +0 -1
  122. package/lib/order-actions.js +0 -38
  123. package/lib/order-actions.js.map +0 -1
  124. package/lib/order-utils.d.ts.map +0 -1
  125. package/lib/order-utils.js.map +0 -1
  126. package/lib/public-data/index.d.ts +0 -5
  127. package/lib/public-data/index.d.ts.map +0 -1
  128. package/lib/public-data/index.js +0 -7
  129. package/lib/public-data/index.js.map +0 -1
  130. package/lib/public-data/interest-rate.d.ts.map +0 -1
  131. package/lib/public-data/interest-rate.js.map +0 -1
  132. package/lib/public-data/ohlc.js.map +0 -1
  133. package/lib/public-data/product.d.ts.map +0 -1
  134. package/lib/public-data/product.js.map +0 -1
  135. package/lib/public-data/quote.js.map +0 -1
  136. /package/lib/{public-data → services/markets}/interest-rate.d.ts +0 -0
  137. /package/lib/{public-data → services/markets}/ohlc.d.ts +0 -0
  138. /package/lib/{public-data → services/markets}/product.d.ts +0 -0
  139. /package/lib/{public-data → services/markets}/quote.d.ts +0 -0
  140. /package/lib/{order-actions-with-credential.d.ts → services/order-actions-with-credential.d.ts} +0 -0
@@ -30,7 +30,7 @@ const callApi = async (method, path, params) => {
30
30
  return JSON.parse(retStr);
31
31
  }
32
32
  catch (err) {
33
- console.error(formatTime(Date.now()), 'HyperliquidRequestFailed', path, JSON.stringify(params), retStr);
33
+ console.error(formatTime(Date.now()), 'HyperliquidRequestFailed', path, JSON.stringify(params), retStr, err);
34
34
  throw err;
35
35
  }
36
36
  };
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AA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GAAG,IAAI,EAAE,CAAC;IACxB,MAAM,IAAI,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAC1C,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAC5C,QAAQ,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAC1E,OAAO,CAAC,KAAM,CAAC,EACf,WAAW,CAAC,CAAC,CAAC,CACf,CAAC;IACF,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;IACjE,OAAO,CAAC,MAAA,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,mCAAI,IAAI,CAAM,CAAC;AAC9D,CAAC,CAAC","sourcesContent":["import { UUID, formatTime } from '@yuants/utils';\nimport { Subject, filter, firstValueFrom, mergeMap, of, shareReplay, throwError, timeout, timer } from 'rxjs';\n\ntype HttpMethod = 'GET' | 'POST';\n\nconst BASE_URL = 'https://api.hyperliquid.xyz';\n\nconst buildUrl = (path: string, method: HttpMethod, params?: any) => {\n const url = new URL(BASE_URL);\n url.pathname = path;\n if (method === 'GET' && params) {\n const entries = Object.entries(params).sort(([a], [b]) => a.localeCompare(b));\n for (const [key, value] of entries) {\n url.searchParams.set(key, '' + value);\n }\n }\n return url;\n};\n\nconst callApi = async (method: HttpMethod, path: string, params?: any) => {\n const url = buildUrl(path, method, params);\n const body = method === 'GET' ? '' : JSON.stringify(params ?? {});\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers,\n body: method === 'GET' ? undefined : body || undefined,\n });\n const retStr = await res.text();\n try {\n if (process.env.LOG_LEVEL === 'DEBUG') {\n console.debug(formatTime(Date.now()), 'HyperliquidResponse', path, JSON.stringify(params), retStr);\n }\n return JSON.parse(retStr);\n } catch (err) {\n console.error(formatTime(Date.now()), 'HyperliquidRequestFailed', path, JSON.stringify(params), retStr);\n throw err;\n }\n};\n\ntype FlowController = {\n requestQueue: Array<{ trace_id: string; method: HttpMethod; path: string; params?: any }>;\n responseChannel: Subject<{ trace_id: string; response?: any; error?: Error }>;\n};\n\nconst controllers = new Map<string, FlowController>();\n\nconst ensureController = (path: string, period: number, limit: number) => {\n if (controllers.has(path)) {\n return controllers.get(path)!;\n }\n const controller: FlowController = {\n requestQueue: [],\n responseChannel: new Subject(),\n };\n timer(0, period)\n .pipe(\n filter(() => controller.requestQueue.length > 0),\n mergeMap(() => controller.requestQueue.splice(0, limit)),\n mergeMap(async (request) => {\n try {\n const response = await callApi(request.method, request.path, request.params);\n return { trace_id: request.trace_id, response };\n } catch (error) {\n return { trace_id: request.trace_id, error: error as Error };\n }\n }),\n )\n .subscribe(controller.responseChannel);\n controllers.set(path, controller);\n return controller;\n};\n\nexport const request = <T = any>(method: HttpMethod, path: string, params?: any) =>\n callApi(method, path, params) as Promise<T>;\n\nexport const requestWithFlowControl = async <T = any>(\n method: HttpMethod,\n path: string,\n flowControl: { period: number; limit: number },\n params?: any,\n) => {\n const controller = ensureController(path, flowControl.period, flowControl.limit);\n const trace_id = UUID();\n const res$ = controller.responseChannel.pipe(\n filter((resp) => resp.trace_id === trace_id),\n mergeMap((resp) => (resp.error ? throwError(() => resp.error) : of(resp))),\n timeout(30_000),\n shareReplay(1),\n );\n controller.requestQueue.push({ trace_id, method, path, params });\n return ((await firstValueFrom(res$)).response ?? null) as T;\n};\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,eAAe,C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AAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAC1C,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAC5C,QAAQ,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAC1E,OAAO,CAAC,KAAM,CAAC,EACf,WAAW,CAAC,CAAC,CAAC,CACf,CAAC;IACF,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;IACjE,OAAO,CAAC,MAAA,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,mCAAI,IAAI,CAAM,CAAC;AAC9D,CAAC,CAAC","sourcesContent":["import { UUID, formatTime } from '@yuants/utils';\nimport { Subject, filter, firstValueFrom, mergeMap, of, shareReplay, throwError, timeout, timer } from 'rxjs';\n\ntype HttpMethod = 'GET' | 'POST';\n\nconst BASE_URL = 'https://api.hyperliquid.xyz';\n\nconst buildUrl = (path: string, method: HttpMethod, params?: any) => {\n const url = new URL(BASE_URL);\n url.pathname = path;\n if (method === 'GET' && params) {\n const entries = Object.entries(params).sort(([a], [b]) => a.localeCompare(b));\n for (const [key, value] of entries) {\n url.searchParams.set(key, '' + value);\n }\n }\n return url;\n};\n\nconst callApi = async (method: HttpMethod, path: string, params?: any) => {\n const url = buildUrl(path, method, params);\n const body = method === 'GET' ? '' : JSON.stringify(params ?? {});\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers,\n body: method === 'GET' ? undefined : body || undefined,\n });\n const retStr = await res.text();\n try {\n if (process.env.LOG_LEVEL === 'DEBUG') {\n console.debug(formatTime(Date.now()), 'HyperliquidResponse', path, JSON.stringify(params), retStr);\n }\n return JSON.parse(retStr);\n } catch (err) {\n console.error(\n formatTime(Date.now()),\n 'HyperliquidRequestFailed',\n path,\n JSON.stringify(params),\n retStr,\n err,\n );\n throw err;\n }\n};\n\ntype FlowController = {\n requestQueue: Array<{ trace_id: string; method: HttpMethod; path: string; params?: any }>;\n responseChannel: Subject<{ trace_id: string; response?: any; error?: Error }>;\n};\n\nconst controllers = new Map<string, FlowController>();\n\nconst ensureController = (path: string, period: number, limit: number) => {\n if (controllers.has(path)) {\n return controllers.get(path)!;\n }\n const controller: FlowController = {\n requestQueue: [],\n responseChannel: new Subject(),\n };\n timer(0, period)\n .pipe(\n filter(() => controller.requestQueue.length > 0),\n mergeMap(() => controller.requestQueue.splice(0, limit)),\n mergeMap(async (request) => {\n try {\n const response = await callApi(request.method, request.path, request.params);\n return { trace_id: request.trace_id, response };\n } catch (error) {\n return { trace_id: request.trace_id, error: error as Error };\n }\n }),\n )\n .subscribe(controller.responseChannel);\n controllers.set(path, controller);\n return controller;\n};\n\nexport const request = <T = any>(method: HttpMethod, path: string, params?: any) =>\n callApi(method, path, params) as Promise<T>;\n\nexport const requestWithFlowControl = async <T = any>(\n method: HttpMethod,\n path: string,\n flowControl: { period: number; limit: number },\n params?: any,\n) => {\n const controller = ensureController(path, flowControl.period, flowControl.limit);\n const trace_id = UUID();\n const res$ = controller.responseChannel.pipe(\n filter((resp) => resp.trace_id === trace_id),\n mergeMap((resp) => (resp.error ? throwError(() => resp.error) : of(resp))),\n timeout(30_000),\n shareReplay(1),\n );\n controller.requestQueue.push({ trace_id, method, path, params });\n return ((await firstValueFrom(res$)).response ?? null) as T;\n};\n"]}
@@ -8,6 +8,14 @@ const getWallet = (credential) => {
8
8
  }
9
9
  return walletCache.get(credential.private_key);
10
10
  };
11
+ /**
12
+ * Place orders on Hyperliquid exchange
13
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
14
+ * API Endpoint: POST /exchange
15
+ * @param credential - User credential containing private key for signing
16
+ * @param params - Order placement parameters
17
+ * @returns Promise resolving to exchange response
18
+ */
11
19
  export const placeOrder = async (credential, params) => {
12
20
  var _a, _b;
13
21
  const action = {
@@ -22,6 +30,14 @@ export const placeOrder = async (credential, params) => {
22
30
  const signature = await signL1Action(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
23
31
  return request('POST', 'exchange', { action, nonce, signature });
24
32
  };
33
+ /**
34
+ * Cancel orders on Hyperliquid exchange
35
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s
36
+ * API Endpoint: POST /exchange
37
+ * @param credential - User credential containing private key for signing
38
+ * @param params - Order cancellation parameters
39
+ * @returns Promise resolving to exchange response
40
+ */
25
41
  export const cancelOrder = async (credential, params) => {
26
42
  var _a, _b;
27
43
  const action = {
@@ -32,4 +48,44 @@ export const cancelOrder = async (credential, params) => {
32
48
  const signature = await signL1Action(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
33
49
  return request('POST', 'exchange', { action, nonce, signature });
34
50
  };
51
+ /**
52
+ * Modify an existing order on Hyperliquid exchange
53
+ * API Endpoint: POST /exchange
54
+ * @param credential - User credential containing private key for signing
55
+ * @param params - Order modification parameters
56
+ * @returns Promise resolving to exchange response
57
+ */
58
+ export const modifyOrder = async (credential, params) => {
59
+ var _a, _b;
60
+ const action = {
61
+ type: 'modify',
62
+ oid: params.oid,
63
+ order: params.order,
64
+ };
65
+ const nonce = Date.now();
66
+ const signature = await signL1Action(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
67
+ return request('POST', 'exchange', { action, nonce, signature });
68
+ };
69
+ /**
70
+ * Get user's fill history (trade history) from Hyperliquid
71
+ * API Endpoint: POST /info (type: userFills)
72
+ * @param credential - User credential containing private key for authentication
73
+ * @param params - Optional time range parameters
74
+ * @returns Promise resolving to user fill history with detailed trade information
75
+ */
76
+ export const getUserFills = async (credential, params) => {
77
+ const wallet = getWallet(credential);
78
+ const address = wallet.address;
79
+ const requestBody = {
80
+ type: 'userFills',
81
+ user: address,
82
+ };
83
+ if (params === null || params === void 0 ? void 0 : params.startTime) {
84
+ requestBody.startTime = params.startTime;
85
+ }
86
+ if (params === null || params === void 0 ? void 0 : params.endTime) {
87
+ requestBody.endTime = params.endTime;
88
+ }
89
+ return request('POST', 'info', requestBody);
90
+ };
35
91
  //# sourceMappingURL=private-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAyBnC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE9C,MAAM,SAAS,GAAG,CAAC,UAAuB,EAAE,EAAE;IAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE;QAC5C,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,IAAI,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC7E;IACD,OAAO,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAE,CAAC;AAClD,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,EAC7B,UAAuB,EACvB,MAKC,EACD,EAAE;;IACF,MAAM,MAAM,GAAwB;QAClC,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,IAAI,MAAM,CAAC,OAAO,EAAE;QAClB,MAAM,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC;KACpC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACzB,MAAM,SAAS,GAAG,MAAM,YAAY,CAClC,SAAS,CAAC,UAAU,CAAC,EACrB,MAAM,EACN,MAAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,KAAK,EACL,MAAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,IAAI,CACL,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;AACnE,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAC9B,UAAuB,EACvB,MAAkF,EAClF,EAAE;;IACF,MAAM,MAAM,GAAwB;QAClC,IAAI,EAAE,QAAQ;QACd,OAAO,EAAE,MAAM,CAAC,OAAO;KACxB,CAAC;IACF,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACzB,MAAM,SAAS,GAAG,MAAM,YAAY,CAClC,SAAS,CAAC,UAAU,CAAC,EACrB,MAAM,EACN,MAAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,KAAK,EACL,MAAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,IAAI,CACL,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;AACnE,CAAC,CAAC","sourcesContent":["import { Wallet } from 'ethers';\nimport { signL1Action } from '../sign';\nimport { request } from './client';\nimport { ICredential } from './types';\n\ntype OrderPayload = {\n a: number;\n b: boolean;\n p: string;\n s: string;\n r: boolean;\n t: {\n limit?: { tif: string };\n trigger?: {\n isMarket: boolean;\n triggerPx: string;\n tpsl: string;\n };\n };\n c?: number;\n};\n\ntype CancelPayload = {\n a: number;\n o: number;\n};\n\nconst walletCache = new Map<string, Wallet>();\n\nconst getWallet = (credential: ICredential) => {\n if (!walletCache.has(credential.private_key)) {\n walletCache.set(credential.private_key, new Wallet(credential.private_key));\n }\n return walletCache.get(credential.private_key)!;\n};\n\nexport const placeOrder = async (\n credential: ICredential,\n params: {\n orders: OrderPayload[];\n builder?: { b: string; f: number };\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action: Record<string, any> = {\n type: 'order',\n orders: params.orders,\n grouping: 'na',\n };\n if (params.builder) {\n action['builder'] = params.builder;\n }\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\nexport const cancelOrder = async (\n credential: ICredential,\n params: { cancels: CancelPayload[]; vaultAddress?: string; expiresAfter?: number },\n) => {\n const action: Record<string, any> = {\n type: 'cancel',\n cancels: params.cancels,\n };\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n"]}
1
+ {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAuDnC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE9C,MAAM,SAAS,GAAG,CAAC,UAAuB,EAAE,EAAE;IAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU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AM,CAAC,SAAS,CAAC;KAC1C;IAED,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,EAAE;QACnB,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;KACtC;IAED,OAAO,OAAO,CAuBX,MAAM,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AAClC,CAAC,CAAC","sourcesContent":["import { Wallet } from 'ethers';\nimport { signL1Action } from '../sign';\nimport { request } from './client';\nimport { ICredential } from './types';\n\n/**\n * Order payload for placing orders on Hyperliquid\n */\ntype OrderPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Buy flag (true for buy, false for sell) */\n b: boolean;\n /** Limit price string */\n p: string;\n /** Size string */\n s: string;\n /** Reduce only flag */\n r: boolean;\n /** Order type configuration */\n t: {\n /** Time in force for limit orders: \"Alo\" (Post-Only), \"Ioc\" (Immediate or Cancel), \"Gtc\" (Good til Cancel) */\n limit?: { tif: string };\n /** Trigger order configuration */\n trigger?: {\n /** Is market trigger price */\n isMarket: boolean;\n /** Trigger price string */\n triggerPx: string;\n /** Take profit/stop loss indicator */\n tpsl: string;\n };\n };\n /** Order fee coefficient */\n c?: number;\n};\n\n/**\n * Cancel order payload\n */\ntype CancelPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Order ID */\n o: number;\n};\n\n/**\n * Modify order payload\n */\ntype ModifyOrderPayload = {\n /** Order ID to modify */\n oid: number | string;\n /** New order parameters */\n order: OrderPayload;\n};\n\nconst walletCache = new Map<string, Wallet>();\n\nconst getWallet = (credential: ICredential) => {\n if (!walletCache.has(credential.private_key)) {\n walletCache.set(credential.private_key, new Wallet(credential.private_key));\n }\n return walletCache.get(credential.private_key)!;\n};\n\n/**\n * Place orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order placement parameters\n * @returns Promise resolving to exchange response\n */\nexport const placeOrder = async (\n credential: ICredential,\n params: {\n orders: OrderPayload[];\n builder?: { b: string; f: number };\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action: Record<string, any> = {\n type: 'order',\n orders: params.orders,\n grouping: 'na',\n };\n if (params.builder) {\n action['builder'] = params.builder;\n }\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Cancel orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order cancellation parameters\n * @returns Promise resolving to exchange response\n */\nexport const cancelOrder = async (\n credential: ICredential,\n params: { cancels: CancelPayload[]; vaultAddress?: string; expiresAfter?: number },\n) => {\n const action: Record<string, any> = {\n type: 'cancel',\n cancels: params.cancels,\n };\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Modify an existing order on Hyperliquid exchange\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order modification parameters\n * @returns Promise resolving to exchange response\n */\nexport const modifyOrder = async (\n credential: ICredential,\n params: {\n oid: number | string;\n order: OrderPayload;\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action: Record<string, any> = {\n type: 'modify',\n oid: params.oid,\n order: params.order,\n };\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Get user's fill history (trade history) from Hyperliquid\n * API Endpoint: POST /info (type: userFills)\n * @param credential - User credential containing private key for authentication\n * @param params - Optional time range parameters\n * @returns Promise resolving to user fill history with detailed trade information\n */\nexport const getUserFills = async (\n credential: ICredential,\n params?: { startTime?: number; endTime?: number },\n) => {\n const wallet = getWallet(credential);\n const address = wallet.address;\n\n const requestBody: any = {\n type: 'userFills',\n user: address,\n };\n\n if (params?.startTime) {\n requestBody.startTime = params.startTime;\n }\n\n if (params?.endTime) {\n requestBody.endTime = params.endTime;\n }\n\n return request<{\n fills: {\n time: number;\n feedId: string;\n hash: string;\n coin: string;\n side: string;\n px: string;\n sz: string;\n oid: number;\n startPos: string;\n fee: string;\n feeToken: string;\n closedSize: string;\n closedPnl: string;\n dir: string;\n source: string;\n type: string;\n positionAction: string;\n asset: number;\n tid: string;\n crossChain: any;\n }[];\n }>('POST', 'info', requestBody);\n};\n"]}
@@ -1,12 +1,94 @@
1
1
  import { request } from './client';
2
+ /**
3
+ * Get user's perpetual account summary including positions, margin, and portfolio information
4
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary
5
+ * API Endpoint: POST /info (type: clearinghouseState)
6
+ * @param params - Query parameters
7
+ * @param params.user - User's wallet address
8
+ * @returns Promise resolving to account summary with margin information, positions, and portfolio details
9
+ */
2
10
  export const getUserPerpetualsAccountSummary = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'clearinghouseState' }));
11
+ /**
12
+ * Get perpetual market metadata including available assets, their specifications, and margin tiers
13
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata
14
+ * API Endpoint: POST /info (type: meta)
15
+ * @param params - Optional query parameters
16
+ * @param params.dex - Optional DEX identifier
17
+ * @returns Promise resolving to universe of perpetual assets and margin configuration
18
+ */
3
19
  export const getPerpetualsMetaData = (params) => request('POST', 'info', Object.assign(Object.assign({}, (params !== null && params !== void 0 ? params : {})), { type: 'meta' }));
20
+ /**
21
+ * Get spot market metadata including available tokens and trading pairs
22
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-metadata
23
+ * API Endpoint: POST /info (type: spotMeta)
24
+ * @returns Promise resolving to spot universe with token information and pair configurations
25
+ */
4
26
  export const getSpotMetaData = () => request('POST', 'info', { type: 'spotMeta' });
27
+ /**
28
+ * Get user's funding rate payment history for perpetual positions
29
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-a-users-funding-history-or-non-funding-ledger-updates
30
+ * API Endpoint: POST /info (type: fundingHistory)
31
+ * @param params - Query parameters
32
+ * @param params.user - User's wallet address
33
+ * @param params.startTime - Optional start timestamp in milliseconds
34
+ * @param params.endTime - Optional end timestamp in milliseconds
35
+ * @returns Promise resolving to array of funding payment records with amounts and rates
36
+ */
5
37
  export const getUserFundingHistory = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'fundingHistory' }));
6
- export const getUserTokenBalances = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'tokenBalances' }));
38
+ /**
39
+ * Get user's token balances for both spot and perpetual accounts
40
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances
41
+ * API Endpoint: POST /info (type: tokenBalances)
42
+ * @param params - Query parameters
43
+ * @param params.user - User's wallet address
44
+ * @returns Promise resolving to array of token balances with held and total amounts
45
+ */
46
+ export const getUserTokenBalances = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'spotClearinghouseState' }));
47
+ /**
48
+ * Get user's currently open orders across all markets
49
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#open-orders
50
+ * API Endpoint: POST /info (type: openOrders)
51
+ * @param params - Query parameters
52
+ * @param params.user - User's wallet address
53
+ * @returns Promise resolving to array of open order details with prices, sizes, and timestamps
54
+ */
7
55
  export const getUserOpenOrders = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'openOrders' }));
56
+ /**
57
+ * Get historical funding rates for a specific perpetual asset
58
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates
59
+ * API Endpoint: POST /info (type: fundingHistory)
60
+ * @param params - Query parameters
61
+ * @param params.coin - Asset symbol (e.g., "BTC", "ETH")
62
+ * @param params.startTime - Start timestamp in milliseconds
63
+ * @param params.endTime - Optional end timestamp in milliseconds
64
+ * @returns Promise resolving to array of historical funding rate records
65
+ */
8
66
  export const getHistoricalFundingRates = (params) => request('POST', 'info', Object.assign(Object.assign({}, params), { type: 'fundingHistory' }));
67
+ /**
68
+ * Get current mid prices for all tradable assets
69
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-mids-for-all-coins
70
+ * API Endpoint: POST /info (type: allMids)
71
+ * @returns Promise resolving to record of asset symbols mapped to their mid prices
72
+ */
9
73
  export const getAllMids = () => request('POST', 'info', { type: 'allMids' });
74
+ /**
75
+ * Get metadata and asset contexts (prices, funding, OI) for all perpetuals
76
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc.
77
+ * API Endpoint: POST /info (type: metaAndAssetCtxs)
78
+ * @returns Promise resolving to metadata and current asset contexts
79
+ */
10
80
  export const getMetaAndAssetCtxs = () => request('POST', 'info', { type: 'metaAndAssetCtxs' });
81
+ /**
82
+ * Get candle/K-line data for a specific asset and time range
83
+ * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot
84
+ * API Endpoint: POST /info (type: candleSnapshot)
85
+ * @param params - Query parameters
86
+ * @param params.req - Request object with candle parameters
87
+ * @param params.req.coin - Asset symbol
88
+ * @param params.req.interval - Time interval (e.g., "1m", "5m", "1h", "1d")
89
+ * @param params.req.startTime - Start timestamp in milliseconds
90
+ * @param params.req.endTime - End timestamp in milliseconds
91
+ * @returns Promise resolving to candle data with OHLCV information
92
+ */
11
93
  export const getCandleSnapshot = (params) => request('POST', 'info', Object.assign({ type: 'candleSnapshot' }, params));
12
94
  //# sourceMappingURL=public-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"public-api.js","sourceRoot":"","sources":["../../src/api/public-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAEnC,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC1E,OAAO,CAoCJ,MAAM,EAAE,MAAM,kCAAO,MAAM,KAAE,IAAI,EAAE,oBAAoB,IAAG,CAAC;AAEhE,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,MAAyB,EAAE,EAAE,CACjE,OAAO,CAkBJ,MAAM,EAAE,MAAM,kCAAO,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAC,KAAE,IAAI,EAAE,MAAM,IAAG,CAAC;AAE1D,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,EAAE,CAClC,OAAO,CAiBJ,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;AAE3C,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,MAA8D,EAAE,EAAE,CACtG,OAAO,CAML,MAAM,EAAE,MAAM,kCAAO,MAAM,KAAE,IAAI,EAAE,gBAAgB,IAAG,CAAC;AAE3D,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC/D,OAAO,CACL,MAAM,EACN,MAAM,kCAED,MAAM,KACT,IAAI,EAAE,eAAe,IAExB,CAAC;AAEJ,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC5D,OAAO,CACL,MAAM,EACN,MAAM,kCAED,MAAM,KACT,IAAI,EAAE,YAAY,IAErB,CAAC;AAEJ,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,MAA6D,EAAE,EAAE,CACzG,OAAO,CAAyE,MAAM,EAAE,MAAM,kCACzF,MAAM,KACT,IAAI,EAAE,gBAAgB,IACtB,CAAC;AAEL,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,CAAyB,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;AAErG,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,EAAE,CACtC,OAAO,CAuBL,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,MAEjC,EAAE,EAAE,CACH,OAAO,CAaL,MAAM,EAAE,MAAM,kBAAI,IAAI,EAAE,gBAAgB,IAAK,MAAM,EAAG,CAAC","sourcesContent":["import { request } from './client';\n\nexport const getUserPerpetualsAccountSummary = (params: { user: string }) =>\n request<{\n marginSummary: {\n accountValue: string;\n totalNtlPos: string;\n totalRawUsd: string;\n totalMarginUsed: string;\n };\n crossMarginSummary: {\n accountValue: string;\n totalNtlPos: string;\n totalRawUsd: string;\n totalMarginUsed: string;\n };\n crossMaintenanceMarginUsed: string;\n withdrawable: string;\n assetPositions: {\n type: string;\n position: {\n coin: string;\n szi: string;\n leverage: { type: string; value: number };\n entryPx: string;\n positionValue: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n liquidationPx: string;\n marginUsed: string;\n maxLeverage: number;\n cumFunding: {\n allTime: string;\n sinceOpen: string;\n sinceChange: string;\n };\n };\n }[];\n time: number;\n }>('POST', 'info', { ...params, type: 'clearinghouseState' });\n\nexport const getPerpetualsMetaData = (params?: { dex?: string }) =>\n request<{\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n onlyIsolated?: boolean;\n isDelisted?: boolean;\n }[];\n marginTables: [\n number,\n {\n description: string;\n marginTiers: {\n lowerBound: string;\n maxLeverage: number;\n }[];\n },\n ][];\n }>('POST', 'info', { ...(params ?? {}), type: 'meta' });\n\nexport const getSpotMetaData = () =>\n request<{\n tokens: {\n name: string;\n szDecimals: number;\n weiDecimals: number;\n index: number;\n tokenId: string;\n isCanonical: boolean;\n evmContract: null;\n fullName: null;\n }[];\n universe: {\n name: string;\n tokens: number[];\n index: number;\n isCanonical: boolean;\n }[];\n }>('POST', 'info', { type: 'spotMeta' });\n\nexport const getUserFundingHistory = (params: { user: string; startTime?: number; endTime?: number }) =>\n request<\n {\n time: number;\n hash: string;\n delta: { type: string; coin: string; usdc: string; szi: string; fundingRate: string };\n }[]\n >('POST', 'info', { ...params, type: 'fundingHistory' });\n\nexport const getUserTokenBalances = (params: { user: string }) =>\n request<{ balances: { coin: string; token: number; hold: string; total: string; entryNtl: string }[] }>(\n 'POST',\n 'info',\n {\n ...params,\n type: 'tokenBalances',\n },\n );\n\nexport const getUserOpenOrders = (params: { user: string }) =>\n request<{ coin: string; limitPx: string; oid: number; side: string; sz: string; timestamp: number }[]>(\n 'POST',\n 'info',\n {\n ...params,\n type: 'openOrders',\n },\n );\n\nexport const getHistoricalFundingRates = (params: { coin: string; startTime: number; endTime?: number }) =>\n request<{ coin: string; fundingRate: string; premium: string; time: number }[]>('POST', 'info', {\n ...params,\n type: 'fundingHistory',\n });\n\nexport const getAllMids = () => request<Record<string, string>>('POST', 'info', { type: 'allMids' });\n\nexport const getMetaAndAssetCtxs = () =>\n request<\n [\n {\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n onlyIsolated?: boolean;\n isDelisted?: boolean;\n }[];\n },\n {\n dayNtlVlm: string;\n funding: string;\n impactPxs: [string, string];\n markPx: string;\n midPx: string;\n openInterest: string;\n oraclePx: string;\n premium: string;\n prevDayPx: string;\n }[],\n ]\n >('POST', 'info', { type: 'metaAndAssetCtxs' });\n\nexport const getCandleSnapshot = (params: {\n req: { coin: string; interval: string; startTime: number; endTime: number };\n}) =>\n request<\n {\n T: number;\n c: string;\n h: string;\n i: string;\n l: string;\n o: string;\n n: number;\n s: string;\n t: number;\n v: string;\n }[]\n >('POST', 'info', { type: 'candleSnapshot', ...params });\n"]}
1
+ {"version":3,"file":"public-api.js","sourceRoot":"","sources":["../../src/api/public-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AAEnC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC1E,OAAO,CAoCJ,MAAM,EAAE,MAAM,kCAAO,MAAM,KAAE,IAAI,EAAE,oBAAoB,IAAG,CAAC;AAEhE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,MAAyB,EAAE,EAAE,CACjE,OAAO,CAkBJ,MAAM,EAAE,MAAM,kCAAO,CAAC,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,EAAE,CAAC,KAAE,IAAI,EAAE,MAAM,IAAG,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,EAAE,CAClC,OAAO,CAiBJ,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;AAE3C;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,MAA8D,EAAE,EAAE,CACtG,OAAO,CAML,MAAM,EAAE,MAAM,kCAAO,MAAM,KAAE,IAAI,EAAE,gBAAgB,IAAG,CAAC;AAE3D;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC/D,OAAO,CACL,MAAM,EACN,MAAM,kCAED,MAAM,KACT,IAAI,EAAE,wBAAwB,IAEjC,CAAC;AAEJ;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,MAAwB,EAAE,EAAE,CAC5D,OAAO,CACL,MAAM,EACN,MAAM,kCAED,MAAM,KACT,IAAI,EAAE,YAAY,IAErB,CAAC;AAEJ;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,MAA6D,EAAE,EAAE,CACzG,OAAO,CAAyE,MAAM,EAAE,MAAM,kCACzF,MAAM,KACT,IAAI,EAAE,gBAAgB,IACtB,CAAC;AAEL;;;;;GAKG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,CAAyB,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;AAErG;;;;;GAKG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,EAAE,CACtC,OAAO,CAuBL,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,CAAC;AAElD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,MAEjC,EAAE,EAAE,CACH,OAAO,CAaL,MAAM,EAAE,MAAM,kBAAI,IAAI,EAAE,gBAAgB,IAAK,MAAM,EAAG,CAAC","sourcesContent":["import { request } from './client';\n\n/**\n * Get user's perpetual account summary including positions, margin, and portfolio information\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-users-perpetuals-account-summary\n * API Endpoint: POST /info (type: clearinghouseState)\n * @param params - Query parameters\n * @param params.user - User's wallet address\n * @returns Promise resolving to account summary with margin information, positions, and portfolio details\n */\nexport const getUserPerpetualsAccountSummary = (params: { user: string }) =>\n request<{\n marginSummary: {\n accountValue: string;\n totalNtlPos: string;\n totalRawUsd: string;\n totalMarginUsed: string;\n };\n crossMarginSummary: {\n accountValue: string;\n totalNtlPos: string;\n totalRawUsd: string;\n totalMarginUsed: string;\n };\n crossMaintenanceMarginUsed: string;\n withdrawable: string;\n assetPositions: {\n type: string;\n position: {\n coin: string;\n szi: string;\n leverage: { type: string; value: number };\n entryPx: string;\n positionValue: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n liquidationPx: string;\n marginUsed: string;\n maxLeverage: number;\n cumFunding: {\n allTime: string;\n sinceOpen: string;\n sinceChange: string;\n };\n };\n }[];\n time: number;\n }>('POST', 'info', { ...params, type: 'clearinghouseState' });\n\n/**\n * Get perpetual market metadata including available assets, their specifications, and margin tiers\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-metadata\n * API Endpoint: POST /info (type: meta)\n * @param params - Optional query parameters\n * @param params.dex - Optional DEX identifier\n * @returns Promise resolving to universe of perpetual assets and margin configuration\n */\nexport const getPerpetualsMetaData = (params?: { dex?: string }) =>\n request<{\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n onlyIsolated?: boolean;\n isDelisted?: boolean;\n }[];\n marginTables: [\n number,\n {\n description: string;\n marginTiers: {\n lowerBound: string;\n maxLeverage: number;\n }[];\n },\n ][];\n }>('POST', 'info', { ...(params ?? {}), type: 'meta' });\n\n/**\n * Get spot market metadata including available tokens and trading pairs\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-spot-metadata\n * API Endpoint: POST /info (type: spotMeta)\n * @returns Promise resolving to spot universe with token information and pair configurations\n */\nexport const getSpotMetaData = () =>\n request<{\n tokens: {\n name: string;\n szDecimals: number;\n weiDecimals: number;\n index: number;\n tokenId: string;\n isCanonical: boolean;\n evmContract: null;\n fullName: null;\n }[];\n universe: {\n name: string;\n tokens: number[];\n index: number;\n isCanonical: boolean;\n }[];\n }>('POST', 'info', { type: 'spotMeta' });\n\n/**\n * Get user's funding rate payment history for perpetual positions\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-a-users-funding-history-or-non-funding-ledger-updates\n * API Endpoint: POST /info (type: fundingHistory)\n * @param params - Query parameters\n * @param params.user - User's wallet address\n * @param params.startTime - Optional start timestamp in milliseconds\n * @param params.endTime - Optional end timestamp in milliseconds\n * @returns Promise resolving to array of funding payment records with amounts and rates\n */\nexport const getUserFundingHistory = (params: { user: string; startTime?: number; endTime?: number }) =>\n request<\n {\n time: number;\n hash: string;\n delta: { type: string; coin: string; usdc: string; szi: string; fundingRate: string };\n }[]\n >('POST', 'info', { ...params, type: 'fundingHistory' });\n\n/**\n * Get user's token balances for both spot and perpetual accounts\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/spot#retrieve-a-users-token-balances\n * API Endpoint: POST /info (type: tokenBalances)\n * @param params - Query parameters\n * @param params.user - User's wallet address\n * @returns Promise resolving to array of token balances with held and total amounts\n */\nexport const getUserTokenBalances = (params: { user: string }) =>\n request<{ balances: { coin: string; token: number; hold: string; total: string; entryNtl: string }[] }>(\n 'POST',\n 'info',\n {\n ...params,\n type: 'spotClearinghouseState',\n },\n );\n\n/**\n * Get user's currently open orders across all markets\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#open-orders\n * API Endpoint: POST /info (type: openOrders)\n * @param params - Query parameters\n * @param params.user - User's wallet address\n * @returns Promise resolving to array of open order details with prices, sizes, and timestamps\n */\nexport const getUserOpenOrders = (params: { user: string }) =>\n request<{ coin: string; limitPx: string; oid: number; side: string; sz: string; timestamp: number }[]>(\n 'POST',\n 'info',\n {\n ...params,\n type: 'openOrders',\n },\n );\n\n/**\n * Get historical funding rates for a specific perpetual asset\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-historical-funding-rates\n * API Endpoint: POST /info (type: fundingHistory)\n * @param params - Query parameters\n * @param params.coin - Asset symbol (e.g., \"BTC\", \"ETH\")\n * @param params.startTime - Start timestamp in milliseconds\n * @param params.endTime - Optional end timestamp in milliseconds\n * @returns Promise resolving to array of historical funding rate records\n */\nexport const getHistoricalFundingRates = (params: { coin: string; startTime: number; endTime?: number }) =>\n request<{ coin: string; fundingRate: string; premium: string; time: number }[]>('POST', 'info', {\n ...params,\n type: 'fundingHistory',\n });\n\n/**\n * Get current mid prices for all tradable assets\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-mids-for-all-coins\n * API Endpoint: POST /info (type: allMids)\n * @returns Promise resolving to record of asset symbols mapped to their mid prices\n */\nexport const getAllMids = () => request<Record<string, string>>('POST', 'info', { type: 'allMids' });\n\n/**\n * Get metadata and asset contexts (prices, funding, OI) for all perpetuals\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint/perpetuals#retrieve-perpetuals-asset-contexts-includes-mark-price-current-funding-open-interest-etc.\n * API Endpoint: POST /info (type: metaAndAssetCtxs)\n * @returns Promise resolving to metadata and current asset contexts\n */\nexport const getMetaAndAssetCtxs = () =>\n request<\n [\n {\n universe: {\n name: string;\n szDecimals: number;\n maxLeverage: number;\n onlyIsolated?: boolean;\n isDelisted?: boolean;\n }[];\n },\n {\n dayNtlVlm: string;\n funding: string;\n impactPxs: [string, string];\n markPx: string;\n midPx: string;\n openInterest: string;\n oraclePx: string;\n premium: string;\n prevDayPx: string;\n }[],\n ]\n >('POST', 'info', { type: 'metaAndAssetCtxs' });\n\n/**\n * Get candle/K-line data for a specific asset and time range\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candle-snapshot\n * API Endpoint: POST /info (type: candleSnapshot)\n * @param params - Query parameters\n * @param params.req - Request object with candle parameters\n * @param params.req.coin - Asset symbol\n * @param params.req.interval - Time interval (e.g., \"1m\", \"5m\", \"1h\", \"1d\")\n * @param params.req.startTime - Start timestamp in milliseconds\n * @param params.req.endTime - End timestamp in milliseconds\n * @returns Promise resolving to candle data with OHLCV information\n */\nexport const getCandleSnapshot = (params: {\n req: { coin: string; interval: string; startTime: number; endTime: number };\n}) =>\n request<\n {\n T: number;\n c: string;\n h: string;\n i: string;\n l: string;\n o: string;\n n: number;\n s: string;\n t: number;\n v: string;\n }[]\n >('POST', 'info', { type: 'candleSnapshot', ...params });\n"]}
package/dist/api/types.js CHANGED
@@ -1,8 +1,25 @@
1
1
  import { Wallet } from 'ethers';
2
+ /**
3
+ * 从凭证获取地址
4
+ * @param credential 凭证对象
5
+ * @returns 钱包地址
6
+ */
7
+ export const getAddressFromCredential = (credential) => {
8
+ const wallet = new Wallet(credential.private_key);
9
+ return wallet.address;
10
+ };
11
+ /**
12
+ * 创建凭证对象
13
+ * @param private_key 私钥
14
+ * @returns 凭证对象
15
+ */
2
16
  export const createCredential = (private_key) => {
3
- const wallet = new Wallet(private_key);
4
- return { private_key, address: wallet.address };
17
+ return { private_key };
5
18
  };
19
+ /**
20
+ * 获取默认凭证(从环境变量)
21
+ * @returns 默认凭证对象
22
+ */
6
23
  export const getDefaultCredential = () => {
7
24
  const private_key = process.env.PRIVATE_KEY;
8
25
  if (!private_key) {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAOhC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,WAAmB,EAAe,EAAE;IACnE,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,WAAW,CAAC,CAAC;IACvC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AAClD,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IAC5C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;KAC5E;IACD,OAAO,gBAAgB,CAAC,WAAW,CAAC,CAAC;AACvC,CAAC,CAAC","sourcesContent":["import { Wallet } from 'ethers';\n\nexport interface ICredential {\n private_key: string;\n address: string;\n}\n\nexport const createCredential = (private_key: string): ICredential => {\n const wallet = new Wallet(private_key);\n return { private_key, address: wallet.address };\n};\n\nexport const getDefaultCredential = (): ICredential => {\n const private_key = process.env.PRIVATE_KEY;\n if (!private_key) {\n throw new Error('Missing Hyperliquid credential: PRIVATE_KEY must be set');\n }\n return createCredential(private_key);\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAUhC;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,UAAuB,EAAU,EAAE;IAC1E,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC,OAAO,CAAC;AACxB,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,WAAmB,EAAe,EAAE;IACnE,OAAO,EAAE,WAAW,EAAE,CAAC;AACzB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IAC5C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;KAC5E;IACD,OAAO,gBAAgB,CAAC,WAAW,CAAC,CAAC;AACvC,CAAC,CAAC","sourcesContent":["import { Wallet } from 'ethers';\n\n/**\n * Hyperliquid 凭证接口\n * 仅包含核心数据,行为方法通过辅助函数提供\n */\nexport interface ICredential {\n private_key: string;\n}\n\n/**\n * 从凭证获取地址\n * @param credential 凭证对象\n * @returns 钱包地址\n */\nexport const getAddressFromCredential = (credential: ICredential): string => {\n const wallet = new Wallet(credential.private_key);\n return wallet.address;\n};\n\n/**\n * 创建凭证对象\n * @param private_key 私钥\n * @returns 凭证对象\n */\nexport const createCredential = (private_key: string): ICredential => {\n return { private_key };\n};\n\n/**\n * 获取默认凭证(从环境变量)\n * @returns 默认凭证对象\n */\nexport const getDefaultCredential = (): ICredential => {\n const private_key = process.env.PRIVATE_KEY;\n if (!private_key) {\n throw new Error('Missing Hyperliquid credential: PRIVATE_KEY must be set');\n }\n return createCredential(private_key);\n};\n"]}
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
- import './account';
2
- import './order-actions';
3
- import './order-actions-with-credential';
4
- import './public-data';
1
+ // Import services from new structure
2
+ import './services/account-actions-with-credential';
3
+ import './services/accounts/perp';
4
+ import './services/order-actions-with-credential';
5
+ // Import market data services
6
+ import './services/markets/interest-rate';
7
+ import './services/markets/ohlc';
8
+ import './services/markets/product';
9
+ import './services/markets/quote';
5
10
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,CAAC;AACnB,OAAO,iBAAiB,CAAC;AACzB,OAAO,iCAAiC,CAAC;AACzC,OAAO,eAAe,CAAC","sourcesContent":["import './account';\nimport './order-actions';\nimport './order-actions-with-credential';\nimport './public-data';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAqC;AACrC,OAAO,4CAA4C,CAAC;AACpD,OAAO,0BAA0B,CAAC;AAClC,OAAO,0CAA0C,CAAC;AAElD,8BAA8B;AAC9B,OAAO,kCAAkC,CAAC;AAC1C,OAAO,yBAAyB,CAAC;AACjC,OAAO,4BAA4B,CAAC;AACpC,OAAO,0BAA0B,CAAC","sourcesContent":["// Import services from new structure\nimport './services/account-actions-with-credential';\nimport './services/accounts/perp';\nimport './services/order-actions-with-credential';\n\n// Import market data services\nimport './services/markets/interest-rate';\nimport './services/markets/ohlc';\nimport './services/markets/product';\nimport './services/markets/quote';\n"]}
@@ -0,0 +1,122 @@
1
+ import { provideAccountActionsWithCredential } from '@yuants/data-account';
2
+ import { Terminal } from '@yuants/protocol';
3
+ import { encodePath, formatTime } from '@yuants/utils';
4
+ import { getUserOpenOrders, getUserPerpetualsAccountSummary, getUserTokenBalances } from '../api/public-api';
5
+ import { getAddressFromCredential } from '../api/types';
6
+ /**
7
+ * Get account info for perpetual account
8
+ */
9
+ const getPerpAccountInfo = async (credential, account_id) => {
10
+ console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);
11
+ const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });
12
+ const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });
13
+ // Map positions
14
+ const positions = summary.assetPositions.map((position) => ({
15
+ position_id: `${position.position.coin}-USD`,
16
+ datasource_id: 'HYPERLIQUID',
17
+ product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),
18
+ direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',
19
+ volume: Math.abs(+position.position.szi),
20
+ free_volume: Math.abs(+position.position.szi),
21
+ position_price: +position.position.entryPx,
22
+ closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),
23
+ floating_profit: +position.position.unrealizedPnl,
24
+ valuation: +position.position.positionValue,
25
+ margin: +position.position.marginUsed,
26
+ }));
27
+ // Map orders
28
+ const mapOrderDirection = (side) => {
29
+ const normalized = side.toUpperCase();
30
+ if (normalized === 'BID' || normalized === 'BUY') {
31
+ return 'OPEN_LONG';
32
+ }
33
+ if (normalized === 'ASK' || normalized === 'SELL') {
34
+ return 'OPEN_SHORT';
35
+ }
36
+ return 'OPEN_LONG';
37
+ };
38
+ const pending_orders = orders.map((order) => {
39
+ var _a, _b;
40
+ return ({
41
+ order_id: `${order.oid}`,
42
+ account_id,
43
+ product_id: encodePath('PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
44
+ order_type: 'LIMIT',
45
+ order_direction: mapOrderDirection(order.side),
46
+ volume: Number(order.sz) || 0,
47
+ price: Number(order.limitPx) || undefined,
48
+ submit_at: Number((_b = order.timestamp) !== null && _b !== void 0 ? _b : Date.now()),
49
+ });
50
+ });
51
+ return {
52
+ money: {
53
+ currency: 'USDC',
54
+ equity: +summary.crossMarginSummary.accountValue,
55
+ free: +summary.withdrawable,
56
+ },
57
+ positions,
58
+ pending_orders,
59
+ };
60
+ };
61
+ /**
62
+ * Get account info for spot account
63
+ */
64
+ const getSpotAccountInfo = async (credential, account_id) => {
65
+ console.info(`[${formatTime(Date.now())}] Getting spot account info for ${account_id}`);
66
+ const balances = await getUserTokenBalances({ user: getAddressFromCredential(credential) });
67
+ // Map token balances to positions (using spot as "positions")
68
+ const positions = balances.balances
69
+ .filter((balance) => Number(balance.total) > 0)
70
+ .map((balance) => ({
71
+ position_id: `${balance.coin}`,
72
+ datasource_id: 'HYPERLIQUID',
73
+ product_id: encodePath('SPOT', `${balance.coin}-USDC`),
74
+ direction: 'LONG',
75
+ volume: Number(balance.total),
76
+ free_volume: Number(balance.total) - Number(balance.hold),
77
+ position_price: 1,
78
+ closable_price: 1,
79
+ floating_profit: 0,
80
+ valuation: Number(balance.total),
81
+ margin: 0,
82
+ }));
83
+ return {
84
+ money: {
85
+ currency: 'USDC',
86
+ equity: positions.reduce((sum, pos) => sum + pos.valuation, 0),
87
+ free: positions.reduce((sum, pos) => sum + pos.free_volume, 0),
88
+ },
89
+ positions,
90
+ pending_orders: [], // Spot orders would need separate API call
91
+ };
92
+ };
93
+ provideAccountActionsWithCredential(Terminal.fromNodeEnv(), 'HYPERLIQUID', {
94
+ type: 'object',
95
+ required: ['private_key'],
96
+ properties: {
97
+ private_key: { type: 'string' },
98
+ },
99
+ }, {
100
+ listAccounts: async (credential) => {
101
+ console.info(`[${formatTime(Date.now())}] Listing accounts for ${getAddressFromCredential(credential)}`);
102
+ return [
103
+ {
104
+ account_id: `hyperliquid/${getAddressFromCredential(credential)}/perp/USDC`,
105
+ },
106
+ {
107
+ account_id: `hyperliquid/${getAddressFromCredential(credential)}/spot/USDC`,
108
+ },
109
+ ];
110
+ },
111
+ getAccountInfo: async (credential, account_id) => {
112
+ console.info(`[${formatTime(Date.now())}] Getting account info for ${account_id}`);
113
+ if (account_id.endsWith('/perp/USDC')) {
114
+ return getPerpAccountInfo(credential, account_id);
115
+ }
116
+ if (account_id.endsWith('/spot/USDC')) {
117
+ return getSpotAccountInfo(credential, account_id);
118
+ }
119
+ throw new Error(`Unsupported account type for account_id: ${account_id}`);
120
+ },
121
+ });
122
+ //# sourceMappingURL=account-actions-with-credential.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-actions-with-credential.js","sourceRoot":"","sources":["../../src/services/account-actions-with-credential.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,+BAA+B,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC7G,OAAO,EAAe,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAErE;;GAEG;AACH,MAAM,kBAAkB,GAAG,KAAK,EAAE,UAAuB,EAAE,UAAkB,EAAE,EAAE;IAC/E,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,mCAAmC,UAAU,EAAE,CAAC,CAAC;IAExF,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC,EAAE,IAAI,EAAE,wBAAwB,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IACtG,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC,EAAE,IAAI,EAAE,wBAAwB,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IAEvF,gBAAg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,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;KAChC;CACF,EACD;IACE,YAAY,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;QACjC,OAAO,CAAC,IAAI,CACV,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,0BAA0B,wBAAwB,CAAC,UAAU,CAAC,EAAE,CAC3F,CAAC;QACF,OAAO;YACL;gBACE,UAAU,EAAE,eAAe,wBAAwB,CAAC,UAAU,CAAC,YAAY;aAC5E;YACD;gBACE,UAAU,EAAE,eAAe,wBAAwB,CAAC,UAAU,CAAC,YAAY;aAC5E;SACF,CAAC;IACJ,CAAC;IACD,cAAc,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QAC/C,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,8BAA8B,UAAU,EAAE,CAAC,CAAC;QAEnF,IAAI,UAAU,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE;YACrC,OAAO,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SACnD;QACD,IAAI,UAAU,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE;YACrC,OAAO,kBAAkB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SACnD;QACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,UAAU,EAAE,CAAC,CAAC;IAC5E,CAAC;CACF,CACF,CAAC","sourcesContent":["import { provideAccountActionsWithCredential } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { getUserOpenOrders, getUserPerpetualsAccountSummary, getUserTokenBalances } from '../api/public-api';\nimport { ICredential, getAddressFromCredential } from '../api/types';\n\n/**\n * Get account info for perpetual account\n */\nconst getPerpAccountInfo = async (credential: ICredential, account_id: string) => {\n console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);\n\n const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });\n const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });\n\n // Map positions\n const positions = summary.assetPositions.map((position) => ({\n position_id: `${position.position.coin}-USD`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),\n direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',\n volume: Math.abs(+position.position.szi),\n free_volume: Math.abs(+position.position.szi),\n position_price: +position.position.entryPx,\n closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),\n floating_profit: +position.position.unrealizedPnl,\n valuation: +position.position.positionValue,\n margin: +position.position.marginUsed,\n }));\n\n // Map orders\n const mapOrderDirection = (side: string) => {\n const normalized = side.toUpperCase();\n if (normalized === 'BID' || normalized === 'BUY') {\n return 'OPEN_LONG';\n }\n if (normalized === 'ASK' || normalized === 'SELL') {\n return 'OPEN_SHORT';\n }\n return 'OPEN_LONG';\n };\n\n const pending_orders = orders.map((order) => ({\n order_id: `${order.oid}`,\n account_id,\n product_id: encodePath('PERPETUAL', `${order.coin?.trim()}-USD`),\n order_type: 'LIMIT',\n order_direction: mapOrderDirection(order.side),\n volume: Number(order.sz) || 0,\n price: Number(order.limitPx) || undefined,\n submit_at: Number(order.timestamp ?? Date.now()),\n }));\n\n return {\n money: {\n currency: 'USDC',\n equity: +summary.crossMarginSummary.accountValue,\n free: +summary.withdrawable,\n },\n positions,\n pending_orders,\n };\n};\n\n/**\n * Get account info for spot account\n */\nconst getSpotAccountInfo = async (credential: ICredential, account_id: string) => {\n console.info(`[${formatTime(Date.now())}] Getting spot account info for ${account_id}`);\n\n const balances = await getUserTokenBalances({ user: getAddressFromCredential(credential) });\n\n // Map token balances to positions (using spot as \"positions\")\n const positions = balances.balances\n .filter((balance: any) => Number(balance.total) > 0)\n .map((balance: any) => ({\n position_id: `${balance.coin}`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('SPOT', `${balance.coin}-USDC`),\n direction: 'LONG',\n volume: Number(balance.total),\n free_volume: Number(balance.total) - Number(balance.hold),\n position_price: 1, // USDC as quote currency\n closable_price: 1,\n floating_profit: 0,\n valuation: Number(balance.total),\n margin: 0,\n }));\n\n return {\n money: {\n currency: 'USDC',\n equity: positions.reduce((sum: number, pos: any) => sum + pos.valuation, 0),\n free: positions.reduce((sum: number, pos: any) => sum + pos.free_volume, 0),\n },\n positions,\n pending_orders: [], // Spot orders would need separate API call\n };\n};\n\nprovideAccountActionsWithCredential<ICredential>(\n Terminal.fromNodeEnv(),\n 'HYPERLIQUID',\n {\n type: 'object',\n required: ['private_key'],\n properties: {\n private_key: { type: 'string' },\n },\n },\n {\n listAccounts: async (credential) => {\n console.info(\n `[${formatTime(Date.now())}] Listing accounts for ${getAddressFromCredential(credential)}`,\n );\n return [\n {\n account_id: `hyperliquid/${getAddressFromCredential(credential)}/perp/USDC`,\n },\n {\n account_id: `hyperliquid/${getAddressFromCredential(credential)}/spot/USDC`,\n },\n ];\n },\n getAccountInfo: async (credential, account_id) => {\n console.info(`[${formatTime(Date.now())}] Getting account info for ${account_id}`);\n\n if (account_id.endsWith('/perp/USDC')) {\n return getPerpAccountInfo(credential, account_id);\n }\n if (account_id.endsWith('/spot/USDC')) {\n return getSpotAccountInfo(credential, account_id);\n }\n throw new Error(`Unsupported account type for account_id: ${account_id}`);\n },\n },\n);\n"]}
@@ -2,11 +2,11 @@ import { addAccountMarket, provideAccountInfoService } from '@yuants/data-accoun
2
2
  import { providePendingOrdersService } from '@yuants/data-order';
3
3
  import { Terminal } from '@yuants/protocol';
4
4
  import { encodePath } from '@yuants/utils';
5
- import { getUserOpenOrders, getUserPerpetualsAccountSummary } from './api/public-api';
6
- import { getDefaultCredential } from './api/types';
5
+ import { getUserOpenOrders, getUserPerpetualsAccountSummary } from '../../api/public-api';
6
+ import { getDefaultCredential, getAddressFromCredential } from '../../api/types';
7
7
  const terminal = Terminal.fromNodeEnv();
8
8
  const credential = getDefaultCredential();
9
- const walletAddress = credential.address.toLowerCase();
9
+ const walletAddress = getAddressFromCredential(credential).toLowerCase();
10
10
  export const defaultPerpAccountId = `hyperliquid/${walletAddress}/perp/USDC`;
11
11
  addAccountMarket(terminal, { account_id: defaultPerpAccountId, market_id: 'HYPERLIQUID/PERP' });
12
12
  const mapPosition = (position) => ({
@@ -23,7 +23,7 @@ const mapPosition = (position) => ({
23
23
  margin: +position.position.marginUsed,
24
24
  });
25
25
  provideAccountInfoService(terminal, defaultPerpAccountId, async () => {
26
- const summary = await getUserPerpetualsAccountSummary({ user: credential.address });
26
+ const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });
27
27
  return {
28
28
  money: {
29
29
  currency: 'USDC',
@@ -44,7 +44,7 @@ const mapOrderDirection = (side) => {
44
44
  return 'OPEN_LONG';
45
45
  };
46
46
  providePendingOrdersService(terminal, defaultPerpAccountId, async () => {
47
- const orders = await getUserOpenOrders({ user: credential.address });
47
+ const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });
48
48
  return orders.map((order) => {
49
49
  var _a, _b;
50
50
  return ({
@@ -59,4 +59,4 @@ providePendingOrdersService(terminal, defaultPerpAccountId, async () => {
59
59
  });
60
60
  });
61
61
  }, { auto_refresh_interval: 2000 });
62
- //# sourceMappingURL=account.js.map
62
+ //# sourceMappingURL=perp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perp.js","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAa,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAU,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AAC1F,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,M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AAK,CAAC,IAAI,0CAAE,IAAI,EAAE,MAAM,CAAC;YAChE,UAAU,EAAE,OAAO;YACnB,eAAe,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC;YAC9C,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC;YAC7B,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,SAAS;YACzC,SAAS,EAAE,MAAM,CAAC,MAAA,KAAK,CAAC,SAAS,mCAAI,IAAI,CAAC,GAAG,EAAE,CAAC;SACjD,CAAC,CAAA;KAAA,CACH,CAAC;AACJ,CAAC,EACD,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAChC,CAAC","sourcesContent":["import { addAccountMarket, IPosition, provideAccountInfoService } from '@yuants/data-account';\nimport { IOrder, providePendingOrdersService } from '@yuants/data-order';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { getUserOpenOrders, getUserPerpetualsAccountSummary } from '../../api/public-api';\nimport { getDefaultCredential, getAddressFromCredential } from '../../api/types';\n\nconst terminal = Terminal.fromNodeEnv();\nconst credential = getDefaultCredential();\nconst walletAddress = getAddressFromCredential(credential).toLowerCase();\nexport const defaultPerpAccountId = `hyperliquid/${walletAddress}/perp/USDC`;\n\naddAccountMarket(terminal, { account_id: defaultPerpAccountId, market_id: 'HYPERLIQUID/PERP' });\n\nconst mapPosition = (position: any): IPosition => ({\n position_id: `${position.position.coin}-USD`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),\n direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',\n volume: Math.abs(+position.position.szi),\n free_volume: Math.abs(+position.position.szi),\n position_price: +position.position.entryPx,\n closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),\n floating_profit: +position.position.unrealizedPnl,\n valuation: +position.position.positionValue,\n margin: +position.position.marginUsed,\n});\n\nprovideAccountInfoService(\n terminal,\n defaultPerpAccountId,\n async () => {\n const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });\n return {\n money: {\n currency: 'USDC',\n equity: +summary.crossMarginSummary.accountValue,\n free: +summary.withdrawable,\n },\n positions: summary.assetPositions.map(mapPosition),\n };\n },\n { auto_refresh_interval: 1000 },\n);\n\nconst mapOrderDirection = (side: string): IOrder['order_direction'] => {\n const normalized = side.toUpperCase();\n if (normalized === 'BID' || normalized === 'BUY') {\n return 'OPEN_LONG';\n }\n if (normalized === 'ASK' || normalized === 'SELL') {\n return 'OPEN_SHORT';\n }\n return 'OPEN_LONG';\n};\n\nprovidePendingOrdersService(\n terminal,\n defaultPerpAccountId,\n async () => {\n const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });\n return orders.map(\n (order): IOrder => ({\n order_id: `${order.oid}`,\n account_id: defaultPerpAccountId,\n product_id: encodePath('PERPETUAL', `${order.coin?.trim()}-USD`),\n order_type: 'LIMIT',\n order_direction: mapOrderDirection(order.side),\n volume: Number(order.sz) || 0,\n price: Number(order.limitPx) || undefined,\n submit_at: Number(order.timestamp ?? Date.now()),\n }),\n );\n },\n { auto_refresh_interval: 2000 },\n);\n"]}
@@ -15,7 +15,7 @@ import { Terminal } from '@yuants/protocol';
15
15
  import { createSQLWriter } from '@yuants/sql';
16
16
  import { decodePath, encodePath, formatTime } from '@yuants/utils';
17
17
  import { defer, map, mergeAll, repeat, retry, shareReplay, tap } from 'rxjs';
18
- import { getHistoricalFundingRates, getPerpetualsMetaData } from '../api/public-api';
18
+ import { getHistoricalFundingRates, getPerpetualsMetaData } from '../../api/public-api';
19
19
  const terminal = Terminal.fromNodeEnv();
20
20
  const perpetualProducts$ = defer(async () => {
21
21
  const meta = await getPerpetualsMetaData();
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interest-rate.js","sourceRoot":"","sources":["../../../src/services/markets/interest-rate.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,oBAAoB,EAAyB,MA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ACpB,OAAO,OAAO,IAAI,GAAG,EAAE;gBACrB,MAAM,GAAG,GAAG,cAAM,yBAAyB,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAA,CAAC;gBACxF,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;oBAC5B,MAAM;iBACP;gBACD,MAAM,QAAQ,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,OAAO,IAAI,CAAC,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;gBACvE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE;oBACpB,MAAM;iBACP;gBACD,oBAAM,QAAQ,CAAC,GAAG,CAChB,CAAC,CAAC,EAAiB,EAAE,CAAC,CAAC;oBACrB,SAAS;oBACT,UAAU;oBACV,aAAa;oBACb,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC;oBAC9B,SAAS,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE;oBAC1C,UAAU,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE;oBAC9B,gBAAgB,EAAE,EAAE;iBACrB,CAAC,CACH,CAAA,CAAC;gBACF,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;oBACpB,MAAM;iBACP;gBACD,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;aAClD;QACH,CAAC;KAAA;CACF,CAAC,CAAC","sourcesContent":["import { IInterestRate } from '@yuants/data-interest-rate';\nimport { createSeriesProvider, ISeriesCollectingTask } from '@yuants/data-series';\nimport { Terminal } from '@yuants/protocol';\nimport { createSQLWriter } from '@yuants/sql';\nimport { decodePath, encodePath, formatTime } from '@yuants/utils';\nimport { defer, map, mergeAll, repeat, retry, shareReplay, tap } from 'rxjs';\nimport { getHistoricalFundingRates, getPerpetualsMetaData } from '../../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst perpetualProducts$ = defer(async () => {\n const meta = await getPerpetualsMetaData();\n return meta.universe.map((product) => ({\n product_id: encodePath('PERPETUAL', `${product.name}-USD`),\n datasource_id: 'HYPERLIQUID',\n no_interest_rate: false,\n }));\n}).pipe(\n tap({ error: (err) => console.error(formatTime(Date.now()), 'PerpetualProductFetchFailed', err) }),\n retry({ delay: 10_000 }),\n repeat({ delay: 3600_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\ncreateSQLWriter<ISeriesCollectingTask>(terminal, {\n data$: perpetualProducts$.pipe(\n map((products) => products.filter((product) => product.no_interest_rate === false)),\n mergeAll(),\n map(\n (product): ISeriesCollectingTask => ({\n series_id: encodePath(product.datasource_id, product.product_id),\n table_name: 'interest_rate',\n cron_pattern: '0 * * * *',\n cron_timezone: 'UTC',\n disabled: false,\n replay_count: 0,\n }),\n ),\n ),\n tableName: 'series_collecting_task',\n writeInterval: 1000,\n conflictKeys: ['series_id', 'table_name'],\n});\n\ncreateSeriesProvider<IInterestRate>(terminal, {\n tableName: 'interest_rate',\n series_id_prefix_parts: ['HYPERLIQUID'],\n reversed: true,\n serviceOptions: { concurrent: 1 },\n queryFn: async function* ({ series_id, started_at, ended_at }) {\n const start = started_at || 0;\n const end = ended_at || Date.now();\n const [datasource_id, product_id] = decodePath(series_id);\n const [, instId] = decodePath(product_id);\n const coin = instId.split('-')[0];\n let current = start;\n while (current <= end) {\n const res = await getHistoricalFundingRates({ coin, startTime: current, endTime: end });\n if (!res || res.length === 0) {\n break;\n }\n const filtered = res.filter((v) => v.time >= current && v.time <= end);\n if (!filtered.length) {\n break;\n }\n yield filtered.map(\n (v): IInterestRate => ({\n series_id,\n product_id,\n datasource_id,\n created_at: formatTime(v.time),\n long_rate: `${-parseFloat(v.fundingRate)}`,\n short_rate: `${v.fundingRate}`,\n settlement_price: '',\n }),\n );\n if (res.length < 500) {\n break;\n }\n current = filtered[filtered.length - 1].time + 1;\n }\n },\n});\n"]}
@@ -13,7 +13,7 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
13
13
  import { createSeriesProvider } from '@yuants/data-series';
14
14
  import { Terminal } from '@yuants/protocol';
15
15
  import { decodePath, formatTime } from '@yuants/utils';
16
- import { getCandleSnapshot } from '../api/public-api';
16
+ import { getCandleSnapshot } from '../../api/public-api';
17
17
  const terminal = Terminal.fromNodeEnv();
18
18
  const DURATION_TO_HYPERLIQUID_INTERVAL = {
19
19
  PT1M: '1m',
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ohlc.js","sourceRoot":"","sources":["../../../src/services/markets/ohlc.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,gCAAgC,GAA2B;IAC/D,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;IACV,KAAK,EAAE,KAAK;IACZ,KAAK,EAAE,KAAK;IACZ,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;IACV,KAAK,EAAE,KAAK;IACZ,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;IACT,GAAG,EAAE,IAAI;CACV,CAAC;AAEF,MAAM,yBAAyB,GAA2B;IACxD,IAAI,EAAE,EAAE;IACR,IAAI,EAAE,GAAG;IACT,IAAI,EAAE,GA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YACpB,MAAM,GAAG,GAAG,cAAM,iBAAiB,CAAC;gBAClC,GAAG,EAAE;oBACH,IAAI;oBACJ,QAAQ;oBACR,SAAS;oBACT,OAAO,EAAE,QAAQ;iBAClB;aACF,CAAC,CAAA,CAAC;YACH,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE;gBACvB,6BAAO;aACR;YACD,MAAM,IAAI,GAAG,GAAG;iBACb,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC;iBAC7B,GAAG,CACF,CAAC,CAAC,EAAS,EAAE,CAAC,CAAC;gBACb,SAAS;gBACT,aAAa;gBACb,UAAU;gBACV,QAAQ;gBACR,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC3B,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,aAAa,GAAG,IAAI,CAAC;gBACjD,IAAI,EAAE,CAAC,CAAC,CAAC;gBACT,IAAI,EAAE,CAAC,CAAC,CAAC;gBACT,GAAG,EAAE,CAAC,CAAC,CAAC;gBACR,KAAK,EAAE,CAAC,CAAC,CAAC;gBACV,MAAM,EAAE,CAAC,CAAC,CAAC;gBACX,aAAa,EAAE,GAAG;aACnB,CAAC,CACH;iBACA,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YACvF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;gBACnB,oBAAM,IAAI,CAAA,CAAC;aACZ;QACH,CAAC;KAAA;CACF,CAAC,CAAC","sourcesContent":["import { IOHLC } from '@yuants/data-ohlc';\nimport { createSeriesProvider } from '@yuants/data-series';\nimport { Terminal } from '@yuants/protocol';\nimport { decodePath, formatTime } from '@yuants/utils';\nimport { getCandleSnapshot } from '../../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst DURATION_TO_HYPERLIQUID_INTERVAL: Record<string, string> = {\n PT1M: '1m',\n PT3M: '3m',\n PT5M: '5m',\n PT15M: '15m',\n PT30M: '30m',\n PT1H: '1h',\n PT2H: '2h',\n PT4H: '4h',\n PT8H: '8h',\n PT12H: '12h',\n P1D: '1d',\n P3D: '3d',\n P1W: '1w',\n P1M: '1M',\n};\n\nconst DURATION_TO_PERIOD_IN_SEC: Record<string, number> = {\n PT1M: 60,\n PT3M: 180,\n PT5M: 300,\n PT15M: 900,\n PT30M: 1800,\n PT1H: 3600,\n PT2H: 7200,\n PT4H: 14400,\n PT8H: 28800,\n PT12H: 43200,\n P1D: 86400,\n P3D: 259200,\n P1W: 604800,\n P1M: 2592000,\n};\n\ncreateSeriesProvider<IOHLC>(terminal, {\n tableName: 'ohlc',\n series_id_prefix_parts: ['HYPERLIQUID'],\n reversed: true,\n serviceOptions: { concurrent: 1 },\n queryFn: async function* ({ series_id, ended_at }) {\n const [datasource_id, product_id, duration] = decodePath(series_id);\n const period_in_sec = DURATION_TO_PERIOD_IN_SEC[duration];\n if (!datasource_id || !product_id || !period_in_sec) {\n throw new Error(`Invalid series_id: ${series_id}`);\n }\n const [, instId] = decodePath(product_id);\n if (!instId) {\n throw new Error(`Invalid product_id: ${product_id}`);\n }\n const coin = instId.split('-')[0];\n const interval = DURATION_TO_HYPERLIQUID_INTERVAL[duration];\n if (!interval) {\n throw new Error(`Unsupported duration: ${duration}`);\n }\n const startTime = 0;\n const res = await getCandleSnapshot({\n req: {\n coin,\n interval,\n startTime,\n endTime: ended_at,\n },\n });\n if (!res || !res.length) {\n return;\n }\n const data = res\n .filter((x) => x.t < ended_at)\n .map(\n (x): IOHLC => ({\n series_id,\n datasource_id,\n product_id,\n duration,\n created_at: formatTime(x.t),\n closed_at: formatTime(x.t + period_in_sec * 1000),\n open: x.o,\n high: x.h,\n low: x.l,\n close: x.c,\n volume: x.v,\n open_interest: '0',\n }),\n )\n .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());\n if (data.length > 0) {\n yield data;\n }\n },\n});\n"]}