@yuants/vendor-okx 0.19.1 → 0.20.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.js +10 -0
- package/dist/api.js.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/loan-account.js +60 -0
- package/dist/loan-account.js.map +1 -0
- package/dist/quote.js +79 -11
- package/dist/quote.js.map +1 -1
- package/dist/trade.js +1 -0
- package/dist/trade.js.map +1 -1
- package/dist/websocket.js +6 -0
- package/dist/websocket.js.map +1 -1
- package/lib/api.d.ts +32 -0
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +10 -0
- package/lib/api.js.map +1 -1
- package/lib/index.d.ts +4 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +4 -2
- package/lib/index.js.map +1 -1
- package/lib/loan-account.d.ts +2 -0
- package/lib/loan-account.d.ts.map +1 -0
- package/lib/loan-account.js +62 -0
- package/lib/loan-account.js.map +1 -0
- package/lib/quote.d.ts +3 -22
- package/lib/quote.d.ts.map +1 -1
- package/lib/quote.js +79 -11
- package/lib/quote.js.map +1 -1
- package/lib/trade.js +1 -0
- package/lib/trade.js.map +1 -1
- package/lib/websocket.d.ts.map +1 -1
- package/lib/websocket.js +6 -0
- package/lib/websocket.js.map +1 -1
- package/package.json +1 -1
- package/temp/image-tag +1 -1
- package/temp/package-deps.json +9 -8
package/dist/api.js
CHANGED
@@ -397,6 +397,16 @@ export class OkxClient {
|
|
397
397
|
* https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-index-tickers
|
398
398
|
*/
|
399
399
|
this.getMarketIndexTicker = (params) => this.request('GET', '/api/v5/market/index-tickers', params);
|
400
|
+
/**
|
401
|
+
* GET / 借贷信息
|
402
|
+
* 限速:5次/2s
|
403
|
+
* 限速规则:User ID
|
404
|
+
* 权限:读取
|
405
|
+
* HTTP请求
|
406
|
+
*
|
407
|
+
* https://www.okx.com/docs-v5/zh/#financial-product-flexible-loan-get-loan-info
|
408
|
+
*/
|
409
|
+
this.getFlexibleLoanInfo = () => this.request('GET', '/api/v5/finance/flexible-loan/loan-info');
|
400
410
|
/**
|
401
411
|
* 账单流水查询(近七天)
|
402
412
|
*
|
package/dist/api.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,aAAa;AACb,OAAO,QAAQ,MAAM,WAAW,CAAC;AAEjC;;GAEG;AACH,MAAM,OAAO,SAAS;IAEpB,YACS,MAMN;QANM,WAAM,GAAN,MAAM,CAMZ;QARH,WAAM,GAAG,IAAI,CAAC;QAmDd;;;;;;;;;WASG;QACH,qBAAgB,GAAG,CAAC,MAInB,EAqBE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,wBAAwB,EAAE,MAAM,CAAC,CAAC;QAE5D;;;;;;;;;WASG;QACH,sBAAiB,GAAG,CAAC,MAEpB,EAaE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,+BAA+B,EAAE,MAAM,CAAC,CAAC;QAEnE;;;;;;;;;WASG;QACH,oBAAe,GAAG,CAAC,MAKlB,EAUE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,8BAA8B,EAAE,MAAM,CAAC,CAAC;QAElE;;;;;;;;WAQG;QACH,qBAAgB,GAAG,GAyBhB,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC;QAEpD;;;;;;;WAOG;QACH,6BAAwB,GAAG,GAiBxB,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,yCAAyC,CAAC,CAAC;QAErE;;;;;;;;;WASG;QACH,mBAAc,GAAG,CAAC,MAKjB,EAmCE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,4B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CAAC,IAAI,EAAE,CAAC;IACpB,CAAC;CAy4CF;AAgCD,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IAClC,IAAI,EAAE;QACJ,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;KACpC;CACF,CAAC,CAAC","sourcesContent":["import { formatTime } from '@yuants/utils';\n// @ts-ignore\nimport CryptoJS from 'crypto-js';\n\n/**\n * API v5: https://www.okx.com/docs-v5/#overview\n */\nexport class OkxClient {\n noAuth = true;\n constructor(\n public config: {\n auth: {\n public_key: string;\n secret_key: string;\n passphrase: string;\n };\n },\n ) {\n if (config.auth.public_key && config.auth.secret_key && config.auth.passphrase) {\n this.noAuth = false;\n }\n }\n\n async request(method: string, path: string, params?: any) {\n const url = new URL('https://www.okx.com');\n url.pathname = path;\n if (method === 'GET') {\n for (const key in params) {\n url.searchParams.set(key, params[key]);\n }\n }\n if (this.noAuth) {\n console.info(formatTime(Date.now()), method, url.href);\n const res = await fetch(url.href, { method });\n return res.json();\n }\n const timestamp = formatTime(Date.now(), 'UTC').replace(' ', 'T');\n const secret_key = this.config.auth.secret_key;\n const body = method === 'GET' ? '' : JSON.stringify(params);\n const signData = timestamp + method + url.pathname + url.search + body;\n const str = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(signData, secret_key));\n\n const headers = {\n 'Content-Type': 'application/json',\n 'OK-ACCESS-KEY': this.config.auth.public_key!,\n 'OK-ACCESS-SIGN': str,\n 'OK-ACCESS-TIMESTAMP': timestamp,\n 'OK-ACCESS-PASSPHRASE': this.config.auth.passphrase,\n };\n\n console.info(formatTime(Date.now()), method, url.href, JSON.stringify(headers), body, signData);\n const res = await fetch(url.href, {\n method,\n headers,\n body: body || undefined,\n });\n return res.json();\n }\n\n /**\n * 获取所有产品行情信息\n *\n * 获取产品行情信息\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-tickers\n */\n getMarketTickers = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n last: string;\n lastSz: string;\n askPx: string;\n askSz: string;\n bidPx: string;\n bidSz: string;\n open24h: string;\n high24h: string;\n low24h: string;\n volCcy24h: string;\n vol24h: string;\n sodUtc0: string;\n sodUtc8: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/market/tickers', params);\n\n /**\n * 获取账户资产估值\n *\n * 查看账户资产估值\n *\n * 限速:1次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-account-asset-valuation\n */\n getAssetValuation = (params?: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n details: {\n classic: string;\n earn: string;\n funding: string;\n trading: string;\n };\n totalBal: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/asset/asset-valuation', params);\n\n /**\n * 获取持仓总量\n *\n * 查询单个交易产品的市场的持仓总量\n *\n * 限速:20次/2s\n * 限速规则:IP + instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-open-interest\n */\n getOpenInterest = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n instId: string;\n oi: string;\n oiCcy: string;\n ts: string;\n }[];\n }> => this.request('GET', '/api/v5/public/open-interest', params);\n\n /**\n * 查看账户配置\n * 查看当前账户的配置信息。\n *\n * 限速:5次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-account-configuration\n */\n getAccountConfig = (): Promise<{\n code: string;\n data: Array<{\n acctLv: string;\n autoLoan: boolean;\n ctIsoMode: string;\n greeksType: string;\n level: string;\n levelTmp: string;\n mgnIsoMode: string;\n posMode: string;\n spotOffsetType: string;\n uid: string;\n label: string;\n roleType: string;\n traderInsts: any[];\n spotRoleType: string;\n spotTraderInsts: any[];\n opAuth: string;\n kycLv: string;\n ip: string;\n perm: string;\n mainUid: string;\n }>;\n msg: string;\n }> => this.request('GET', '/api/v5/account/config');\n\n /**\n * 获取市场借币杠杆利率和借币限额\n *\n * 限速:2次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-interest-rate-and-loan-quota\n */\n getInterestRateLoanQuota = (): Promise<{\n code: string;\n data?: Array<{\n basic: Array<{\n ccy: string;\n rate: string;\n quota: string;\n }>;\n vip: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n regular: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n }>;\n }> => this.request('GET', '/api/v5/public/interest-rate-loan-quota');\n\n /**\n * 获取交易产品基础信息\n *\n * 获取所有可交易产品的信息列表。\n *\n * 限速:20次/2s\n * 限速规则:IP +instType\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-instruments\n */\n getInstruments = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n alias: string;\n baseCcy: string;\n category: string;\n ctMult: string;\n ctType: string;\n ctVal: string;\n ctValCcy: string;\n expTime: string;\n instFamily: string;\n instId: string;\n instType: string;\n lever: string;\n listTime: string;\n lotSz: string;\n maxIcebergSz: string;\n maxLmtAmt: string;\n maxLmtSz: string;\n maxMktAmt: string;\n maxMktSz: string;\n maxStopSz: string;\n maxTriggerSz: string;\n maxTwapSz: string;\n minSz: string;\n optType: string;\n quoteCcy: string;\n settleCcy: string;\n state: string;\n stk: string;\n tickSz: string;\n uly: string;\n }>;\n }> => this.request('GET', '/api/v5/public/instruments', params);\n\n /**\n * 获取永续合约当前资金费率\n * 获取当前资金费率\n *\n * 限速:20次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate\n */\n getFundingRate = (params: {\n instId: string;\n }): Promise<{\n code: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n maxFundingRate: string;\n minFundingRate: string;\n nextFundingRate: string;\n nextFundingTime: string;\n premium: string;\n settFundingRate: string;\n settState: string;\n ts: string;\n }>;\n msg: string;\n }> => this.request('GET', '/api/v5/public/funding-rate', params);\n\n /**\n * 获取永续合约历史资金费率\n *\n * 获取最近3个月的历史资金费率\n *\n * 限速:10次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate-history\n */\n getFundingRateHistory = (params: {\n instId: string;\n before?: string;\n after?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n realizedRate: string;\n }>;\n }> => this.request('GET', '/api/v5/public/funding-rate-history', params);\n\n /**\n * 获取标记价格历史K线数据\n *\n * 获取最近几年的标记价格K线数据\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-mark-price-candlesticks-history\n */\n getHistoryMarkPriceCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<[ts: string, o: string, h: string, l: string, c: string, confirm: string]>;\n }> => this.request('GET', '/api/v5/market/history-mark-price-candles', params);\n\n /**\n * GET / 获取交易产品历史K线数据\n *\n * 获取最近几年的历史k线数据(1s k线支持查询最近3个月的数据)\n *\n * 限速:20次/2s\n *\n * 限速规则:IP\n *\n * 期权不支持 1s K线, 其他业务线 (币币, 杠杆, 交割和永续)支持\n */\n getHistoryCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<\n [\n ts: string,\n o: string,\n h: string,\n l: string,\n c: string,\n vol: string,\n volCcy: string,\n volCcyQuote: string,\n confirm: string,\n ]\n >;\n }> => this.request('GET', '/api/v5/market/history-candles', params);\n\n /**\n * 获取余币宝余额\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-saving-balance\n */\n getFinanceSavingsBalance = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n earnings: string;\n redemptAmt: string;\n rate: string;\n ccy: string;\n amt: string;\n loanAmt: string;\n pendingAmt: string;\n }[];\n }> => this.request('GET', '/api/v5/finance/savings/balance', params);\n\n /**\n * 余币宝申购/赎回\n *\n * 仅资金账户中的资产支持余币宝申购。\n *\n * 限速:6次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-post-savings-purchase-redemption\n */\n postFinanceSavingsPurchaseRedempt = (params: {\n ccy: string;\n amt: string;\n side: string;\n rate: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n amt: string;\n side: string;\n rate: string;\n }[];\n }> => this.request('POST', '/api/v5/finance/savings/purchase-redempt', params);\n\n /**\n * GET / 获取市场借贷历史(公共)\n *\n * 公共接口无须鉴权\n *\n * 返回2021年12月14日后的记录\n *\n * 限速:6次/s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-public-borrow-history-public\n */\n getLendingRateHistory = (params: {\n ccy?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n ccy: string;\n amt: string;\n rate: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/finance/savings/lending-rate-history', params);\n\n /**\n * 提币\n *\n * 用户提币。普通子账户不支持提币。\n *\n * API只能提币到免认证地址/账户上,通过 WEB/APP 可以设置免认证地址。\n *\n * 关于标签:某些币种如XRP充币时同时需要一个充值地址和标签(又名memo/payment_id),标签是一种保证您的充币地址唯一性的数字串,与充币地址成对出现并一一对应。请您务必遵守正确的充值步骤,在提币时输入完整信息,否则将面临丢失币的风险!\n * 对于有标签的币种,如果是OKX用户间的提币,请走内部转账不要走链上提币。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-withdrawal\n */\n postAssetWithdrawal = (params: {\n amt: string;\n fee: string;\n dest: string;\n ccy: string;\n chain?: string;\n toAddr: string;\n clientId?: string;\n rcvrInfo?: {\n walletType: string;\n exchId: string;\n rcvrFirstName: string;\n rcvrLastName: string;\n };\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n amt: string;\n wdId: string;\n ccy: string;\n clientId: string;\n chain: string;\n }>;\n }> => this.request('POST', '/api/v5/asset/withdrawal', params);\n\n /**\n * 获取充值地址信息\n *\n * 获取各个币种的充值地址,包括曾使用过的老地址。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-deposit-address\n */\n getAssetDepositAddress = (params: {\n ccy: string;\n }): Promise<{\n code: string;\n data: {\n chain: string;\n ctAddr: string;\n ccy: string;\n to: string;\n addr: string;\n verifiedName: string;\n selected: boolean;\n }[];\n msg: string;\n }> => this.request('GET', '/api/v5/asset/deposit-address', params);\n\n /**\n * 获取提币记录\n *\n * 根据币种,提币状态,时间范围获取提币记录,按照时间倒序排列,默认返回100条数据。\n * 支持Websocket订阅,参考 提币信息频道。\n *\n * 限速:6 次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-withdrawal-history\n */\n getAssetWithdrawalHistory = (params: {\n ccy?: string;\n wdId?: string;\n clientId?: string;\n txId?: string;\n type?: string;\n state?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n chain: string;\n fee: string;\n feeCcy: string;\n ccy: string;\n clientId: string;\n amt: string;\n txId: string;\n from: string;\n areaCodeFrom: string;\n to: string;\n areaCodeTo: string;\n state: string;\n ts: string;\n nonTradableAsset: boolean;\n wdId: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/withdrawal-history', params);\n\n /**\n * 获取充值记录\n *\n * 根据币种,充值状态,时间范围获取充值记录,按照时间倒序排列,默认返回 100 条数据。\n * 支持Websocket订阅,参考 充值信息频道。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-deposit-history\n */\n getAssetDepositHistory = (params: {\n ccy?: string;\n depId?: string;\n state?: string;\n fromWdId?: string;\n txId?: string;\n type?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n actualDepBlkConfirm: string;\n amt: string;\n areaCodeFrom: string;\n ccy: string;\n chain: string;\n depId: string;\n from: string;\n fromWdId: string;\n state: string;\n to: string;\n ts: string;\n txId: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/deposit-history', params);\n\n /**\n * 获取资金账户余额\n *\n * 获取资金账户所有资产列表,查询各币种的余额、冻结和可用等信息。\n *\n * 只返回余额大于0的币资产信息。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-balance\n */\n getAssetBalances = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n availBal: string;\n bal: string;\n ccy: string;\n frozenBal: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/balances', params);\n\n /**\n * 资金划转\n *\n * 调用时,API Key 需要有交易权限。\n *\n * 支持母账户的资金账户划转到交易账户,母账户到子账户的资金账户和交易账户划转。\n *\n * 子账户默认可转出至母账户,划转到同一母账户下的其他子账户,需要先调用 设置子账户主动转出权限 接口进行授权。\n *\n * 请求失败不代表划转失败,建议以获取资金划转状态接口返回的状态为准。\n *\n * 限速:2 次/s\n * 限速规则:UserID + Currency\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-funds-transfer\n */\n postAssetTransfer = (params: {\n ccy: string;\n type?: string;\n amt: string;\n from: string;\n to: string;\n subAcct?: string;\n loanTrans?: boolean;\n omitPosRisk?: string;\n clientId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n transId: string;\n ccy: string;\n clientId: string;\n from: string;\n amt: string;\n to: string;\n }[];\n }> => this.request('POST', '/api/v5/asset/transfer', params);\n\n /**\n * 查看账户余额\n *\n * 获取交易账户中资金余额信息。\n *\n * 免息额度和折算率都是公共数据,不在账户接口内展示\n *\n * 限速:10次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-balance\n */\n getAccountBalance = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n data: {\n adjEq: string;\n borrowFroz: string;\n details: {\n availBal: string;\n availEq: string;\n borrowFroz: string;\n cashBal: string;\n ccy: string;\n crossLiab: string;\n disEq: string;\n eq: string;\n eqUsd: string;\n fixedBal: string;\n frozenBal: string;\n imr: string;\n interest: string;\n isoEq: string;\n isoLiab: string;\n isoUpl: string;\n liab: string;\n maxLoan: string;\n mgnRatio: string;\n mmr: string;\n notionalLever: string;\n ordFrozen: string;\n rewardBal: string;\n spotInUseAmt: string;\n spotIsoBal: string;\n stgyEq: string;\n twap: string;\n uTime: string;\n upl: string;\n uplLiab: string;\n openAvgPx: string;\n spotUpl: string;\n accAvgPx: string;\n totalPnl: string;\n spotBal: string;\n }[];\n imr: string;\n isoEq: string;\n mgnRatio: string;\n mmr: string;\n notionalUsd: string;\n ordFroz: string;\n totalEq: string;\n uTime: string;\n upl: string;\n }[];\n msg: string;\n }> => this.request('GET', '/api/v5/account/balance', params);\n\n /**\n * 查看持仓信息\n *\n * 获取该账户下拥有实际持仓的信息。账户为买卖模式会显示净持仓(net),账户为开平仓模式下会分别返回开多(long)或开空(short)的仓位。按照仓位创建时间倒序排列。\n *\n * 如果该 instId 拥有过仓位且当前持仓量为0,传 instId 时,如果当前存在有效的posId,会返回仓位信息,如果当前不存在有效的 posId 时,不会返回仓位信息;不传 instId 时,仓位信息不返回。\n *\n * 逐仓交易设置中,如果设置为自主划转模式,逐仓转入保证金后,会生成一个持仓量为0的仓位\n *\n * 限速:10次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-positions\n */\n getAccountPositions = (params: {\n instType?: string;\n instId?: string;\n posId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n adl: string;\n availPos: string;\n avgPx: string;\n cTime: string;\n ccy: string;\n deltaBS: string;\n deltaPA: string;\n gammaBS: string;\n gammaPA: string;\n imr: string;\n instId: string;\n instType: string;\n interest: string;\n idxPx: string;\n last: string;\n usdPx: string;\n bePx: string;\n lever: string;\n liab: string;\n liabCcy: string;\n liqPx: string;\n markPx: string;\n margin: string;\n mgnMode: string;\n mgnRatio: string;\n mmr: string;\n notionalUsd: string;\n optVal: string;\n pTime: string;\n pos: string;\n posCcy: string;\n posId: string;\n posSide: string;\n spotInUseAmt: string;\n spotInUseCcy: string;\n thetaBS: string;\n thetaPA: string;\n tradeId: string;\n bizRefId: string;\n bizRefType: string;\n quoteBal: string;\n baseBal: string;\n baseBorrowed: string;\n baseInterest: string;\n quoteBorrowed: string;\n quoteInterest: string;\n uTime: string;\n upl: string;\n uplLastPx: string;\n uplRatio: string;\n uplRatioLastPx: string;\n vegaBS: string;\n vegaPA: string;\n realizedPnl: string;\n pnl: string;\n fee: string;\n fundingFee: string;\n liqPenalty: string;\n closeOrderAlgo: {\n algoId: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n closeFraction: string;\n }[];\n }[];\n }> => this.request('GET', '/api/v5/account/positions', params);\n\n /**\n * 赚币\n * GET / 查看项目\n *\n * 限速:3次/s\n * 限速规则:UserID\n */\n getFinanceStakingDeFiOffers = (params: {\n productId?: string;\n protocolType?: string;\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n productId: string;\n protocol: string;\n protocolType: string;\n term: string;\n apy: string;\n earlyRedeem: boolean;\n investData: {\n ccy: string;\n bal: string;\n minAmt: string;\n maxAmt: string;\n }[];\n earningData: {\n ccy: string;\n earningType: string;\n }[];\n state: string;\n earningCcy?: string[];\n }[];\n }> => this.request('GET', '/api/v5/finance/staking-defi/offers', params);\n\n /**\n * 赚币\n * GET / 查看活跃订单\n *\n * 限速:3次/s\n * 限速规则:UserID\n */\n getFinanceStakingDeFiOrdersActive = (params: {\n productId?: string;\n protocolType?: string;\n ccy?: string;\n state?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ordId: string;\n state: string;\n ccy: string;\n protocol: string;\n protocolType: string;\n term: string;\n apy: string;\n investData: {\n ccy: string;\n amt: string;\n minAmt?: string;\n maxAmt?: string;\n }[];\n earningData: {\n ccy: string;\n earningType: string;\n earnings: string;\n }[];\n purchasedTime: string;\n estSettlementTime: string;\n cancelRedemptionDeadline: string;\n tag: string;\n earningCcy?: string[];\n }[];\n }> => this.request('GET', '/api/v5/finance/staking-defi/orders-active', params);\n\n /**\n * 下单\n *\n * 只有当您的账户有足够的资金才能下单。\n *\n * 限速:60次/2s\n *\n * 跟单交易带单产品的限速:4次/2s\n *\n * 限速规则(期权以外):UserID + Instrument ID\n *\n * 限速规则(只限期权):UserID + Instrument Family\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-place-order\n */\n postTradeOrder = (params: {\n instId: string;\n tdMode: string;\n ccy?: string;\n clOrdId?: string;\n tag?: string;\n side: string;\n posSide?: string;\n ordType: string;\n sz: string;\n px?: string;\n pxUsd?: string;\n pxVol?: string;\n reduceOnly?: string;\n tgtCcy?: string;\n banAmend?: string;\n quickMgnType?: string;\n stpId?: string;\n stpMode?: string;\n attachAlgoOrds?: Array<{\n attachAlgoClOrdId?: string;\n tpTriggerPx?: string;\n tpOrdPx?: string;\n tpOrdKind?: string;\n slTriggerPx?: string;\n slOrdPx?: string;\n tpTriggerPxType?: string;\n slTriggerPxType?: string;\n sz?: string;\n amendPxOnTriggerType?: string;\n }>;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n tag: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/order', params);\n\n /**\n * 修改订单\n *\n * 修改当前未成交的挂单\n *\n * 限速:60次/2s\n *\n * 跟单交易带单员带单产品的限速:4个/2s\n *\n * 限速规则:User ID + Instrument ID\n *\n * 权限:交易\n *\n * 该接口限速同时受到 子账户限速 及 基于成交比率的子账户限速 限速规则的影响。\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-amend-order\n */\n postTradeAmendOrder = (params: {\n instId: string;\n cxIOnFail?: boolean;\n ordId?: string;\n clOrdId?: string;\n reqId?: string;\n newSz?: string;\n newPx?: string;\n newPxUsd?: string;\n newPxVol?: string;\n attachAlgoOrds?: Array<{\n attachAlgoId?: string;\n attachAlgoClOrdId?: string;\n newTpTriggerPx?: string;\n newTpOrdPx?: string;\n newTpOrdKind?: string;\n newSlTriggerPx?: string;\n newSlOrdPx?: string;\n newTpTriggerPxType?: string;\n newSlTriggerPxType?: string;\n sz?: string;\n amendPxOnTriggerType?: string;\n }>;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n ts: string;\n reqId: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/amend-order', params);\n\n /**\n * 获取未成交订单列表\n *\n * 获取当前账户下所有未成交订单信息\n *\n * 限速:60次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-get-order-list\n */\n getTradeOrdersPending = (params: {\n instType?: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n ordType?: string;\n state?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n accFillSz: string;\n avgPx: string;\n cTime: string;\n category: string;\n ccy: string;\n clOrdId: string;\n fee: string;\n feeCcy: string;\n fillPx: string;\n fillSz: string;\n fillTime: string;\n instId: string;\n instType: string;\n lever: string;\n ordId: string;\n ordType: string;\n pnl: string;\n posSide: string;\n px: string;\n pxUsd: string;\n pxVol: string;\n pxType: string;\n rebate: string;\n rebateCcy: string;\n side: string;\n attachAlgoClOrdId: string;\n slOrdPx: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n attachAlgoOrds: any[];\n source: string;\n state: string;\n stpId: string;\n stpMode: string;\n sz: string;\n tag: string;\n tdMode: string;\n tgtCcy: string;\n tpOrdPx: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n tradeId: string;\n reduceOnly: string;\n quickMgnType: string;\n algoClOrdId: string;\n algoId: string;\n isTpLimit: string;\n uTime: string;\n }[];\n }> => this.request('GET', '/api/v5/trade/orders-pending', params);\n\n /**\n * 获取历史订单记录(近七天)\n *\n * 获取最近7天挂单,且完成的订单数据,包括7天以前挂单,但近7天才成交的订单数据。按照订单创建时间倒序排序。\n *\n * 已经撤销的未成交单 只保留2小时\n * 限速:40次/2s\n * 限速规则:User ID\n */\n getTradeOrdersHistory = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n ordType?: string;\n state?: string;\n category?: string;\n after?: string;\n before?: string;\n begin?: string;\n end?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n tgtCcy: string;\n ccy: string;\n ordId: string;\n clOrdId: string;\n tag: string;\n px: string;\n pxUsd: string;\n pxVol: string;\n pxType: string;\n sz: string;\n ordType: string;\n side: string;\n posSide: string;\n tdMode: string;\n accFillSz: string;\n fillPx: string;\n tradeId: string;\n fillSz: string;\n fillTime: string;\n avgPx: string;\n state: string;\n lever: string;\n attachAlgoClOrdId: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n tpOrdPx: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n slOrdPx: string;\n attachAlgoOrds: any[];\n linkedAlgoOrd: any[];\n stpId: string;\n stpMode: string;\n feeCcy: string;\n fee: string;\n rebateCcy: string;\n source: string;\n rebate: string;\n pnl: string;\n category: string;\n reduceOnly: string;\n cancelSource: string;\n cancelSourceReason: string;\n algoClOrdId: string;\n algoId: string;\n isTpLimit: string;\n uTime: string;\n cTime: string;\n tradeQuoteCcy: string;\n }>;\n }> => this.request('GET', '/api/v5/trade/orders-history', params);\n\n /**\n * 撤单\n *\n * 撤销之前下的未完成订单。\n *\n * 限速:60次/2s\n *\n * 限速规则(期权以外):UserID + Instrument ID\n *\n * 限速规则(只限期权):UserID + Instrument Family\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-cancel-order\n */\n postTradeCancelOrder = (params: {\n instId: string;\n ordId?: string;\n clOrdId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/cancel-order', params);\n\n /**\n * 查看子账户列表\n *\n * 仅适用于母账户。\n *\n * 限速:2次/2s\n *\n * 限速规则:UserID\n */\n getSubAccountList = (params?: {\n enable?: string;\n subAct?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n data: {\n type: string;\n enable: string;\n subAcct: string;\n uid: string;\n label: string;\n mobile: string;\n gAuth: boolean;\n frozenFunc: string[];\n canTransOut: boolean;\n ts: string;\n }[];\n code: string;\n msg: string;\n }> => this.request('GET', '/api/v5/users/subaccount/list', params);\n\n /**\n * 设置子账户主动转出权限\n *\n * 设置子账户转出权限(仅适用于母账户),默认可转出至母账户。\n *\n * 限速:1次/s\n *\n * 限速规则:UserID\n */\n postSetSubAccountTransferOut = (params: {\n subAcct: string;\n canTransOut: boolean;\n }): Promise<{\n subAcct: string;\n canTransOut: boolean;\n }> => this.request('POST', '/api/v5/users/subaccount/set-transfer-out', params);\n\n /**\n * 获取资金划转状态\n *\n * 获取最近2个星期内的资金划转状态数据\n *\n * 限速:10 次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-funds-transfer-state\n */\n getAssetTransferState = (params: {\n transId?: string;\n clientId?: string;\n type?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n transId: string;\n clientId: string;\n ccy: string;\n amt: string;\n type: string;\n from: string;\n to: string;\n subAcct: string;\n // success | pending | failed\n state: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/transfer-state', params);\n\n /**\n * 获取币种列表\n *\n * 获取当前用户KYC实体支持的币种列表。\n *\n * 限速:6 次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-currencies\n */\n getAssetCurrencies = (params?: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n name: string;\n chain: string;\n canWd: boolean;\n canInternal: boolean;\n minWd: string;\n maxWd: string;\n wdTickSz: string;\n wdQuota: string;\n usedWdQuota: string;\n minFee: string;\n maxFee: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/currencies', params);\n\n /**\n * 获取指数行情数据\n *\n *\n * 限速:20 次/2s\n *\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-index-tickers\n */\n getMarketIndexTicker = (params?: {\n quoteCcy?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instId: string;\n idxPx: string;\n high24h: string;\n sodUtc0: string;\n open24h: string;\n low24h: string;\n sodUtc8: string;\n ts: string;\n }[];\n }> => this.request('GET', '/api/v5/market/index-tickers', params);\n\n /**\n * 账单流水查询(近七天)\n *\n *\n * 限速:5次/s\n *\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-bills-details-last-7-days\n */\n getAccountBills = (params?: {\n instType?: string;\n instId?: string;\n ccy?: string;\n mgnMode?: 'isolated' | 'cross';\n ctType?: 'linear' | 'inverse';\n type?: AccountBillType;\n subType?: string;\n after?: string; //请求此id之前(更旧的数据)的分页内容,传的值为对应接口的billId\n before?: string; //请求此id之后(更新的数据)的分页内容,传的值为对应接口的billId\n begin?: string; //筛选的开始时间戳 ts,Unix 时间戳为毫秒数格式,如 1597026383085\n end?: string;\n limit?: string; //分页返回的结果集数量,最大为100,不填默认返回100条\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n billId: string;\n type: string;\n subType: string;\n ts: string;\n balChg: string;\n posBalChg: string;\n bal: string;\n posBal: string;\n sz: string;\n px: string;\n ccy: string;\n pnl: string;\n fee: string;\n mgnMode: 'isolated' | 'cross' | 'cash' | '';\n instId: string;\n ordId: string;\n execType: string;\n from: string;\n to: string;\n notes: string;\n interest: string;\n tag: string;\n fillTime: string;\n tradeId: string;\n clOrdId: string;\n fillIdxPx: string;\n fillMarkPx: string;\n fillPxVol: string;\n fillPxUsd: string;\n fillMarkVol: string;\n fillFwdPx: string;\n }[];\n }> => this.request('GET', '/api/v5/account/bills', params);\n\n /**\n * 账单流水查询(近三个月)\n *\n *\n * 限速:5次/2s\n *\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-bills-details-last-3-months\n */\n getAccountBillsArchive = (params?: {\n instType?: string;\n instId?: string;\n ccy?: string;\n mgnMode?: 'isolated' | 'cross';\n ctType?: 'linear' | 'inverse';\n type?: AccountBillType;\n subType?: string;\n after?: string; //请求此id之前(更旧的数据)的分页内容,传的值为对应接口的billId\n before?: string; //请求此id之后(更新的数据)的分页内容,传的值为对应接口的billId\n begin?: string; //筛选的开始时间戳 ts,Unix 时间戳为毫秒数格式,如 1597026383085\n end?: string;\n limit?: string; //分页返回的结果集数量,最大为100,不填默认返回100条\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n billId: string;\n type: string;\n subType: string;\n ts: string;\n balChg: string;\n posBalChg: string;\n bal: string;\n posBal: string;\n sz: string;\n px: string;\n ccy: string;\n pnl: string;\n fee: string;\n mgnMode: 'isolated' | 'cross' | 'cash' | '';\n instId: string;\n ordId: string;\n execType: string;\n from: string;\n to: string;\n notes: string;\n interest: string;\n tag: string;\n fillTime: string;\n tradeId: string;\n clOrdId: string;\n fillIdxPx: string;\n fillMarkPx: string;\n fillPxVol: string;\n fillPxUsd: string;\n fillMarkVol: string;\n fillFwdPx: string;\n }[];\n }> => this.request('GET', '/api/v5/account/bills-archive', params);\n}\n\ntype AccountBillType =\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | '8'\n | '9'\n | '10'\n | '11'\n | '12'\n | '13'\n | '14'\n | '15'\n | '16'\n | '22'\n | '24'\n | '26'\n | '27'\n | '28'\n | '29'\n | '30'\n | '32'\n | '33'\n | '34'\n | '250'\n | '251';\n\nexport const client = new OkxClient({\n auth: {\n public_key: process.env.ACCESS_KEY!,\n secret_key: process.env.SECRET_KEY!,\n passphrase: process.env.PASSPHRASE!,\n },\n});\n"]}
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,aAAa;AACb,OAAO,QAAQ,MAAM,WAAW,CAAC;AAEjC;;GAEG;AACH,MAAM,OAAO,SAAS;IAEpB,YACS,MAMN;QANM,WAAM,GAAN,MAAM,CAMZ;QARH,WAAM,GAAG,IAAI,CAAC;QAmDd;;;;;;;;;WASG;QACH,qBAAgB,GAAG,CAAC,MAInB,EAqBE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,wBAAwB,EAAE,MAAM,CAAC,CAAC;QAE5D;;;;;;;;;WASG;QACH,sBAAiB,GAAG,CAAC,MAEpB,EAaE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,+BAA+B,EAAE,MAAM,CAAC,CAAC;QAEnE;;;;;;;;;WASG;QACH,oBAAe,GAAG,CAAC,MAKlB,EAUE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,8BAA8B,EAAE,MAAM,CAAC,CAAC;QAElE;;;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AG;YACrB,qBAAqB,EAAE,SAAS;YAChC,sBAAsB,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU;SACpD,CAAC;QAEF,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;QAChG,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE;YAChC,MAAM;YACN,OAAO;YACP,IAAI,EAAE,IAAI,IAAI,SAAS;SACxB,CAAC,CAAC;QACH,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;IACpB,CAAC;CA06CF;AAgCD,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IAClC,IAAI,EAAE;QACJ,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;KACpC;CACF,CAAC,CAAC","sourcesContent":["import { formatTime } from '@yuants/utils';\n// @ts-ignore\nimport CryptoJS from 'crypto-js';\n\n/**\n * API v5: https://www.okx.com/docs-v5/#overview\n */\nexport class OkxClient {\n noAuth = true;\n constructor(\n public config: {\n auth: {\n public_key: string;\n secret_key: string;\n passphrase: string;\n };\n },\n ) {\n if (config.auth.public_key && config.auth.secret_key && config.auth.passphrase) {\n this.noAuth = false;\n }\n }\n\n async request(method: string, path: string, params?: any) {\n const url = new URL('https://www.okx.com');\n url.pathname = path;\n if (method === 'GET') {\n for (const key in params) {\n url.searchParams.set(key, params[key]);\n }\n }\n if (this.noAuth) {\n console.info(formatTime(Date.now()), method, url.href);\n const res = await fetch(url.href, { method });\n return res.json();\n }\n const timestamp = formatTime(Date.now(), 'UTC').replace(' ', 'T');\n const secret_key = this.config.auth.secret_key;\n const body = method === 'GET' ? '' : JSON.stringify(params);\n const signData = timestamp + method + url.pathname + url.search + body;\n const str = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(signData, secret_key));\n\n const headers = {\n 'Content-Type': 'application/json',\n 'OK-ACCESS-KEY': this.config.auth.public_key!,\n 'OK-ACCESS-SIGN': str,\n 'OK-ACCESS-TIMESTAMP': timestamp,\n 'OK-ACCESS-PASSPHRASE': this.config.auth.passphrase,\n };\n\n console.info(formatTime(Date.now()), method, url.href, JSON.stringify(headers), body, signData);\n const res = await fetch(url.href, {\n method,\n headers,\n body: body || undefined,\n });\n return res.json();\n }\n\n /**\n * 获取所有产品行情信息\n *\n * 获取产品行情信息\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-tickers\n */\n getMarketTickers = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n last: string;\n lastSz: string;\n askPx: string;\n askSz: string;\n bidPx: string;\n bidSz: string;\n open24h: string;\n high24h: string;\n low24h: string;\n volCcy24h: string;\n vol24h: string;\n sodUtc0: string;\n sodUtc8: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/market/tickers', params);\n\n /**\n * 获取账户资产估值\n *\n * 查看账户资产估值\n *\n * 限速:1次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-account-asset-valuation\n */\n getAssetValuation = (params?: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n details: {\n classic: string;\n earn: string;\n funding: string;\n trading: string;\n };\n totalBal: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/asset/asset-valuation', params);\n\n /**\n * 获取持仓总量\n *\n * 查询单个交易产品的市场的持仓总量\n *\n * 限速:20次/2s\n * 限速规则:IP + instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-open-interest\n */\n getOpenInterest = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n instId: string;\n oi: string;\n oiCcy: string;\n ts: string;\n }[];\n }> => this.request('GET', '/api/v5/public/open-interest', params);\n\n /**\n * 查看账户配置\n * 查看当前账户的配置信息。\n *\n * 限速:5次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-account-configuration\n */\n getAccountConfig = (): Promise<{\n code: string;\n data: Array<{\n acctLv: string;\n autoLoan: boolean;\n ctIsoMode: string;\n greeksType: string;\n level: string;\n levelTmp: string;\n mgnIsoMode: string;\n posMode: string;\n spotOffsetType: string;\n uid: string;\n label: string;\n roleType: string;\n traderInsts: any[];\n spotRoleType: string;\n spotTraderInsts: any[];\n opAuth: string;\n kycLv: string;\n ip: string;\n perm: string;\n mainUid: string;\n }>;\n msg: string;\n }> => this.request('GET', '/api/v5/account/config');\n\n /**\n * 获取市场借币杠杆利率和借币限额\n *\n * 限速:2次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-interest-rate-and-loan-quota\n */\n getInterestRateLoanQuota = (): Promise<{\n code: string;\n data?: Array<{\n basic: Array<{\n ccy: string;\n rate: string;\n quota: string;\n }>;\n vip: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n regular: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n }>;\n }> => this.request('GET', '/api/v5/public/interest-rate-loan-quota');\n\n /**\n * 获取交易产品基础信息\n *\n * 获取所有可交易产品的信息列表。\n *\n * 限速:20次/2s\n * 限速规则:IP +instType\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-instruments\n */\n getInstruments = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n alias: string;\n baseCcy: string;\n category: string;\n ctMult: string;\n ctType: string;\n ctVal: string;\n ctValCcy: string;\n expTime: string;\n instFamily: string;\n instId: string;\n instType: string;\n lever: string;\n listTime: string;\n lotSz: string;\n maxIcebergSz: string;\n maxLmtAmt: string;\n maxLmtSz: string;\n maxMktAmt: string;\n maxMktSz: string;\n maxStopSz: string;\n maxTriggerSz: string;\n maxTwapSz: string;\n minSz: string;\n optType: string;\n quoteCcy: string;\n settleCcy: string;\n state: string;\n stk: string;\n tickSz: string;\n uly: string;\n }>;\n }> => this.request('GET', '/api/v5/public/instruments', params);\n\n /**\n * 获取永续合约当前资金费率\n * 获取当前资金费率\n *\n * 限速:20次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate\n */\n getFundingRate = (params: {\n instId: string;\n }): Promise<{\n code: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n maxFundingRate: string;\n minFundingRate: string;\n nextFundingRate: string;\n nextFundingTime: string;\n premium: string;\n settFundingRate: string;\n settState: string;\n ts: string;\n }>;\n msg: string;\n }> => this.request('GET', '/api/v5/public/funding-rate', params);\n\n /**\n * 获取永续合约历史资金费率\n *\n * 获取最近3个月的历史资金费率\n *\n * 限速:10次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate-history\n */\n getFundingRateHistory = (params: {\n instId: string;\n before?: string;\n after?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n realizedRate: string;\n }>;\n }> => this.request('GET', '/api/v5/public/funding-rate-history', params);\n\n /**\n * 获取标记价格历史K线数据\n *\n * 获取最近几年的标记价格K线数据\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-mark-price-candlesticks-history\n */\n getHistoryMarkPriceCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<[ts: string, o: string, h: string, l: string, c: string, confirm: string]>;\n }> => this.request('GET', '/api/v5/market/history-mark-price-candles', params);\n\n /**\n * GET / 获取交易产品历史K线数据\n *\n * 获取最近几年的历史k线数据(1s k线支持查询最近3个月的数据)\n *\n * 限速:20次/2s\n *\n * 限速规则:IP\n *\n * 期权不支持 1s K线, 其他业务线 (币币, 杠杆, 交割和永续)支持\n */\n getHistoryCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<\n [\n ts: string,\n o: string,\n h: string,\n l: string,\n c: string,\n vol: string,\n volCcy: string,\n volCcyQuote: string,\n confirm: string,\n ]\n >;\n }> => this.request('GET', '/api/v5/market/history-candles', params);\n\n /**\n * 获取余币宝余额\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-saving-balance\n */\n getFinanceSavingsBalance = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n earnings: string;\n redemptAmt: string;\n rate: string;\n ccy: string;\n amt: string;\n loanAmt: string;\n pendingAmt: string;\n }[];\n }> => this.request('GET', '/api/v5/finance/savings/balance', params);\n\n /**\n * 余币宝申购/赎回\n *\n * 仅资金账户中的资产支持余币宝申购。\n *\n * 限速:6次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-post-savings-purchase-redemption\n */\n postFinanceSavingsPurchaseRedempt = (params: {\n ccy: string;\n amt: string;\n side: string;\n rate: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n amt: string;\n side: string;\n rate: string;\n }[];\n }> => this.request('POST', '/api/v5/finance/savings/purchase-redempt', params);\n\n /**\n * GET / 获取市场借贷历史(公共)\n *\n * 公共接口无须鉴权\n *\n * 返回2021年12月14日后的记录\n *\n * 限速:6次/s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-public-borrow-history-public\n */\n getLendingRateHistory = (params: {\n ccy?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n ccy: string;\n amt: string;\n rate: string;\n ts: string;\n }>;\n }> => this.request('GET', '/api/v5/finance/savings/lending-rate-history', params);\n\n /**\n * 提币\n *\n * 用户提币。普通子账户不支持提币。\n *\n * API只能提币到免认证地址/账户上,通过 WEB/APP 可以设置免认证地址。\n *\n * 关于标签:某些币种如XRP充币时同时需要一个充值地址和标签(又名memo/payment_id),标签是一种保证您的充币地址唯一性的数字串,与充币地址成对出现并一一对应。请您务必遵守正确的充值步骤,在提币时输入完整信息,否则将面临丢失币的风险!\n * 对于有标签的币种,如果是OKX用户间的提币,请走内部转账不要走链上提币。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-withdrawal\n */\n postAssetWithdrawal = (params: {\n amt: string;\n fee: string;\n dest: string;\n ccy: string;\n chain?: string;\n toAddr: string;\n clientId?: string;\n rcvrInfo?: {\n walletType: string;\n exchId: string;\n rcvrFirstName: string;\n rcvrLastName: string;\n };\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n amt: string;\n wdId: string;\n ccy: string;\n clientId: string;\n chain: string;\n }>;\n }> => this.request('POST', '/api/v5/asset/withdrawal', params);\n\n /**\n * 获取充值地址信息\n *\n * 获取各个币种的充值地址,包括曾使用过的老地址。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-deposit-address\n */\n getAssetDepositAddress = (params: {\n ccy: string;\n }): Promise<{\n code: string;\n data: {\n chain: string;\n ctAddr: string;\n ccy: string;\n to: string;\n addr: string;\n verifiedName: string;\n selected: boolean;\n }[];\n msg: string;\n }> => this.request('GET', '/api/v5/asset/deposit-address', params);\n\n /**\n * 获取提币记录\n *\n * 根据币种,提币状态,时间范围获取提币记录,按照时间倒序排列,默认返回100条数据。\n * 支持Websocket订阅,参考 提币信息频道。\n *\n * 限速:6 次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-withdrawal-history\n */\n getAssetWithdrawalHistory = (params: {\n ccy?: string;\n wdId?: string;\n clientId?: string;\n txId?: string;\n type?: string;\n state?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n chain: string;\n fee: string;\n feeCcy: string;\n ccy: string;\n clientId: string;\n amt: string;\n txId: string;\n from: string;\n areaCodeFrom: string;\n to: string;\n areaCodeTo: string;\n state: string;\n ts: string;\n nonTradableAsset: boolean;\n wdId: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/withdrawal-history', params);\n\n /**\n * 获取充值记录\n *\n * 根据币种,充值状态,时间范围获取充值记录,按照时间倒序排列,默认返回 100 条数据。\n * 支持Websocket订阅,参考 充值信息频道。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-deposit-history\n */\n getAssetDepositHistory = (params: {\n ccy?: string;\n depId?: string;\n state?: string;\n fromWdId?: string;\n txId?: string;\n type?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n actualDepBlkConfirm: string;\n amt: string;\n areaCodeFrom: string;\n ccy: string;\n chain: string;\n depId: string;\n from: string;\n fromWdId: string;\n state: string;\n to: string;\n ts: string;\n txId: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/deposit-history', params);\n\n /**\n * 获取资金账户余额\n *\n * 获取资金账户所有资产列表,查询各币种的余额、冻结和可用等信息。\n *\n * 只返回余额大于0的币资产信息。\n *\n * 限速:6次/s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-balance\n */\n getAssetBalances = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n availBal: string;\n bal: string;\n ccy: string;\n frozenBal: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/balances', params);\n\n /**\n * 资金划转\n *\n * 调用时,API Key 需要有交易权限。\n *\n * 支持母账户的资金账户划转到交易账户,母账户到子账户的资金账户和交易账户划转。\n *\n * 子账户默认可转出至母账户,划转到同一母账户下的其他子账户,需要先调用 设置子账户主动转出权限 接口进行授权。\n *\n * 请求失败不代表划转失败,建议以获取资金划转状态接口返回的状态为准。\n *\n * 限速:2 次/s\n * 限速规则:UserID + Currency\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-funds-transfer\n */\n postAssetTransfer = (params: {\n ccy: string;\n type?: string;\n amt: string;\n from: string;\n to: string;\n subAcct?: string;\n loanTrans?: boolean;\n omitPosRisk?: string;\n clientId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n transId: string;\n ccy: string;\n clientId: string;\n from: string;\n amt: string;\n to: string;\n }[];\n }> => this.request('POST', '/api/v5/asset/transfer', params);\n\n /**\n * 查看账户余额\n *\n * 获取交易账户中资金余额信息。\n *\n * 免息额度和折算率都是公共数据,不在账户接口内展示\n *\n * 限速:10次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-balance\n */\n getAccountBalance = (params: {\n ccy?: string;\n }): Promise<{\n code: string;\n data: {\n adjEq: string;\n borrowFroz: string;\n details: {\n availBal: string;\n availEq: string;\n borrowFroz: string;\n cashBal: string;\n ccy: string;\n crossLiab: string;\n disEq: string;\n eq: string;\n eqUsd: string;\n fixedBal: string;\n frozenBal: string;\n imr: string;\n interest: string;\n isoEq: string;\n isoLiab: string;\n isoUpl: string;\n liab: string;\n maxLoan: string;\n mgnRatio: string;\n mmr: string;\n notionalLever: string;\n ordFrozen: string;\n rewardBal: string;\n spotInUseAmt: string;\n spotIsoBal: string;\n stgyEq: string;\n twap: string;\n uTime: string;\n upl: string;\n uplLiab: string;\n openAvgPx: string;\n spotUpl: string;\n accAvgPx: string;\n totalPnl: string;\n spotBal: string;\n }[];\n imr: string;\n isoEq: string;\n mgnRatio: string;\n mmr: string;\n notionalUsd: string;\n ordFroz: string;\n totalEq: string;\n uTime: string;\n upl: string;\n }[];\n msg: string;\n }> => this.request('GET', '/api/v5/account/balance', params);\n\n /**\n * 查看持仓信息\n *\n * 获取该账户下拥有实际持仓的信息。账户为买卖模式会显示净持仓(net),账户为开平仓模式下会分别返回开多(long)或开空(short)的仓位。按照仓位创建时间倒序排列。\n *\n * 如果该 instId 拥有过仓位且当前持仓量为0,传 instId 时,如果当前存在有效的posId,会返回仓位信息,如果当前不存在有效的 posId 时,不会返回仓位信息;不传 instId 时,仓位信息不返回。\n *\n * 逐仓交易设置中,如果设置为自主划转模式,逐仓转入保证金后,会生成一个持仓量为0的仓位\n *\n * 限速:10次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-positions\n */\n getAccountPositions = (params: {\n instType?: string;\n instId?: string;\n posId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n adl: string;\n availPos: string;\n avgPx: string;\n cTime: string;\n ccy: string;\n deltaBS: string;\n deltaPA: string;\n gammaBS: string;\n gammaPA: string;\n imr: string;\n instId: string;\n instType: string;\n interest: string;\n idxPx: string;\n last: string;\n usdPx: string;\n bePx: string;\n lever: string;\n liab: string;\n liabCcy: string;\n liqPx: string;\n markPx: string;\n margin: string;\n mgnMode: string;\n mgnRatio: string;\n mmr: string;\n notionalUsd: string;\n optVal: string;\n pTime: string;\n pos: string;\n posCcy: string;\n posId: string;\n posSide: string;\n spotInUseAmt: string;\n spotInUseCcy: string;\n thetaBS: string;\n thetaPA: string;\n tradeId: string;\n bizRefId: string;\n bizRefType: string;\n quoteBal: string;\n baseBal: string;\n baseBorrowed: string;\n baseInterest: string;\n quoteBorrowed: string;\n quoteInterest: string;\n uTime: string;\n upl: string;\n uplLastPx: string;\n uplRatio: string;\n uplRatioLastPx: string;\n vegaBS: string;\n vegaPA: string;\n realizedPnl: string;\n pnl: string;\n fee: string;\n fundingFee: string;\n liqPenalty: string;\n closeOrderAlgo: {\n algoId: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n closeFraction: string;\n }[];\n }[];\n }> => this.request('GET', '/api/v5/account/positions', params);\n\n /**\n * 赚币\n * GET / 查看项目\n *\n * 限速:3次/s\n * 限速规则:UserID\n */\n getFinanceStakingDeFiOffers = (params: {\n productId?: string;\n protocolType?: string;\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n productId: string;\n protocol: string;\n protocolType: string;\n term: string;\n apy: string;\n earlyRedeem: boolean;\n investData: {\n ccy: string;\n bal: string;\n minAmt: string;\n maxAmt: string;\n }[];\n earningData: {\n ccy: string;\n earningType: string;\n }[];\n state: string;\n earningCcy?: string[];\n }[];\n }> => this.request('GET', '/api/v5/finance/staking-defi/offers', params);\n\n /**\n * 赚币\n * GET / 查看活跃订单\n *\n * 限速:3次/s\n * 限速规则:UserID\n */\n getFinanceStakingDeFiOrdersActive = (params: {\n productId?: string;\n protocolType?: string;\n ccy?: string;\n state?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ordId: string;\n state: string;\n ccy: string;\n protocol: string;\n protocolType: string;\n term: string;\n apy: string;\n investData: {\n ccy: string;\n amt: string;\n minAmt?: string;\n maxAmt?: string;\n }[];\n earningData: {\n ccy: string;\n earningType: string;\n earnings: string;\n }[];\n purchasedTime: string;\n estSettlementTime: string;\n cancelRedemptionDeadline: string;\n tag: string;\n earningCcy?: string[];\n }[];\n }> => this.request('GET', '/api/v5/finance/staking-defi/orders-active', params);\n\n /**\n * 下单\n *\n * 只有当您的账户有足够的资金才能下单。\n *\n * 限速:60次/2s\n *\n * 跟单交易带单产品的限速:4次/2s\n *\n * 限速规则(期权以外):UserID + Instrument ID\n *\n * 限速规则(只限期权):UserID + Instrument Family\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-place-order\n */\n postTradeOrder = (params: {\n instId: string;\n tdMode: string;\n ccy?: string;\n clOrdId?: string;\n tag?: string;\n side: string;\n posSide?: string;\n ordType: string;\n sz: string;\n px?: string;\n pxUsd?: string;\n pxVol?: string;\n reduceOnly?: string;\n tgtCcy?: string;\n banAmend?: string;\n quickMgnType?: string;\n stpId?: string;\n stpMode?: string;\n attachAlgoOrds?: Array<{\n attachAlgoClOrdId?: string;\n tpTriggerPx?: string;\n tpOrdPx?: string;\n tpOrdKind?: string;\n slTriggerPx?: string;\n slOrdPx?: string;\n tpTriggerPxType?: string;\n slTriggerPxType?: string;\n sz?: string;\n amendPxOnTriggerType?: string;\n }>;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n tag: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/order', params);\n\n /**\n * 修改订单\n *\n * 修改当前未成交的挂单\n *\n * 限速:60次/2s\n *\n * 跟单交易带单员带单产品的限速:4个/2s\n *\n * 限速规则:User ID + Instrument ID\n *\n * 权限:交易\n *\n * 该接口限速同时受到 子账户限速 及 基于成交比率的子账户限速 限速规则的影响。\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-amend-order\n */\n postTradeAmendOrder = (params: {\n instId: string;\n cxIOnFail?: boolean;\n ordId?: string;\n clOrdId?: string;\n reqId?: string;\n newSz?: string;\n newPx?: string;\n newPxUsd?: string;\n newPxVol?: string;\n attachAlgoOrds?: Array<{\n attachAlgoId?: string;\n attachAlgoClOrdId?: string;\n newTpTriggerPx?: string;\n newTpOrdPx?: string;\n newTpOrdKind?: string;\n newSlTriggerPx?: string;\n newSlOrdPx?: string;\n newTpTriggerPxType?: string;\n newSlTriggerPxType?: string;\n sz?: string;\n amendPxOnTriggerType?: string;\n }>;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n ts: string;\n reqId: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/amend-order', params);\n\n /**\n * 获取未成交订单列表\n *\n * 获取当前账户下所有未成交订单信息\n *\n * 限速:60次/2s\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-get-order-list\n */\n getTradeOrdersPending = (params: {\n instType?: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n ordType?: string;\n state?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n accFillSz: string;\n avgPx: string;\n cTime: string;\n category: string;\n ccy: string;\n clOrdId: string;\n fee: string;\n feeCcy: string;\n fillPx: string;\n fillSz: string;\n fillTime: string;\n instId: string;\n instType: string;\n lever: string;\n ordId: string;\n ordType: string;\n pnl: string;\n posSide: string;\n px: string;\n pxUsd: string;\n pxVol: string;\n pxType: string;\n rebate: string;\n rebateCcy: string;\n side: string;\n attachAlgoClOrdId: string;\n slOrdPx: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n attachAlgoOrds: any[];\n source: string;\n state: string;\n stpId: string;\n stpMode: string;\n sz: string;\n tag: string;\n tdMode: string;\n tgtCcy: string;\n tpOrdPx: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n tradeId: string;\n reduceOnly: string;\n quickMgnType: string;\n algoClOrdId: string;\n algoId: string;\n isTpLimit: string;\n uTime: string;\n }[];\n }> => this.request('GET', '/api/v5/trade/orders-pending', params);\n\n /**\n * 获取历史订单记录(近七天)\n *\n * 获取最近7天挂单,且完成的订单数据,包括7天以前挂单,但近7天才成交的订单数据。按照订单创建时间倒序排序。\n *\n * 已经撤销的未成交单 只保留2小时\n * 限速:40次/2s\n * 限速规则:User ID\n */\n getTradeOrdersHistory = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n ordType?: string;\n state?: string;\n category?: string;\n after?: string;\n before?: string;\n begin?: string;\n end?: string;\n limit?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n tgtCcy: string;\n ccy: string;\n ordId: string;\n clOrdId: string;\n tag: string;\n px: string;\n pxUsd: string;\n pxVol: string;\n pxType: string;\n sz: string;\n ordType: string;\n side: string;\n posSide: string;\n tdMode: string;\n accFillSz: string;\n fillPx: string;\n tradeId: string;\n fillSz: string;\n fillTime: string;\n avgPx: string;\n state: string;\n lever: string;\n attachAlgoClOrdId: string;\n tpTriggerPx: string;\n tpTriggerPxType: string;\n tpOrdPx: string;\n slTriggerPx: string;\n slTriggerPxType: string;\n slOrdPx: string;\n attachAlgoOrds: any[];\n linkedAlgoOrd: any[];\n stpId: string;\n stpMode: string;\n feeCcy: string;\n fee: string;\n rebateCcy: string;\n source: string;\n rebate: string;\n pnl: string;\n category: string;\n reduceOnly: string;\n cancelSource: string;\n cancelSourceReason: string;\n algoClOrdId: string;\n algoId: string;\n isTpLimit: string;\n uTime: string;\n cTime: string;\n tradeQuoteCcy: string;\n }>;\n }> => this.request('GET', '/api/v5/trade/orders-history', params);\n\n /**\n * 撤单\n *\n * 撤销之前下的未完成订单。\n *\n * 限速:60次/2s\n *\n * 限速规则(期权以外):UserID + Instrument ID\n *\n * 限速规则(只限期权):UserID + Instrument Family\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-trade-post-cancel-order\n */\n postTradeCancelOrder = (params: {\n instId: string;\n ordId?: string;\n clOrdId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n clOrdId: string;\n ordId: string;\n sCode: string;\n sMsg: string;\n }[];\n inTime: string;\n outTime: string;\n }> => this.request('POST', '/api/v5/trade/cancel-order', params);\n\n /**\n * 查看子账户列表\n *\n * 仅适用于母账户。\n *\n * 限速:2次/2s\n *\n * 限速规则:UserID\n */\n getSubAccountList = (params?: {\n enable?: string;\n subAct?: string;\n after?: string;\n before?: string;\n limit?: string;\n }): Promise<{\n data: {\n type: string;\n enable: string;\n subAcct: string;\n uid: string;\n label: string;\n mobile: string;\n gAuth: boolean;\n frozenFunc: string[];\n canTransOut: boolean;\n ts: string;\n }[];\n code: string;\n msg: string;\n }> => this.request('GET', '/api/v5/users/subaccount/list', params);\n\n /**\n * 设置子账户主动转出权限\n *\n * 设置子账户转出权限(仅适用于母账户),默认可转出至母账户。\n *\n * 限速:1次/s\n *\n * 限速规则:UserID\n */\n postSetSubAccountTransferOut = (params: {\n subAcct: string;\n canTransOut: boolean;\n }): Promise<{\n subAcct: string;\n canTransOut: boolean;\n }> => this.request('POST', '/api/v5/users/subaccount/set-transfer-out', params);\n\n /**\n * 获取资金划转状态\n *\n * 获取最近2个星期内的资金划转状态数据\n *\n * 限速:10 次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-funds-transfer-state\n */\n getAssetTransferState = (params: {\n transId?: string;\n clientId?: string;\n type?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n transId: string;\n clientId: string;\n ccy: string;\n amt: string;\n type: string;\n from: string;\n to: string;\n subAcct: string;\n // success | pending | failed\n state: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/transfer-state', params);\n\n /**\n * 获取币种列表\n *\n * 获取当前用户KYC实体支持的币种列表。\n *\n * 限速:6 次/s\n *\n * 限速规则:UserID\n *\n * https://www.okx.com/docs-v5/zh/#funding-account-rest-api-get-currencies\n */\n getAssetCurrencies = (params?: {\n ccy?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n ccy: string;\n name: string;\n chain: string;\n canWd: boolean;\n canInternal: boolean;\n minWd: string;\n maxWd: string;\n wdTickSz: string;\n wdQuota: string;\n usedWdQuota: string;\n minFee: string;\n maxFee: string;\n }[];\n }> => this.request('GET', '/api/v5/asset/currencies', params);\n\n /**\n * 获取指数行情数据\n *\n *\n * 限速:20 次/2s\n *\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-index-tickers\n */\n getMarketIndexTicker = (params?: {\n quoteCcy?: string;\n instId?: string;\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instId: string;\n idxPx: string;\n high24h: string;\n sodUtc0: string;\n open24h: string;\n low24h: string;\n sodUtc8: string;\n ts: string;\n }[];\n }> => this.request('GET', '/api/v5/market/index-tickers', params);\n\n /**\n * GET / 借贷信息\n * 限速:5次/2s\n * 限速规则:User ID\n * 权限:读取\n * HTTP请求\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-flexible-loan-get-loan-info\n */\n getFlexibleLoanInfo = (): Promise<{\n code: string;\n data: {\n collateralData: {\n amt: string;\n ccy: string;\n }[];\n collateralNotionalUsd: string;\n curLTV: string;\n liqLTV: string;\n loanData: {\n amt: string;\n ccy: string;\n }[];\n loanNotionalUsd: string;\n marginCallLTV: string;\n riskWarningData: {\n instId: string;\n liqPx: string;\n };\n }[];\n msg: string;\n }> => this.request('GET', '/api/v5/finance/flexible-loan/loan-info');\n\n /**\n * 账单流水查询(近七天)\n *\n *\n * 限速:5次/s\n *\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-bills-details-last-7-days\n */\n getAccountBills = (params?: {\n instType?: string;\n instId?: string;\n ccy?: string;\n mgnMode?: 'isolated' | 'cross';\n ctType?: 'linear' | 'inverse';\n type?: AccountBillType;\n subType?: string;\n after?: string; //请求此id之前(更旧的数据)的分页内容,传的值为对应接口的billId\n before?: string; //请求此id之后(更新的数据)的分页内容,传的值为对应接口的billId\n begin?: string; //筛选的开始时间戳 ts,Unix 时间戳为毫秒数格式,如 1597026383085\n end?: string;\n limit?: string; //分页返回的结果集数量,最大为100,不填默认返回100条\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n billId: string;\n type: string;\n subType: string;\n ts: string;\n balChg: string;\n posBalChg: string;\n bal: string;\n posBal: string;\n sz: string;\n px: string;\n ccy: string;\n pnl: string;\n fee: string;\n mgnMode: 'isolated' | 'cross' | 'cash' | '';\n instId: string;\n ordId: string;\n execType: string;\n from: string;\n to: string;\n notes: string;\n interest: string;\n tag: string;\n fillTime: string;\n tradeId: string;\n clOrdId: string;\n fillIdxPx: string;\n fillMarkPx: string;\n fillPxVol: string;\n fillPxUsd: string;\n fillMarkVol: string;\n fillFwdPx: string;\n }[];\n }> => this.request('GET', '/api/v5/account/bills', params);\n\n /**\n * 账单流水查询(近三个月)\n *\n *\n * 限速:5次/2s\n *\n *\n * https://www.okx.com/docs-v5/zh/#trading-account-rest-api-get-bills-details-last-3-months\n */\n getAccountBillsArchive = (params?: {\n instType?: string;\n instId?: string;\n ccy?: string;\n mgnMode?: 'isolated' | 'cross';\n ctType?: 'linear' | 'inverse';\n type?: AccountBillType;\n subType?: string;\n after?: string; //请求此id之前(更旧的数据)的分页内容,传的值为对应接口的billId\n before?: string; //请求此id之后(更新的数据)的分页内容,传的值为对应接口的billId\n begin?: string; //筛选的开始时间戳 ts,Unix 时间戳为毫秒数格式,如 1597026383085\n end?: string;\n limit?: string; //分页返回的结果集数量,最大为100,不填默认返回100条\n }): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n billId: string;\n type: string;\n subType: string;\n ts: string;\n balChg: string;\n posBalChg: string;\n bal: string;\n posBal: string;\n sz: string;\n px: string;\n ccy: string;\n pnl: string;\n fee: string;\n mgnMode: 'isolated' | 'cross' | 'cash' | '';\n instId: string;\n ordId: string;\n execType: string;\n from: string;\n to: string;\n notes: string;\n interest: string;\n tag: string;\n fillTime: string;\n tradeId: string;\n clOrdId: string;\n fillIdxPx: string;\n fillMarkPx: string;\n fillPxVol: string;\n fillPxUsd: string;\n fillMarkVol: string;\n fillFwdPx: string;\n }[];\n }> => this.request('GET', '/api/v5/account/bills-archive', params);\n}\n\ntype AccountBillType =\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | '8'\n | '9'\n | '10'\n | '11'\n | '12'\n | '13'\n | '14'\n | '15'\n | '16'\n | '22'\n | '24'\n | '26'\n | '27'\n | '28'\n | '29'\n | '30'\n | '32'\n | '33'\n | '34'\n | '250'\n | '251';\n\nexport const client = new OkxClient({\n auth: {\n public_key: process.env.ACCESS_KEY!,\n secret_key: process.env.SECRET_KEY!,\n passphrase: process.env.PASSPHRASE!,\n },\n});\n"]}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,CAAC;AACzB,OAAO,gBAAgB,CAAC;AACxB,OAAO,QAAQ,CAAC;AAChB,OAAO,SAAS,CAAC;AACjB,OAAO,
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,CAAC;AACnB,OAAO,iBAAiB,CAAC;AACzB,OAAO,gBAAgB,CAAC;AACxB,OAAO,gBAAgB,CAAC;AACxB,OAAO,QAAQ,CAAC;AAChB,OAAO,SAAS,CAAC;AACjB,OAAO,SAAS,CAAC;AACjB,OAAO,SAAS,CAAC","sourcesContent":["import './account';\nimport './interest_rate';\nimport './legacy_index';\nimport './loan-account';\nimport './ohlc';\nimport './order';\nimport './quote';\nimport './trade';\n"]}
|
@@ -0,0 +1,60 @@
|
|
1
|
+
import { publishAccountInfo } from '@yuants/data-account';
|
2
|
+
import { Terminal } from '@yuants/protocol';
|
3
|
+
import { encodePath } from '@yuants/utils';
|
4
|
+
import { defer, filter, firstValueFrom, map, repeat, retry } from 'rxjs';
|
5
|
+
import { accountUid$ } from './account';
|
6
|
+
import { client } from './api';
|
7
|
+
defer(async () => {
|
8
|
+
const uid = await firstValueFrom(accountUid$);
|
9
|
+
const loanAccountId = `okx/${uid}/loan/USDT`;
|
10
|
+
publishAccountInfo(Terminal.fromNodeEnv(), loanAccountId, defer(() => client.getFlexibleLoanInfo())
|
11
|
+
.pipe(filter((x) => x.data && x.data.length > 0), map((x) => x.data[0]), retry({ delay: 1000 }), repeat({ delay: 1000 }))
|
12
|
+
.pipe(map((x) => {
|
13
|
+
const positions = [];
|
14
|
+
for (const loan of x.loanData) {
|
15
|
+
positions.push({
|
16
|
+
product_id: `SPOT/${loan.ccy}-USDT`,
|
17
|
+
volume: +loan.amt,
|
18
|
+
free_volume: +loan.amt,
|
19
|
+
position_id: encodePath('loan', loan.ccy),
|
20
|
+
direction: 'SHORT',
|
21
|
+
position_price: 0,
|
22
|
+
closable_price: 0,
|
23
|
+
floating_profit: 0,
|
24
|
+
valuation: 0,
|
25
|
+
});
|
26
|
+
}
|
27
|
+
for (const collateral of x.collateralData) {
|
28
|
+
positions.push({
|
29
|
+
product_id: `SPOT/${collateral.ccy}-USDT`,
|
30
|
+
volume: +collateral.amt,
|
31
|
+
free_volume: +collateral.amt,
|
32
|
+
position_id: encodePath('collateral', collateral.ccy),
|
33
|
+
direction: 'LONG',
|
34
|
+
position_price: 0,
|
35
|
+
closable_price: 0,
|
36
|
+
floating_profit: 0,
|
37
|
+
valuation: 0,
|
38
|
+
});
|
39
|
+
}
|
40
|
+
const equity = +x.collateralNotionalUsd - +x.loanNotionalUsd;
|
41
|
+
const balance = +x.collateralNotionalUsd;
|
42
|
+
const profit = equity - balance;
|
43
|
+
const used = balance;
|
44
|
+
const free = equity - used;
|
45
|
+
return {
|
46
|
+
account_id: `okx/${uid}/loan/USDT`,
|
47
|
+
updated_at: Date.now(),
|
48
|
+
money: {
|
49
|
+
currency: 'USDT',
|
50
|
+
equity,
|
51
|
+
balance,
|
52
|
+
used,
|
53
|
+
free,
|
54
|
+
profit,
|
55
|
+
},
|
56
|
+
positions,
|
57
|
+
};
|
58
|
+
})));
|
59
|
+
}).subscribe();
|
60
|
+
//# sourceMappingURL=loan-account.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"loan-account.js","sourceRoot":"","sources":["../src/loan-account.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,MAA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@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { defer, filter, firstValueFrom, map, repeat, retry } from 'rxjs';\nimport { accountUid$ } from './account';\nimport { client } from './api';\n\ndefer(async () => {\n const uid = await firstValueFrom(accountUid$);\n const loanAccountId = `okx/${uid}/loan/USDT`;\n\n publishAccountInfo(\n Terminal.fromNodeEnv(),\n loanAccountId,\n defer(() => client.getFlexibleLoanInfo())\n .pipe(\n filter((x) => x.data && x.data.length > 0),\n map((x) => x.data[0]),\n retry({ delay: 1_000 }),\n repeat({ delay: 1_000 }),\n )\n .pipe(\n map((x): IAccountInfo => {\n const positions: IPosition[] = [];\n for (const loan of x.loanData) {\n positions.push({\n product_id: `SPOT/${loan.ccy}-USDT`,\n volume: +loan.amt,\n free_volume: +loan.amt,\n position_id: encodePath('loan', loan.ccy),\n direction: 'SHORT',\n position_price: 0,\n closable_price: 0,\n floating_profit: 0,\n valuation: 0,\n });\n }\n for (const collateral of x.collateralData) {\n positions.push({\n product_id: `SPOT/${collateral.ccy}-USDT`,\n volume: +collateral.amt,\n free_volume: +collateral.amt,\n position_id: encodePath('collateral', collateral.ccy),\n direction: 'LONG',\n position_price: 0,\n closable_price: 0,\n floating_profit: 0,\n valuation: 0,\n });\n }\n const equity = +x.collateralNotionalUsd - +x.loanNotionalUsd;\n const balance = +x.collateralNotionalUsd;\n const profit = equity - balance;\n const used = balance;\n const free = equity - used;\n return {\n account_id: `okx/${uid}/loan/USDT`,\n updated_at: Date.now(),\n money: {\n currency: 'USDT',\n equity,\n balance,\n used,\n free,\n profit,\n },\n positions,\n };\n }),\n ),\n );\n}).subscribe();\n"]}
|
package/dist/quote.js
CHANGED
@@ -1,13 +1,57 @@
|
|
1
|
-
import { encodePath } from '@yuants/utils';
|
2
1
|
import { Terminal } from '@yuants/protocol';
|
3
2
|
import { writeToSQL } from '@yuants/sql';
|
4
|
-
import {
|
3
|
+
import { decodePath, encodePath } from '@yuants/utils';
|
4
|
+
import { defer, filter, from, groupBy, map, merge, mergeMap, Observable, repeat, retry, scan, share, shareReplay, toArray, } from 'rxjs';
|
5
5
|
import { client } from './api';
|
6
|
-
|
6
|
+
import { OKXWsClient } from './websocket';
|
7
|
+
const wsPool = [];
|
8
|
+
// ISSUE: 连接限制:3 次/秒 (基于IP)
|
9
|
+
//
|
10
|
+
// https://www.okx.com/docs-v5/zh/#overview-websocket-connect
|
11
|
+
//
|
12
|
+
// 当订阅公有频道时,使用公有服务的地址;当订阅私有频道时,使用私有服务的地址
|
13
|
+
//
|
14
|
+
// 请求限制:
|
15
|
+
//
|
16
|
+
// 每个连接 对于 订阅/取消订阅/登录 请求的总次数限制为 480 次/小时
|
17
|
+
const getWsClient = () => {
|
18
|
+
const existing = wsPool.find((item) => !item.isFull);
|
19
|
+
if (existing) {
|
20
|
+
existing.requests++;
|
21
|
+
if (existing.requests >= 480) {
|
22
|
+
existing.isFull = true;
|
23
|
+
}
|
24
|
+
return existing.client;
|
25
|
+
}
|
26
|
+
const newClient = new OKXWsClient('ws/v5/public');
|
27
|
+
wsPool.push({ client: newClient, requests: 1, isFull: false });
|
28
|
+
return newClient;
|
29
|
+
};
|
30
|
+
const swapInstruments$ = defer(() => client.getInstruments({ instType: 'SWAP' })).pipe(repeat({ delay: 3600000 }), retry({ delay: 10000 }), map((x) => x.data), shareReplay(1));
|
31
|
+
const spotInstruments$ = defer(() => client.getInstruments({ instType: 'SPOT' })).pipe(repeat({ delay: 3600000 }), retry({ delay: 10000 }), map((x) => x.data), shareReplay(1));
|
7
32
|
const spotTickers$ = defer(() => client.getMarketTickers({ instType: 'SPOT' })).pipe(repeat({ delay: 5000 }), retry({ delay: 5000 }), shareReplay(1));
|
8
|
-
|
33
|
+
// depend by SubmitOrders
|
9
34
|
export const spotMarketTickers$ = defer(() => spotTickers$).pipe(mergeMap((x) => from(x.data).pipe(map((x) => [x.instId, x]), toArray(), map((x) => Object.fromEntries(x)))), repeat({ delay: 5000 }), retry({ delay: 5000 }), shareReplay(1));
|
10
|
-
const
|
35
|
+
const swapTicker$ = swapInstruments$.pipe(mergeMap((x) => {
|
36
|
+
return new Observable((subscriber) => {
|
37
|
+
for (const inst of x) {
|
38
|
+
getWsClient().subscribe('tickers', inst.instId, (data) => {
|
39
|
+
subscriber.next(data);
|
40
|
+
});
|
41
|
+
}
|
42
|
+
});
|
43
|
+
}), share());
|
44
|
+
const spotTicker$ = spotInstruments$.pipe(mergeMap((x) => {
|
45
|
+
console.info('SPOT INSTRUMENTS', x.length);
|
46
|
+
return new Observable((subscriber) => {
|
47
|
+
for (const inst of x) {
|
48
|
+
getWsClient().subscribe('tickers', inst.instId, (data) => {
|
49
|
+
subscriber.next(data);
|
50
|
+
});
|
51
|
+
}
|
52
|
+
});
|
53
|
+
}), share());
|
54
|
+
const quote1$ = swapTicker$.pipe(map((ticker) => ({
|
11
55
|
datasource_id: 'OKX',
|
12
56
|
product_id: encodePath('SWAP', ticker.instId),
|
13
57
|
last_price: ticker.last,
|
@@ -15,8 +59,8 @@ const quote1$ = swapTickers$.pipe(mergeMap((x) => x.data || []), map((ticker) =>
|
|
15
59
|
bid_price: ticker.bidPx,
|
16
60
|
ask_volume: ticker.askSz,
|
17
61
|
bid_volume: ticker.bidSz,
|
18
|
-
})));
|
19
|
-
const quote2$ =
|
62
|
+
})), share());
|
63
|
+
const quote2$ = spotTicker$.pipe(map((ticker) => ({
|
20
64
|
datasource_id: 'OKX',
|
21
65
|
product_id: encodePath('SPOT', ticker.instId),
|
22
66
|
last_price: ticker.last,
|
@@ -24,8 +68,8 @@ const quote2$ = spotTickers$.pipe(mergeMap((x) => x.data || []), map((ticker) =>
|
|
24
68
|
bid_price: ticker.bidPx,
|
25
69
|
ask_volume: ticker.askSz,
|
26
70
|
bid_volume: ticker.bidSz,
|
27
|
-
})));
|
28
|
-
const
|
71
|
+
})), share());
|
72
|
+
const quote3$ = spotTicker$.pipe(map((ticker) => ({
|
29
73
|
datasource_id: 'OKX',
|
30
74
|
product_id: encodePath('MARGIN', ticker.instId),
|
31
75
|
last_price: ticker.last,
|
@@ -33,13 +77,37 @@ const quote4$ = spotTickers$.pipe(mergeMap((x) => x.data || []), map((ticker) =>
|
|
33
77
|
bid_price: ticker.bidPx,
|
34
78
|
ask_volume: ticker.askSz,
|
35
79
|
bid_volume: ticker.bidSz,
|
80
|
+
})), share());
|
81
|
+
const swapOpenInterestInner$ = swapInstruments$.pipe(mergeMap((x) => new Observable((subscriber) => {
|
82
|
+
for (const inst of x) {
|
83
|
+
getWsClient().subscribe('open-interest', inst.instId, (data) => {
|
84
|
+
subscriber.next(data);
|
85
|
+
});
|
86
|
+
}
|
36
87
|
})));
|
37
88
|
const swapOpenInterests$ = defer(() => client.getOpenInterest({ instType: 'SWAP' })).pipe(repeat({ delay: 10000 }), retry({ delay: 10000 }), shareReplay(1));
|
38
|
-
const
|
89
|
+
const quote4$ = swapOpenInterestInner$.pipe(map((x) => ({
|
39
90
|
datasource_id: 'OKX',
|
40
91
|
product_id: encodePath('SWAP', x.instId),
|
41
92
|
open_interest: x.oi,
|
42
|
-
})));
|
93
|
+
})), share());
|
94
|
+
const quote$ = merge(
|
95
|
+
//
|
96
|
+
quote1$, quote2$, quote3$, quote4$).pipe(groupBy((x) => encodePath(x.datasource_id, x.product_id)), mergeMap((group$) => {
|
97
|
+
return group$.pipe(
|
98
|
+
//
|
99
|
+
scan((acc, cur) => Object.assign(acc, cur), {}));
|
100
|
+
}), share());
|
101
|
+
Terminal.fromNodeEnv().channel.publishChannel('quote', { pattern: `^OKX/` }, (channel_id) => {
|
102
|
+
const [datasource_id, product_id] = decodePath(channel_id);
|
103
|
+
if (!datasource_id) {
|
104
|
+
throw 'datasource_id is required';
|
105
|
+
}
|
106
|
+
if (!product_id) {
|
107
|
+
throw 'product_id is required';
|
108
|
+
}
|
109
|
+
return quote$.pipe(filter((x) => x.product_id === product_id));
|
110
|
+
});
|
43
111
|
// 合并不同来源的数据并进行合并,避免死锁
|
44
112
|
if (process.env.WRITE_QUOT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EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,aAAa,EAAE,KAAK,CAAC,UAAU,CAAC;QACnE,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;CAChB;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,CAAC,IAAI,CACnE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAU,CAAC,CAAC,CAAC,EAClE,WAAW,CAAC,CAAC,CAAC,CACf,CAAC","sourcesContent":["import { encodePath } from '@yuants/utils';\nimport { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { defer, from, groupBy, map, merge, mergeMap, repeat, retry, scan, shareReplay, toArray } from 'rxjs';\nimport { client } from './api';\n\nconst swapTickers$ = defer(() => client.getMarketTickers({ instType: 'SWAP' })).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst spotTickers$ = defer(() => client.getMarketTickers({ instType: 'SPOT' })).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const swapMarketTickers$ = defer(() => swapTickers$).pipe(\n mergeMap((x) =>\n from(x.data).pipe(\n map((x) => [x.instId, x] as const),\n toArray(),\n map((x) => Object.fromEntries(x)),\n ),\n ),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const spotMarketTickers$ = defer(() => spotTickers$).pipe(\n mergeMap((x) =>\n from(x.data).pipe(\n map((x) => [x.instId, x] as const),\n toArray(),\n map((x) => Object.fromEntries(x)),\n ),\n ),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst quote1$ = swapTickers$.pipe(\n mergeMap((x) => x.data || []),\n map(\n (ticker): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n }),\n ),\n);\n\nconst quote2$ = spotTickers$.pipe(\n mergeMap((x) => x.data || []),\n map(\n (ticker): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n }),\n ),\n);\n\nconst quote4$ = spotTickers$.pipe(\n mergeMap((x) => x.data || []),\n map(\n (ticker): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n }),\n ),\n);\n\nconst swapOpenInterests$ = defer(() => client.getOpenInterest({ instType: 'SWAP' })).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nconst quote3$ = swapOpenInterests$.pipe(\n mergeMap((x) => x.data || []),\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', x.instId),\n open_interest: x.oi,\n }),\n ),\n);\n\n// 合并不同来源的数据并进行合并,避免死锁\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n merge(quote1$, quote2$, quote3$, quote4$)\n .pipe(\n groupBy((x) => encodePath(x.datasource_id, x.product_id)),\n mergeMap((group$) => {\n return group$.pipe(scan((acc, cur) => Object.assign(acc, cur), {} as Partial<IQuote>));\n }),\n writeToSQL({\n terminal: Terminal.fromNodeEnv(),\n writeInterval: 1000,\n tableName: 'quote',\n keyFn: (quote) => encodePath(quote.datasource_id, quote.product_id),\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nexport const swapOpenInterest$ = defer(() => swapOpenInterests$).pipe(\n map((x) => new Map(x.data.map((x) => [x.instId, +x.oi] as const))),\n shareReplay(1),\n);\n"]}
|
1
|
+
{"version":3,"file":"quote.js","sourceRoot":"","sources":["../src/quote.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EACL,KAAK,EACL,MAAM,EACN,IAAI,EACJ,OAAO,EACP,GAAG,EACH,KAAK,EACL,QAAQ,EACR,UAAU,EACV,MAAM,EACN,KAAK,EACL,IAAI,EACJ,KAAK,EACL,WAAW,EACX,OAAO,GACR,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,MAAM,GAIN,EAAE,CAAC;AAET,2BAA2B;AAC3B,EAAE;AACF,6DAA6D;AAC7D,EAAE;AACF,wCAAwC;AACxC,EAAE;AACF,QAAQ;AACR,EAAE;AACF,wCAAwC;AACxC,MAAM,WAAW,GAAG,GAAG,EAAE;IACvB,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACrD,IAAI,QAAQ,EAAE;QACZ,QAAQ,CAAC,QAAQ,EAAE,CAAC;QACpB,IAAI,QAAQ,CAAC,QAAQ,IAAI,GAAG,EAAE;YAC5B,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC;SACxB;Q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C,CAAC,UAAU,CAAC,CAAC,EACzD,QAAQ,CAAC,CAAC,MAAM,EAAE,EAAE;QAClB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EAAqB,CAAC,CAAC,CAAC;IACzF,CAAC,CAAC,EACF,UAAU,CAAC;QACT,QAAQ,EAAE,QAAQ,CAAC,WAAW,EAAE;QAChC,aAAa,EAAE,IAAI;QACnB,SAAS,EAAE,OAAO;QAClB,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,aAAa,EAAE,KAAK,CAAC,UAAU,CAAC;QACnE,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;CAChB;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,CAAC,IAAI,CACnE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAU,CAAC,CAAC,CAAC,EACvE,WAAW,CAAC,CAAC,CAAC,CACf,CAAC","sourcesContent":["import { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath } from '@yuants/utils';\nimport {\n defer,\n filter,\n from,\n groupBy,\n map,\n merge,\n mergeMap,\n Observable,\n repeat,\n retry,\n scan,\n share,\n shareReplay,\n toArray,\n} from 'rxjs';\nimport { client } from './api';\nimport { OKXWsClient } from './websocket';\n\nconst wsPool: {\n client: OKXWsClient;\n requests: number;\n isFull: boolean;\n}[] = [];\n\n// ISSUE: 连接限制:3 次/秒 (基于IP)\n//\n// https://www.okx.com/docs-v5/zh/#overview-websocket-connect\n//\n// 当订阅公有频道时,使用公有服务的地址;当订阅私有频道时,使用私有服务的地址\n//\n// 请求限制:\n//\n// 每个连接 对于 订阅/取消订阅/登录 请求的总次数限制为 480 次/小时\nconst getWsClient = () => {\n const existing = wsPool.find((item) => !item.isFull);\n if (existing) {\n existing.requests++;\n if (existing.requests >= 480) {\n existing.isFull = true;\n }\n return existing.client;\n }\n const newClient = new OKXWsClient('ws/v5/public');\n wsPool.push({ client: newClient, requests: 1, isFull: false });\n return newClient;\n};\n\nconst swapInstruments$ = defer(() => client.getInstruments({ instType: 'SWAP' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\nconst spotInstruments$ = defer(() => client.getInstruments({ instType: 'SPOT' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\n\nconst spotTickers$ = defer(() => client.getMarketTickers({ instType: 'SPOT' })).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\n// depend by SubmitOrders\nexport const spotMarketTickers$ = defer(() => spotTickers$).pipe(\n mergeMap((x) =>\n from(x.data).pipe(\n map((x) => [x.instId, x] as const),\n toArray(),\n map((x) => Object.fromEntries(x)),\n ),\n ),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst swapTicker$ = swapInstruments$.pipe(\n mergeMap((x) => {\n return new Observable<any>((subscriber) => {\n for (const inst of x) {\n getWsClient().subscribe('tickers', inst.instId, (data: any) => {\n subscriber.next(data);\n });\n }\n });\n }),\n share(),\n);\nconst spotTicker$ = spotInstruments$.pipe(\n mergeMap((x) => {\n console.info('SPOT INSTRUMENTS', x.length);\n return new Observable<any>((subscriber) => {\n for (const inst of x) {\n getWsClient().subscribe('tickers', inst.instId, (data: any) => {\n subscriber.next(data);\n });\n }\n });\n }),\n share(),\n);\n\nconst quote1$ = swapTicker$.pipe(\n map((ticker) => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n })),\n share(),\n);\nconst quote2$ = spotTicker$.pipe(\n map((ticker) => ({\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n })),\n share(),\n);\n\nconst quote3$ = spotTicker$.pipe(\n map((ticker) => ({\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', ticker.instId),\n last_price: ticker.last,\n ask_price: ticker.askPx,\n bid_price: ticker.bidPx,\n ask_volume: ticker.askSz,\n bid_volume: ticker.bidSz,\n })),\n share(),\n);\n\nconst swapOpenInterestInner$ = swapInstruments$.pipe(\n mergeMap(\n (x) =>\n new Observable<any>((subscriber) => {\n for (const inst of x) {\n getWsClient().subscribe('open-interest', inst.instId, (data: any) => {\n subscriber.next(data);\n });\n }\n }),\n ),\n);\n\nconst swapOpenInterests$ = defer(() => client.getOpenInterest({ instType: 'SWAP' })).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nconst quote4$ = swapOpenInterestInner$.pipe(\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', x.instId),\n open_interest: x.oi,\n }),\n ),\n share(),\n);\n\nconst quote$ = merge(\n //\n quote1$,\n quote2$,\n quote3$,\n quote4$,\n).pipe(\n groupBy((x) => encodePath(x.datasource_id, x.product_id)),\n mergeMap((group$) => {\n return group$.pipe(\n //\n scan((acc, cur) => Object.assign(acc, cur), {} as Partial<IQuote>),\n );\n }),\n share(),\n);\n\nTerminal.fromNodeEnv().channel.publishChannel('quote', { pattern: `^OKX/` }, (channel_id) => {\n const [datasource_id, product_id] = decodePath(channel_id);\n if (!datasource_id) {\n throw 'datasource_id is required';\n }\n if (!product_id) {\n throw 'product_id is required';\n }\n return quote$.pipe(filter((x) => x.product_id === product_id));\n});\n\n// 合并不同来源的数据并进行合并,避免死锁\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n merge(quote1$, quote2$, quote3$, quote4$)\n .pipe(\n groupBy((x) => encodePath(x.datasource_id, x.product_id)),\n mergeMap((group$) => {\n return group$.pipe(scan((acc, cur) => Object.assign(acc, cur), {} as Partial<IQuote>));\n }),\n writeToSQL({\n terminal: Terminal.fromNodeEnv(),\n writeInterval: 1000,\n tableName: 'quote',\n keyFn: (quote) => encodePath(quote.datasource_id, quote.product_id),\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nexport const swapOpenInterest$ = defer(() => swapOpenInterests$).pipe(\n map((x) => new Map(x.data.map((x: any) => [x.instId, +x.oi] as const))),\n shareReplay(1),\n);\n"]}
|
package/dist/trade.js
CHANGED
@@ -29,6 +29,7 @@ const tradeParser = async (accountId, params) => {
|
|
29
29
|
v.forEach((bill) => {
|
30
30
|
trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();
|
31
31
|
trade.product_id = bill.instId;
|
32
|
+
trade.traded_price = bill.px;
|
32
33
|
if (bill.instType === 'SWAP') {
|
33
34
|
if (bill.subType === '3')
|
34
35
|
trade.direction = 'OPEN_LONG';
|
package/dist/trade.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAA4B,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACtG,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;A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AE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,OAAO,CAAC,KAAM,CAAC,EAAE,aAAa;IAC9B,UAAU,CAAC,CAAC,GAAG,EAAE,EAAE;QACjB,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACnE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IAChB,CAAC,CAAC,CACH;SACA,SAAS,EAAE,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["import { catchError, defer, first, firstValueFrom, interval, of, repeat, retry, timeout } from 'rxjs';\nimport { client } from './api';\nimport { ITrade } from '@yuants/data-trade';\nimport { accountUid$ } from './account';\nimport { formatTime } from '@yuants/utils';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { Terminal } from '@yuants/protocol';\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await client.getAccountBillsArchive(params);\n\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) =>\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]),\n );\n mapTradeIdToBillList.forEach((v, tradeId) => {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) return;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = bill.instId;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n tradeList.push(trade);\n });\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n params['end'] = Date.now().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\ndefer(() => accountUid$)\n .pipe(first())\n .subscribe((uid) => {\n const account_id = `okx/${uid}/trading`;\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n timeout(10_000), // 超时设定:10 秒\n catchError((err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n return of([]);\n }),\n )\n .subscribe();\n });\n"]}
|
1
|
+
{"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAA4B,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACtG,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,MAAM,WAAW,GAAG,KAAK,EAAE,SAAiB,EAAE,MAA8B,EAAqB,EAAE;IACjG,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC;IAE3D,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,EAAE;QACtC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;QACzB,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAuB,CAAC;QAC5D,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,WACpB,OAAA,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,MAAA,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,mCAAI,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAA,EAAA,CAClG,C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AAK,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC;KACrB,IAAI,CAAC,KAAK,EAAE,CAAC;KACb,SAAS,CAAC,CAAC,GAAG,EAAE,EAAE;IACjB,MAAM,UAAU,GAAG,OAAO,GAAG,UAAU,CAAC;IACxC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,iBAAiB,EAAE,cAAc,UAAU,EAAE,CAAC,CAAC;IACnF,KAAK,CAAC,GAAG,EAAE,CAAC,4BAA4B,CAAC,UAAU,CAAC,CAAC;SAClD,IAAI;IACH,EAAE;IACF,MAAM,CAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,OAAO,CAAC,KAAM,CAAC,EAAE,aAAa;IAC9B,UAAU,CAAC,CAAC,GAAG,EAAE,EAAE;QACjB,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACnE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IAChB,CAAC,CAAC,CACH;SACA,SAAS,EAAE,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["import { catchError, defer, first, firstValueFrom, interval, of, repeat, retry, timeout } from 'rxjs';\nimport { client } from './api';\nimport { ITrade } from '@yuants/data-trade';\nimport { accountUid$ } from './account';\nimport { formatTime } from '@yuants/utils';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { Terminal } from '@yuants/protocol';\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await client.getAccountBillsArchive(params);\n\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) =>\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]),\n );\n mapTradeIdToBillList.forEach((v, tradeId) => {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) return;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = bill.instId;\n trade.traded_price = bill.px;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n tradeList.push(trade);\n });\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n params['end'] = Date.now().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\ndefer(() => accountUid$)\n .pipe(first())\n .subscribe((uid) => {\n const account_id = `okx/${uid}/trading`;\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n timeout(10_000), // 超时设定:10 秒\n catchError((err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n return of([]);\n }),\n )\n .subscribe();\n });\n"]}
|
package/dist/websocket.js
CHANGED
@@ -28,6 +28,12 @@ export class OKXWsClient {
|
|
28
28
|
}
|
29
29
|
});
|
30
30
|
this.ws.addEventListener('message', (raw) => this.handleMessage(raw));
|
31
|
+
this.ws.addEventListener('error', (raw) => {
|
32
|
+
console.error(formatTime(Date.now()), '❌ WS error', raw);
|
33
|
+
});
|
34
|
+
this.ws.addEventListener('close', (event) => {
|
35
|
+
console.error(formatTime(Date.now()), '❌ WS closed', event);
|
36
|
+
});
|
31
37
|
this.subscriptions = new Set();
|
32
38
|
this.handlers = {}; // key: channel, value: callback
|
33
39
|
}
|