@yuants/vendor-binance 0.8.7 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.js +2 -4
- package/dist/api/client.js.map +1 -1
- package/dist/legacy_index.js +11 -214
- package/dist/legacy_index.js.map +1 -1
- package/dist/public-data/interest_rate.js +5 -3
- package/dist/public-data/interest_rate.js.map +1 -1
- package/dist/public-data/ohlc.js +1 -1
- package/dist/public-data/ohlc.js.map +1 -1
- package/dist/public-data/product.js +1 -1
- package/dist/public-data/product.js.map +1 -1
- package/dist/public-data/quote.js +5 -5
- package/dist/public-data/quote.js.map +1 -1
- package/dist/services/accounts/spot.js +1 -1
- package/dist/services/accounts/spot.js.map +1 -1
- package/dist/services/accounts/unified.js +1 -1
- package/dist/services/accounts/unified.js.map +1 -1
- package/dist/services/orders/cancelOrder.js +5 -3
- package/dist/services/orders/cancelOrder.js.map +1 -1
- package/dist/services/orders/listOrders.js +2 -2
- package/dist/services/orders/listOrders.js.map +1 -1
- package/dist/services/orders/modifyOrder.js +6 -3
- package/dist/services/orders/modifyOrder.js.map +1 -1
- package/dist/services/orders/order-utils.js +29 -7
- package/dist/services/orders/order-utils.js.map +1 -1
- package/dist/services/orders/submitOrder.js +5 -3
- package/dist/services/orders/submitOrder.js.map +1 -1
- package/lib/api/client.d.ts.map +1 -1
- package/lib/api/client.js +1 -6
- package/lib/api/client.js.map +1 -1
- package/lib/legacy_index.js +10 -213
- package/lib/legacy_index.js.map +1 -1
- package/lib/public-data/interest_rate.js +5 -3
- package/lib/public-data/interest_rate.js.map +1 -1
- package/lib/public-data/ohlc.js +1 -1
- package/lib/public-data/ohlc.js.map +1 -1
- package/lib/public-data/product.js +1 -1
- package/lib/public-data/product.js.map +1 -1
- package/lib/public-data/quote.js +5 -5
- package/lib/public-data/quote.js.map +1 -1
- package/lib/services/accounts/spot.js +1 -1
- package/lib/services/accounts/spot.js.map +1 -1
- package/lib/services/accounts/unified.js +1 -1
- package/lib/services/accounts/unified.js.map +1 -1
- package/lib/services/orders/cancelOrder.d.ts.map +1 -1
- package/lib/services/orders/cancelOrder.js +5 -3
- package/lib/services/orders/cancelOrder.js.map +1 -1
- package/lib/services/orders/listOrders.js +2 -2
- package/lib/services/orders/listOrders.js.map +1 -1
- package/lib/services/orders/modifyOrder.d.ts.map +1 -1
- package/lib/services/orders/modifyOrder.js +6 -3
- package/lib/services/orders/modifyOrder.js.map +1 -1
- package/lib/services/orders/order-utils.d.ts.map +1 -1
- package/lib/services/orders/order-utils.js +29 -7
- package/lib/services/orders/order-utils.js.map +1 -1
- package/lib/services/orders/submitOrder.d.ts.map +1 -1
- package/lib/services/orders/submitOrder.js +5 -3
- package/lib/services/orders/submitOrder.js.map +1 -1
- package/package.json +1 -1
- package/temp/package-deps.json +16 -17
- package/dist/cli.js +0 -3
- package/dist/cli.js.map +0 -1
- package/lib/cli.d.ts +0 -3
- package/lib/cli.d.ts.map +0 -1
- package/lib/cli.js +0 -5
- package/lib/cli.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quote.js","sourceRoot":"","sources":["../../src/public-data/quote.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EACL,KAAK,EACL,MAAM,EACN,IAAI,EACJ,OAAO,EACP,GAAG,EACH,KAAK,EACL,QAAQ,EACR,MAAM,EACN,KAAK,EACL,IAAI,EACJ,KAAK,EACL,WAAW,GACZ,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,iBAAiB,EAAE,+BAA+B,EAAe,MAAM,oBAAoB,CAAC;AACrG,OAAO,EACL,mBAAmB,EACnB,q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EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE;YAC/B,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;SACtD;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC;IACxE,CAAC,CAAC,CAAC;CACJ","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath, formatTime } from '@yuants/utils';\nimport {\n defer,\n filter,\n from,\n groupBy,\n map,\n merge,\n mergeMap,\n repeat,\n retry,\n scan,\n share,\n shareReplay,\n} from 'rxjs';\nimport { getMarginAllPairs, getMarginNextHourlyInterestRate, IMarginPair } from '../api/private-api';\nimport {\n getFutureBookTicker,\n getFutureOpenInterest,\n getFuturePremiumIndex,\n getSpotBookTicker,\n} from '../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\nconst OPEN_INTEREST_TTL = process.env.OPEN_INTEREST_TTL ? Number(process.env.OPEN_INTEREST_TTL) : 120_000;\n\nconst openInterestCache = createCache<number>(\n async (symbol: string) => {\n try {\n const data = await getFutureOpenInterest({ symbol });\n return Number(data.openInterest ?? 0);\n } catch (err) {\n console.warn('getFutureOpenInterest failed', symbol, err);\n return undefined;\n }\n },\n {\n expire: OPEN_INTEREST_TTL,\n },\n);\n\nconst futurePremiumIndex$ = defer(() => getFuturePremiumIndex({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst futureBookTicker$ = defer(() => getFutureBookTicker({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quoteFromPremiumIndex$ = futurePremiumIndex$.pipe(\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('usdt-future', entry.symbol),\n last_price: entry.markPrice,\n // Use the latest funding rate so that long pays when fundingRate > 0\n interest_rate_long: `${-Number(entry.lastFundingRate)}`,\n interest_rate_short: entry.lastFundingRate,\n interest_rate_next_settled_at: formatTime(entry.nextFundingTime),\n updated_at: formatTime(entry.time ?? Date.now()),\n }),\n ),\n);\n\nconst quoteFromBookTicker$ = futureBookTicker$.pipe(\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('usdt-future', entry.symbol),\n bid_price: entry.bidPrice,\n ask_price: entry.askPrice,\n updated_at: formatTime(entry.time ?? Date.now()),\n }),\n ),\n);\n\nconst quoteFromOpenInterest$ = futureBookTicker$.pipe(\n mergeMap((entries) => from(entries || [])),\n mergeMap(\n (entry) =>\n from(openInterestCache.query(entry.symbol)).pipe(\n map(\n (openInterest): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('usdt-future', entry.symbol),\n open_interest: `${openInterest ?? 0}`,\n }),\n ),\n ),\n 5,\n ),\n);\n\nconst quoteFromSpotBookTicker$ = defer(() => getSpotBookTicker({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('spot', entry.symbol),\n bid_price: entry.bidPrice,\n ask_price: entry.askPrice,\n bid_volume: entry.bidQty,\n ask_volume: entry.askQty,\n updated_at: formatTime(Date.now()),\n }),\n ),\n);\n\nconst marginInterestRateCache = createCache<string>(\n async (asset: string) => {\n try {\n const data = await getMarginNextHourlyInterestRate({\n assets: asset,\n isIsolated: false,\n });\n return data[0]?.nextHourlyInterestRate;\n } catch (err) {\n return undefined;\n }\n },\n {\n expire: 60_000,\n },\n);\n\nconst marginPairs$ = defer(() => getMarginAllPairs()).pipe(\n repeat({ delay: 3600_000 }), // Refresh pair list hourly\n retry({ delay: 60_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quoteFromMarginRates$ = marginPairs$.pipe(\n mergeMap((pairs: IMarginPair[]) =>\n from(pairs).pipe(\n mergeMap(\n (pair) =>\n defer(async () => {\n const [baseRate, quoteRate] = await Promise.all([\n marginInterestRateCache.query(pair.base),\n marginInterestRateCache.query(pair.quote),\n ]);\n return {\n datasource_id: 'BINANCE',\n product_id: encodePath('spot', pair.symbol),\n // User instruction: Long = Quote Rate, Short = Base Rate\n interest_rate_long: quoteRate,\n interest_rate_short: baseRate,\n updated_at: formatTime(Date.now()),\n } as Partial<IQuote>;\n }),\n 5, // Concurrency\n ),\n ),\n ),\n repeat({ delay: 60_000 }),\n);\n\nconst quote$ = merge(\n quoteFromPremiumIndex$,\n quoteFromBookTicker$,\n quoteFromOpenInterest$,\n quoteFromSpotBookTicker$,\n quoteFromMarginRates$,\n).pipe(\n groupBy((quote) => quote.product_id),\n mergeMap((group$) =>\n group$.pipe(\n scan(\n (acc, cur) =>\n Object.assign(acc, cur, {\n datasource_id: 'BINANCE',\n product_id: group$.key,\n }),\n {} as Partial<IQuote>,\n ),\n ),\n ),\n share(),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n quote$\n .pipe(\n writeToSQL({\n terminal,\n tableName: 'quote',\n writeInterval: 1_000,\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n\n terminal.channel.publishChannel('quote', { pattern: '^BINANCE/' }, (channel_id) => {\n const [datasourceId, productId] = decodePath(channel_id);\n if (!datasourceId || !productId) {\n throw new Error(`Invalid channel_id: ${channel_id}`);\n }\n return quote$.pipe(filter((quote) => quote.product_id === productId));\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CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE;IACtB,aAAa,EAAE,SAAS;IACxB,UAAU,EAAE,MAAM,CAAC,GAAG;CACvB,CAAC,EACJ,EAAqB,CACtB,CACF,CACF,EACD,KAAK,EAAE,EACP,WAAW,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAC/C,CAAC;AAEF,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,MAAM,EAAE;IAC7C,MAAM;SACH,IAAI,CACH,UAAU,CAAC;QACT,QAAQ;QACR,SAAS,EAAE,OAAO;QAClB,aAAa,EAAE,IAAK;QACpB,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;IAEf,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,UAAU,EAAE,EAAE;QAChF,MAAM,CAAC,YAAY,EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE;YAC/B,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;SACtD;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC;IACxE,CAAC,CAAC,CAAC;CACJ","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath, formatTime } from '@yuants/utils';\nimport {\n defer,\n filter,\n from,\n groupBy,\n map,\n merge,\n mergeMap,\n repeat,\n retry,\n scan,\n share,\n shareReplay,\n} from 'rxjs';\nimport { getMarginAllPairs, getMarginNextHourlyInterestRate, IMarginPair } from '../api/private-api';\nimport {\n getFutureBookTicker,\n getFutureOpenInterest,\n getFuturePremiumIndex,\n getSpotBookTicker,\n} from '../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\nconst OPEN_INTEREST_TTL = process.env.OPEN_INTEREST_TTL ? Number(process.env.OPEN_INTEREST_TTL) : 120_000;\n\nconst openInterestCache = createCache<number>(\n async (symbol: string) => {\n try {\n const data = await getFutureOpenInterest({ symbol });\n return Number(data.openInterest ?? 0);\n } catch (err) {\n console.warn('getFutureOpenInterest failed', symbol, err);\n return undefined;\n }\n },\n {\n expire: OPEN_INTEREST_TTL,\n },\n);\n\nconst futurePremiumIndex$ = defer(() => getFuturePremiumIndex({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst futureBookTicker$ = defer(() => getFutureBookTicker({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quoteFromPremiumIndex$ = futurePremiumIndex$.pipe(\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'USDT-FUTURE', entry.symbol),\n last_price: entry.markPrice,\n // Use the latest funding rate so that long pays when fundingRate > 0\n interest_rate_long: `${-Number(entry.lastFundingRate)}`,\n interest_rate_short: entry.lastFundingRate,\n interest_rate_next_settled_at: formatTime(entry.nextFundingTime),\n updated_at: formatTime(entry.time ?? Date.now()),\n }),\n ),\n);\n\nconst quoteFromBookTicker$ = futureBookTicker$.pipe(\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'USDT-FUTURE', entry.symbol),\n bid_price: entry.bidPrice,\n ask_price: entry.askPrice,\n updated_at: formatTime(entry.time ?? Date.now()),\n }),\n ),\n);\n\nconst quoteFromOpenInterest$ = futureBookTicker$.pipe(\n mergeMap((entries) => from(entries || [])),\n mergeMap(\n (entry) =>\n from(openInterestCache.query(entry.symbol)).pipe(\n map(\n (openInterest): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'USDT-FUTURE', entry.symbol),\n open_interest: `${openInterest ?? 0}`,\n }),\n ),\n ),\n 5,\n ),\n);\n\nconst quoteFromSpotBookTicker$ = defer(() => getSpotBookTicker({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n mergeMap((entries) => from(entries || [])),\n map(\n (entry): Partial<IQuote> => ({\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'SPOT', entry.symbol),\n bid_price: entry.bidPrice,\n ask_price: entry.askPrice,\n bid_volume: entry.bidQty,\n ask_volume: entry.askQty,\n updated_at: formatTime(Date.now()),\n }),\n ),\n);\n\nconst marginInterestRateCache = createCache<string>(\n async (asset: string) => {\n try {\n const data = await getMarginNextHourlyInterestRate({\n assets: asset,\n isIsolated: false,\n });\n return data[0]?.nextHourlyInterestRate;\n } catch (err) {\n return undefined;\n }\n },\n {\n expire: 60_000,\n },\n);\n\nconst marginPairs$ = defer(() => getMarginAllPairs()).pipe(\n repeat({ delay: 3600_000 }), // Refresh pair list hourly\n retry({ delay: 60_000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quoteFromMarginRates$ = marginPairs$.pipe(\n mergeMap((pairs: IMarginPair[]) =>\n from(pairs).pipe(\n mergeMap(\n (pair) =>\n defer(async () => {\n const [baseRate, quoteRate] = await Promise.all([\n marginInterestRateCache.query(pair.base),\n marginInterestRateCache.query(pair.quote),\n ]);\n return {\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'SPOT', pair.symbol),\n // User instruction: Long = Quote Rate, Short = Base Rate\n interest_rate_long: quoteRate,\n interest_rate_short: baseRate,\n updated_at: formatTime(Date.now()),\n } as Partial<IQuote>;\n }),\n 5, // Concurrency\n ),\n ),\n ),\n repeat({ delay: 60_000 }),\n);\n\nconst quote$ = merge(\n quoteFromPremiumIndex$,\n quoteFromBookTicker$,\n quoteFromOpenInterest$,\n quoteFromSpotBookTicker$,\n quoteFromMarginRates$,\n).pipe(\n groupBy((quote) => quote.product_id),\n mergeMap((group$) =>\n group$.pipe(\n scan(\n (acc, cur) =>\n Object.assign(acc, cur, {\n datasource_id: 'BINANCE',\n product_id: group$.key,\n }),\n {} as Partial<IQuote>,\n ),\n ),\n ),\n share(),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n quote$\n .pipe(\n writeToSQL({\n terminal,\n tableName: 'quote',\n writeInterval: 1_000,\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n\n terminal.channel.publishChannel('quote', { pattern: '^BINANCE/' }, (channel_id) => {\n const [datasourceId, productId] = decodePath(channel_id);\n if (!datasourceId || !productId) {\n throw new Error(`Invalid channel_id: ${channel_id}`);\n }\n return quote$.pipe(filter((quote) => quote.product_id === productId));\n });\n}\n"]}
|
|
@@ -15,7 +15,7 @@ export const getSpotAccountInfoSnapshot = async (credential) => {
|
|
|
15
15
|
const position = makeSpotPosition({
|
|
16
16
|
position_id: `spot/${balance.asset}`,
|
|
17
17
|
datasource_id: 'BINANCE',
|
|
18
|
-
product_id: encodePath('
|
|
18
|
+
product_id: encodePath('BINANCE', 'SPOT', `${balance.asset}USDT`),
|
|
19
19
|
volume,
|
|
20
20
|
free_volume: +balance.free,
|
|
21
21
|
closable_price: 0, // TODO: fetch price later
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6C,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAA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B,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7E,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;KAC1B;IACD,MAAM,SAAS,GAAG,GAAG,CAAC,QAAQ;SAC3B,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE;QACf,MAAM,MAAM,GAAG,CAAC,OAAO,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC;QAC/C,IAAI,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC;QAC9B,MAAM,QAAQ,GAAc,gBAAgB,CAAC;YAC3C,WAAW,EAAE,QAAQ,OAAO,CAAC,KAAK,EAAE;YACpC,aAAa,EAAE,SAAS;YACxB,UAAU,EAAE,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,KAAK,MAAM,CAAC;YACjE,MAAM;YACN,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI;YAC1B,cAAc,EAAE,CAAC,EAAE,0BAA0B;SAC9C,CAAC,CAAC;QACH,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,QAAQ,EAAyB,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAClE,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { isApiError } from '../../api/client';\nimport { getSpotAccountInfo, ICredential } from '../../api/private-api';\n\nexport const getSpotAccountInfoSnapshot: IActionHandlerOfGetAccountInfo<ICredential> = async (credential) => {\n const res = await getSpotAccountInfo(credential, { omitZeroBalances: true });\n if (isApiError(res)) {\n throw new Error(res.msg);\n }\n const positions = res.balances\n .map((balance) => {\n const volume = +balance.free + +balance.locked;\n if (!volume) return undefined;\n const position: IPosition = makeSpotPosition({\n position_id: `spot/${balance.asset}`,\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'SPOT', `${balance.asset}USDT`),\n volume,\n free_volume: +balance.free,\n closable_price: 0, // TODO: fetch price later\n });\n return position;\n })\n .filter((position): position is IPosition => Boolean(position));\n return positions;\n};\n"]}
|
|
@@ -27,7 +27,7 @@ export const getUnifiedAccountInfo = async (credential, _accountId) => {
|
|
|
27
27
|
.map((position) => ({
|
|
28
28
|
position_id: `${position.symbol}/${position.positionSide}`,
|
|
29
29
|
datasource_id: 'BINANCE',
|
|
30
|
-
product_id: encodePath('
|
|
30
|
+
product_id: encodePath('BINANCE', 'USDT-FUTURE', position.symbol),
|
|
31
31
|
direction: position.positionSide === 'LONG'
|
|
32
32
|
? 'LONG'
|
|
33
33
|
: position.positionSide === 'SHORT'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unified.js","sourceRoot":"","sources":["../../../src/services/accounts/unified.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAe,MAAM,uBAAuB,CAAC;AAEnG,MAAM,CAAC,MAAM,qBAAqB,GAAgD,KAAK,EACrF,UAAU,EACV,UAAU,EACV,EAAE;IACF,MAAM,CAAC,UAAU,EAAE,YAAY,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACnD,wBAAwB,CAAC,UAAU,CAAC;QACpC,mBAAmB,CAAC,UAAU,CAAC;KAChC,CAAC,CAAC;IACH,IAAI,UAAU,CAAC,UAAU,CAAC,EAAE;QAC1B,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;KACjC;IACD,IAAI,UAAU,CAAC,YAAY,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;KACnC;IACD,MAAM,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,YAAY,EAAE;QAC1D,aAAa,EAAE,SAAS;QACxB,UAAU,EAAE,UAAU,CAAC,SAAS,EAAE,aAAa,EAAE,QAAQ,CAAC,MAAM,CAAC;QACjE,SAAS,EACP,QAAQ,CAAC,YAAY,KAAK,MAAM;YAC9B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,QAAQ,CAAC,YAAY,KAAK,OAAO;gBACnC,CAAC,CAAC,OAAO;gBACT,CAAC,CAAC,QAAQ,CAAC,YAAY,KAAK,MAAM;oBAClC,CAAC,CAAC,MAAM;oBACR,CAAC,CAAC,SAAS;QACf,MAAM,EAAE,CAAC,QAAQ,CAAC,WAAW;QAC7B,WAAW,EAAE,CAAC,QAAQ,CAAC,WAAW;QAClC,cAAc,EAAE,CAAC,QAAQ,CAAC,UAAU;QACpC,cAAc,EAAE,CAAC,QAAQ,CAAC,UAAU,GAAG,CAAC,QAAQ,CAAC,gBAAgB,GAAG,CAAC,QAAQ,CAAC,WAAW;QACzF,eAAe,EAAE,CAAC,QAAQ,CAAC,gBAAgB;QAC3C,SAAS,EACP,CAAC,QAAQ,CAAC,WAAW;YACrB,CAAC,CAAC,QAAQ,CAAC,UAAU;gBACnB,CAAC,CAAC,QAAQ,CAAC,WAAW,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,gBAAgB,GAAG,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;KAC5F,CAAC,CAAC,CAAC;IAEN,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { isApiError } from '../../api/client';\nimport { getUnifiedAccountBalance, getUnifiedUmAccount, ICredential } from '../../api/private-api';\n\nexport const getUnifiedAccountInfo: IActionHandlerOfGetAccountInfo<ICredential> = async (\n credential,\n _accountId,\n) => {\n const [balanceRes, umAccountRes] = await Promise.all([\n getUnifiedAccountBalance(credential),\n getUnifiedUmAccount(credential),\n ]);\n if (isApiError(balanceRes)) {\n throw new Error(balanceRes.msg);\n }\n if (isApiError(umAccountRes)) {\n throw new Error(umAccountRes.msg);\n }\n const usdtBalance = balanceRes.find((item) => item.asset === 'USDT');\n if (!usdtBalance) {\n throw new Error('USDT balance not found');\n }\n const usdtAsset = umAccountRes.assets.find((item) => item.asset === 'USDT');\n if (!usdtAsset) {\n throw new Error('USDT asset not found in UM account');\n }\n\n const equity = +usdtBalance.totalWalletBalance + +usdtBalance.umUnrealizedPNL;\n const free = equity - +usdtAsset.initialMargin;\n\n const positions: IPosition[] = umAccountRes.positions\n .filter((position) => +position.positionAmt !== 0)\n .map((position) => ({\n position_id: `${position.symbol}/${position.positionSide}`,\n datasource_id: 'BINANCE',\n product_id: encodePath('BINANCE', 'USDT-FUTURE', position.symbol),\n direction:\n position.positionSide === 'LONG'\n ? 'LONG'\n : position.positionSide === 'SHORT'\n ? 'SHORT'\n : position.positionSide === 'BOTH'\n ? 'BOTH'\n : 'UNKNOWN',\n volume: +position.positionAmt,\n free_volume: +position.positionAmt,\n position_price: +position.entryPrice,\n closable_price: +position.entryPrice + +position.unrealizedProfit / +position.positionAmt,\n floating_profit: +position.unrealizedProfit,\n valuation:\n +position.positionAmt *\n (+position.entryPrice +\n (+position.positionAmt === 0 ? 0 : +position.unrealizedProfit / +position.positionAmt)),\n }));\n\n return positions;\n};\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isApiError } from '../../api/client';
|
|
2
2
|
import { deleteSpotOrder, deleteUmOrder } from '../../api/private-api';
|
|
3
3
|
import { decodeFutureSymbol, decodeSpotSymbol } from './order-utils';
|
|
4
|
+
import { decodePath, newError } from '@yuants/utils';
|
|
4
5
|
const cancelUnifiedOrder = async (credential, order) => {
|
|
5
6
|
if (!order.order_id) {
|
|
6
7
|
throw new Error('Binance cancelOrder requires order_id');
|
|
@@ -28,12 +29,13 @@ const cancelSpotOrder = async (credential, order) => {
|
|
|
28
29
|
}
|
|
29
30
|
};
|
|
30
31
|
export const cancelOrder = async (credential, order) => {
|
|
31
|
-
|
|
32
|
+
const [, TYPE] = decodePath(order.product_id);
|
|
33
|
+
if (TYPE === 'USDT-FUTURE') {
|
|
32
34
|
return cancelUnifiedOrder(credential, order);
|
|
33
35
|
}
|
|
34
|
-
if (
|
|
36
|
+
if (TYPE === 'SPOT') {
|
|
35
37
|
return cancelSpotOrder(credential, order);
|
|
36
38
|
}
|
|
37
|
-
throw
|
|
39
|
+
throw newError('BINANCE_CANCEL_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });
|
|
38
40
|
};
|
|
39
41
|
//# sourceMappingURL=cancelOrder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../src/services/orders/cancelOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,aAAa,EAAe,MAAM,uBAAuB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../src/services/orders/cancelOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,aAAa,EAAe,MAAM,uBAAuB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAErD,MAAM,kBAAkB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IAC/F,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;KAC1D;IACD,MAAM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MAAM,QAAQ,CAAC,+CAA+C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAC7E,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfCancelOrder } from '@yuants/data-order';\nimport { isApiError } from '../../api/client';\nimport { deleteSpotOrder, deleteUmOrder, ICredential } from '../../api/private-api';\nimport { decodeFutureSymbol, decodeSpotSymbol } from './order-utils';\nimport { decodePath, newError } from '@yuants/utils';\n\nconst cancelUnifiedOrder: IActionHandlerOfCancelOrder<ICredential> = async (credential, order) => {\n if (!order.order_id) {\n throw new Error('Binance cancelOrder requires order_id');\n }\n const symbol = decodeFutureSymbol(order.product_id);\n const res = await deleteUmOrder(credential, {\n symbol,\n orderId: order.order_id,\n });\n if (isApiError(res)) {\n throw new Error(`Binance cancel unified order failed: ${res.code} ${res.msg}`);\n }\n};\n\nconst cancelSpotOrder: IActionHandlerOfCancelOrder<ICredential> = async (credential, order) => {\n if (!order.order_id) {\n throw new Error('Binance cancelOrder requires order_id');\n }\n const symbol = decodeSpotSymbol(order.product_id);\n const res = await deleteSpotOrder(credential, {\n symbol,\n orderId: order.order_id,\n });\n if (isApiError(res)) {\n throw new Error(`Binance cancel spot order failed: ${res.code} ${res.msg}`);\n }\n};\n\nexport const cancelOrder: IActionHandlerOfCancelOrder<ICredential> = async (credential, order) => {\n const [, TYPE] = decodePath(order.product_id);\n if (TYPE === 'USDT-FUTURE') {\n return cancelUnifiedOrder(credential, order);\n }\n if (TYPE === 'SPOT') {\n return cancelSpotOrder(credential, order);\n }\n throw newError('BINANCE_CANCEL_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });\n};\n"]}
|
|
@@ -13,7 +13,7 @@ export const listOrders = async (credential, account_id) => {
|
|
|
13
13
|
return ({
|
|
14
14
|
order_id: `${order.orderId}`,
|
|
15
15
|
account_id,
|
|
16
|
-
product_id: encodePath('
|
|
16
|
+
product_id: encodePath('BINANCE', 'USDT-FUTURE', order.symbol),
|
|
17
17
|
order_type: mapBinanceOrderTypeToYuants(order.type),
|
|
18
18
|
order_direction: (_a = mapBinanceSideToYuantsDirection(order.side, order.positionSide)) !== null && _a !== void 0 ? _a : (order.side === 'BUY' ? 'OPEN_LONG' : 'OPEN_SHORT'),
|
|
19
19
|
volume: +order.origQty,
|
|
@@ -33,7 +33,7 @@ export const listOrders = async (credential, account_id) => {
|
|
|
33
33
|
return res.map((order) => ({
|
|
34
34
|
order_id: `${order.orderId}`,
|
|
35
35
|
account_id,
|
|
36
|
-
product_id: encodePath('
|
|
36
|
+
product_id: encodePath('BINANCE', 'SPOT', order.symbol),
|
|
37
37
|
order_type: mapBinanceOrderTypeToYuants(order.type),
|
|
38
38
|
order_direction: mapSpotSideToOrderDirection(order.side),
|
|
39
39
|
volume: +order.origQty,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listOrders.js","sourceRoot":"","sources":["../../../src/services/orders/listOrders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAe,MAAM,uBAAuB,CAAC;AAC/F,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC3B,+BAA+B,EAC/B,2BAA2B,GAC5B,MAAM,eAAe,CAAC;AAEvB,MAAM,CAAC,MAAM,UAAU,GAA4C,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;IAClG,IAAI,UAAU,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE;QACpC,MAAM,GAAG,GAAG,MAAM,sBAAsB,CAAC,UAAU,CAAC,CAAC;QACrD,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;YACnB,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;SAC1B;QACD,OAAO,GAAG,CAAC,GAAG,CACZ,CAAC,KAAK,EAAU,EAAE;;YAAC,OAAA,CAA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C,KAAK,CAAC,UAAU,CAAC;YACxC,YAAY,EAAE,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;SAClD,CAAC,CACH,CAAC;KACH;IACD,MAAM,IAAI,KAAK,CAAC,0CAA0C,UAAU,EAAE,CAAC,CAAC;AAC1E,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfListOrders, IOrder } from '@yuants/data-order';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { isApiError } from '../../api/client';\nimport { getSpotOpenOrders, getUnifiedUmOpenOrders, ICredential } from '../../api/private-api';\nimport {\n mapBinanceOrderStatus,\n mapBinanceOrderTypeToYuants,\n mapBinanceSideToYuantsDirection,\n mapSpotSideToOrderDirection,\n} from './order-utils';\n\nexport const listOrders: IActionHandlerOfListOrders<ICredential> = async (credential, account_id) => {\n if (account_id.includes('/unified/')) {\n const res = await getUnifiedUmOpenOrders(credential);\n if (isApiError(res)) {\n throw new Error(res.msg);\n }\n return res.map(\n (order): IOrder => ({\n order_id: `${order.orderId}`,\n account_id,\n product_id: encodePath('BINANCE', 'USDT-FUTURE', order.symbol),\n order_type: mapBinanceOrderTypeToYuants(order.type),\n order_direction:\n mapBinanceSideToYuantsDirection(order.side, order.positionSide) ??\n (order.side === 'BUY' ? 'OPEN_LONG' : 'OPEN_SHORT'),\n volume: +order.origQty,\n traded_volume: +order.executedQty,\n price: order.price === undefined ? undefined : +order.price,\n submit_at: order.time,\n updated_at: formatTime(order.updateTime),\n order_status: mapBinanceOrderStatus(order.status),\n }),\n );\n }\n if (account_id.includes('/spot/')) {\n const res = await getSpotOpenOrders(credential);\n if (isApiError(res)) {\n throw new Error(res.msg);\n }\n return res.map(\n (order): IOrder => ({\n order_id: `${order.orderId}`,\n account_id,\n product_id: encodePath('BINANCE', 'SPOT', order.symbol),\n order_type: mapBinanceOrderTypeToYuants(order.type),\n order_direction: mapSpotSideToOrderDirection(order.side),\n volume: +order.origQty,\n traded_volume: +order.executedQty,\n price: order.price ? +order.price : undefined,\n submit_at: order.time,\n updated_at: formatTime(order.updateTime),\n order_status: mapBinanceOrderStatus(order.status),\n }),\n );\n }\n throw new Error(`Unsupported account_id for listOrders: ${account_id}`);\n};\n"]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { isApiError } from '../../api/client';
|
|
2
2
|
import { postSpotOrderCancelReplace, putUmOrder } from '../../api/private-api';
|
|
3
3
|
import { decodeFutureSymbol, decodeSpotSymbol, deriveClientOrderId, mapOrderDirectionToSide, mapOrderTypeToOrdType, } from './order-utils';
|
|
4
|
+
import { newError } from '@yuants/utils/lib/error';
|
|
5
|
+
import { decodePath } from '@yuants/utils/lib/path';
|
|
4
6
|
const modifyUnifiedOrder = async (credential, order) => {
|
|
5
7
|
const symbol = decodeFutureSymbol(order.product_id);
|
|
6
8
|
const side = mapOrderDirectionToSide(order.order_direction);
|
|
@@ -47,12 +49,13 @@ const modifySpotOrder = async (credential, order) => {
|
|
|
47
49
|
}
|
|
48
50
|
};
|
|
49
51
|
export const modifyOrder = async (credential, order) => {
|
|
50
|
-
|
|
52
|
+
const [, TYPE] = decodePath(order.product_id);
|
|
53
|
+
if (TYPE === 'USDT-FUTURE') {
|
|
51
54
|
return modifyUnifiedOrder(credential, order);
|
|
52
55
|
}
|
|
53
|
-
if (
|
|
56
|
+
if (TYPE === 'SPOT') {
|
|
54
57
|
return modifySpotOrder(credential, order);
|
|
55
58
|
}
|
|
56
|
-
throw
|
|
59
|
+
throw newError('BINANCE_MODIFY_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });
|
|
57
60
|
};
|
|
58
61
|
//# sourceMappingURL=modifyOrder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../../src/services/orders/modifyOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAe,0BAA0B,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AA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EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KAC7E;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IAC/F,MAAM,CAAC,EAAE,IAAI,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAE9C,IAAI,IAAI,KAAK,aAAa,EAAE;QAC1B,OAAO,kBAAkB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KAC9C;IACD,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,eAAe,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KAC3C;IAED,MAAM,QAAQ,CAAC,+CAA+C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAC7E,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfModifyOrder } from '@yuants/data-order';\nimport { isApiError } from '../../api/client';\nimport { ICredential, postSpotOrderCancelReplace, putUmOrder } from '../../api/private-api';\nimport {\n decodeFutureSymbol,\n decodeSpotSymbol,\n deriveClientOrderId,\n mapOrderDirectionToSide,\n mapOrderTypeToOrdType,\n} from './order-utils';\nimport { newError } from '@yuants/utils/lib/error';\nimport { decodePath } from '@yuants/utils/lib/path';\n\nconst modifyUnifiedOrder: IActionHandlerOfModifyOrder<ICredential> = async (credential, order) => {\n const symbol = decodeFutureSymbol(order.product_id);\n const side = mapOrderDirectionToSide(order.order_direction);\n\n const res = await putUmOrder(credential, {\n symbol,\n side,\n orderId: order.order_id ? parseInt(order.order_id) : undefined,\n // origClientOrderId: order.client_order_id, // TODO: support client_order_id\n quantity: order.volume,\n price: order.price,\n });\n if (isApiError(res)) {\n throw new Error(`Binance modify unified order failed: ${res.code} ${res.msg}`);\n }\n};\n\nconst modifySpotOrder: IActionHandlerOfModifyOrder<ICredential> = async (credential, order) => {\n const symbol = decodeSpotSymbol(order.product_id);\n const side = mapOrderDirectionToSide(order.order_direction);\n const type = mapOrderTypeToOrdType(order.order_type);\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n\n const params: Parameters<typeof postSpotOrderCancelReplace>[1] = {\n symbol,\n side,\n type,\n cancelReplaceMode: 'STOP_ON_FAILURE',\n cancelOrderId: order.order_id ? parseInt(order.order_id) : undefined,\n // cancelOrigClientOrderId: order.client_order_id, // TODO: support client_order_id\n newClientOrderId: deriveClientOrderId(order),\n quantity: order.volume,\n };\n\n if (type === 'LIMIT') {\n if (order.price === undefined) {\n throw new Error('Binance spot LIMIT order requires price');\n }\n params.price = order.price;\n params.timeInForce = timeInForce;\n }\n if (order.price !== undefined && type === 'MARKET') {\n params.price = order.price;\n }\n\n const res = await postSpotOrderCancelReplace(credential, params);\n if (isApiError(res)) {\n throw new Error(`Binance modify spot order failed: ${res.code} ${res.msg}`);\n }\n};\n\nexport const modifyOrder: IActionHandlerOfModifyOrder<ICredential> = async (credential, order) => {\n const [, TYPE] = decodePath(order.product_id);\n\n if (TYPE === 'USDT-FUTURE') {\n return modifyUnifiedOrder(credential, order);\n }\n if (TYPE === 'SPOT') {\n return modifySpotOrder(credential, order);\n }\n\n throw newError('BINANCE_MODIFY_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });\n};\n"]}
|
|
@@ -1,17 +1,39 @@
|
|
|
1
1
|
import { decodePath } from '@yuants/utils';
|
|
2
2
|
import { createHash } from 'crypto';
|
|
3
3
|
export const decodeFutureSymbol = (product_id) => {
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
const parts = decodePath(product_id);
|
|
5
|
+
// Support both old format (usdt-future/symbol) and new format (BINANCE/USDT-FUTURE/symbol)
|
|
6
|
+
if (parts.length === 2) {
|
|
7
|
+
const [instType, symbol] = parts;
|
|
8
|
+
if (instType !== 'usdt-future' || !symbol) {
|
|
9
|
+
throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);
|
|
10
|
+
}
|
|
11
|
+
return symbol;
|
|
12
|
+
}
|
|
13
|
+
else if (parts.length === 3) {
|
|
14
|
+
const [datasource, instType, symbol] = parts;
|
|
15
|
+
if (datasource !== 'BINANCE' || instType !== 'USDT-FUTURE' || !symbol) {
|
|
16
|
+
throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);
|
|
17
|
+
}
|
|
18
|
+
return symbol;
|
|
7
19
|
}
|
|
8
|
-
|
|
20
|
+
throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);
|
|
9
21
|
};
|
|
10
22
|
export const decodeSpotSymbol = (product_id) => {
|
|
11
23
|
try {
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
24
|
+
const parts = decodePath(product_id);
|
|
25
|
+
// Support both old format (spot/symbol) and new format (BINANCE/SPOT/symbol)
|
|
26
|
+
if (parts.length === 2) {
|
|
27
|
+
const [instType, symbol] = parts;
|
|
28
|
+
if ((instType === null || instType === void 0 ? void 0 : instType.toLowerCase()) === 'spot' && symbol) {
|
|
29
|
+
return symbol;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
else if (parts.length === 3) {
|
|
33
|
+
const [datasource, instType, symbol] = parts;
|
|
34
|
+
if (datasource === 'BINANCE' && instType === 'SPOT' && symbol) {
|
|
35
|
+
return symbol;
|
|
36
|
+
}
|
|
15
37
|
}
|
|
16
38
|
}
|
|
17
39
|
catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"order-utils.js","sourceRoot":"","sources":["../../../src/services/orders/order-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,UAAkB,EAAE,EAAE;IACvD,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,U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AAG,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC;QAC7B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC,CAAC;IACH,OAAO,SAAS,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;AACpF,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAA2C;IACpE,GAAG,EAAE,UAAU;IACf,gBAAgB,EAAE,QAAQ;IAC1B,MAAM,EAAE,QAAQ;IAChB,WAAW,EAAE,UAAU;IACvB,cAAc,EAAE,WAAW;IAC3B,QAAQ,EAAE,WAAW;IACrB,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,WAAW;IACrB,OAAO,EAAE,WAAW;CACrB,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,MAAe,EAA0B,EAAE;;IAC/E,IAAI,CAAC,MAAM;QAAE,OAAO,UAAU,CAAC;IAC/B,OAAO,MAAA,qBAAqB,CAAC,MAAM,CAAC,mCAAI,UAAU,CAAC;AACrD,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { createHash } from 'crypto';\n\nexport const decodeFutureSymbol = (product_id: string) => {\n const parts = decodePath(product_id);\n // Support both old format (usdt-future/symbol) and new format (BINANCE/USDT-FUTURE/symbol)\n if (parts.length === 2) {\n const [instType, symbol] = parts;\n if (instType !== 'usdt-future' || !symbol) {\n throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);\n }\n return symbol;\n } else if (parts.length === 3) {\n const [datasource, instType, symbol] = parts;\n if (datasource !== 'BINANCE' || instType !== 'USDT-FUTURE' || !symbol) {\n throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);\n }\n return symbol;\n }\n throw new Error(`Unsupported product_id for Binance futures: ${product_id}`);\n};\n\nexport const decodeSpotSymbol = (product_id: string) => {\n try {\n const parts = decodePath(product_id);\n // Support both old format (spot/symbol) and new format (BINANCE/SPOT/symbol)\n if (parts.length === 2) {\n const [instType, symbol] = parts;\n if (instType?.toLowerCase() === 'spot' && symbol) {\n return symbol;\n }\n } else if (parts.length === 3) {\n const [datasource, instType, symbol] = parts;\n if (datasource === 'BINANCE' && instType === 'SPOT' && symbol) {\n return symbol;\n }\n }\n } catch (err) {\n // ignore decode errors and fall back to raw product id\n }\n if (!product_id.includes('/')) {\n return product_id;\n }\n throw new Error(`Unsupported product_id for Binance spot: ${product_id}`);\n};\n\nexport const mapOrderDirectionToSide = (direction?: IOrder['order_direction']) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'BUY';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'SELL';\n default:\n throw new Error(`Unsupported order_direction: ${direction}`);\n }\n};\n\nexport const mapOrderDirectionToPositionSide = (direction?: IOrder['order_direction']) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'LONG';\n case 'OPEN_SHORT':\n case 'CLOSE_SHORT':\n return 'SHORT';\n default:\n throw new Error(`Unsupported order_direction for positionSide: ${direction}`);\n }\n};\n\nexport const mapOrderTypeToOrdType = (order_type?: IOrder['order_type']) => {\n switch (order_type) {\n case 'LIMIT':\n case 'MAKER':\n return 'LIMIT';\n case 'MARKET':\n return 'MARKET';\n default:\n throw new Error(`Unsupported order_type: ${order_type}`);\n }\n};\n\nexport const mapBinanceOrderTypeToYuants = (binanceType?: string): IOrder['order_type'] => {\n switch (binanceType) {\n case 'LIMIT':\n return 'LIMIT';\n case 'MARKET':\n return 'MARKET';\n default:\n return 'LIMIT';\n }\n};\n\nexport const mapBinanceSideToYuantsDirection = (\n side?: string,\n positionSide?: string,\n): IOrder['order_direction'] | undefined => {\n if (!side || !positionSide) {\n return undefined;\n }\n if (positionSide === 'LONG') {\n return side === 'BUY' ? 'OPEN_LONG' : 'CLOSE_LONG';\n }\n if (positionSide === 'SHORT') {\n return side === 'SELL' ? 'OPEN_SHORT' : 'CLOSE_SHORT';\n }\n return undefined;\n};\n\nexport const mapSpotSideToOrderDirection = (side?: string): IOrder['order_direction'] => {\n if (side === 'SELL') {\n return 'CLOSE_LONG';\n }\n return 'OPEN_LONG';\n};\n\nexport const deriveClientOrderId = (order: IOrder) => {\n if (order.order_id) return `${order.order_id}`;\n const payload = JSON.stringify({\n account_id: order.account_id,\n product_id: order.product_id,\n order_direction: order.order_direction,\n order_type: order.order_type,\n price: order.price,\n volume: order.volume,\n });\n return `YUANTS${createHash('sha256').update(payload).digest('hex').slice(0, 24)}`;\n};\n\nconst BinanceOrderStatusMap: Record<string, IOrder['order_status']> = {\n NEW: 'ACCEPTED',\n PARTIALLY_FILLED: 'TRADED',\n FILLED: 'TRADED',\n PENDING_NEW: 'ACCEPTED',\n PENDING_CANCEL: 'CANCELLED',\n CANCELED: 'CANCELLED',\n CANCELLED: 'CANCELLED',\n REJECTED: 'CANCELLED',\n EXPIRED: 'CANCELLED',\n};\n\nexport const mapBinanceOrderStatus = (status?: string): IOrder['order_status'] => {\n if (!status) return 'ACCEPTED';\n return BinanceOrderStatusMap[status] ?? 'ACCEPTED';\n};\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { decodePath, newError } from '@yuants/utils';
|
|
1
2
|
import { isApiError } from '../../api/client';
|
|
2
3
|
import { postSpotOrder, postUmOrder } from '../../api/private-api';
|
|
3
4
|
import { decodeFutureSymbol, decodeSpotSymbol, deriveClientOrderId, mapOrderDirectionToPositionSide, mapOrderDirectionToSide, mapOrderTypeToOrdType, } from './order-utils';
|
|
@@ -59,12 +60,13 @@ const submitSpotOrder = async (credential, order) => {
|
|
|
59
60
|
return { order_id: `${res.orderId}` };
|
|
60
61
|
};
|
|
61
62
|
export const submitOrder = async (credential, order) => {
|
|
62
|
-
|
|
63
|
+
const [, TYPE] = decodePath(order.product_id);
|
|
64
|
+
if (TYPE === 'USDT-FUTURE') {
|
|
63
65
|
return submitUnifiedOrder(credential, order);
|
|
64
66
|
}
|
|
65
|
-
if (
|
|
67
|
+
if (TYPE === 'SPOT') {
|
|
66
68
|
return submitSpotOrder(credential, order);
|
|
67
69
|
}
|
|
68
|
-
throw
|
|
70
|
+
throw newError('BINANCE_SUBMIT_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });
|
|
69
71
|
};
|
|
70
72
|
//# sourceMappingURL=submitOrder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAe,aAAa,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAChF,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,mBAAmB,EACnB,+BAA+B,EAC/B,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,eAAe,CAAC;AAEvB,MAAM,kBAAkB,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IAC/F,MAAM,MAAM,GAAG,kBAAkB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACpD,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;QACjB,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;KACxE;IACD,MAAM,IAAI,GAAG,uBAAuB,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IAC5D,MAAM,YAAY,GAAG,+BAA+B,CAAC,KAAK,CAAC,eAAe,CAAC,C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,KAAK,CAAC,KAAK,CAAC;QAC3B,MAAM,CAAC,WAAW,GAAG,WAAW,CAAC;KAClC;IACD,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,IAAI,KAAK,QAAQ,EAAE;QAClD,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;KAC5B;IACD,MAAM,GAAG,GAAG,MAAM,aAAa,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACpD,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,qCAAqC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KAC7E;IACD,OAAO,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;AACxC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAA6C,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;IAC/F,MAAM,CAAC,EAAE,IAAI,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAE9C,IAAI,IAAI,KAAK,aAAa,EAAE;QAC1B,OAAO,kBAAkB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KAC9C;IACD,IAAI,IAAI,KAAK,MAAM,EAAE;QACnB,OAAO,eAAe,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;KAC3C;IAED,MAAM,QAAQ,CAAC,+CAA+C,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAC7E,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfSubmitOrder } from '@yuants/data-order';\nimport { decodePath, newError } from '@yuants/utils';\nimport { isApiError } from '../../api/client';\nimport { ICredential, postSpotOrder, postUmOrder } from '../../api/private-api';\nimport {\n decodeFutureSymbol,\n decodeSpotSymbol,\n deriveClientOrderId,\n mapOrderDirectionToPositionSide,\n mapOrderDirectionToSide,\n mapOrderTypeToOrdType,\n} from './order-utils';\n\nconst submitUnifiedOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const symbol = decodeFutureSymbol(order.product_id);\n if (!order.volume) {\n throw new Error('Binance submitOrder requires order.volume to be set');\n }\n const side = mapOrderDirectionToSide(order.order_direction);\n const positionSide = mapOrderDirectionToPositionSide(order.order_direction);\n const type = mapOrderTypeToOrdType(order.order_type);\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n const reduceOnly =\n order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'true' : undefined;\n\n const res = await postUmOrder(credential, {\n symbol,\n side,\n positionSide,\n type,\n quantity: order.volume,\n price: order.price,\n timeInForce,\n reduceOnly,\n newClientOrderId: deriveClientOrderId(order),\n });\n if (isApiError(res)) {\n throw new Error(`Binance submit unified order failed: ${res.code} ${res.msg}`);\n }\n return { order_id: `${res.orderId}` };\n};\n\nconst submitSpotOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const symbol = decodeSpotSymbol(order.product_id);\n if (!order.volume) {\n throw new Error('Binance submitOrder requires order.volume to be set');\n }\n const side = mapOrderDirectionToSide(order.order_direction);\n const type = mapOrderTypeToOrdType(order.order_type);\n const timeInForce = order.order_type === 'MAKER' ? 'GTX' : order.order_type === 'LIMIT' ? 'GTC' : undefined;\n const params: Parameters<typeof postSpotOrder>[1] = {\n symbol,\n side,\n type,\n quantity: order.volume,\n newClientOrderId: deriveClientOrderId(order),\n };\n if (type === 'LIMIT') {\n if (order.price === undefined) {\n throw new Error('Binance spot LIMIT order requires price');\n }\n params.price = order.price;\n params.timeInForce = timeInForce;\n }\n if (order.price !== undefined && type === 'MARKET') {\n params.price = order.price;\n }\n const res = await postSpotOrder(credential, params);\n if (isApiError(res)) {\n throw new Error(`Binance submit spot order failed: ${res.code} ${res.msg}`);\n }\n return { order_id: `${res.orderId}` };\n};\n\nexport const submitOrder: IActionHandlerOfSubmitOrder<ICredential> = async (credential, order) => {\n const [, TYPE] = decodePath(order.product_id);\n\n if (TYPE === 'USDT-FUTURE') {\n return submitUnifiedOrder(credential, order);\n }\n if (TYPE === 'SPOT') {\n return submitSpotOrder(credential, order);\n }\n\n throw newError('BINANCE_SUBMIT_ORDER_UNSUPPORTED_PRODUCT_TYPE', { order });\n};\n"]}
|
package/lib/api/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAKA,aAAK,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEpD,aAAK,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC,CAAC;AAE3E,MAAM,WAAW,WAAW;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;CACb;AAED,eAAO,MAAM,UAAU,iDAC0E,CAAC;AA+ElG,eAAO,MAAM,aAAa,cAAe,UAAU,YAAY,MAAM,WAAW,aAAa,eACvD,CAAC;AAEvC,eAAO,MAAM,cAAc,kBACb,WAAW,UACf,UAAU,YACR,MAAM,WACP,aAAa,eAC6B,CAAC;AAEtD,eAAO,MAAM,oBAAoB,QAAO,WAOvC,CAAC"}
|
package/lib/api/client.js
CHANGED
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
3
|
exports.getDefaultCredential = exports.requestPrivate = exports.requestPublic = exports.isApiError = void 0;
|
|
7
4
|
const protocol_1 = require("@yuants/protocol");
|
|
8
5
|
const utils_1 = require("@yuants/utils");
|
|
9
|
-
// @ts-ignore
|
|
10
|
-
const crypto_js_1 = __importDefault(require("crypto-js"));
|
|
11
6
|
const MetricBinanceApiUsedWeight = protocol_1.GlobalPrometheusRegistry.gauge('binance_api_used_weight', '');
|
|
12
7
|
const isApiError = (value) => typeof (value === null || value === void 0 ? void 0 : value.code) === 'number' && typeof (value === null || value === void 0 ? void 0 : value.msg) === 'string';
|
|
13
8
|
exports.isApiError = isApiError;
|
|
@@ -42,7 +37,7 @@ const callApi = async (method, endpoint, params, credential) => {
|
|
|
42
37
|
let headers;
|
|
43
38
|
if (credential) {
|
|
44
39
|
const signData = url.search.slice(1);
|
|
45
|
-
const signature =
|
|
40
|
+
const signature = Buffer.from(await (0, utils_1.HmacSHA256)(new TextEncoder().encode(signData), new TextEncoder().encode(credential.secret_key))).toString('hex');
|
|
46
41
|
url.searchParams.set('signature', signature);
|
|
47
42
|
headers = {
|
|
48
43
|
'Content-Type': 'application/json;charset=utf-8',
|
package/lib/api/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":";;;AAAA,+CAA4D;AAC5D,yCAAuD;AAEvD,MAAM,0BAA0B,GAAG,mCAAwB,CAAC,KAAK,CAAC,yBAAyB,EAAE,EAAE,CAAC,CAAC;AAgB1F,MAAM,UAAU,GAAG,CAAI,KAAoB,EAAsB,EAAE,CACxE,OAAO,CAAC,KAAmB,aAAnB,KAAK,uBAAL,KAAK,CAAgB,IAAI,CAAA,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAmB,aAAnB,KAAK,uBAAL,KAAK,CAAgB,GAAG,C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PW,QAAA,oBAAoB,wBAO/B","sourcesContent":["import { GlobalPrometheusRegistry } from '@yuants/protocol';\nimport { formatTime, HmacSHA256 } from '@yuants/utils';\n\nconst MetricBinanceApiUsedWeight = GlobalPrometheusRegistry.gauge('binance_api_used_weight', '');\n\ntype HttpMethod = 'GET' | 'POST' | 'DELETE' | 'PUT';\n\ntype RequestParams = Record<string, string | number | boolean | undefined>;\n\nexport interface ICredential {\n access_key: string;\n secret_key: string;\n}\n\nexport interface IApiError {\n code: number;\n msg: string;\n}\n\nexport const isApiError = <T>(value: T | IApiError): value is IApiError =>\n typeof (value as IApiError)?.code === 'number' && typeof (value as IApiError)?.msg === 'string';\n\nconst appendParams = (url: URL, params?: RequestParams) => {\n if (!params) return;\n const entries = Object.entries(params).filter(([, value]) => value !== undefined);\n const timestampEntry = entries.find(([key]) => key === 'timestamp');\n const restEntries = entries.filter(([key]) => key !== 'timestamp');\n restEntries\n .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))\n .forEach(([key, value]) => {\n url.searchParams.set(key, String(value));\n });\n if (timestampEntry) {\n url.searchParams.set(timestampEntry[0], String(timestampEntry[1]));\n }\n};\n\nconst callApi = async <T>(\n method: HttpMethod,\n endpoint: string,\n params?: RequestParams,\n credential?: ICredential,\n): Promise<T> => {\n const url = new URL(endpoint);\n const normalizedParams: RequestParams = { ...params };\n if (credential) {\n if (normalizedParams.recvWindow === undefined) {\n // FYI https://developers.binance.com/docs/derivatives/usds-margined-futures/general-info#timing-security\n normalizedParams.recvWindow = 5000;\n }\n if (normalizedParams.timestamp === undefined) {\n normalizedParams.timestamp = Date.now();\n }\n }\n appendParams(url, normalizedParams);\n\n let headers: Record<string, string> | undefined;\n if (credential) {\n const signData = url.search.slice(1);\n\n const signature = Buffer.from(\n await HmacSHA256(new TextEncoder().encode(signData), new TextEncoder().encode(credential.secret_key)),\n ).toString('hex');\n url.searchParams.set('signature', signature);\n headers = {\n 'Content-Type': 'application/json;charset=utf-8',\n 'X-MBX-APIKEY': credential.access_key,\n };\n console.info(\n formatTime(Date.now()),\n method,\n url.href,\n JSON.stringify(headers),\n url.searchParams.toString(),\n signData,\n );\n } else {\n console.info(formatTime(Date.now()), method, url.href);\n }\n\n const res = await fetch(url.href, {\n method,\n headers,\n });\n const usedWeight1M = res.headers.get('x-mbx-used-weight-1m');\n console.info(\n formatTime(Date.now()),\n 'response',\n method,\n url.href,\n res.status,\n `usedWeight1M=${usedWeight1M ?? 'N/A'}`,\n );\n if (usedWeight1M) {\n MetricBinanceApiUsedWeight.set(+usedWeight1M);\n }\n return res.json() as Promise<T>;\n};\n\nexport const requestPublic = <T>(method: HttpMethod, endpoint: string, params?: RequestParams) =>\n callApi<T>(method, endpoint, params);\n\nexport const requestPrivate = <T>(\n credential: ICredential,\n method: HttpMethod,\n endpoint: string,\n params?: RequestParams,\n) => callApi<T>(method, endpoint, params, credential);\n\nexport const getDefaultCredential = (): ICredential => {\n const access_key = process.env.ACCESS_KEY;\n const secret_key = process.env.SECRET_KEY;\n if (!access_key || !secret_key) {\n throw new Error('Missing Binance credential: ACCESS_KEY and SECRET_KEY must be set');\n }\n return { access_key, secret_key };\n};\n"]}
|