@yuants/vendor-aster 0.7.23 → 0.7.25

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.
@@ -1,4 +1,4 @@
1
- import { encodeHex, HmacSHA256 } from '@yuants/utils';
1
+ import { encodeHex, HmacSHA256, newError } from '@yuants/utils';
2
2
  import { GlobalPrometheusRegistry, Terminal } from '@yuants/protocol';
3
3
  const MetricsAsterApiCallCounter = GlobalPrometheusRegistry.counter('aster_api_call', 'Number of aster api call');
4
4
  const terminal = Terminal.fromNodeEnv();
@@ -31,7 +31,12 @@ const request = async (credential, method, baseURL, endpoint, params = {}) => {
31
31
  return res;
32
32
  }
33
33
  catch (e) {
34
- throw `APIError: ${response.status} ${response.statusText} ${resText}`;
34
+ throw newError('ASTER_API_ERROR', {
35
+ status: response.status,
36
+ statusText: response.statusText,
37
+ resText,
38
+ params,
39
+ }, e);
35
40
  }
36
41
  };
37
42
  const createApi = (baseURL) => (method, endpoint) => (credential, params) => request(credential, method, baseURL, endpoint, params);
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EAAE,wBAAwB,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEtE,MAAM,0BAA0B,GAAG,wBAAwB,CAAC,OAAO,CACjE,gBAAgB,EAChB,0BAA0B,CAC3B,CAAC;AACF,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAkDxC,MAAM,OAAO,GAAG,KAAK,EACnB,UAAuB,EACvB,MAAc,EACd,OAAe,EACf,QAAgB,EAChB,SAAc,EAAE,EACJ,EAAE;IACd,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAC;IACxB,KAAK,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AC,MAAM,mBAAmB,GAAG,aAAa,CAO9C,KAAK,EAAE,sBAAsB,CAAC,CAAC;AAEjC,MAAM,CAAC,MAAM,cAAc,GAAG,aAAa,CAazC,MAAM,EAAE,eAAe,CAAC,CAAC;AAE3B;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAO3C,QAAQ,EAAE,eAAe,CAAC,CAAC","sourcesContent":["import { encodeHex, HmacSHA256 } from '@yuants/utils';\n\nimport { GlobalPrometheusRegistry, Terminal } from '@yuants/protocol';\n\nconst MetricsAsterApiCallCounter = GlobalPrometheusRegistry.counter(\n 'aster_api_call',\n 'Number of aster api call',\n);\nconst terminal = Terminal.fromNodeEnv();\n\nexport interface ICredential {\n address: string;\n api_key: string;\n secret_key: string;\n}\n\nexport interface IAsterFutureOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n updateTime: number;\n avgPrice: string;\n reduceOnly?: boolean;\n closePosition?: boolean;\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n workingType?: string;\n priceProtect?: boolean;\n origType?: string;\n stopPrice?: string;\n symbol: string;\n}\n\nexport interface IAsterSpotOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n cummulativeQuoteQty?: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n stopPrice?: string;\n icebergQty?: string;\n time: number;\n updateTime: number;\n isWorking?: boolean;\n avgPrice?: string;\n symbol: string;\n}\n\nconst request = async <T>(\n credential: ICredential,\n method: string,\n baseURL: string,\n endpoint: string,\n params: any = {},\n): Promise<T> => {\n const url = new URL(baseURL);\n url.pathname = endpoint;\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, `${value}`);\n }\n\n url.searchParams.set('timestamp', `${Date.now()}`);\n const msg = url.search.slice(1); // 去掉开头的 '?'\n const signature = encodeHex(\n await HmacSHA256(new TextEncoder().encode(msg), new TextEncoder().encode(credential.secret_key)),\n );\n url.searchParams.set('signature', signature);\n\n console.info(url.toString());\n MetricsAsterApiCallCounter.labels({ path: url.pathname, terminal_id: terminal.terminal_id }).inc();\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'X-MBX-APIKEY': credential.api_key,\n },\n });\n\n const resText = await response.text();\n\n try {\n const res = JSON.parse(resText);\n\n if (res.code && res.code !== 0) {\n throw resText;\n }\n return res;\n } catch (e) {\n throw `APIError: ${response.status} ${response.statusText} ${resText}`;\n }\n};\n\nconst createApi =\n (baseURL: string) =>\n <TReq, TRes>(method: string, endpoint: string) =>\n (credential: ICredential, params: TReq) =>\n request<TRes>(credential, method, baseURL, endpoint, params);\n\nconst createFutureApi = createApi('https://fapi.asterdex.com');\nconst createSpotApi = createApi('https://sapi.asterdex.com');\n\n/**\n * 获取账户信息\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AFv4-user_data\n */\nexport const getFApiV4Account = createFutureApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n updateTime: number;\n totalInitialMargin: string;\n totalMaintMargin: string;\n totalWalletBalance: string;\n totalUnrealizedProfit: string;\n totalMarginBalance: string;\n totalPositionInitialMargin: string;\n totalOpenOrderInitialMargin: string;\n totalCrossWalletBalance: string;\n totalCrossUnPnl: string;\n availableBalance: string;\n maxWithdrawAmount: string;\n assets: {\n asset: string;\n walletBalance: string;\n unrealizedProfit: string;\n marginBalance: string;\n maintMargin: string;\n initialMargin: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n maxWithdrawAmount: string;\n crossWalletBalance: string;\n crossUnPnl: string;\n availableBalance: string;\n marginAvailable: boolean;\n updateTime: number;\n }[];\n positions: {\n symbol: string;\n initialMargin: string;\n maintMargin: string;\n unrealizedProfit: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n leverage: string;\n isolated: boolean;\n entryPrice: string;\n maxNotional: string;\n positionSide: 'BOTH' | 'LONG' | 'SHORT';\n positionAmt: string;\n notional: string;\n isolatedWallet: string;\n updateTime: number;\n }[];\n }\n>('GET', '/fapi/v4/account');\n\nexport const getFApiV2Balance = createFutureApi<\n {},\n {\n accountAlias: string; // 账户唯一识别码\n asset: string; // 资产\n balance: string; // 总余额\n crossWalletBalance: string; // 全仓余额\n crossUnPnl: string; // 全仓持仓未实现盈亏\n availableBalance: string; // 下单可用余额\n maxWithdrawAmount: string; // 最大可转出余额\n marginAvailable: boolean; // 是否可用作联合保证金\n updateTime: number;\n }[]\n>('GET', '/fapi/v2/balance');\n\nexport const postFApiV1Order = createFutureApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n type:\n | 'MARKET'\n | 'LIMIT'\n | 'STOP'\n | 'STOP_MARKET'\n | 'TAKE_PROFIT'\n | 'TAKE_PROFIT_MARKET'\n | 'TRAILING_STOP_MARKET';\n reduceOnly?: 'true' | 'false';\n quantity?: number;\n price?: number;\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX' | 'HIDDEN';\n },\n {}\n>('POST', '/fapi/v1/order');\n\n/**\n * 查询当前挂单 (永续)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#L2728-L2766\n */\nexport const getFApiV1OpenOrders = createFutureApi<\n {\n symbol?: string;\n },\n IAsterFutureOpenOrder[]\n>('GET', '/fapi/v1/openOrders');\n\n/**\n * 查询当前挂单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1196-L1234\n */\nexport const getApiV1OpenOrders = createSpotApi<\n {\n symbol?: string;\n },\n IAsterSpotOpenOrder[]\n>('GET', '/api/v1/openOrders');\n\nexport const deleteFApiV1Order = createFutureApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/fapi/v1/order');\n\n/**\n * 获取账户信息 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AF-user_data\n */\nexport const getApiV1Account = createSpotApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n canBurnAsset: boolean;\n updateTime: number;\n balances: {\n asset: string;\n free: string;\n locked: string;\n }[];\n }\n>('GET', '/api/v1/account');\n\n/**\n * 获取最新价格\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC\n */\nexport const getApiV1TickerPrice = createSpotApi<\n {},\n {\n symbol: string;\n price: string;\n time: number;\n }[]\n>('GET', '/api/v1/ticker/price');\n\nexport const postApiV1Order = createSpotApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n type: 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET';\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX';\n quantity?: number;\n quoteOrderQty?: number;\n price?: number;\n },\n {\n orderId: number; // 系统的订单ID\n }\n>('POST', '/api/v1/order');\n\n/**\n * 取消有效订单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1040-L1074\n */\nexport const deleteApiV1Order = createSpotApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/api/v1/order');\n"]}
1
+ {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,EAAE,wBAAwB,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;A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C,MAAM,EAAE,gBAAgB,CAAC,CAAC;AAE5B;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,eAAe,CAKhD,KAAK,EAAE,qBAAqB,CAAC,CAAC;AAEhC;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAK7C,KAAK,EAAE,oBAAoB,CAAC,CAAC;AAE/B,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAO9C,QAAQ,EAAE,gBAAgB,CAAC,CAAC;AAE9B;;;;GAIG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,aAAa,CAe1C,KAAK,EAAE,iBAAiB,CAAC,CAAC;AAE5B;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,aAAa,CAO9C,KAAK,EAAE,sBAAsB,CAAC,CAAC;AAEjC,MAAM,CAAC,MAAM,cAAc,GAAG,aAAa,CAazC,MAAM,EAAE,eAAe,CAAC,CAAC;AAE3B;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,aAAa,CAO3C,QAAQ,EAAE,eAAe,CAAC,CAAC","sourcesContent":["import { encodeHex, HmacSHA256, newError } from '@yuants/utils';\n\nimport { GlobalPrometheusRegistry, Terminal } from '@yuants/protocol';\n\nconst MetricsAsterApiCallCounter = GlobalPrometheusRegistry.counter(\n 'aster_api_call',\n 'Number of aster api call',\n);\nconst terminal = Terminal.fromNodeEnv();\n\nexport interface ICredential {\n address: string;\n api_key: string;\n secret_key: string;\n}\n\nexport interface IAsterFutureOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n updateTime: number;\n avgPrice: string;\n reduceOnly?: boolean;\n closePosition?: boolean;\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n workingType?: string;\n priceProtect?: boolean;\n origType?: string;\n stopPrice?: string;\n symbol: string;\n}\n\nexport interface IAsterSpotOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n cummulativeQuoteQty?: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n stopPrice?: string;\n icebergQty?: string;\n time: number;\n updateTime: number;\n isWorking?: boolean;\n avgPrice?: string;\n symbol: string;\n}\n\nconst request = async <T>(\n credential: ICredential,\n method: string,\n baseURL: string,\n endpoint: string,\n params: any = {},\n): Promise<T> => {\n const url = new URL(baseURL);\n url.pathname = endpoint;\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, `${value}`);\n }\n\n url.searchParams.set('timestamp', `${Date.now()}`);\n const msg = url.search.slice(1); // 去掉开头的 '?'\n const signature = encodeHex(\n await HmacSHA256(new TextEncoder().encode(msg), new TextEncoder().encode(credential.secret_key)),\n );\n url.searchParams.set('signature', signature);\n\n console.info(url.toString());\n MetricsAsterApiCallCounter.labels({ path: url.pathname, terminal_id: terminal.terminal_id }).inc();\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'X-MBX-APIKEY': credential.api_key,\n },\n });\n\n const resText = await response.text();\n\n try {\n const res = JSON.parse(resText);\n\n if (res.code && res.code !== 0) {\n throw resText;\n }\n return res;\n } catch (e) {\n throw newError(\n 'ASTER_API_ERROR',\n {\n status: response.status,\n statusText: response.statusText,\n resText,\n params,\n },\n e,\n );\n }\n};\n\nconst createApi =\n (baseURL: string) =>\n <TReq, TRes>(method: string, endpoint: string) =>\n (credential: ICredential, params: TReq) =>\n request<TRes>(credential, method, baseURL, endpoint, params);\n\nconst createFutureApi = createApi('https://fapi.asterdex.com');\nconst createSpotApi = createApi('https://sapi.asterdex.com');\n\n/**\n * 获取账户信息\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AFv4-user_data\n */\nexport const getFApiV4Account = createFutureApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n updateTime: number;\n totalInitialMargin: string;\n totalMaintMargin: string;\n totalWalletBalance: string;\n totalUnrealizedProfit: string;\n totalMarginBalance: string;\n totalPositionInitialMargin: string;\n totalOpenOrderInitialMargin: string;\n totalCrossWalletBalance: string;\n totalCrossUnPnl: string;\n availableBalance: string;\n maxWithdrawAmount: string;\n assets: {\n asset: string;\n walletBalance: string;\n unrealizedProfit: string;\n marginBalance: string;\n maintMargin: string;\n initialMargin: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n maxWithdrawAmount: string;\n crossWalletBalance: string;\n crossUnPnl: string;\n availableBalance: string;\n marginAvailable: boolean;\n updateTime: number;\n }[];\n positions: {\n symbol: string;\n initialMargin: string;\n maintMargin: string;\n unrealizedProfit: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n leverage: string;\n isolated: boolean;\n entryPrice: string;\n maxNotional: string;\n positionSide: 'BOTH' | 'LONG' | 'SHORT';\n positionAmt: string;\n notional: string;\n isolatedWallet: string;\n updateTime: number;\n }[];\n }\n>('GET', '/fapi/v4/account');\n\nexport const getFApiV2Balance = createFutureApi<\n {},\n {\n accountAlias: string; // 账户唯一识别码\n asset: string; // 资产\n balance: string; // 总余额\n crossWalletBalance: string; // 全仓余额\n crossUnPnl: string; // 全仓持仓未实现盈亏\n availableBalance: string; // 下单可用余额\n maxWithdrawAmount: string; // 最大可转出余额\n marginAvailable: boolean; // 是否可用作联合保证金\n updateTime: number;\n }[]\n>('GET', '/fapi/v2/balance');\n\nexport const postFApiV1Order = createFutureApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n type:\n | 'MARKET'\n | 'LIMIT'\n | 'STOP'\n | 'STOP_MARKET'\n | 'TAKE_PROFIT'\n | 'TAKE_PROFIT_MARKET'\n | 'TRAILING_STOP_MARKET';\n reduceOnly?: 'true' | 'false';\n quantity?: number;\n price?: number;\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX' | 'HIDDEN';\n },\n {}\n>('POST', '/fapi/v1/order');\n\n/**\n * 查询当前挂单 (永续)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#L2728-L2766\n */\nexport const getFApiV1OpenOrders = createFutureApi<\n {\n symbol?: string;\n },\n IAsterFutureOpenOrder[]\n>('GET', '/fapi/v1/openOrders');\n\n/**\n * 查询当前挂单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1196-L1234\n */\nexport const getApiV1OpenOrders = createSpotApi<\n {\n symbol?: string;\n },\n IAsterSpotOpenOrder[]\n>('GET', '/api/v1/openOrders');\n\nexport const deleteFApiV1Order = createFutureApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/fapi/v1/order');\n\n/**\n * 获取账户信息 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AF-user_data\n */\nexport const getApiV1Account = createSpotApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n canBurnAsset: boolean;\n updateTime: number;\n balances: {\n asset: string;\n free: string;\n locked: string;\n }[];\n }\n>('GET', '/api/v1/account');\n\n/**\n * 获取最新价格\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC\n */\nexport const getApiV1TickerPrice = createSpotApi<\n {},\n {\n symbol: string;\n price: string;\n time: number;\n }[]\n>('GET', '/api/v1/ticker/price');\n\nexport const postApiV1Order = createSpotApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n type: 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET';\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX';\n quantity?: number;\n quoteOrderQty?: number;\n price?: number;\n },\n {\n orderId: number; // 系统的订单ID\n }\n>('POST', '/api/v1/order');\n\n/**\n * 取消有效订单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1040-L1074\n */\nexport const deleteApiV1Order = createSpotApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/api/v1/order');\n"]}
@@ -9,7 +9,7 @@ const asBNBPrice = createCache(() => fetch('https://api.coingecko.com/api/v3/sim
9
9
  .then((data) => data['astherus-staked-bnb'].usd), {
10
10
  expire: 60000, // 1 minute
11
11
  });
12
- const buildSpotProductMap = async () => {
12
+ const spotProductMapCache = createCache(async () => {
13
13
  const products = await listProducts();
14
14
  const map = new Map();
15
15
  for (const product of products) {
@@ -19,7 +19,7 @@ const buildSpotProductMap = async () => {
19
19
  }
20
20
  }
21
21
  return map;
22
- };
22
+ }, { expire: 86400000 });
23
23
  export const getPositions = async (credential) => {
24
24
  var _a, _b, _c, _d, _e;
25
25
  const positions = [];
@@ -27,14 +27,15 @@ export const getPositions = async (credential) => {
27
27
  getApiV1Account(credential, {}),
28
28
  getApiV1TickerPrice(credential, {}),
29
29
  getFApiV4Account(credential, {}),
30
- buildSpotProductMap(),
30
+ spotProductMapCache.query(''),
31
31
  ]);
32
+ const resolvedSpotProductMap = spotProductMap !== null && spotProductMap !== void 0 ? spotProductMap : new Map();
32
33
  for (const b of x.balances) {
33
34
  const thePrice = b.asset === 'USDT' ? 1 : (_b = (_a = prices.find((p) => p.symbol === b.asset + 'USDT')) === null || _a === void 0 ? void 0 : _a.price) !== null && _b !== void 0 ? _b : 0;
34
35
  positions.push(makeSpotPosition({
35
36
  position_id: b.asset,
36
37
  datasource_id: 'ASTER',
37
- product_id: (_c = spotProductMap.get(b.asset)) !== null && _c !== void 0 ? _c : encodePath('ASTER', 'SPOT', b.asset),
38
+ product_id: (_c = resolvedSpotProductMap.get(b.asset)) !== null && _c !== void 0 ? _c : encodePath('ASTER', 'SPOT', b.asset),
38
39
  volume: +b.free + +b.locked,
39
40
  free_volume: +b.free,
40
41
  closable_price: +thePrice,
@@ -1 +1 @@
1
- {"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAa,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,gBAAgB,EAAe,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,qFAAqF;AACrF,MAAM,UAAU,GAAG,WAAW,CAC5B,GAAG,EAAE,CACH,KAAK,CAAC,yFAAyF,CAAC;KAC7F,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;KACzB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,GAAa,CAAC,EAC9D;IACE,MAAM,EAAE,KAAM,EAAE,WAAW;CAC5B,CACF,CAAC;AAEF,MAAM,mBAAmB,GAAG,KAAK,IAAI,EAAE;IACrC,MAAM,QAAQ,GAAG,MAAM,YAAY,EAAE,CAAC;IACtC,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC9B,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;SACpD;KACF;IACD,OA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AS,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;YAC/F,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YAChC,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YACrC,cAAc,EAAE,CAAC,CAAC,CAAC,UAAU;YAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC;YACtD,eAAe,EAAE,CAAC,CAAC,CAAC,gBAAgB;YACpC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;SACjC,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getApiV1Account, getApiV1TickerPrice, getFApiV4Account, ICredential } from '../../api/private-api';\nimport { listProducts } from '../markets/product';\n\n// ISSUE: ASBNB price is not available in the price API, need to fetch from coingecko\nconst asBNBPrice = createCache(\n () =>\n fetch('https://api.coingecko.com/api/v3/simple/price?ids=astherus-staked-bnb&vs_currencies=usd')\n .then((res) => res.json())\n .then((data) => data['astherus-staked-bnb'].usd as number),\n {\n expire: 60_000, // 1 minute\n },\n);\n\nconst buildSpotProductMap = async () => {\n const products = await listProducts();\n const map = new Map<string, string>();\n for (const product of products) {\n const [, instType] = product.product_id.split('/');\n if (instType === 'SPOT') {\n map.set(product.base_currency, product.product_id);\n }\n }\n return map;\n};\n\nexport const getPositions = async (credential: ICredential) => {\n const positions: IPosition[] = [];\n const [x, prices, prep, spotProductMap] = await Promise.all([\n getApiV1Account(credential, {}),\n getApiV1TickerPrice(credential, {}),\n getFApiV4Account(credential, {}),\n buildSpotProductMap(),\n ]);\n\n for (const b of x.balances) {\n const thePrice = b.asset === 'USDT' ? 1 : prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0;\n positions.push(\n makeSpotPosition({\n position_id: b.asset,\n datasource_id: 'ASTER',\n product_id: spotProductMap.get(b.asset) ?? encodePath('ASTER', 'SPOT', b.asset),\n volume: +b.free + +b.locked,\n free_volume: +b.free,\n closable_price: +thePrice,\n }),\n );\n }\n\n for (const b of prep.assets) {\n if (+b.walletBalance === 0) continue;\n let thePrice = 0;\n if (b.asset === 'USDT') {\n thePrice = 1;\n } else if (b.asset === 'ASBNB') {\n const _p = await asBNBPrice.query('').catch(() => 0);\n if (_p) {\n thePrice = _p;\n }\n } else {\n thePrice = +(prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0);\n }\n\n positions.push(\n makeSpotPosition({\n position_id: encodePath(b.asset, 'ASSET'),\n datasource_id: 'ASTER',\n product_id: encodePath('ASTER', 'PERP-ASSET', b.asset),\n volume: +b.walletBalance,\n free_volume: +b.walletBalance,\n closable_price: thePrice,\n }),\n );\n }\n\n for (const p of prep.positions) {\n if (+p.positionAmt === 0) continue;\n positions.push({\n position_id: p.symbol,\n product_id: encodePath('ASTER', 'PERP', p.symbol),\n datasource_id: 'ASTER',\n direction: p.positionSide === 'BOTH' ? (+p.positionAmt > 0 ? 'LONG' : 'SHORT') : p.positionSide,\n volume: Math.abs(+p.positionAmt),\n free_volume: Math.abs(+p.positionAmt),\n position_price: +p.entryPrice,\n closable_price: Math.abs(+p.notional / +p.positionAmt),\n floating_profit: +p.unrealizedProfit,\n valuation: Math.abs(+p.notional),\n });\n }\n\n return positions;\n};\n"]}
1
+ {"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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AC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;YAC/F,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YAChC,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YACrC,cAAc,EAAE,CAAC,CAAC,CAAC,UAAU;YAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC;YACtD,eAAe,EAAE,CAAC,CAAC,CAAC,gBAAgB;YACpC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;SACjC,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getApiV1Account, getApiV1TickerPrice, getFApiV4Account, ICredential } from '../../api/private-api';\nimport { listProducts } from '../markets/product';\n\n// ISSUE: ASBNB price is not available in the price API, need to fetch from coingecko\nconst asBNBPrice = createCache(\n () =>\n fetch('https://api.coingecko.com/api/v3/simple/price?ids=astherus-staked-bnb&vs_currencies=usd')\n .then((res) => res.json())\n .then((data) => data['astherus-staked-bnb'].usd as number),\n {\n expire: 60_000, // 1 minute\n },\n);\n\nconst spotProductMapCache = createCache(\n async () => {\n const products = await listProducts();\n const map = new Map<string, string>();\n for (const product of products) {\n const [, instType] = product.product_id.split('/');\n if (instType === 'SPOT') {\n map.set(product.base_currency, product.product_id);\n }\n }\n return map;\n },\n { expire: 86_400_000 },\n);\n\nexport const getPositions = async (credential: ICredential) => {\n const positions: IPosition[] = [];\n const [x, prices, prep, spotProductMap] = await Promise.all([\n getApiV1Account(credential, {}),\n getApiV1TickerPrice(credential, {}),\n getFApiV4Account(credential, {}),\n spotProductMapCache.query(''),\n ]);\n\n const resolvedSpotProductMap = spotProductMap ?? new Map<string, string>();\n\n for (const b of x.balances) {\n const thePrice = b.asset === 'USDT' ? 1 : prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0;\n positions.push(\n makeSpotPosition({\n position_id: b.asset,\n datasource_id: 'ASTER',\n product_id: resolvedSpotProductMap.get(b.asset) ?? encodePath('ASTER', 'SPOT', b.asset),\n volume: +b.free + +b.locked,\n free_volume: +b.free,\n closable_price: +thePrice,\n }),\n );\n }\n\n for (const b of prep.assets) {\n if (+b.walletBalance === 0) continue;\n let thePrice = 0;\n if (b.asset === 'USDT') {\n thePrice = 1;\n } else if (b.asset === 'ASBNB') {\n const _p = await asBNBPrice.query('').catch(() => 0);\n if (_p) {\n thePrice = _p;\n }\n } else {\n thePrice = +(prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0);\n }\n\n positions.push(\n makeSpotPosition({\n position_id: encodePath(b.asset, 'ASSET'),\n datasource_id: 'ASTER',\n product_id: encodePath('ASTER', 'PERP-ASSET', b.asset),\n volume: +b.walletBalance,\n free_volume: +b.walletBalance,\n closable_price: thePrice,\n }),\n );\n }\n\n for (const p of prep.positions) {\n if (+p.positionAmt === 0) continue;\n positions.push({\n position_id: p.symbol,\n product_id: encodePath('ASTER', 'PERP', p.symbol),\n datasource_id: 'ASTER',\n direction: p.positionSide === 'BOTH' ? (+p.positionAmt > 0 ? 'LONG' : 'SHORT') : p.positionSide,\n volume: Math.abs(+p.positionAmt),\n free_volume: Math.abs(+p.positionAmt),\n position_price: +p.entryPrice,\n closable_price: Math.abs(+p.notional / +p.positionAmt),\n floating_profit: +p.unrealizedProfit,\n valuation: Math.abs(+p.notional),\n });\n }\n\n return positions;\n};\n"]}
@@ -63,13 +63,17 @@ const handleSubmitOrderOfPerp = async (credential, order) => {
63
63
  throw new Error(`Unsupported order_type: ${order.order_type}`);
64
64
  const quantity = order.volume;
65
65
  const price = order.price;
66
- const positionSide = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'
67
- ? 'LONG'
68
- : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'
69
- ? 'SHORT'
70
- : undefined;
66
+ const isPositionSingleSide = true; // FIXME: Aster 永续合约仅支持单向持仓模式
67
+ const positionSide = isPositionSingleSide
68
+ ? undefined
69
+ : order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'
70
+ ? 'LONG'
71
+ : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'
72
+ ? 'SHORT'
73
+ : undefined;
71
74
  const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;
72
75
  const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;
76
+ //
73
77
  const res = await postFApiV1Order(credential, {
74
78
  symbol,
75
79
  side,
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAe,cAAc,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE1G,MAAM,cAAc,GAAG,CAAC,SAAkB,EAAE,EAAE;IAC5C,IAAI,CAAC,SAAS,EAAE;QACd,OAAO,EAAE,QAAQ,EAAE,SAA+B,EAAE,MAAM,EAAE,SAA+B,EAAE,CAAC;KAC/F;IACD,MAAM,KAAK,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;QACrB,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,K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MAAM;QACN,IAAI;QACJ,IAAI;QACJ,QAAQ;QACR,KAAK;QACL,WAAW;QACX,YAAY;QACZ,UAAU;KACX,CAAC,CAAC;IAEH,MAAM,OAAO,GACX,MAAA,MAAA,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,OAAO,mCACpB,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,QAAQ,mCACtB,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,IAAI,0CAAE,OAAO,mCAC3B,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,IAAI,0CAAE,QAAQ,CAAC;IAE/B,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAE3E,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACpC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IACrG,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,8BAA8B;IAClF,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;AACjF,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfSubmitOrder } from '@yuants/data-order';\nimport { decodePath, roundToStep } from '@yuants/utils';\nimport { getApiV1TickerPrice, ICredential, postApiV1Order, postFApiV1Order } from '../../api/private-api';\n\nconst parseProductId = (productId?: string) => {\n if (!productId) {\n return { category: undefined as string | undefined, symbol: undefined as string | undefined };\n }\n const parts = decodePath(productId);\n if (parts.length >= 3) {\n return { category: parts[1], symbol: parts.slice(2).join('/') };\n }\n return { category: undefined, symbol: parts[0] };\n};\n\nconst handleSubmitOrderOfSpot: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n const resolvedSymbol = symbol ?? order.product_id;\n if (!resolvedSymbol) {\n throw new Error(`Invalid product_id: unable to resolve spot symbol from \"${order.product_id}\"`);\n }\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const price = order.price;\n\n let quantity: number | undefined = order.volume;\n let quoteOrderQty: number | undefined;\n\n if (type === 'MARKET' && side === 'BUY') {\n const spotPrice = await getApiV1TickerPrice(credential, {});\n const thePrice = spotPrice.find((x) => x.symbol === resolvedSymbol)?.price;\n if (!thePrice) throw new Error(`Cannot get price for symbol ${resolvedSymbol}`);\n quantity = undefined;\n quoteOrderQty = roundToStep(order.volume * +thePrice, 0.01);\n }\n\n const res = await postApiV1Order(credential, {\n symbol: resolvedSymbol,\n type,\n side,\n timeInForce,\n price,\n quantity,\n quoteOrderQty,\n });\n\n if (!res.orderId) {\n throw new Error('Failed to retrieve order ID from response');\n }\n\n return { order_id: '' + res.orderId };\n};\n\nconst handleSubmitOrderOfPerp: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n if (!symbol) {\n throw new Error(`Invalid product_id: unable to decode symbol from \"${order.product_id}\"`);\n }\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const quantity = order.volume;\n const price = order.price;\n\n const positionSide =\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'\n ? 'LONG'\n : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'\n ? 'SHORT'\n : undefined;\n\n const reduceOnly =\n order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const res = await postFApiV1Order(credential, {\n symbol,\n side,\n type,\n quantity,\n price,\n timeInForce,\n positionSide,\n reduceOnly,\n });\n\n const orderId =\n (res as any)?.orderId ??\n (res as any)?.order_id ??\n (res as any)?.data?.orderId ??\n (res as any)?.data?.order_id;\n\n if (!orderId) throw new Error('Failed to retrieve order ID from response');\n\n return { order_id: `${orderId}` };\n};\n\nexport const handleSubmitOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const [_, instType] = decodePath(order.product_id); // BITGET/USDT-FUTURES/BTCUSDT\n if (instType === 'SPOT') {\n return handleSubmitOrderOfSpot(credential, order);\n }\n if (instType === 'PERP') {\n return handleSubmitOrderOfPerp(credential, order);\n }\n throw new Error(`Unsupported account_id for SubmitOrder: ${order.account_id}`);\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,mBAAmB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A8B;IAClF,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;AACjF,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfSubmitOrder } from '@yuants/data-order';\nimport { decodePath, roundToStep } from '@yuants/utils';\nimport { getApiV1TickerPrice, ICredential, postApiV1Order, postFApiV1Order } from '../../api/private-api';\n\nconst parseProductId = (productId?: string) => {\n if (!productId) {\n return { category: undefined as string | undefined, symbol: undefined as string | undefined };\n }\n const parts = decodePath(productId);\n if (parts.length >= 3) {\n return { category: parts[1], symbol: parts.slice(2).join('/') };\n }\n return { category: undefined, symbol: parts[0] };\n};\n\nconst handleSubmitOrderOfSpot: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n const resolvedSymbol = symbol ?? order.product_id;\n if (!resolvedSymbol) {\n throw new Error(`Invalid product_id: unable to resolve spot symbol from \"${order.product_id}\"`);\n }\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const price = order.price;\n\n let quantity: number | undefined = order.volume;\n let quoteOrderQty: number | undefined;\n\n if (type === 'MARKET' && side === 'BUY') {\n const spotPrice = await getApiV1TickerPrice(credential, {});\n const thePrice = spotPrice.find((x) => x.symbol === resolvedSymbol)?.price;\n if (!thePrice) throw new Error(`Cannot get price for symbol ${resolvedSymbol}`);\n quantity = undefined;\n quoteOrderQty = roundToStep(order.volume * +thePrice, 0.01);\n }\n\n const res = await postApiV1Order(credential, {\n symbol: resolvedSymbol,\n type,\n side,\n timeInForce,\n price,\n quantity,\n quoteOrderQty,\n });\n\n if (!res.orderId) {\n throw new Error('Failed to retrieve order ID from response');\n }\n\n return { order_id: '' + res.orderId };\n};\n\nconst handleSubmitOrderOfPerp: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n if (!symbol) {\n throw new Error(`Invalid product_id: unable to decode symbol from \"${order.product_id}\"`);\n }\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const quantity = order.volume;\n const price = order.price;\n\n const isPositionSingleSide = true; // FIXME: Aster 永续合约仅支持单向持仓模式\n\n const positionSide = isPositionSingleSide\n ? undefined\n : order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'\n ? 'LONG'\n : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'\n ? 'SHORT'\n : undefined;\n\n const reduceOnly =\n order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n //\n const res = await postFApiV1Order(credential, {\n symbol,\n side,\n type,\n quantity,\n price,\n timeInForce,\n positionSide,\n reduceOnly,\n });\n\n const orderId =\n (res as any)?.orderId ??\n (res as any)?.order_id ??\n (res as any)?.data?.orderId ??\n (res as any)?.data?.order_id;\n\n if (!orderId) throw new Error('Failed to retrieve order ID from response');\n\n return { order_id: `${orderId}` };\n};\n\nexport const handleSubmitOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const [_, instType] = decodePath(order.product_id); // BITGET/USDT-FUTURES/BTCUSDT\n if (instType === 'SPOT') {\n return handleSubmitOrderOfSpot(credential, order);\n }\n if (instType === 'PERP') {\n return handleSubmitOrderOfPerp(credential, order);\n }\n throw new Error(`Unsupported account_id for SubmitOrder: ${order.account_id}`);\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.d.ts","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,KAAK,GAAG,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;IACzC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;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AACH,eAAO,MAAM,kBAAkB,eAvHhB,WAAW;;oCA4HI,CAAC;AAE/B,eAAO,MAAM,iBAAiB,eA9Hf,WAAW;YAgId,MAAM;;;iBAKW,CAAC;AAE9B;;;;GAIG;AACH,eAAO,MAAM,eAAe,eA5Ib,WAAW;aA+Ib,MAAM;cACL,OAAO;gBACL,OAAO;iBACN,OAAO;kBACN,OAAO;gBACT,MAAM;cACR;QACR,KAAK,EAAE,MAAM,CAAC;QACd,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;KAChB,EAAE;EAEoB,CAAC;AAE5B;;;GAGG;AACH,eAAO,MAAM,mBAAmB,eAjKjB,WAAW;YAoKd,MAAM;WACP,MAAM;UACP,MAAM;IAEgB,CAAC;AAEjC,eAAO,MAAM,cAAc,eA1KZ,WAAW;YA4Kd,MAAM;UACR,KAAK,GAAG,MAAM;UACd,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,aAAa,GAAG,aAAa,GAAG,oBAAoB;;;;;;aAO/E,MAAM;EAEO,CAAC;AAE3B;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,eA9Ld,WAAW;YAgMd,MAAM;;;iBAKU,CAAC"}
@@ -34,7 +34,12 @@ const request = async (credential, method, baseURL, endpoint, params = {}) => {
34
34
  return res;
35
35
  }
36
36
  catch (e) {
37
- throw `APIError: ${response.status} ${response.statusText} ${resText}`;
37
+ throw (0, utils_1.newError)('ASTER_API_ERROR', {
38
+ status: response.status,
39
+ statusText: response.statusText,
40
+ resText,
41
+ params,
42
+ }, e);
38
43
  }
39
44
  };
40
45
  const createApi = (baseURL) => (method, endpoint) => (credential, params) => request(credential, method, baseURL, endpoint, params);
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":";;;AAAA,yCAAsD;AAEtD,+CAAsE;AAEtE,MAAM,0BAA0B,GAAG,mCAAwB,CAAC,OAAO,CACjE,gBAAgB,EAChB,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,aAAa,CAK7C,KAAK,EAAE,oBAAoB,CAAC,CAAC;AAElB,QAAA,iBAAiB,GAAG,eAAe,CAO9C,QAAQ,EAAE,gBAAgB,CAAC,CAAC;AAE9B;;;;GAIG;AACU,QAAA,eAAe,GAAG,aAAa,CAe1C,KAAK,EAAE,iBAAiB,CAAC,CAAC;AAE5B;;;GAGG;AACU,QAAA,mBAAmB,GAAG,aAAa,CAO9C,KAAK,EAAE,sBAAsB,CAAC,CAAC;AAEpB,QAAA,cAAc,GAAG,aAAa,CAazC,MAAM,EAAE,eAAe,CAAC,CAAC;AAE3B;;;;GAIG;AACU,QAAA,gBAAgB,GAAG,aAAa,CAO3C,QAAQ,EAAE,eAAe,CAAC,CAAC","sourcesContent":["import { encodeHex, HmacSHA256 } from '@yuants/utils';\n\nimport { GlobalPrometheusRegistry, Terminal } from '@yuants/protocol';\n\nconst MetricsAsterApiCallCounter = GlobalPrometheusRegistry.counter(\n 'aster_api_call',\n 'Number of aster api call',\n);\nconst terminal = Terminal.fromNodeEnv();\n\nexport interface ICredential {\n address: string;\n api_key: string;\n secret_key: string;\n}\n\nexport interface IAsterFutureOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n updateTime: number;\n avgPrice: string;\n reduceOnly?: boolean;\n closePosition?: boolean;\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n workingType?: string;\n priceProtect?: boolean;\n origType?: string;\n stopPrice?: string;\n symbol: string;\n}\n\nexport interface IAsterSpotOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n cummulativeQuoteQty?: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n stopPrice?: string;\n icebergQty?: string;\n time: number;\n updateTime: number;\n isWorking?: boolean;\n avgPrice?: string;\n symbol: string;\n}\n\nconst request = async <T>(\n credential: ICredential,\n method: string,\n baseURL: string,\n endpoint: string,\n params: any = {},\n): Promise<T> => {\n const url = new URL(baseURL);\n url.pathname = endpoint;\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, `${value}`);\n }\n\n url.searchParams.set('timestamp', `${Date.now()}`);\n const msg = url.search.slice(1); // 去掉开头的 '?'\n const signature = encodeHex(\n await HmacSHA256(new TextEncoder().encode(msg), new TextEncoder().encode(credential.secret_key)),\n );\n url.searchParams.set('signature', signature);\n\n console.info(url.toString());\n MetricsAsterApiCallCounter.labels({ path: url.pathname, terminal_id: terminal.terminal_id }).inc();\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'X-MBX-APIKEY': credential.api_key,\n },\n });\n\n const resText = await response.text();\n\n try {\n const res = JSON.parse(resText);\n\n if (res.code && res.code !== 0) {\n throw resText;\n }\n return res;\n } catch (e) {\n throw `APIError: ${response.status} ${response.statusText} ${resText}`;\n }\n};\n\nconst createApi =\n (baseURL: string) =>\n <TReq, TRes>(method: string, endpoint: string) =>\n (credential: ICredential, params: TReq) =>\n request<TRes>(credential, method, baseURL, endpoint, params);\n\nconst createFutureApi = createApi('https://fapi.asterdex.com');\nconst createSpotApi = createApi('https://sapi.asterdex.com');\n\n/**\n * 获取账户信息\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AFv4-user_data\n */\nexport const getFApiV4Account = createFutureApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n updateTime: number;\n totalInitialMargin: string;\n totalMaintMargin: string;\n totalWalletBalance: string;\n totalUnrealizedProfit: string;\n totalMarginBalance: string;\n totalPositionInitialMargin: string;\n totalOpenOrderInitialMargin: string;\n totalCrossWalletBalance: string;\n totalCrossUnPnl: string;\n availableBalance: string;\n maxWithdrawAmount: string;\n assets: {\n asset: string;\n walletBalance: string;\n unrealizedProfit: string;\n marginBalance: string;\n maintMargin: string;\n initialMargin: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n maxWithdrawAmount: string;\n crossWalletBalance: string;\n crossUnPnl: string;\n availableBalance: string;\n marginAvailable: boolean;\n updateTime: number;\n }[];\n positions: {\n symbol: string;\n initialMargin: string;\n maintMargin: string;\n unrealizedProfit: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n leverage: string;\n isolated: boolean;\n entryPrice: string;\n maxNotional: string;\n positionSide: 'BOTH' | 'LONG' | 'SHORT';\n positionAmt: string;\n notional: string;\n isolatedWallet: string;\n updateTime: number;\n }[];\n }\n>('GET', '/fapi/v4/account');\n\nexport const getFApiV2Balance = createFutureApi<\n {},\n {\n accountAlias: string; // 账户唯一识别码\n asset: string; // 资产\n balance: string; // 总余额\n crossWalletBalance: string; // 全仓余额\n crossUnPnl: string; // 全仓持仓未实现盈亏\n availableBalance: string; // 下单可用余额\n maxWithdrawAmount: string; // 最大可转出余额\n marginAvailable: boolean; // 是否可用作联合保证金\n updateTime: number;\n }[]\n>('GET', '/fapi/v2/balance');\n\nexport const postFApiV1Order = createFutureApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n type:\n | 'MARKET'\n | 'LIMIT'\n | 'STOP'\n | 'STOP_MARKET'\n | 'TAKE_PROFIT'\n | 'TAKE_PROFIT_MARKET'\n | 'TRAILING_STOP_MARKET';\n reduceOnly?: 'true' | 'false';\n quantity?: number;\n price?: number;\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX' | 'HIDDEN';\n },\n {}\n>('POST', '/fapi/v1/order');\n\n/**\n * 查询当前挂单 (永续)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#L2728-L2766\n */\nexport const getFApiV1OpenOrders = createFutureApi<\n {\n symbol?: string;\n },\n IAsterFutureOpenOrder[]\n>('GET', '/fapi/v1/openOrders');\n\n/**\n * 查询当前挂单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1196-L1234\n */\nexport const getApiV1OpenOrders = createSpotApi<\n {\n symbol?: string;\n },\n IAsterSpotOpenOrder[]\n>('GET', '/api/v1/openOrders');\n\nexport const deleteFApiV1Order = createFutureApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/fapi/v1/order');\n\n/**\n * 获取账户信息 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AF-user_data\n */\nexport const getApiV1Account = createSpotApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n canBurnAsset: boolean;\n updateTime: number;\n balances: {\n asset: string;\n free: string;\n locked: string;\n }[];\n }\n>('GET', '/api/v1/account');\n\n/**\n * 获取最新价格\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC\n */\nexport const getApiV1TickerPrice = createSpotApi<\n {},\n {\n symbol: string;\n price: string;\n time: number;\n }[]\n>('GET', '/api/v1/ticker/price');\n\nexport const postApiV1Order = createSpotApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n type: 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET';\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX';\n quantity?: number;\n quoteOrderQty?: number;\n price?: number;\n },\n {\n orderId: number; // 系统的订单ID\n }\n>('POST', '/api/v1/order');\n\n/**\n * 取消有效订单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1040-L1074\n */\nexport const deleteApiV1Order = createSpotApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/api/v1/order');\n"]}
1
+ {"version":3,"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CAa7C,KAAK,EAAE,kBAAkB,CAAC,CAAC;AAEhB,QAAA,eAAe,GAAG,eAAe,CAmB5C,MAAM,EAAE,gBAAgB,CAAC,CAAC;AAE5B;;;;GAIG;AACU,QAAA,mBAAmB,GAAG,eAAe,CAKhD,KAAK,EAAE,qBAAqB,CAAC,CAAC;AAEhC;;;;GAIG;AACU,QAAA,kBAAkB,GAAG,aAAa,CAK7C,KAAK,EAAE,oBAAoB,CAAC,CAAC;AAElB,QAAA,iBAAiB,GAAG,eAAe,CAO9C,QAAQ,EAAE,gBAAgB,CAAC,CAAC;AAE9B;;;;GAIG;AACU,QAAA,eAAe,GAAG,aAAa,CAe1C,KAAK,EAAE,iBAAiB,CAAC,CAAC;AAE5B;;;GAGG;AACU,QAAA,mBAAmB,GAAG,aAAa,CAO9C,KAAK,EAAE,sBAAsB,CAAC,CAAC;AAEpB,QAAA,cAAc,GAAG,aAAa,CAazC,MAAM,EAAE,eAAe,CAAC,CAAC;AAE3B;;;;GAIG;AACU,QAAA,gBAAgB,GAAG,aAAa,CAO3C,QAAQ,EAAE,eAAe,CAAC,CAAC","sourcesContent":["import { encodeHex, HmacSHA256, newError } from '@yuants/utils';\n\nimport { GlobalPrometheusRegistry, Terminal } from '@yuants/protocol';\n\nconst MetricsAsterApiCallCounter = GlobalPrometheusRegistry.counter(\n 'aster_api_call',\n 'Number of aster api call',\n);\nconst terminal = Terminal.fromNodeEnv();\n\nexport interface ICredential {\n address: string;\n api_key: string;\n secret_key: string;\n}\n\nexport interface IAsterFutureOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n updateTime: number;\n avgPrice: string;\n reduceOnly?: boolean;\n closePosition?: boolean;\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n workingType?: string;\n priceProtect?: boolean;\n origType?: string;\n stopPrice?: string;\n symbol: string;\n}\n\nexport interface IAsterSpotOpenOrder {\n orderId: number;\n clientOrderId: string;\n price: string;\n origQty: string;\n executedQty: string;\n cummulativeQuoteQty?: string;\n status: string;\n timeInForce: string;\n type: string;\n side: 'BUY' | 'SELL';\n stopPrice?: string;\n icebergQty?: string;\n time: number;\n updateTime: number;\n isWorking?: boolean;\n avgPrice?: string;\n symbol: string;\n}\n\nconst request = async <T>(\n credential: ICredential,\n method: string,\n baseURL: string,\n endpoint: string,\n params: any = {},\n): Promise<T> => {\n const url = new URL(baseURL);\n url.pathname = endpoint;\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, `${value}`);\n }\n\n url.searchParams.set('timestamp', `${Date.now()}`);\n const msg = url.search.slice(1); // 去掉开头的 '?'\n const signature = encodeHex(\n await HmacSHA256(new TextEncoder().encode(msg), new TextEncoder().encode(credential.secret_key)),\n );\n url.searchParams.set('signature', signature);\n\n console.info(url.toString());\n MetricsAsterApiCallCounter.labels({ path: url.pathname, terminal_id: terminal.terminal_id }).inc();\n const response = await fetch(url.toString(), {\n method,\n headers: {\n 'X-MBX-APIKEY': credential.api_key,\n },\n });\n\n const resText = await response.text();\n\n try {\n const res = JSON.parse(resText);\n\n if (res.code && res.code !== 0) {\n throw resText;\n }\n return res;\n } catch (e) {\n throw newError(\n 'ASTER_API_ERROR',\n {\n status: response.status,\n statusText: response.statusText,\n resText,\n params,\n },\n e,\n );\n }\n};\n\nconst createApi =\n (baseURL: string) =>\n <TReq, TRes>(method: string, endpoint: string) =>\n (credential: ICredential, params: TReq) =>\n request<TRes>(credential, method, baseURL, endpoint, params);\n\nconst createFutureApi = createApi('https://fapi.asterdex.com');\nconst createSpotApi = createApi('https://sapi.asterdex.com');\n\n/**\n * 获取账户信息\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AFv4-user_data\n */\nexport const getFApiV4Account = createFutureApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n updateTime: number;\n totalInitialMargin: string;\n totalMaintMargin: string;\n totalWalletBalance: string;\n totalUnrealizedProfit: string;\n totalMarginBalance: string;\n totalPositionInitialMargin: string;\n totalOpenOrderInitialMargin: string;\n totalCrossWalletBalance: string;\n totalCrossUnPnl: string;\n availableBalance: string;\n maxWithdrawAmount: string;\n assets: {\n asset: string;\n walletBalance: string;\n unrealizedProfit: string;\n marginBalance: string;\n maintMargin: string;\n initialMargin: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n maxWithdrawAmount: string;\n crossWalletBalance: string;\n crossUnPnl: string;\n availableBalance: string;\n marginAvailable: boolean;\n updateTime: number;\n }[];\n positions: {\n symbol: string;\n initialMargin: string;\n maintMargin: string;\n unrealizedProfit: string;\n positionInitialMargin: string;\n openOrderInitialMargin: string;\n leverage: string;\n isolated: boolean;\n entryPrice: string;\n maxNotional: string;\n positionSide: 'BOTH' | 'LONG' | 'SHORT';\n positionAmt: string;\n notional: string;\n isolatedWallet: string;\n updateTime: number;\n }[];\n }\n>('GET', '/fapi/v4/account');\n\nexport const getFApiV2Balance = createFutureApi<\n {},\n {\n accountAlias: string; // 账户唯一识别码\n asset: string; // 资产\n balance: string; // 总余额\n crossWalletBalance: string; // 全仓余额\n crossUnPnl: string; // 全仓持仓未实现盈亏\n availableBalance: string; // 下单可用余额\n maxWithdrawAmount: string; // 最大可转出余额\n marginAvailable: boolean; // 是否可用作联合保证金\n updateTime: number;\n }[]\n>('GET', '/fapi/v2/balance');\n\nexport const postFApiV1Order = createFutureApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n positionSide?: 'BOTH' | 'LONG' | 'SHORT';\n type:\n | 'MARKET'\n | 'LIMIT'\n | 'STOP'\n | 'STOP_MARKET'\n | 'TAKE_PROFIT'\n | 'TAKE_PROFIT_MARKET'\n | 'TRAILING_STOP_MARKET';\n reduceOnly?: 'true' | 'false';\n quantity?: number;\n price?: number;\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX' | 'HIDDEN';\n },\n {}\n>('POST', '/fapi/v1/order');\n\n/**\n * 查询当前挂单 (永续)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-futures-api_CN.md#L2728-L2766\n */\nexport const getFApiV1OpenOrders = createFutureApi<\n {\n symbol?: string;\n },\n IAsterFutureOpenOrder[]\n>('GET', '/fapi/v1/openOrders');\n\n/**\n * 查询当前挂单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1196-L1234\n */\nexport const getApiV1OpenOrders = createSpotApi<\n {\n symbol?: string;\n },\n IAsterSpotOpenOrder[]\n>('GET', '/api/v1/openOrders');\n\nexport const deleteFApiV1Order = createFutureApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/fapi/v1/order');\n\n/**\n * 获取账户信息 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E8%B4%A6%E6%88%B7%E4%BF%A1%E6%81%AF-user_data\n */\nexport const getApiV1Account = createSpotApi<\n {},\n {\n feeTier: number;\n canTrade: boolean;\n canDeposit: boolean;\n canWithdraw: boolean;\n canBurnAsset: boolean;\n updateTime: number;\n balances: {\n asset: string;\n free: string;\n locked: string;\n }[];\n }\n>('GET', '/api/v1/account');\n\n/**\n * 获取最新价格\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#%E6%9C%80%E6%96%B0%E4%BB%B7%E6%A0%BC\n */\nexport const getApiV1TickerPrice = createSpotApi<\n {},\n {\n symbol: string;\n price: string;\n time: number;\n }[]\n>('GET', '/api/v1/ticker/price');\n\nexport const postApiV1Order = createSpotApi<\n {\n symbol: string;\n side: 'BUY' | 'SELL';\n type: 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET';\n timeInForce?: 'GTC' | 'IOC' | 'FOK' | 'GTX';\n quantity?: number;\n quoteOrderQty?: number;\n price?: number;\n },\n {\n orderId: number; // 系统的订单ID\n }\n>('POST', '/api/v1/order');\n\n/**\n * 取消有效订单 (现货)\n *\n * https://github.com/asterdex/api-docs/blob/master/aster-finance-spot-api_CN.md#L1040-L1074\n */\nexport const deleteApiV1Order = createSpotApi<\n {\n symbol: string;\n orderId?: string | number;\n origClientOrderId?: string;\n },\n {}\n>('DELETE', '/api/v1/order');\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"spot.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAoB,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAA0D,WAAW,EAAE,MAAM,uBAAuB,CAAC;AA0B5G,eAAO,MAAM,YAAY,eAAsB,WAAW,yBAkEzD,CAAC"}
1
+ {"version":3,"file":"spot.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAoB,MAAM,sBAAsB,CAAC;AAEnE,OAAO,EAA0D,WAAW,EAAE,MAAM,uBAAuB,CAAC;AA6B5G,eAAO,MAAM,YAAY,eAAsB,WAAW,yBAoEzD,CAAC"}
@@ -12,7 +12,7 @@ const asBNBPrice = (0, cache_1.createCache)(() => fetch('https://api.coingecko.c
12
12
  .then((data) => data['astherus-staked-bnb'].usd), {
13
13
  expire: 60000, // 1 minute
14
14
  });
15
- const buildSpotProductMap = async () => {
15
+ const spotProductMapCache = (0, cache_1.createCache)(async () => {
16
16
  const products = await (0, product_1.listProducts)();
17
17
  const map = new Map();
18
18
  for (const product of products) {
@@ -22,7 +22,7 @@ const buildSpotProductMap = async () => {
22
22
  }
23
23
  }
24
24
  return map;
25
- };
25
+ }, { expire: 86400000 });
26
26
  const getPositions = async (credential) => {
27
27
  var _a, _b, _c, _d, _e;
28
28
  const positions = [];
@@ -30,14 +30,15 @@ const getPositions = async (credential) => {
30
30
  (0, private_api_1.getApiV1Account)(credential, {}),
31
31
  (0, private_api_1.getApiV1TickerPrice)(credential, {}),
32
32
  (0, private_api_1.getFApiV4Account)(credential, {}),
33
- buildSpotProductMap(),
33
+ spotProductMapCache.query(''),
34
34
  ]);
35
+ const resolvedSpotProductMap = spotProductMap !== null && spotProductMap !== void 0 ? spotProductMap : new Map();
35
36
  for (const b of x.balances) {
36
37
  const thePrice = b.asset === 'USDT' ? 1 : (_b = (_a = prices.find((p) => p.symbol === b.asset + 'USDT')) === null || _a === void 0 ? void 0 : _a.price) !== null && _b !== void 0 ? _b : 0;
37
38
  positions.push((0, data_account_1.makeSpotPosition)({
38
39
  position_id: b.asset,
39
40
  datasource_id: 'ASTER',
40
- product_id: (_c = spotProductMap.get(b.asset)) !== null && _c !== void 0 ? _c : (0, utils_1.encodePath)('ASTER', 'SPOT', b.asset),
41
+ product_id: (_c = resolvedSpotProductMap.get(b.asset)) !== null && _c !== void 0 ? _c : (0, utils_1.encodePath)('ASTER', 'SPOT', b.asset),
41
42
  volume: +b.free + +b.locked,
42
43
  free_volume: +b.free,
43
44
  closable_price: +thePrice,
@@ -1 +1 @@
1
- {"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAC5C,uDAAmE;AACnE,yCAA2C;AAC3C,uDAA4G;AAC5G,gDAAkD;AAElD,qFAAqF;AACrF,MAAM,UAAU,GAAG,IAAA,mBAAW,EAC5B,GAAG,EAAE,CACH,KAAK,CAAC,yFAAyF,CAAC;KAC7F,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;KACzB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,GAAa,CAAC,EAC9D;IACE,MAAM,EAAE,KAAM,EAAE,WAAW;CAC5B,CACF,CAAC;AAEF,MAAM,mBAAmB,GAAG,KAAK,IAAI,EAAE;IACrC,MA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AM,EAAE,CAAC,CAAC,CAAC,aAAa;YACxB,WAAW,EAAE,CAAC,CAAC,CAAC,aAAa;YAC7B,cAAc,EAAE,QAAQ;SACzB,CAAC,CACH,CAAC;KACH;IAED,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,SAAS,EAAE;QAC9B,IAAI,CAAC,CAAC,CAAC,WAAW,KAAK,CAAC;YAAE,SAAS;QACnC,SAAS,CAAC,IAAI,CAAC;YACb,WAAW,EAAE,CAAC,CAAC,MAAM;YACrB,UAAU,EAAE,IAAA,kBAAU,EAAC,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC;YACjD,aAAa,EAAE,OAAO;YACtB,SAAS,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;YAC/F,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YAChC,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YACrC,cAAc,EAAE,CAAC,CAAC,CAAC,UAAU;YAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC;YACtD,eAAe,EAAE,CAAC,CAAC,CAAC,gBAAgB;YACpC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;SACjC,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAlEW,QAAA,YAAY,gBAkEvB","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getApiV1Account, getApiV1TickerPrice, getFApiV4Account, ICredential } from '../../api/private-api';\nimport { listProducts } from '../markets/product';\n\n// ISSUE: ASBNB price is not available in the price API, need to fetch from coingecko\nconst asBNBPrice = createCache(\n () =>\n fetch('https://api.coingecko.com/api/v3/simple/price?ids=astherus-staked-bnb&vs_currencies=usd')\n .then((res) => res.json())\n .then((data) => data['astherus-staked-bnb'].usd as number),\n {\n expire: 60_000, // 1 minute\n },\n);\n\nconst buildSpotProductMap = async () => {\n const products = await listProducts();\n const map = new Map<string, string>();\n for (const product of products) {\n const [, instType] = product.product_id.split('/');\n if (instType === 'SPOT') {\n map.set(product.base_currency, product.product_id);\n }\n }\n return map;\n};\n\nexport const getPositions = async (credential: ICredential) => {\n const positions: IPosition[] = [];\n const [x, prices, prep, spotProductMap] = await Promise.all([\n getApiV1Account(credential, {}),\n getApiV1TickerPrice(credential, {}),\n getFApiV4Account(credential, {}),\n buildSpotProductMap(),\n ]);\n\n for (const b of x.balances) {\n const thePrice = b.asset === 'USDT' ? 1 : prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0;\n positions.push(\n makeSpotPosition({\n position_id: b.asset,\n datasource_id: 'ASTER',\n product_id: spotProductMap.get(b.asset) ?? encodePath('ASTER', 'SPOT', b.asset),\n volume: +b.free + +b.locked,\n free_volume: +b.free,\n closable_price: +thePrice,\n }),\n );\n }\n\n for (const b of prep.assets) {\n if (+b.walletBalance === 0) continue;\n let thePrice = 0;\n if (b.asset === 'USDT') {\n thePrice = 1;\n } else if (b.asset === 'ASBNB') {\n const _p = await asBNBPrice.query('').catch(() => 0);\n if (_p) {\n thePrice = _p;\n }\n } else {\n thePrice = +(prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0);\n }\n\n positions.push(\n makeSpotPosition({\n position_id: encodePath(b.asset, 'ASSET'),\n datasource_id: 'ASTER',\n product_id: encodePath('ASTER', 'PERP-ASSET', b.asset),\n volume: +b.walletBalance,\n free_volume: +b.walletBalance,\n closable_price: thePrice,\n }),\n );\n }\n\n for (const p of prep.positions) {\n if (+p.positionAmt === 0) continue;\n positions.push({\n position_id: p.symbol,\n product_id: encodePath('ASTER', 'PERP', p.symbol),\n datasource_id: 'ASTER',\n direction: p.positionSide === 'BOTH' ? (+p.positionAmt > 0 ? 'LONG' : 'SHORT') : p.positionSide,\n volume: Math.abs(+p.positionAmt),\n free_volume: Math.abs(+p.positionAmt),\n position_price: +p.entryPrice,\n closable_price: Math.abs(+p.notional / +p.positionAmt),\n floating_profit: +p.unrealizedProfit,\n valuation: Math.abs(+p.notional),\n });\n }\n\n return positions;\n};\n"]}
1
+ {"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAC5C,uDAAmE;AACnE,yCAA2C;AAC3C,uDAA4G;AAC5G,gDAAkD;AAElD,qFAAqF;AACrF,MAAM,UAAU,GAAG,IAAA,mBAAW,EAC5B,GAAG,EAAE,CACH,KAAK,CAAC,yFAAyF,CAAC;KAC7F,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;KACzB,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,GAAa,CAAC,EAC9D;IACE,MAAM,EAAE,KAAM,EAAE,WAAW;CAC5B,CACF,CAAC;AAEF,MAAM,mBAAmB,GAAG,IAAA,mBAAW,EACrC,KAAK,IAAI,EAAE;IACT,MAAM,QAAQ,GAAG,MAAM,IAAA,sBAAY,GAAE,CAAC;IACtC,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE;QAC9B,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnD,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,GAAG,CAAC,GAAG,CAAC,OAA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AAI,IAAI,CAAC,SAAS,EAAE;QAC9B,IAAI,CAAC,CAAC,CAAC,WAAW,KAAK,CAAC;YAAE,SAAS;QACnC,SAAS,CAAC,IAAI,CAAC;YACb,WAAW,EAAE,CAAC,CAAC,MAAM;YACrB,UAAU,EAAE,IAAA,kBAAU,EAAC,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC;YACjD,aAAa,EAAE,OAAO;YACtB,SAAS,EAAE,CAAC,CAAC,YAAY,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY;YAC/F,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YAChC,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC;YACrC,cAAc,EAAE,CAAC,CAAC,CAAC,UAAU;YAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC;YACtD,eAAe,EAAE,CAAC,CAAC,CAAC,gBAAgB;YACpC,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;SACjC,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AApEW,QAAA,YAAY,gBAoEvB","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getApiV1Account, getApiV1TickerPrice, getFApiV4Account, ICredential } from '../../api/private-api';\nimport { listProducts } from '../markets/product';\n\n// ISSUE: ASBNB price is not available in the price API, need to fetch from coingecko\nconst asBNBPrice = createCache(\n () =>\n fetch('https://api.coingecko.com/api/v3/simple/price?ids=astherus-staked-bnb&vs_currencies=usd')\n .then((res) => res.json())\n .then((data) => data['astherus-staked-bnb'].usd as number),\n {\n expire: 60_000, // 1 minute\n },\n);\n\nconst spotProductMapCache = createCache(\n async () => {\n const products = await listProducts();\n const map = new Map<string, string>();\n for (const product of products) {\n const [, instType] = product.product_id.split('/');\n if (instType === 'SPOT') {\n map.set(product.base_currency, product.product_id);\n }\n }\n return map;\n },\n { expire: 86_400_000 },\n);\n\nexport const getPositions = async (credential: ICredential) => {\n const positions: IPosition[] = [];\n const [x, prices, prep, spotProductMap] = await Promise.all([\n getApiV1Account(credential, {}),\n getApiV1TickerPrice(credential, {}),\n getFApiV4Account(credential, {}),\n spotProductMapCache.query(''),\n ]);\n\n const resolvedSpotProductMap = spotProductMap ?? new Map<string, string>();\n\n for (const b of x.balances) {\n const thePrice = b.asset === 'USDT' ? 1 : prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0;\n positions.push(\n makeSpotPosition({\n position_id: b.asset,\n datasource_id: 'ASTER',\n product_id: resolvedSpotProductMap.get(b.asset) ?? encodePath('ASTER', 'SPOT', b.asset),\n volume: +b.free + +b.locked,\n free_volume: +b.free,\n closable_price: +thePrice,\n }),\n );\n }\n\n for (const b of prep.assets) {\n if (+b.walletBalance === 0) continue;\n let thePrice = 0;\n if (b.asset === 'USDT') {\n thePrice = 1;\n } else if (b.asset === 'ASBNB') {\n const _p = await asBNBPrice.query('').catch(() => 0);\n if (_p) {\n thePrice = _p;\n }\n } else {\n thePrice = +(prices.find((p) => p.symbol === b.asset + 'USDT')?.price ?? 0);\n }\n\n positions.push(\n makeSpotPosition({\n position_id: encodePath(b.asset, 'ASSET'),\n datasource_id: 'ASTER',\n product_id: encodePath('ASTER', 'PERP-ASSET', b.asset),\n volume: +b.walletBalance,\n free_volume: +b.walletBalance,\n closable_price: thePrice,\n }),\n );\n }\n\n for (const p of prep.positions) {\n if (+p.positionAmt === 0) continue;\n positions.push({\n position_id: p.symbol,\n product_id: encodePath('ASTER', 'PERP', p.symbol),\n datasource_id: 'ASTER',\n direction: p.positionSide === 'BOTH' ? (+p.positionAmt > 0 ? 'LONG' : 'SHORT') : p.positionSide,\n volume: Math.abs(+p.positionAmt),\n free_volume: Math.abs(+p.positionAmt),\n position_price: +p.entryPrice,\n closable_price: Math.abs(+p.notional / +p.positionAmt),\n floating_profit: +p.unrealizedProfit,\n valuation: Math.abs(+p.notional),\n });\n }\n\n return positions;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAuB,WAAW,EAAmC,MAAM,uBAAuB,CAAC;AA+G1G,eAAO,MAAM,iBAAiB,EAAE,2BAA2B,CAAC,WAAW,CAStE,CAAC"}
1
+ {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAuB,WAAW,EAAmC,MAAM,uBAAuB,CAAC;AAmH1G,eAAO,MAAM,iBAAiB,EAAE,2BAA2B,CAAC,WAAW,CAStE,CAAC"}
@@ -66,13 +66,17 @@ const handleSubmitOrderOfPerp = async (credential, order) => {
66
66
  throw new Error(`Unsupported order_type: ${order.order_type}`);
67
67
  const quantity = order.volume;
68
68
  const price = order.price;
69
- const positionSide = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'
70
- ? 'LONG'
71
- : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'
72
- ? 'SHORT'
73
- : undefined;
69
+ const isPositionSingleSide = true; // FIXME: Aster 永续合约仅支持单向持仓模式
70
+ const positionSide = isPositionSingleSide
71
+ ? undefined
72
+ : order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'
73
+ ? 'LONG'
74
+ : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'
75
+ ? 'SHORT'
76
+ : undefined;
74
77
  const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;
75
78
  const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;
79
+ //
76
80
  const res = await (0, private_api_1.postFApiV1Order)(credential, {
77
81
  symbol,
78
82
  side,
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAAwD;AACxD,uDAA0G;AAE1G,MAAM,cAAc,GAAG,CAAC,SAAkB,EAAE,EAAE;IAC5C,IAAI,CAAC,SAAS,EAAE;QACd,OAAO,EAAE,QAAQ,EAAE,SAA+B,EAAE,MAAM,EAAE,SAA+B,EAAE,CAAC;KAC/F;IACD,MAAM,KAAK,GAAG,IAAA,kBAAU,EAAC,SAAS,CAAC,CAAC;IACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;QACrB,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;KACjE;IACD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACnD,CAAC,CAAC;AAEF,MAAM,uBAAuB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;;IACpG,MAAM,EAAE,MAAM,EAAE,GAAG,cAAc,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACpD,MAAM,cAAc,GAAG,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,KAAK,CAAC,UAAU,CAAC;IAClD,IAAI,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AO;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAE3E,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACpC,CAAC,CAAC;AAEK,MAAM,iBAAiB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IACrG,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,8BAA8B;IAClF,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;AACjF,CAAC,CAAC;AATW,QAAA,iBAAiB,qBAS5B","sourcesContent":["import { IActionHandlerOfSubmitOrder } from '@yuants/data-order';\nimport { decodePath, roundToStep } from '@yuants/utils';\nimport { getApiV1TickerPrice, ICredential, postApiV1Order, postFApiV1Order } from '../../api/private-api';\n\nconst parseProductId = (productId?: string) => {\n if (!productId) {\n return { category: undefined as string | undefined, symbol: undefined as string | undefined };\n }\n const parts = decodePath(productId);\n if (parts.length >= 3) {\n return { category: parts[1], symbol: parts.slice(2).join('/') };\n }\n return { category: undefined, symbol: parts[0] };\n};\n\nconst handleSubmitOrderOfSpot: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n const resolvedSymbol = symbol ?? order.product_id;\n if (!resolvedSymbol) {\n throw new Error(`Invalid product_id: unable to resolve spot symbol from \"${order.product_id}\"`);\n }\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const price = order.price;\n\n let quantity: number | undefined = order.volume;\n let quoteOrderQty: number | undefined;\n\n if (type === 'MARKET' && side === 'BUY') {\n const spotPrice = await getApiV1TickerPrice(credential, {});\n const thePrice = spotPrice.find((x) => x.symbol === resolvedSymbol)?.price;\n if (!thePrice) throw new Error(`Cannot get price for symbol ${resolvedSymbol}`);\n quantity = undefined;\n quoteOrderQty = roundToStep(order.volume * +thePrice, 0.01);\n }\n\n const res = await postApiV1Order(credential, {\n symbol: resolvedSymbol,\n type,\n side,\n timeInForce,\n price,\n quantity,\n quoteOrderQty,\n });\n\n if (!res.orderId) {\n throw new Error('Failed to retrieve order ID from response');\n }\n\n return { order_id: '' + res.orderId };\n};\n\nconst handleSubmitOrderOfPerp: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n if (!symbol) {\n throw new Error(`Invalid product_id: unable to decode symbol from \"${order.product_id}\"`);\n }\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const quantity = order.volume;\n const price = order.price;\n\n const positionSide =\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'\n ? 'LONG'\n : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'\n ? 'SHORT'\n : undefined;\n\n const reduceOnly =\n order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const res = await postFApiV1Order(credential, {\n symbol,\n side,\n type,\n quantity,\n price,\n timeInForce,\n positionSide,\n reduceOnly,\n });\n\n const orderId =\n (res as any)?.orderId ??\n (res as any)?.order_id ??\n (res as any)?.data?.orderId ??\n (res as any)?.data?.order_id;\n\n if (!orderId) throw new Error('Failed to retrieve order ID from response');\n\n return { order_id: `${orderId}` };\n};\n\nexport const handleSubmitOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const [_, instType] = decodePath(order.product_id); // BITGET/USDT-FUTURES/BTCUSDT\n if (instType === 'SPOT') {\n return handleSubmitOrderOfSpot(credential, order);\n }\n if (instType === 'PERP') {\n return handleSubmitOrderOfPerp(credential, order);\n }\n throw new Error(`Unsupported account_id for SubmitOrder: ${order.account_id}`);\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAAwD;AACxD,uDAA0G;AAE1G,MAAM,cAAc,GAAG,CAAC,SAAkB,EAAE,EAAE;IAC5C,IAAI,CAAC,SAAS,EAAE;QACd,OAAO,EAAE,QAAQ,EAAE,SAA+B,EAAE,MAAM,EAAE,SAA+B,EAAE,CAAC;KAC/F;IACD,MAAM,KAAK,GAAG,IAAA,kBAAU,EAAC,SAAS,CAAC,CAAC;IACpC,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,EAAE;QACrB,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;KACjE;IACD,OAAO,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AG,MAAM,IAAA,6BAAe,EAAC,UAAU,EAAE;QAC5C,MAAM;QACN,IAAI;QACJ,IAAI;QACJ,QAAQ;QACR,KAAK;QACL,WAAW;QACX,YAAY;QACZ,UAAU;KACX,CAAC,CAAC;IAEH,MAAM,OAAO,GACX,MAAA,MAAA,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,OAAO,mCACpB,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,QAAQ,mCACtB,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,IAAI,0CAAE,OAAO,mCAC3B,MAAC,GAAW,aAAX,GAAG,uBAAH,GAAG,CAAU,IAAI,0CAAE,QAAQ,CAAC;IAE/B,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;IAE3E,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACpC,CAAC,CAAC;AAEK,MAAM,iBAAiB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IACrG,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,8BAA8B;IAClF,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KACnD;IACD,MAAM,IAAI,KAAK,CAAC,2CAA2C,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;AACjF,CAAC,CAAC;AATW,QAAA,iBAAiB,qBAS5B","sourcesContent":["import { IActionHandlerOfSubmitOrder } from '@yuants/data-order';\nimport { decodePath, roundToStep } from '@yuants/utils';\nimport { getApiV1TickerPrice, ICredential, postApiV1Order, postFApiV1Order } from '../../api/private-api';\n\nconst parseProductId = (productId?: string) => {\n if (!productId) {\n return { category: undefined as string | undefined, symbol: undefined as string | undefined };\n }\n const parts = decodePath(productId);\n if (parts.length >= 3) {\n return { category: parts[1], symbol: parts.slice(2).join('/') };\n }\n return { category: undefined, symbol: parts[0] };\n};\n\nconst handleSubmitOrderOfSpot: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n const resolvedSymbol = symbol ?? order.product_id;\n if (!resolvedSymbol) {\n throw new Error(`Invalid product_id: unable to resolve spot symbol from \"${order.product_id}\"`);\n }\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const price = order.price;\n\n let quantity: number | undefined = order.volume;\n let quoteOrderQty: number | undefined;\n\n if (type === 'MARKET' && side === 'BUY') {\n const spotPrice = await getApiV1TickerPrice(credential, {});\n const thePrice = spotPrice.find((x) => x.symbol === resolvedSymbol)?.price;\n if (!thePrice) throw new Error(`Cannot get price for symbol ${resolvedSymbol}`);\n quantity = undefined;\n quoteOrderQty = roundToStep(order.volume * +thePrice, 0.01);\n }\n\n const res = await postApiV1Order(credential, {\n symbol: resolvedSymbol,\n type,\n side,\n timeInForce,\n price,\n quantity,\n quoteOrderQty,\n });\n\n if (!res.orderId) {\n throw new Error('Failed to retrieve order ID from response');\n }\n\n return { order_id: '' + res.orderId };\n};\n\nconst handleSubmitOrderOfPerp: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const { symbol } = parseProductId(order.product_id);\n if (!symbol) {\n throw new Error(`Invalid product_id: unable to decode symbol from \"${order.product_id}\"`);\n }\n\n const side = ({ OPEN_LONG: 'BUY', OPEN_SHORT: 'SELL', CLOSE_LONG: 'SELL', CLOSE_SHORT: 'BUY' } as const)[\n order.order_direction!\n ];\n if (!side) throw new Error(`Unsupported order_direction: ${order.order_direction}`);\n\n const type = ({ MARKET: 'MARKET', LIMIT: 'LIMIT', MAKER: 'LIMIT' } as const)[order.order_type!];\n if (!type) throw new Error(`Unsupported order_type: ${order.order_type}`);\n\n const quantity = order.volume;\n const price = order.price;\n\n const isPositionSingleSide = true; // FIXME: Aster 永续合约仅支持单向持仓模式\n\n const positionSide = isPositionSingleSide\n ? undefined\n : order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_LONG'\n ? 'LONG'\n : order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_SHORT'\n ? 'SHORT'\n : undefined;\n\n const reduceOnly =\n order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;\n\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n //\n const res = await postFApiV1Order(credential, {\n symbol,\n side,\n type,\n quantity,\n price,\n timeInForce,\n positionSide,\n reduceOnly,\n });\n\n const orderId =\n (res as any)?.orderId ??\n (res as any)?.order_id ??\n (res as any)?.data?.orderId ??\n (res as any)?.data?.order_id;\n\n if (!orderId) throw new Error('Failed to retrieve order ID from response');\n\n return { order_id: `${orderId}` };\n};\n\nexport const handleSubmitOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const [_, instType] = decodePath(order.product_id); // BITGET/USDT-FUTURES/BTCUSDT\n if (instType === 'SPOT') {\n return handleSubmitOrderOfSpot(credential, order);\n }\n if (instType === 'PERP') {\n return handleSubmitOrderOfPerp(credential, order);\n }\n throw new Error(`Unsupported account_id for SubmitOrder: ${order.account_id}`);\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuants/vendor-aster",
3
- "version": "0.7.23",
3
+ "version": "0.7.25",
4
4
  "main": "lib/index.js",
5
5
  "files": [
6
6
  "dist",
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "apps/vendor-aster/AGENTS.md": "dcd006d19a5c3b73081525d7c0afea68cd6d058b",
3
- "apps/vendor-aster/CHANGELOG.json": "7841bcca263f924f344b41d7d754a76d2e3242d2",
4
- "apps/vendor-aster/CHANGELOG.md": "30fed97c26f4c5c48a70f3ab4caf3274aca86f49",
5
- "apps/vendor-aster/SESSION_NOTES.md": "9734c99b07dd143cd0a36274f582f746d549fe12",
3
+ "apps/vendor-aster/CHANGELOG.json": "b01e4c9fc9b22676a4593281cf0aa2d850bdb817",
4
+ "apps/vendor-aster/CHANGELOG.md": "9e5b3842300fbeb58d58ae4b31a08a29e5d6d75a",
5
+ "apps/vendor-aster/SESSION_NOTES.md": "d91f7a251d148fab1715b6da62395455edcb3b93",
6
6
  "apps/vendor-aster/config/jest.config.json": "4bb17bde3ee911163a3edb36a6eb71491d80b1bd",
7
7
  "apps/vendor-aster/config/rig.json": "f6c7b5537dc77a3170ba9f008bae3b6c3ee11956",
8
8
  "apps/vendor-aster/config/typescript.json": "854907e8a821f2050f6533368db160c649c25348",
9
- "apps/vendor-aster/package.json": "3896d935a2f2a242be339b5b210b397342c1b714",
10
- "apps/vendor-aster/src/api/private-api.ts": "71f2f794377a45c64f688a663111318e36463bdb",
9
+ "apps/vendor-aster/package.json": "6c19a6621c1f0fdf8d70f624141f9fda3eb34f1a",
10
+ "apps/vendor-aster/src/api/private-api.ts": "ddafe28ed90a9dd10974afb9371d41115d7226ff",
11
11
  "apps/vendor-aster/src/api/public-api.ts": "ced2ae976ee7a74a5c1fe704b2c5fb2e25f13ab7",
12
12
  "apps/vendor-aster/src/index.ts": "509ef4c18ec2deb8a6e11ed5682334433cb2bcb2",
13
13
  "apps/vendor-aster/src/services/accounts/profile.ts": "fc57e7d2c865790dd257c043c8dd5cf5c641b7fd",
14
- "apps/vendor-aster/src/services/accounts/spot.ts": "34ec7b03862ab53702ea957942b8217086ee5bb0",
14
+ "apps/vendor-aster/src/services/accounts/spot.ts": "785a165bef3797d5a4e8482d5cc798f2d3eec748",
15
15
  "apps/vendor-aster/src/services/exchange.ts": "71a555ceec0d84b6f12a9c2002834676f1370d51",
16
16
  "apps/vendor-aster/src/services/markets/interest_rate.ts": "8512bb506f3d66b16aceb9d153d1b3a4671de5ef",
17
17
  "apps/vendor-aster/src/services/markets/product.ts": "cae86f69c6f019747ebad07569ed2bc862a78ac6",
18
18
  "apps/vendor-aster/src/services/markets/quote.ts": "ba022abb87d0114a922030bfba56bce1cd23f135",
19
19
  "apps/vendor-aster/src/services/orders/cancelOrder.ts": "09a6d3b10a218ad226346dd68d0ff0207083a7f1",
20
20
  "apps/vendor-aster/src/services/orders/listOrders.ts": "579e83c45f6c4435ad3f5a2d3fe163a036bb9fd1",
21
- "apps/vendor-aster/src/services/orders/submitOrder.ts": "37791f5bf403d6fb229a0a5202d9cdf72abd0719",
21
+ "apps/vendor-aster/src/services/orders/submitOrder.ts": "9580e87b195b7bd3631b0b3e5f6c2a1c37b29feb",
22
22
  "apps/vendor-aster/tsconfig.json": "81da8f78196974b5d15da0edb6b2d9f48641063c",
23
23
  "apps/vendor-aster/.rush/temp/shrinkwrap-deps.json": "5ded440ffb547a8aa495353d5b13c1fd1b164b4a",
24
24
  "libraries/protocol/temp/package-deps.json": "0bd43721e96039b52d7b59c834dc6df45cf75e3f",