okx-api 2.0.6 → 3.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (382) hide show
  1. package/README.md +344 -13
  2. package/dist/cjs/constants/funding.js.map +1 -0
  3. package/dist/cjs/index.d.ts +43 -0
  4. package/dist/cjs/index.js +64 -0
  5. package/dist/cjs/index.js.map +1 -0
  6. package/dist/cjs/package.json +3 -0
  7. package/{lib → dist/cjs}/rest-client.d.ts +28 -15
  8. package/{lib → dist/cjs}/rest-client.js +41 -68
  9. package/dist/cjs/rest-client.js.map +1 -0
  10. package/dist/cjs/types/rest/client.d.ts +36 -0
  11. package/{lib → dist/cjs}/types/rest/client.js.map +1 -1
  12. package/{lib → dist/cjs}/types/rest/request/account.d.ts +1 -1
  13. package/dist/cjs/types/rest/request/account.js.map +1 -0
  14. package/{lib → dist/cjs}/types/rest/request/block-trading.d.ts +1 -1
  15. package/dist/cjs/types/rest/request/block-trading.js.map +1 -0
  16. package/dist/cjs/types/rest/request/convert.js.map +1 -0
  17. package/dist/cjs/types/rest/request/copy-trading.js.map +1 -0
  18. package/dist/cjs/types/rest/request/funding.js.map +1 -0
  19. package/dist/cjs/types/rest/request/grid-trading.js.map +1 -0
  20. package/dist/cjs/types/rest/request/public.js.map +1 -0
  21. package/dist/cjs/types/rest/request/recurring-buy.js.map +1 -0
  22. package/{lib → dist/cjs}/types/rest/request/shared.d.ts +1 -1
  23. package/dist/cjs/types/rest/request/shared.js.map +1 -0
  24. package/dist/cjs/types/rest/request/signal-bot.js.map +1 -0
  25. package/dist/cjs/types/rest/request/simple-earn.js.map +1 -0
  26. package/dist/cjs/types/rest/request/spread-trading.js.map +1 -0
  27. package/dist/cjs/types/rest/request/subaccount.js.map +1 -0
  28. package/{lib → dist/cjs}/types/rest/request/trade.d.ts +1 -1
  29. package/dist/cjs/types/rest/request/trade.js.map +1 -0
  30. package/{lib → dist/cjs}/types/rest/response/private-account.d.ts +1 -1
  31. package/dist/cjs/types/rest/response/private-account.js.map +1 -0
  32. package/{lib → dist/cjs}/types/rest/response/private-block-trading.d.ts +1 -1
  33. package/dist/cjs/types/rest/response/private-block-trading.js.map +1 -0
  34. package/dist/cjs/types/rest/response/private-copy-trading.js.map +1 -0
  35. package/dist/cjs/types/rest/response/private-flexible-loan.js.map +1 -0
  36. package/{lib → dist/cjs}/types/rest/response/private-funding.d.ts +1 -1
  37. package/dist/cjs/types/rest/response/private-funding.js.map +1 -0
  38. package/dist/cjs/types/rest/response/private-recurring-buy.js.map +1 -0
  39. package/dist/cjs/types/rest/response/private-signal-bot.js.map +1 -0
  40. package/dist/cjs/types/rest/response/private-spread-trading.js.map +1 -0
  41. package/dist/cjs/types/rest/response/private-subaccount.js.map +1 -0
  42. package/{lib → dist/cjs}/types/rest/response/private-trade.d.ts +1 -1
  43. package/dist/cjs/types/rest/response/private-trade.js.map +1 -0
  44. package/{lib → dist/cjs}/types/rest/response/public-data.d.ts +1 -1
  45. package/dist/cjs/types/rest/response/public-data.js.map +1 -0
  46. package/{lib → dist/cjs}/types/rest/shared.d.ts +2 -2
  47. package/dist/cjs/types/rest/shared.js.map +1 -0
  48. package/dist/cjs/types/shared.d.ts +13 -0
  49. package/{lib → dist/cjs}/types/shared.js.map +1 -1
  50. package/dist/cjs/types/websockets/ws-api-request.d.ts +61 -0
  51. package/dist/cjs/types/websockets/ws-api-request.js +3 -0
  52. package/dist/cjs/types/websockets/ws-api-request.js.map +1 -0
  53. package/dist/cjs/types/websockets/ws-api-response.d.ts +28 -0
  54. package/dist/cjs/types/websockets/ws-api-response.js +3 -0
  55. package/dist/cjs/types/websockets/ws-api-response.js.map +1 -0
  56. package/dist/cjs/types/websockets/ws-api.d.ts +139 -0
  57. package/dist/cjs/types/websockets/ws-api.js +38 -0
  58. package/dist/cjs/types/websockets/ws-api.js.map +1 -0
  59. package/{lib/types/websockets/event.d.ts → dist/cjs/types/websockets/ws-events.d.ts} +7 -1
  60. package/dist/cjs/types/websockets/ws-events.js +11 -0
  61. package/dist/cjs/types/websockets/ws-events.js.map +1 -0
  62. package/dist/cjs/types/websockets/ws-general.d.ts +48 -0
  63. package/dist/cjs/types/websockets/ws-general.js +3 -0
  64. package/dist/cjs/types/websockets/ws-general.js.map +1 -0
  65. package/{lib/types/websockets/request.d.ts → dist/cjs/types/websockets/ws-request.d.ts} +0 -22
  66. package/dist/cjs/types/websockets/ws-request.js +3 -0
  67. package/dist/cjs/types/websockets/ws-request.js.map +1 -0
  68. package/{lib → dist/cjs}/util/BaseRestClient.d.ts +1 -1
  69. package/dist/cjs/util/BaseRestClient.js +237 -0
  70. package/dist/cjs/util/BaseRestClient.js.map +1 -0
  71. package/dist/cjs/util/BaseWSClient.d.ts +198 -0
  72. package/dist/cjs/util/BaseWSClient.js +770 -0
  73. package/dist/cjs/util/BaseWSClient.js.map +1 -0
  74. package/dist/cjs/util/WsStore.d.ts +75 -0
  75. package/dist/cjs/util/WsStore.js +303 -0
  76. package/dist/cjs/util/WsStore.js.map +1 -0
  77. package/dist/cjs/util/WsStore.types.d.ts +51 -0
  78. package/dist/cjs/util/WsStore.types.js +14 -0
  79. package/dist/cjs/util/WsStore.types.js.map +1 -0
  80. package/dist/cjs/util/logger.d.ts +8 -0
  81. package/{lib → dist/cjs}/util/logger.js +3 -11
  82. package/dist/cjs/util/logger.js.map +1 -0
  83. package/{lib → dist/cjs}/util/requestUtils.d.ts +2 -1
  84. package/{lib → dist/cjs}/util/requestUtils.js +13 -5
  85. package/dist/cjs/util/requestUtils.js.map +1 -0
  86. package/{lib → dist/cjs}/util/typeGuards.d.ts +4 -2
  87. package/{lib → dist/cjs}/util/typeGuards.js +43 -10
  88. package/dist/cjs/util/typeGuards.js.map +1 -0
  89. package/dist/cjs/util/webCryptoAPI.d.ts +15 -0
  90. package/dist/cjs/util/webCryptoAPI.js +82 -0
  91. package/dist/cjs/util/webCryptoAPI.js.map +1 -0
  92. package/dist/cjs/util/websocket-util.d.ts +142 -0
  93. package/dist/cjs/util/websocket-util.js +533 -0
  94. package/dist/cjs/util/websocket-util.js.map +1 -0
  95. package/dist/cjs/websocket-api-client.d.ts +135 -0
  96. package/dist/cjs/websocket-api-client.js +171 -0
  97. package/dist/cjs/websocket-api-client.js.map +1 -0
  98. package/{lib/websocket-client.d.ts → dist/cjs/websocket-client-legacy.d.ts} +16 -39
  99. package/dist/cjs/websocket-client-legacy.js +524 -0
  100. package/dist/cjs/websocket-client-legacy.js.map +1 -0
  101. package/dist/cjs/websocket-client.d.ts +81 -0
  102. package/dist/cjs/websocket-client.js +548 -0
  103. package/dist/cjs/websocket-client.js.map +1 -0
  104. package/dist/mjs/constants/funding.d.ts +139 -0
  105. package/dist/mjs/constants/funding.js +140 -0
  106. package/dist/mjs/constants/funding.js.map +1 -0
  107. package/dist/mjs/index.d.ts +43 -0
  108. package/dist/mjs/index.js +48 -0
  109. package/dist/mjs/index.js.map +1 -0
  110. package/dist/mjs/package.json +3 -0
  111. package/dist/mjs/rest-client.d.ts +1173 -0
  112. package/dist/mjs/rest-client.js +1271 -0
  113. package/dist/mjs/rest-client.js.map +1 -0
  114. package/dist/mjs/types/rest/client.d.ts +36 -0
  115. package/dist/mjs/types/rest/client.js +2 -0
  116. package/{lib/types/websockets → dist/mjs/types/rest}/client.js.map +1 -1
  117. package/dist/mjs/types/rest/request/account.d.ts +144 -0
  118. package/dist/mjs/types/rest/request/account.js +2 -0
  119. package/dist/mjs/types/rest/request/account.js.map +1 -0
  120. package/dist/mjs/types/rest/request/block-trading.d.ts +76 -0
  121. package/dist/mjs/types/rest/request/block-trading.js +2 -0
  122. package/dist/mjs/types/rest/request/block-trading.js.map +1 -0
  123. package/dist/mjs/types/rest/request/convert.d.ts +19 -0
  124. package/dist/mjs/types/rest/request/convert.js +2 -0
  125. package/dist/mjs/types/rest/request/convert.js.map +1 -0
  126. package/dist/mjs/types/rest/request/copy-trading.d.ts +117 -0
  127. package/dist/mjs/types/rest/request/copy-trading.js +2 -0
  128. package/dist/mjs/types/rest/request/copy-trading.js.map +1 -0
  129. package/dist/mjs/types/rest/request/funding.d.ts +43 -0
  130. package/dist/mjs/types/rest/request/funding.js +2 -0
  131. package/dist/mjs/types/rest/request/funding.js.map +1 -0
  132. package/dist/mjs/types/rest/request/grid-trading.d.ts +66 -0
  133. package/dist/mjs/types/rest/request/grid-trading.js +2 -0
  134. package/dist/mjs/types/rest/request/grid-trading.js.map +1 -0
  135. package/dist/mjs/types/rest/request/public.d.ts +55 -0
  136. package/dist/mjs/types/rest/request/public.js +2 -0
  137. package/dist/mjs/types/rest/request/public.js.map +1 -0
  138. package/dist/mjs/types/rest/request/recurring-buy.d.ts +28 -0
  139. package/dist/mjs/types/rest/request/recurring-buy.js +2 -0
  140. package/dist/mjs/types/rest/request/recurring-buy.js.map +1 -0
  141. package/dist/mjs/types/rest/request/shared.d.ts +7 -0
  142. package/dist/mjs/types/rest/request/shared.js +2 -0
  143. package/dist/mjs/types/rest/request/shared.js.map +1 -0
  144. package/dist/mjs/types/rest/request/signal-bot.d.ts +97 -0
  145. package/dist/mjs/types/rest/request/signal-bot.js +2 -0
  146. package/dist/mjs/types/rest/request/signal-bot.js.map +1 -0
  147. package/dist/mjs/types/rest/request/simple-earn.d.ts +23 -0
  148. package/dist/mjs/types/rest/request/simple-earn.js +2 -0
  149. package/dist/mjs/types/rest/request/simple-earn.js.map +1 -0
  150. package/dist/mjs/types/rest/request/spread-trading.d.ts +69 -0
  151. package/dist/mjs/types/rest/request/spread-trading.js +2 -0
  152. package/dist/mjs/types/rest/request/spread-trading.js.map +1 -0
  153. package/dist/mjs/types/rest/request/subaccount.d.ts +33 -0
  154. package/dist/mjs/types/rest/request/subaccount.js +2 -0
  155. package/dist/mjs/types/rest/request/subaccount.js.map +1 -0
  156. package/dist/mjs/types/rest/request/trade.d.ts +194 -0
  157. package/dist/mjs/types/rest/request/trade.js +2 -0
  158. package/dist/mjs/types/rest/request/trade.js.map +1 -0
  159. package/dist/mjs/types/rest/response/private-account.d.ts +448 -0
  160. package/dist/mjs/types/rest/response/private-account.js +2 -0
  161. package/dist/mjs/types/rest/response/private-account.js.map +1 -0
  162. package/dist/mjs/types/rest/response/private-block-trading.d.ts +124 -0
  163. package/dist/mjs/types/rest/response/private-block-trading.js +2 -0
  164. package/dist/mjs/types/rest/response/private-block-trading.js.map +1 -0
  165. package/dist/mjs/types/rest/response/private-copy-trading.d.ts +259 -0
  166. package/dist/mjs/types/rest/response/private-copy-trading.js +2 -0
  167. package/dist/mjs/types/rest/response/private-copy-trading.js.map +1 -0
  168. package/dist/mjs/types/rest/response/private-flexible-loan.d.ts +72 -0
  169. package/dist/mjs/types/rest/response/private-flexible-loan.js +2 -0
  170. package/dist/mjs/types/rest/response/private-flexible-loan.js.map +1 -0
  171. package/dist/mjs/types/rest/response/private-funding.d.ts +102 -0
  172. package/dist/mjs/types/rest/response/private-funding.js +2 -0
  173. package/dist/mjs/types/rest/response/private-funding.js.map +1 -0
  174. package/dist/mjs/types/rest/response/private-recurring-buy.d.ts +63 -0
  175. package/dist/mjs/types/rest/response/private-recurring-buy.js +2 -0
  176. package/dist/mjs/types/rest/response/private-recurring-buy.js.map +1 -0
  177. package/dist/mjs/types/rest/response/private-signal-bot.d.ts +22 -0
  178. package/dist/mjs/types/rest/response/private-signal-bot.js +2 -0
  179. package/dist/mjs/types/rest/response/private-signal-bot.js.map +1 -0
  180. package/dist/mjs/types/rest/response/private-spread-trading.d.ts +126 -0
  181. package/dist/mjs/types/rest/response/private-spread-trading.js +2 -0
  182. package/dist/mjs/types/rest/response/private-spread-trading.js.map +1 -0
  183. package/dist/mjs/types/rest/response/private-subaccount.d.ts +80 -0
  184. package/dist/mjs/types/rest/response/private-subaccount.js +2 -0
  185. package/dist/mjs/types/rest/response/private-subaccount.js.map +1 -0
  186. package/dist/mjs/types/rest/response/private-trade.d.ts +355 -0
  187. package/dist/mjs/types/rest/response/private-trade.js +2 -0
  188. package/dist/mjs/types/rest/response/private-trade.js.map +1 -0
  189. package/dist/mjs/types/rest/response/public-data.d.ts +174 -0
  190. package/dist/mjs/types/rest/response/public-data.js +2 -0
  191. package/dist/mjs/types/rest/response/public-data.js.map +1 -0
  192. package/dist/mjs/types/rest/shared.d.ts +45 -0
  193. package/dist/mjs/types/rest/shared.js +2 -0
  194. package/dist/mjs/types/rest/shared.js.map +1 -0
  195. package/dist/mjs/types/shared.d.ts +13 -0
  196. package/dist/mjs/types/shared.js +2 -0
  197. package/{lib/types/rest → dist/mjs/types}/shared.js.map +1 -1
  198. package/dist/mjs/types/websockets/ws-api-request.d.ts +61 -0
  199. package/dist/mjs/types/websockets/ws-api-request.js +2 -0
  200. package/dist/mjs/types/websockets/ws-api-request.js.map +1 -0
  201. package/dist/mjs/types/websockets/ws-api-response.d.ts +28 -0
  202. package/dist/mjs/types/websockets/ws-api-response.js +2 -0
  203. package/dist/mjs/types/websockets/ws-api-response.js.map +1 -0
  204. package/dist/mjs/types/websockets/ws-api.d.ts +139 -0
  205. package/dist/mjs/types/websockets/ws-api.js +35 -0
  206. package/dist/mjs/types/websockets/ws-api.js.map +1 -0
  207. package/dist/mjs/types/websockets/ws-events.d.ts +33 -0
  208. package/dist/mjs/types/websockets/ws-events.js +8 -0
  209. package/dist/mjs/types/websockets/ws-events.js.map +1 -0
  210. package/dist/mjs/types/websockets/ws-general.d.ts +48 -0
  211. package/dist/mjs/types/websockets/ws-general.js +2 -0
  212. package/dist/mjs/types/websockets/ws-general.js.map +1 -0
  213. package/dist/mjs/types/websockets/ws-request.d.ts +93 -0
  214. package/dist/mjs/types/websockets/ws-request.js +2 -0
  215. package/dist/mjs/types/websockets/ws-request.js.map +1 -0
  216. package/dist/mjs/util/BaseRestClient.d.ts +29 -0
  217. package/dist/mjs/util/BaseRestClient.js +230 -0
  218. package/dist/mjs/util/BaseRestClient.js.map +1 -0
  219. package/dist/mjs/util/BaseWSClient.d.ts +198 -0
  220. package/dist/mjs/util/BaseWSClient.js +763 -0
  221. package/dist/mjs/util/BaseWSClient.js.map +1 -0
  222. package/dist/mjs/util/WsStore.d.ts +75 -0
  223. package/dist/mjs/util/WsStore.js +298 -0
  224. package/dist/mjs/util/WsStore.js.map +1 -0
  225. package/dist/mjs/util/WsStore.types.d.ts +51 -0
  226. package/dist/mjs/util/WsStore.types.js +11 -0
  227. package/dist/mjs/util/WsStore.types.js.map +1 -0
  228. package/dist/mjs/util/logger.d.ts +8 -0
  229. package/dist/mjs/util/logger.js +14 -0
  230. package/dist/mjs/util/logger.js.map +1 -0
  231. package/dist/mjs/util/requestUtils.d.ts +8 -0
  232. package/dist/mjs/util/requestUtils.js +51 -0
  233. package/dist/mjs/util/requestUtils.js.map +1 -0
  234. package/dist/mjs/util/typeGuards.d.ts +19 -0
  235. package/dist/mjs/util/typeGuards.js +85 -0
  236. package/dist/mjs/util/typeGuards.js.map +1 -0
  237. package/dist/mjs/util/webCryptoAPI.d.ts +15 -0
  238. package/dist/mjs/util/webCryptoAPI.js +77 -0
  239. package/dist/mjs/util/webCryptoAPI.js.map +1 -0
  240. package/dist/mjs/util/websocket-util.d.ts +142 -0
  241. package/dist/mjs/util/websocket-util.js +517 -0
  242. package/dist/mjs/util/websocket-util.js.map +1 -0
  243. package/dist/mjs/websocket-api-client.d.ts +135 -0
  244. package/dist/mjs/websocket-api-client.js +167 -0
  245. package/dist/mjs/websocket-api-client.js.map +1 -0
  246. package/dist/mjs/websocket-client-legacy.d.ts +76 -0
  247. package/dist/mjs/websocket-client-legacy.js +517 -0
  248. package/dist/mjs/websocket-client-legacy.js.map +1 -0
  249. package/dist/mjs/websocket-client.d.ts +81 -0
  250. package/dist/mjs/websocket-client.js +544 -0
  251. package/dist/mjs/websocket-client.js.map +1 -0
  252. package/llms.txt +9266 -0
  253. package/package.json +30 -13
  254. package/index.js +0 -1
  255. package/lib/constants/funding.js.map +0 -1
  256. package/lib/constants/index.d.ts +0 -1
  257. package/lib/constants/index.js +0 -18
  258. package/lib/constants/index.js.map +0 -1
  259. package/lib/index.d.ts +0 -5
  260. package/lib/index.js +0 -22
  261. package/lib/index.js.map +0 -1
  262. package/lib/rest-client.js.map +0 -1
  263. package/lib/types/index.d.ts +0 -3
  264. package/lib/types/index.js +0 -20
  265. package/lib/types/index.js.map +0 -1
  266. package/lib/types/rest/client.d.ts +0 -20
  267. package/lib/types/rest/index.d.ts +0 -4
  268. package/lib/types/rest/index.js +0 -21
  269. package/lib/types/rest/index.js.map +0 -1
  270. package/lib/types/rest/request/account.js.map +0 -1
  271. package/lib/types/rest/request/announement.d.ts +0 -0
  272. package/lib/types/rest/request/announement.js +0 -1
  273. package/lib/types/rest/request/announement.js.map +0 -1
  274. package/lib/types/rest/request/block-trading.js.map +0 -1
  275. package/lib/types/rest/request/convert.js.map +0 -1
  276. package/lib/types/rest/request/copy-trading.js.map +0 -1
  277. package/lib/types/rest/request/funding.js.map +0 -1
  278. package/lib/types/rest/request/grid-trading.js.map +0 -1
  279. package/lib/types/rest/request/index.d.ts +0 -14
  280. package/lib/types/rest/request/index.js +0 -31
  281. package/lib/types/rest/request/index.js.map +0 -1
  282. package/lib/types/rest/request/public.js.map +0 -1
  283. package/lib/types/rest/request/recurring-buy.js.map +0 -1
  284. package/lib/types/rest/request/shared.js.map +0 -1
  285. package/lib/types/rest/request/signal-bot.js.map +0 -1
  286. package/lib/types/rest/request/simple-earn.js.map +0 -1
  287. package/lib/types/rest/request/spread-trading.js.map +0 -1
  288. package/lib/types/rest/request/subaccount.js.map +0 -1
  289. package/lib/types/rest/request/trade.js.map +0 -1
  290. package/lib/types/rest/response/index.d.ts +0 -11
  291. package/lib/types/rest/response/index.js +0 -28
  292. package/lib/types/rest/response/index.js.map +0 -1
  293. package/lib/types/rest/response/private-account.js.map +0 -1
  294. package/lib/types/rest/response/private-block-trading.js.map +0 -1
  295. package/lib/types/rest/response/private-copy-trading.js.map +0 -1
  296. package/lib/types/rest/response/private-flexible-loan.js.map +0 -1
  297. package/lib/types/rest/response/private-funding.js.map +0 -1
  298. package/lib/types/rest/response/private-recurring-buy.js.map +0 -1
  299. package/lib/types/rest/response/private-signal-bot.js.map +0 -1
  300. package/lib/types/rest/response/private-spread-trading.js.map +0 -1
  301. package/lib/types/rest/response/private-subaccount.js.map +0 -1
  302. package/lib/types/rest/response/private-trade.js.map +0 -1
  303. package/lib/types/rest/response/public-data.js.map +0 -1
  304. package/lib/types/shared.d.ts +0 -6
  305. package/lib/types/websockets/client.d.ts +0 -22
  306. package/lib/types/websockets/client.js +0 -3
  307. package/lib/types/websockets/event.js +0 -3
  308. package/lib/types/websockets/event.js.map +0 -1
  309. package/lib/types/websockets/index.d.ts +0 -3
  310. package/lib/types/websockets/index.js +0 -20
  311. package/lib/types/websockets/index.js.map +0 -1
  312. package/lib/types/websockets/request.js +0 -3
  313. package/lib/types/websockets/request.js.map +0 -1
  314. package/lib/util/BaseRestClient.js +0 -217
  315. package/lib/util/BaseRestClient.js.map +0 -1
  316. package/lib/util/WsStore.d.ts +0 -66
  317. package/lib/util/WsStore.js +0 -168
  318. package/lib/util/WsStore.js.map +0 -1
  319. package/lib/util/browser-support.d.ts +0 -6
  320. package/lib/util/browser-support.js +0 -49
  321. package/lib/util/browser-support.js.map +0 -1
  322. package/lib/util/index.d.ts +0 -4
  323. package/lib/util/index.js +0 -21
  324. package/lib/util/index.js.map +0 -1
  325. package/lib/util/logger.d.ts +0 -9
  326. package/lib/util/logger.js.map +0 -1
  327. package/lib/util/node-support.d.ts +0 -1
  328. package/lib/util/node-support.js +0 -9
  329. package/lib/util/node-support.js.map +0 -1
  330. package/lib/util/requestUtils.js.map +0 -1
  331. package/lib/util/typeGuards.js.map +0 -1
  332. package/lib/util/websocket-util.d.ts +0 -35
  333. package/lib/util/websocket-util.js +0 -282
  334. package/lib/util/websocket-util.js.map +0 -1
  335. package/lib/websocket-client.js +0 -472
  336. package/lib/websocket-client.js.map +0 -1
  337. /package/{lib → dist/cjs}/constants/funding.d.ts +0 -0
  338. /package/{lib → dist/cjs}/constants/funding.js +0 -0
  339. /package/{lib → dist/cjs}/types/rest/client.js +0 -0
  340. /package/{lib → dist/cjs}/types/rest/request/account.js +0 -0
  341. /package/{lib → dist/cjs}/types/rest/request/block-trading.js +0 -0
  342. /package/{lib → dist/cjs}/types/rest/request/convert.d.ts +0 -0
  343. /package/{lib → dist/cjs}/types/rest/request/convert.js +0 -0
  344. /package/{lib → dist/cjs}/types/rest/request/copy-trading.d.ts +0 -0
  345. /package/{lib → dist/cjs}/types/rest/request/copy-trading.js +0 -0
  346. /package/{lib → dist/cjs}/types/rest/request/funding.d.ts +0 -0
  347. /package/{lib → dist/cjs}/types/rest/request/funding.js +0 -0
  348. /package/{lib → dist/cjs}/types/rest/request/grid-trading.d.ts +0 -0
  349. /package/{lib → dist/cjs}/types/rest/request/grid-trading.js +0 -0
  350. /package/{lib → dist/cjs}/types/rest/request/public.d.ts +0 -0
  351. /package/{lib → dist/cjs}/types/rest/request/public.js +0 -0
  352. /package/{lib → dist/cjs}/types/rest/request/recurring-buy.d.ts +0 -0
  353. /package/{lib → dist/cjs}/types/rest/request/recurring-buy.js +0 -0
  354. /package/{lib → dist/cjs}/types/rest/request/shared.js +0 -0
  355. /package/{lib → dist/cjs}/types/rest/request/signal-bot.d.ts +0 -0
  356. /package/{lib → dist/cjs}/types/rest/request/signal-bot.js +0 -0
  357. /package/{lib → dist/cjs}/types/rest/request/simple-earn.d.ts +0 -0
  358. /package/{lib → dist/cjs}/types/rest/request/simple-earn.js +0 -0
  359. /package/{lib → dist/cjs}/types/rest/request/spread-trading.d.ts +0 -0
  360. /package/{lib → dist/cjs}/types/rest/request/spread-trading.js +0 -0
  361. /package/{lib → dist/cjs}/types/rest/request/subaccount.d.ts +0 -0
  362. /package/{lib → dist/cjs}/types/rest/request/subaccount.js +0 -0
  363. /package/{lib → dist/cjs}/types/rest/request/trade.js +0 -0
  364. /package/{lib → dist/cjs}/types/rest/response/private-account.js +0 -0
  365. /package/{lib → dist/cjs}/types/rest/response/private-block-trading.js +0 -0
  366. /package/{lib → dist/cjs}/types/rest/response/private-copy-trading.d.ts +0 -0
  367. /package/{lib → dist/cjs}/types/rest/response/private-copy-trading.js +0 -0
  368. /package/{lib → dist/cjs}/types/rest/response/private-flexible-loan.d.ts +0 -0
  369. /package/{lib → dist/cjs}/types/rest/response/private-flexible-loan.js +0 -0
  370. /package/{lib → dist/cjs}/types/rest/response/private-funding.js +0 -0
  371. /package/{lib → dist/cjs}/types/rest/response/private-recurring-buy.d.ts +0 -0
  372. /package/{lib → dist/cjs}/types/rest/response/private-recurring-buy.js +0 -0
  373. /package/{lib → dist/cjs}/types/rest/response/private-signal-bot.d.ts +0 -0
  374. /package/{lib → dist/cjs}/types/rest/response/private-signal-bot.js +0 -0
  375. /package/{lib → dist/cjs}/types/rest/response/private-spread-trading.d.ts +0 -0
  376. /package/{lib → dist/cjs}/types/rest/response/private-spread-trading.js +0 -0
  377. /package/{lib → dist/cjs}/types/rest/response/private-subaccount.d.ts +0 -0
  378. /package/{lib → dist/cjs}/types/rest/response/private-subaccount.js +0 -0
  379. /package/{lib → dist/cjs}/types/rest/response/private-trade.js +0 -0
  380. /package/{lib → dist/cjs}/types/rest/response/public-data.js +0 -0
  381. /package/{lib → dist/cjs}/types/rest/shared.js +0 -0
  382. /package/{lib → dist/cjs}/types/shared.js +0 -0
@@ -0,0 +1,763 @@
1
+ /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
2
+ import EventEmitter from 'events';
3
+ import WebSocket from 'isomorphic-ws';
4
+ import { isMessageEvent, } from '../types/websockets/ws-events.js';
5
+ import { DefaultLogger } from './logger.js';
6
+ import { checkWebCryptoAPISupported } from './webCryptoAPI.js';
7
+ import { getNormalisedTopicRequests, safeTerminateWs, WS_LOGGER_CATEGORY, } from './websocket-util.js';
8
+ import WsStore from './WsStore.js';
9
+ import { WsConnectionStateEnum } from './WsStore.types.js';
10
+ /**
11
+ * Appends wsKey and isWSAPIResponse to all events.
12
+ * Some events are arrays, this handles that nested scenario too.
13
+ */
14
+ function getFinalEmittable(emittable, wsKey, isWSAPIResponse) {
15
+ if (Array.isArray(emittable)) {
16
+ return emittable.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
17
+ }
18
+ if (Array.isArray(emittable.event)) {
19
+ // Some topics just emit an array.
20
+ // This is consistent with how it was before the WS API upgrade:
21
+ return emittable.event.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
22
+ // const { event, ...others } = emittable;
23
+ // return {
24
+ // ...others,
25
+ // event: event.map((subEvent) =>
26
+ // getFinalEmittable(subEvent, wsKey, isWSAPIResponse),
27
+ // ),
28
+ // };
29
+ }
30
+ if (emittable.event) {
31
+ return {
32
+ ...emittable.event,
33
+ wsKey: wsKey,
34
+ isWSAPIResponse: !!isWSAPIResponse,
35
+ };
36
+ }
37
+ return {
38
+ ...emittable,
39
+ wsKey: wsKey,
40
+ isWSAPIResponse: !!isWSAPIResponse,
41
+ };
42
+ }
43
+ export class BaseWebsocketClient extends EventEmitter {
44
+ /**
45
+ * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected
46
+ */
47
+ wsStore;
48
+ logger;
49
+ options;
50
+ wsApiRequestId = 0;
51
+ timeOffsetMs = 0;
52
+ /**
53
+ * { [wsKey]: { [requestId]: request } }
54
+ */
55
+ midflightRequestCache = {};
56
+ constructor(options, logger) {
57
+ super();
58
+ this.logger = logger || DefaultLogger;
59
+ this.wsStore = new WsStore(this.logger);
60
+ this.options = {
61
+ // Defaults to global (www.okx.com) API group
62
+ market: 'GLOBAL',
63
+ demoTrading: false,
64
+ pongTimeout: 2000,
65
+ pingInterval: 10000,
66
+ reconnectTimeout: 500,
67
+ // Automatically send an authentication op/request after a connection opens, for private connections.
68
+ authPrivateConnectionsOnConnect: true,
69
+ // Individual requests do not require a signature, so this is disabled.
70
+ authPrivateRequests: false,
71
+ // Whether to use native heartbeats (depends on the exchange)
72
+ useNativeHeartbeats: false,
73
+ ...options,
74
+ };
75
+ if (this.options.accounts?.length && !this.options.customSignMessageFn) {
76
+ // Provide a user friendly error message if the user is using an outdated Node.js version (where Web Crypto API is not available).
77
+ // A few users have been caught out by using the end-of-life Node.js v18 release.
78
+ checkWebCryptoAPISupported();
79
+ }
80
+ }
81
+ isPrivateWsKey(wsKey) {
82
+ return this.getPrivateWSKeys().includes(wsKey);
83
+ }
84
+ /** Returns auto-incrementing request ID, used to track promise references for async requests */
85
+ getNewRequestId() {
86
+ return ++this.wsApiRequestId;
87
+ }
88
+ getTimeOffsetMs() {
89
+ return this.timeOffsetMs;
90
+ }
91
+ setTimeOffsetMs(newOffset) {
92
+ this.timeOffsetMs = newOffset;
93
+ }
94
+ /**
95
+ * Don't call directly! Use subscribe() instead!
96
+ *
97
+ * Subscribe to one or more topics on a WS connection (identified by WS Key).
98
+ *
99
+ * - Topics are automatically cached
100
+ * - Connections are automatically opened, if not yet connected
101
+ * - Authentication is automatically handled
102
+ * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key).
103
+ *
104
+ * @param wsRequests array of topics to subscribe to
105
+ * @param wsKey ws key referring to the ws connection these topics should be subscribed on
106
+ */
107
+ async subscribeTopicsForWsKey(wsTopicRequests, wsKey) {
108
+ const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests);
109
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
110
+ for (const topic of normalisedTopicRequests) {
111
+ this.wsStore.addTopic(wsKey, topic);
112
+ }
113
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED);
114
+ const isConnectionInProgress = this.wsStore.isConnectionAttemptInProgress(wsKey);
115
+ // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
116
+ if (!isConnected && !isConnectionInProgress) {
117
+ return this.connect(wsKey);
118
+ }
119
+ // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore.
120
+ if (!isConnected) {
121
+ /**
122
+ * Are we in the process of connection? Nothing to send yet.
123
+ */
124
+ this.logger.trace('WS not connected - requests queued for retry once connected.', {
125
+ ...WS_LOGGER_CATEGORY,
126
+ wsKey,
127
+ wsTopicRequests,
128
+ });
129
+ return isConnectionInProgress;
130
+ }
131
+ // We're connected. Check if auth is needed and if already authenticated
132
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
133
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
134
+ if (isPrivateConnection && !isAuthenticated) {
135
+ /**
136
+ * If not authenticated yet and auth is required, don't request topics yet.
137
+ *
138
+ * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success.
139
+ */
140
+ return false;
141
+ }
142
+ // Finally, request subscription to topics if the connection is healthy and ready
143
+ return this.requestSubscribeTopics(wsKey, normalisedTopicRequests);
144
+ }
145
+ async unsubscribeTopicsForWsKey(wsTopicRequests, wsKey) {
146
+ const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests);
147
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
148
+ for (const topic of normalisedTopicRequests) {
149
+ this.wsStore.deleteTopic(wsKey, topic);
150
+ }
151
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED);
152
+ // If not connected, don't need to do anything.
153
+ // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect.
154
+ if (!isConnected) {
155
+ return;
156
+ }
157
+ // We're connected. Check if auth is needed and if already authenticated
158
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
159
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
160
+ if (isPrivateConnection && !isAuthenticated) {
161
+ /**
162
+ * If not authenticated yet and auth is required, don't need to do anything.
163
+ * We don't subscribe to topics until auth is complete anyway.
164
+ */
165
+ return;
166
+ }
167
+ // Finally, request subscription to topics if the connection is healthy and ready
168
+ return this.requestUnsubscribeTopics(wsKey, normalisedTopicRequests);
169
+ }
170
+ /**
171
+ * Splits topic requests into two groups, public & private topic requests
172
+ */
173
+ sortTopicRequestsIntoPublicPrivate(wsTopicRequests, wsKey) {
174
+ const publicTopicRequests = [];
175
+ const privateTopicRequests = [];
176
+ for (const topic of wsTopicRequests) {
177
+ if (this.isPrivateTopicRequest(topic, wsKey)) {
178
+ privateTopicRequests.push(topic);
179
+ }
180
+ else {
181
+ publicTopicRequests.push(topic);
182
+ }
183
+ }
184
+ return {
185
+ publicReqs: publicTopicRequests,
186
+ privateReqs: privateTopicRequests,
187
+ };
188
+ }
189
+ /** Get the WsStore that tracks websockets & topics */
190
+ getWsStore() {
191
+ return this.wsStore;
192
+ }
193
+ close(wsKey, force) {
194
+ this.logger.info('Closing connection', { ...WS_LOGGER_CATEGORY, wsKey });
195
+ this.setWsState(wsKey, WsConnectionStateEnum.CLOSING);
196
+ this.clearTimers(wsKey);
197
+ const ws = this.getWs(wsKey);
198
+ ws?.close();
199
+ if (force) {
200
+ safeTerminateWs(ws);
201
+ }
202
+ }
203
+ closeAll(force) {
204
+ const keys = this.wsStore.getKeys();
205
+ this.logger.info(`Closing all ws connections: ${keys}`);
206
+ keys.forEach((key) => {
207
+ this.close(key, force);
208
+ });
209
+ }
210
+ isConnected(wsKey) {
211
+ return this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED);
212
+ }
213
+ /**
214
+ * Request connection to a specific websocket, instead of waiting for automatic connection.
215
+ */
216
+ async connect(wsKey, customUrl, throwOnError) {
217
+ try {
218
+ if (this.wsStore.isWsOpen(wsKey)) {
219
+ this.logger.error('Refused to connect to ws with existing active connection', { ...WS_LOGGER_CATEGORY, wsKey });
220
+ return { wsKey, ws: this.wsStore.getWs(wsKey) };
221
+ }
222
+ if (this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTING)) {
223
+ this.logger.error('Refused to connect to ws, connection attempt already active', { ...WS_LOGGER_CATEGORY, wsKey });
224
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
225
+ }
226
+ if (!this.wsStore.getConnectionState(wsKey) ||
227
+ this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.INITIAL)) {
228
+ this.setWsState(wsKey, WsConnectionStateEnum.CONNECTING);
229
+ }
230
+ if (!this.wsStore.getConnectionInProgressPromise(wsKey)) {
231
+ this.wsStore.createConnectionInProgressPromise(wsKey, false);
232
+ }
233
+ const url = customUrl || (await this.getWsUrl(wsKey));
234
+ const ws = this.connectToWsUrl(url, wsKey);
235
+ this.wsStore.setWs(wsKey, ws);
236
+ }
237
+ catch (err) {
238
+ this.parseWsError('Connection failed', err, wsKey);
239
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
240
+ if (throwOnError) {
241
+ throw err;
242
+ }
243
+ }
244
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
245
+ }
246
+ connectToWsUrl(url, wsKey) {
247
+ this.logger.trace(`Opening WS connection to URL: ${url}`, {
248
+ ...WS_LOGGER_CATEGORY,
249
+ wsKey,
250
+ });
251
+ const { protocols = [], ...wsOptions } = this.options.wsOptions || {};
252
+ const ws = new WebSocket(url, protocols, wsOptions);
253
+ ws.onopen = (event) => this.onWsOpen(event, wsKey, url, ws);
254
+ ws.onmessage = (event) => this.onWsMessage(event, wsKey, ws);
255
+ ws.onerror = (event) => this.parseWsError('Websocket onWsError', event, wsKey);
256
+ ws.onclose = (event) => this.onWsClose(event, wsKey);
257
+ // Native ws ping/pong frames are not in use for okx
258
+ if (this.options.useNativeHeartbeats) {
259
+ if (typeof ws.on === 'function') {
260
+ ws.on('ping', (event) => this.onWsPing(event, wsKey, ws, 'event'));
261
+ ws.on('pong', (event) => this.onWsPong(event, wsKey, 'event'));
262
+ }
263
+ }
264
+ ws.wsKey = wsKey;
265
+ return ws;
266
+ }
267
+ parseWsError(context, error, wsKey) {
268
+ if (!error.message) {
269
+ this.logger.error(`${context} due to unexpected error: `, error);
270
+ this.emit('response', { ...error, wsKey });
271
+ this.emit('exception', { ...error, wsKey });
272
+ return;
273
+ }
274
+ switch (error.message) {
275
+ case 'Unexpected server response: 401':
276
+ this.logger.error(`${context} due to 401 authorization failure.`, {
277
+ ...WS_LOGGER_CATEGORY,
278
+ wsKey,
279
+ });
280
+ break;
281
+ default:
282
+ this.logger.error(`${context} due to unexpected response error: "${error?.msg || error?.message || error}"`, { ...WS_LOGGER_CATEGORY, wsKey, error });
283
+ break;
284
+ }
285
+ this.emit('response', { ...error, wsKey });
286
+ this.emit('exception', { ...error, wsKey });
287
+ }
288
+ /** Get a signature, build the auth request and send it */
289
+ async sendAuthRequest(wsKey) {
290
+ try {
291
+ this.logger.trace('Sending auth request...', {
292
+ ...WS_LOGGER_CATEGORY,
293
+ wsKey,
294
+ });
295
+ await this.assertIsConnected(wsKey);
296
+ if (!this.wsStore.getAuthenticationInProgressPromise(wsKey)) {
297
+ this.wsStore.createAuthenticationInProgressPromise(wsKey, false);
298
+ }
299
+ const request = await this.getWsAuthRequestEvent(wsKey);
300
+ // console.log('ws auth req', request);
301
+ this.tryWsSend(wsKey, JSON.stringify(request));
302
+ return this.wsStore.getAuthenticationInProgressPromise(wsKey)?.promise;
303
+ }
304
+ catch (e) {
305
+ this.logger.trace(e, { ...WS_LOGGER_CATEGORY, wsKey });
306
+ }
307
+ }
308
+ reconnectWithDelay(wsKey, connectionDelayMs) {
309
+ this.clearTimers(wsKey);
310
+ if (this.wsStore.getConnectionState(wsKey) !==
311
+ WsConnectionStateEnum.CONNECTING) {
312
+ this.setWsState(wsKey, WsConnectionStateEnum.RECONNECTING);
313
+ }
314
+ this.wsStore.get(wsKey, true).activeReconnectTimer = setTimeout(() => {
315
+ this.logger.info('Reconnecting to websocket', {
316
+ ...WS_LOGGER_CATEGORY,
317
+ wsKey,
318
+ });
319
+ this.connect(wsKey);
320
+ }, connectionDelayMs);
321
+ }
322
+ ping(wsKey) {
323
+ if (this.wsStore.get(wsKey, true).activePongTimer) {
324
+ return;
325
+ }
326
+ this.clearPongTimer(wsKey);
327
+ this.logger.trace('Sending ping', { ...WS_LOGGER_CATEGORY, wsKey });
328
+ this.tryWsSend(wsKey, 'ping');
329
+ this.wsStore.get(wsKey, true).activePongTimer = setTimeout(() => {
330
+ this.logger.info('Pong timeout - closing socket to reconnect', {
331
+ ...WS_LOGGER_CATEGORY,
332
+ wsKey,
333
+ });
334
+ safeTerminateWs(this.getWs(wsKey), true);
335
+ delete this.wsStore.get(wsKey, true).activePongTimer;
336
+ }, this.options.pongTimeout);
337
+ }
338
+ clearTimers(wsKey) {
339
+ this.clearPingTimer(wsKey);
340
+ this.clearPongTimer(wsKey);
341
+ const wsState = this.wsStore.get(wsKey);
342
+ if (wsState?.activeReconnectTimer) {
343
+ clearTimeout(wsState.activeReconnectTimer);
344
+ }
345
+ }
346
+ // Send a ping at intervals
347
+ clearPingTimer(wsKey) {
348
+ const wsState = this.wsStore.get(wsKey);
349
+ if (wsState?.activePingTimer) {
350
+ clearInterval(wsState.activePingTimer);
351
+ wsState.activePingTimer = undefined;
352
+ }
353
+ }
354
+ // Expect a pong within a time limit
355
+ clearPongTimer(wsKey) {
356
+ const wsState = this.wsStore.get(wsKey);
357
+ if (wsState?.activePongTimer) {
358
+ clearTimeout(wsState.activePongTimer);
359
+ wsState.activePongTimer = undefined;
360
+ }
361
+ }
362
+ /**
363
+ * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics
364
+ *
365
+ * If events are an object, these should be stringified (`return JSON.stringify(event);`)
366
+ * Each event returned by this will be sent one at a time
367
+ *
368
+ * Events are automatically split into smaller batches, by this method, if needed.
369
+ */
370
+ async getWsOperationEventsForTopics(topics, wsKey, operation) {
371
+ if (!topics.length) {
372
+ return [];
373
+ }
374
+ // Events that are ready to send (usually stringified JSON)
375
+ const requestEvents = [];
376
+ const maxTopicsPerEvent = this.getMaxTopicsPerSubscribeEvent(wsKey);
377
+ if (maxTopicsPerEvent &&
378
+ maxTopicsPerEvent !== null &&
379
+ topics.length > maxTopicsPerEvent) {
380
+ for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
381
+ const batch = topics.slice(i, i + maxTopicsPerEvent);
382
+ const subscribeRequestEvents = await this.getWsRequestEvents(operation, batch, wsKey);
383
+ requestEvents.push(...subscribeRequestEvents);
384
+ }
385
+ return requestEvents;
386
+ }
387
+ const subscribeRequestEvents = await this.getWsRequestEvents(operation, topics, wsKey);
388
+ return subscribeRequestEvents;
389
+ }
390
+ /**
391
+ * @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics.
392
+ */
393
+ async requestSubscribeTopics(wsKey, wsTopicRequests) {
394
+ if (!wsTopicRequests.length) {
395
+ return;
396
+ }
397
+ // Automatically splits requests into smaller batches, if needed
398
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'subscribe');
399
+ this.logger.trace(`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
400
+ // console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2));
401
+ for (const midflightRequest of subscribeWsMessages) {
402
+ const wsMessage = midflightRequest.requestEvent;
403
+ if (!this.midflightRequestCache[wsKey]) {
404
+ this.midflightRequestCache[wsKey] = {};
405
+ }
406
+ // Cache the request for this call, so we can enrich the response with request info
407
+ // this.midflightRequestCache[wsKey][midflightRequest.requestKey] =
408
+ // midflightRequest.requestEvent;
409
+ this.logger.trace(
410
+ // `Sending batch via message: "${JSON.stringify(wsMessage)}", cached with key "${midflightRequest.requestKey}"`,
411
+ `Sending batch via message: "${JSON.stringify(wsMessage)}"`);
412
+ try {
413
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage), true);
414
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
415
+ }
416
+ catch (e) {
417
+ delete this.midflightRequestCache[wsKey][midflightRequest.requestKey];
418
+ }
419
+ }
420
+ }
421
+ /**
422
+ * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
423
+ */
424
+ async requestUnsubscribeTopics(wsKey, wsTopicRequests) {
425
+ if (!wsTopicRequests.length) {
426
+ return;
427
+ }
428
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'unsubscribe');
429
+ this.logger.trace(`Unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches. Events: "${JSON.stringify(wsTopicRequests)}"`);
430
+ for (const midflightRequest of subscribeWsMessages) {
431
+ const wsMessage = midflightRequest.requestEvent;
432
+ if (!this.midflightRequestCache[wsKey]) {
433
+ this.midflightRequestCache[wsKey] = {};
434
+ }
435
+ // Cache the request for this call, so we can enrich the response with request info
436
+ // this.midflightRequestCache[wsKey][midflightRequest.requestKey] =
437
+ // midflightRequest.requestEvent;
438
+ this.logger.trace(`Sending batch via message: "${wsMessage}"`);
439
+ try {
440
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage));
441
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
442
+ }
443
+ catch (e) {
444
+ delete this.midflightRequestCache[wsKey][midflightRequest.requestKey];
445
+ }
446
+ }
447
+ this.logger.trace(`Finished unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
448
+ }
449
+ getCachedMidFlightRequest(wsKey, requestKey) {
450
+ if (!this.midflightRequestCache[wsKey]) {
451
+ this.midflightRequestCache[wsKey] = {};
452
+ }
453
+ return this.midflightRequestCache[wsKey][requestKey];
454
+ }
455
+ // Not in use for OKX. If desired, call from resolveEmittableEvents() for WS API responses.
456
+ // See binance SDK for reference
457
+ removeCachedMidFlightRequest(wsKey, requestKey) {
458
+ if (this.getCachedMidFlightRequest(wsKey, requestKey)) {
459
+ delete this.midflightRequestCache[wsKey][requestKey];
460
+ }
461
+ }
462
+ tryWsSend(wsKey, wsMessage, throwExceptions) {
463
+ try {
464
+ this.logger.trace('Sending upstream ws message: ', {
465
+ ...WS_LOGGER_CATEGORY,
466
+ wsMessage,
467
+ wsKey,
468
+ });
469
+ if (!wsKey) {
470
+ throw new Error('Cannot send message due to no known websocket for this wsKey');
471
+ }
472
+ const ws = this.getWs(wsKey);
473
+ if (!ws) {
474
+ throw new Error(`${wsKey} socket not connected yet, call "connectAll()" first then try again when the "open" event arrives`);
475
+ }
476
+ ws.send(wsMessage);
477
+ }
478
+ catch (e) {
479
+ this.logger.error('Failed to send WS message', {
480
+ ...WS_LOGGER_CATEGORY,
481
+ wsMessage,
482
+ wsKey,
483
+ exception: e,
484
+ });
485
+ if (throwExceptions) {
486
+ throw e;
487
+ }
488
+ }
489
+ }
490
+ async onWsOpen(event, wsKey, url, ws) {
491
+ const isFreshConnectionAttempt = this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTING);
492
+ const isReconnectionAttempt = this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.RECONNECTING);
493
+ if (isFreshConnectionAttempt) {
494
+ this.logger.info('Websocket connected', {
495
+ ...WS_LOGGER_CATEGORY,
496
+ wsKey,
497
+ });
498
+ this.emit('open', { wsKey, event, wsUrl: url, ws });
499
+ }
500
+ else if (isReconnectionAttempt) {
501
+ this.logger.info('Websocket reconnected', {
502
+ ...WS_LOGGER_CATEGORY,
503
+ wsKey,
504
+ });
505
+ this.emit('reconnected', { wsKey, event, wsUrl: url, ws });
506
+ }
507
+ this.setWsState(wsKey, WsConnectionStateEnum.CONNECTED);
508
+ this.logger.trace('Enabled ping timer', { ...WS_LOGGER_CATEGORY, wsKey });
509
+ this.wsStore.get(wsKey, true).activePingTimer = setInterval(() => this.ping(wsKey), this.options.pingInterval);
510
+ // Resolve & cleanup deferred "connection attempt in progress" promise
511
+ try {
512
+ const connectionInProgressPromise = this.wsStore.getConnectionInProgressPromise(wsKey);
513
+ if (connectionInProgressPromise?.resolve) {
514
+ connectionInProgressPromise.resolve({
515
+ wsKey,
516
+ ws,
517
+ });
518
+ }
519
+ }
520
+ catch (e) {
521
+ this.logger.error('Exception trying to resolve "connectionInProgress" promise', e);
522
+ }
523
+ // Remove before continuing, in case there's more requests queued
524
+ this.wsStore.removeConnectingInProgressPromise(wsKey);
525
+ // Some websockets require an auth packet to be sent after opening the connection
526
+ if (this.isAuthOnConnectWsKey(wsKey) &&
527
+ this.options.authPrivateConnectionsOnConnect) {
528
+ await this.assertIsAuthenticated(wsKey);
529
+ }
530
+ // Reconnect to topics known before it connected
531
+ const { privateReqs, publicReqs } = this.sortTopicRequestsIntoPublicPrivate([...this.wsStore.getTopics(wsKey)], wsKey);
532
+ // Request sub to public topics, if any
533
+ this.requestSubscribeTopics(wsKey, publicReqs);
534
+ // Request sub to private topics, if auth on connect isn't needed
535
+ // Else, this is automatic after authentication is successfully confirmed
536
+ if (!this.options.authPrivateConnectionsOnConnect) {
537
+ this.requestSubscribeTopics(wsKey, privateReqs);
538
+ }
539
+ }
540
+ /**
541
+ * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
542
+ *
543
+ * Only used for exchanges that require auth before sending private topic subscription requests
544
+ */
545
+ onWsAuthenticated(wsKey, event) {
546
+ const wsState = this.wsStore.get(wsKey, true);
547
+ wsState.isAuthenticated = true;
548
+ // Resolve & cleanup deferred "auth attempt in progress" promise
549
+ try {
550
+ const inProgressPromise = this.wsStore.getAuthenticationInProgressPromise(wsKey);
551
+ if (inProgressPromise?.resolve) {
552
+ inProgressPromise.resolve({
553
+ wsKey,
554
+ event,
555
+ ws: wsState.ws,
556
+ });
557
+ }
558
+ }
559
+ catch (e) {
560
+ this.logger.error('Exception trying to resolve "authenticationInProgress" promise', e);
561
+ }
562
+ // Remove before continuing, in case there's more requests queued
563
+ this.wsStore.removeAuthenticationInProgressPromise(wsKey);
564
+ if (this.options.authPrivateConnectionsOnConnect) {
565
+ const topics = [...this.wsStore.getTopics(wsKey)];
566
+ const privateTopics = topics.filter((topic) => this.isPrivateTopicRequest(topic, wsKey));
567
+ if (privateTopics.length) {
568
+ this.subscribeTopicsForWsKey(privateTopics, wsKey);
569
+ }
570
+ }
571
+ }
572
+ onWsPing(event, wsKey, ws, source) {
573
+ this.logger.trace('Received ping', {
574
+ ...WS_LOGGER_CATEGORY,
575
+ wsKey,
576
+ event,
577
+ source,
578
+ });
579
+ this.sendPongEvent(wsKey, ws);
580
+ }
581
+ onWsPong(event, wsKey, source) {
582
+ this.logger.trace('Received pong', {
583
+ ...WS_LOGGER_CATEGORY,
584
+ wsKey,
585
+ event: event?.data,
586
+ source,
587
+ });
588
+ return;
589
+ }
590
+ /**
591
+ * Raw incoming event handler. Parsing happens in integration layer via resolveEmittableEvents().
592
+ */
593
+ onWsMessage(event, wsKey, ws) {
594
+ try {
595
+ // console.log('onMessageRaw: ', (event as any).data);
596
+ // any message can clear the pong timer - wouldn't get a message if the ws wasn't working
597
+ this.clearPongTimer(wsKey);
598
+ if (this.isWsPong(event)) {
599
+ return this.onWsPong(event, wsKey, 'event');
600
+ }
601
+ if (this.isWsPing(event)) {
602
+ return this.onWsPing(event, wsKey, ws, 'event');
603
+ }
604
+ if (isMessageEvent(event)) {
605
+ const data = event.data;
606
+ const dataType = event.type;
607
+ const emittableEvents = this.resolveEmittableEvents(wsKey, event);
608
+ if (!emittableEvents.length) {
609
+ // console.log(`raw event: `, { data, dataType, emittableEvents });
610
+ this.logger.error('Unhandled/unrecognised ws event message - returned no emittable data', {
611
+ ...WS_LOGGER_CATEGORY,
612
+ message: data || 'no message',
613
+ dataType,
614
+ event,
615
+ wsKey,
616
+ });
617
+ return this.emit('update', { ...event, wsKey });
618
+ }
619
+ for (const emittable of emittableEvents) {
620
+ if (this.isWsPong(emittable)) {
621
+ this.logger.trace('Received pong2', {
622
+ ...WS_LOGGER_CATEGORY,
623
+ wsKey,
624
+ data,
625
+ });
626
+ continue;
627
+ }
628
+ // this.logger.trace(
629
+ // 'getFinalEmittable()->pre(): ',
630
+ // JSON.stringify(emittable),
631
+ // );
632
+ const emittableFinalEvent = getFinalEmittable(emittable, wsKey, emittable.isWSAPIResponse);
633
+ // this.logger.trace(
634
+ // 'getFinalEmittable()->post(): ',
635
+ // JSON.stringify(emittable),
636
+ // );
637
+ if (emittable.eventType === 'authenticated') {
638
+ this.logger.trace('Successfully authenticated', {
639
+ ...WS_LOGGER_CATEGORY,
640
+ wsKey,
641
+ emittable,
642
+ });
643
+ this.emit(emittable.eventType, emittableFinalEvent);
644
+ this.onWsAuthenticated(wsKey, emittable.event);
645
+ continue;
646
+ }
647
+ // Other event types are automatically emitted here
648
+ // this.logger.trace(
649
+ // `onWsMessage().emit(${emittable.eventType})`,
650
+ // emittableFinalEvent,
651
+ // );
652
+ try {
653
+ this.emit(emittable.eventType, emittableFinalEvent);
654
+ }
655
+ catch (e) {
656
+ this.logger.error(`Exception in onWsMessage().emit(${emittable.eventType}) handler:`, e);
657
+ }
658
+ // this.logger.trace(
659
+ // `onWsMessage().emit(${emittable.eventType}).done()`,
660
+ // emittableFinalEvent,
661
+ // );
662
+ }
663
+ return;
664
+ }
665
+ this.logger.error('Unhandled/unrecognised ws event message - unexpected message format', {
666
+ ...WS_LOGGER_CATEGORY,
667
+ message: event || 'no message',
668
+ event,
669
+ wsKey,
670
+ });
671
+ }
672
+ catch (e) {
673
+ this.logger.error('Failed to parse ws event message', {
674
+ ...WS_LOGGER_CATEGORY,
675
+ error: e,
676
+ event,
677
+ wsKey,
678
+ });
679
+ }
680
+ }
681
+ onWsClose(event, wsKey) {
682
+ this.logger.info('Websocket connection closed', {
683
+ ...WS_LOGGER_CATEGORY,
684
+ wsKey,
685
+ });
686
+ const wsState = this.wsStore.get(wsKey, true);
687
+ wsState.isAuthenticated = false;
688
+ if (this.wsStore.getConnectionState(wsKey) !== WsConnectionStateEnum.CLOSING) {
689
+ // unintentional close, attempt recovery
690
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
691
+ // clean up any pending promises for this connection
692
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'connection lost, reconnecting');
693
+ this.setWsState(wsKey, WsConnectionStateEnum.INITIAL);
694
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
695
+ this.emit('reconnect', { wsKey, event });
696
+ }
697
+ else {
698
+ // intentional close - clean up
699
+ // clean up any pending promises for this connection
700
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
701
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'disconnected');
702
+ this.setWsState(wsKey, WsConnectionStateEnum.INITIAL);
703
+ // This was an intentional close, delete all state for this connection, as if it never existed:
704
+ this.wsStore.delete(wsKey);
705
+ this.emit('close', { wsKey, event });
706
+ }
707
+ }
708
+ getWs(wsKey) {
709
+ return this.wsStore.getWs(wsKey);
710
+ }
711
+ setWsState(wsKey, state) {
712
+ this.wsStore.setConnectionState(wsKey, state);
713
+ }
714
+ /**
715
+ * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
716
+ */
717
+ async assertIsConnected(wsKey) {
718
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED);
719
+ if (isConnected) {
720
+ return true;
721
+ }
722
+ const inProgressPromise = this.getWsStore().getConnectionInProgressPromise(wsKey);
723
+ // Already in progress? Await shared promise and retry
724
+ if (inProgressPromise) {
725
+ this.logger.trace('assertIsConnected(): awaiting...');
726
+ await inProgressPromise.promise;
727
+ this.logger.trace('assertIsConnected(): awaiting...connected!');
728
+ return inProgressPromise.promise;
729
+ }
730
+ // Start connection, it should automatically store/return a promise.
731
+ this.logger.trace('assertIsConnected(): connecting...');
732
+ await this.connect(wsKey);
733
+ this.logger.trace('assertIsConnected(): connecting...newly connected!');
734
+ }
735
+ /**
736
+ * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
737
+ */
738
+ async assertIsAuthenticated(wsKey) {
739
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED);
740
+ if (!isConnected) {
741
+ this.logger.trace('assertIsAuthenticated(): connecting...');
742
+ await this.assertIsConnected(wsKey);
743
+ }
744
+ const inProgressPromise = this.getWsStore().getAuthenticationInProgressPromise(wsKey);
745
+ // Already in progress? Await shared promise and retry
746
+ if (inProgressPromise) {
747
+ this.logger.trace('assertIsAuthenticated(): awaiting...');
748
+ await inProgressPromise.promise;
749
+ this.logger.trace('assertIsAuthenticated(): authenticated!');
750
+ return;
751
+ }
752
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
753
+ if (isAuthenticated) {
754
+ // this.logger.trace('assertIsAuthenticated(): ok');
755
+ return;
756
+ }
757
+ // Start authentication, it should automatically store/return a promise.
758
+ this.logger.trace('assertIsAuthenticated(): authenticating...');
759
+ await this.sendAuthRequest(wsKey);
760
+ this.logger.trace('assertIsAuthenticated(): newly authenticated!');
761
+ }
762
+ }
763
+ //# sourceMappingURL=BaseWSClient.js.map