bitget-api 0.0.1 → 1.0.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 (89) hide show
  1. package/README.md +85 -140
  2. package/lib/broker-client.d.ts +46 -0
  3. package/lib/broker-client.js +113 -0
  4. package/lib/broker-client.js.map +1 -0
  5. package/lib/constants/enum.d.ts +17 -0
  6. package/lib/constants/enum.js +21 -0
  7. package/lib/constants/enum.js.map +1 -0
  8. package/lib/futures-client.d.ts +146 -0
  9. package/lib/futures-client.js +380 -0
  10. package/lib/futures-client.js.map +1 -0
  11. package/lib/index.d.ts +8 -1
  12. package/lib/index.js +22 -13
  13. package/lib/index.js.map +1 -1
  14. package/lib/spot-client.d.ts +109 -0
  15. package/lib/spot-client.js +201 -0
  16. package/lib/spot-client.js.map +1 -0
  17. package/lib/types/index.d.ts +4 -0
  18. package/lib/types/index.js +21 -0
  19. package/lib/types/index.js.map +1 -0
  20. package/lib/types/request/broker.d.ts +23 -0
  21. package/lib/types/request/broker.js +3 -0
  22. package/lib/types/request/broker.js.map +1 -0
  23. package/lib/types/request/futures.d.ts +114 -0
  24. package/lib/types/request/futures.js +3 -0
  25. package/lib/types/request/futures.js.map +1 -0
  26. package/lib/types/request/index.d.ts +4 -0
  27. package/lib/types/request/index.js +21 -0
  28. package/lib/types/request/index.js.map +1 -0
  29. package/lib/types/request/shared.d.ts +10 -0
  30. package/lib/types/request/shared.js +3 -0
  31. package/lib/types/request/shared.js.map +1 -0
  32. package/lib/types/request/spot.d.ts +19 -0
  33. package/lib/types/request/spot.js +3 -0
  34. package/lib/types/request/spot.js.map +1 -0
  35. package/lib/types/response/futures.d.ts +55 -0
  36. package/lib/types/response/futures.js +3 -0
  37. package/lib/types/response/futures.js.map +1 -0
  38. package/lib/types/response/index.d.ts +3 -0
  39. package/lib/types/response/index.js +20 -0
  40. package/lib/types/response/index.js.map +1 -0
  41. package/lib/types/response/shared.d.ts +6 -0
  42. package/lib/types/response/shared.js +3 -0
  43. package/lib/types/response/shared.js.map +1 -0
  44. package/lib/types/response/spot.d.ts +21 -0
  45. package/lib/types/response/spot.js +3 -0
  46. package/lib/types/response/spot.js.map +1 -0
  47. package/lib/types/shared.d.ts +5 -0
  48. package/lib/types/shared.js +3 -0
  49. package/lib/types/shared.js.map +1 -0
  50. package/lib/types/websockets/client.d.ts +37 -0
  51. package/lib/types/websockets/client.js +3 -0
  52. package/lib/types/websockets/client.js.map +1 -0
  53. package/lib/types/websockets/events.d.ts +75 -0
  54. package/lib/types/websockets/events.js +3 -0
  55. package/lib/types/websockets/events.js.map +1 -0
  56. package/lib/types/websockets/index.d.ts +2 -0
  57. package/lib/types/websockets/index.js +19 -0
  58. package/lib/types/websockets/index.js.map +1 -0
  59. package/lib/util/BaseRestClient.d.ts +40 -0
  60. package/lib/util/BaseRestClient.js +195 -0
  61. package/lib/util/BaseRestClient.js.map +1 -0
  62. package/lib/util/WsStore.d.ts +62 -0
  63. package/lib/util/WsStore.js +135 -0
  64. package/lib/util/WsStore.js.map +1 -0
  65. package/lib/util/browser-support.d.ts +1 -0
  66. package/lib/util/browser-support.js +44 -0
  67. package/lib/util/browser-support.js.map +1 -0
  68. package/lib/util/index.d.ts +6 -0
  69. package/lib/util/index.js +23 -0
  70. package/lib/util/index.js.map +1 -0
  71. package/lib/util/logger.d.ts +9 -0
  72. package/lib/util/logger.js +24 -0
  73. package/lib/util/logger.js.map +1 -0
  74. package/lib/util/node-support.d.ts +2 -0
  75. package/lib/util/node-support.js +33 -0
  76. package/lib/util/node-support.js.map +1 -0
  77. package/lib/util/requestUtils.d.ts +31 -0
  78. package/lib/util/requestUtils.js +53 -0
  79. package/lib/util/requestUtils.js.map +1 -0
  80. package/lib/util/type-guards.d.ts +9 -0
  81. package/lib/util/type-guards.js +50 -0
  82. package/lib/util/type-guards.js.map +1 -0
  83. package/lib/util/websocket-util.d.ts +38 -0
  84. package/lib/util/websocket-util.js +100 -0
  85. package/lib/util/websocket-util.js.map +1 -0
  86. package/lib/websocket-client.d.ts +121 -0
  87. package/lib/websocket-client.js +442 -0
  88. package/lib/websocket-client.js.map +1 -0
  89. package/package.json +16 -16
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-support.js","sourceRoot":"","sources":["../../src/util/browser-support.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,SAAS,oBAAoB,CAAC,MAAmB;IAC/C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,GAAG,GAAG,KAAK,CAAC,UAAU,CAAC;IAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE;QAC5B,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;KACzC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC7B,CAAC;AAED,SAAsB,WAAW,CAC/B,OAAe,EACf,MAAc,EACd,MAAwB;;QAExB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;QAClC,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAC9C,KAAK,EACL,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,EACtB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAC3C,KAAK,EACL,CAAC,MAAM,CAAC,CACT,CAAC;QAEF,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAC/C,MAAM,EACN,GAAG,EACH,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CACxB,CAAC;QAEF,QAAQ,MAAM,EAAE;YACd,KAAK,KAAK,CAAC,CAAC;gBACV,OAAO,KAAK,CAAC,SAAS,CAAC,GAAG;qBACvB,IAAI,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC,CAAM,EAAE,EAAE,CAC1C,CAAC,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAClC;qBACA,IAAI,CAAC,EAAE,CAAC,CAAC;aACb;YACD,KAAK,QAAQ,CAAC,CAAC;gBACb,OAAO,oBAAoB,CAAC,SAAS,CAAC,CAAC;aACxC;YACD,OAAO,CAAC,CAAC;gBACP,CAAC,CAAC,CAAQ,EAAE,EAAE,GAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;gBAC3B,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;aACrD;SACF;IACH,CAAC;CAAA;AApCD,kCAoCC"}
@@ -0,0 +1,6 @@
1
+ export * from './BaseRestClient';
2
+ export * from './requestUtils';
3
+ export * from './WsStore';
4
+ export * from './logger';
5
+ export * from './type-guards';
6
+ export * from './websocket-util';
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./BaseRestClient"), exports);
18
+ __exportStar(require("./requestUtils"), exports);
19
+ __exportStar(require("./WsStore"), exports);
20
+ __exportStar(require("./logger"), exports);
21
+ __exportStar(require("./type-guards"), exports);
22
+ __exportStar(require("./websocket-util"), exports);
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/util/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,mDAAiC;AACjC,iDAA+B;AAC/B,4CAA0B;AAC1B,2CAAyB;AACzB,gDAA8B;AAC9B,mDAAiC"}
@@ -0,0 +1,9 @@
1
+ export declare type LogParams = null | any;
2
+ export declare const DefaultLogger: {
3
+ silly: (...params: LogParams) => void;
4
+ debug: (...params: LogParams) => void;
5
+ notice: (...params: LogParams) => void;
6
+ info: (...params: LogParams) => void;
7
+ warning: (...params: LogParams) => void;
8
+ error: (...params: LogParams) => void;
9
+ };
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultLogger = void 0;
4
+ exports.DefaultLogger = {
5
+ silly: (...params) => {
6
+ // console.log(params);
7
+ },
8
+ debug: (...params) => {
9
+ console.log(params);
10
+ },
11
+ notice: (...params) => {
12
+ console.log(params);
13
+ },
14
+ info: (...params) => {
15
+ console.info(params);
16
+ },
17
+ warning: (...params) => {
18
+ console.error(params);
19
+ },
20
+ error: (...params) => {
21
+ console.error(params);
22
+ },
23
+ };
24
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/util/logger.ts"],"names":[],"mappings":";;;AAEa,QAAA,aAAa,GAAG;IAC3B,KAAK,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACpC,uBAAuB;IACzB,CAAC;IACD,KAAK,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACpC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IACD,MAAM,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACrC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC;IACD,IAAI,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACnC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACtC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;IACD,KAAK,EAAE,CAAC,GAAG,MAAiB,EAAQ,EAAE;QACpC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACxB,CAAC;CACF,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** This is async because the browser version uses a promise (browser-support) */
2
+ export declare function signMessage(message: string, secret: string, method: 'hex' | 'base64'): Promise<string>;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.signMessage = void 0;
13
+ const crypto_1 = require("crypto");
14
+ /** This is async because the browser version uses a promise (browser-support) */
15
+ function signMessage(message, secret, method) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ const hmac = (0, crypto_1.createHmac)('sha256', secret).update(message);
18
+ switch (method) {
19
+ case 'hex': {
20
+ return hmac.digest('hex');
21
+ }
22
+ case 'base64': {
23
+ return hmac.digest().toString('base64');
24
+ }
25
+ default: {
26
+ ((x) => { })(method);
27
+ throw new Error(`Unhandled sign method: ${method}`);
28
+ }
29
+ }
30
+ });
31
+ }
32
+ exports.signMessage = signMessage;
33
+ //# sourceMappingURL=node-support.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-support.js","sourceRoot":"","sources":["../../src/util/node-support.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAoC;AAEpC,iFAAiF;AACjF,SAAsB,WAAW,CAC/B,OAAe,EACf,MAAc,EACd,MAAwB;;QAExB,MAAM,IAAI,GAAG,IAAA,mBAAU,EAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE1D,QAAQ,MAAM,EAAE;YACd,KAAK,KAAK,CAAC,CAAC;gBACV,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aAC3B;YACD,KAAK,QAAQ,CAAC,CAAC;gBACb,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;aACzC;YACD,OAAO,CAAC,CAAC;gBACP,CAAC,CAAC,CAAQ,EAAE,EAAE,GAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;gBAC3B,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,EAAE,CAAC,CAAC;aACrD;SACF;IACH,CAAC;CAAA;AAnBD,kCAmBC"}
@@ -0,0 +1,31 @@
1
+ export interface RestClientOptions {
2
+ /** Your API key */
3
+ apiKey?: string;
4
+ /** Your API secret */
5
+ apiSecret?: string;
6
+ /** The passphrase you set when creating the API Key (NOT your account password) */
7
+ apiPass?: string;
8
+ /** Set to `true` to connect to testnet. Uses the live environment by default. */
9
+ /** Override the max size of the request window (in ms) */
10
+ recvWindow?: number;
11
+ /** Default: false. If true, we'll throw errors if any params are undefined */
12
+ strictParamValidation?: boolean;
13
+ /**
14
+ * Optionally override API protocol + domain
15
+ * e.g baseUrl: 'https://api.bitget.com'
16
+ **/
17
+ baseUrl?: string;
18
+ /** Default: true. whether to try and post-process request exceptions (and throw them). */
19
+ parseExceptions?: boolean;
20
+ }
21
+ export declare function serializeParams<T extends object | undefined = {}>(params: T, strict_validation?: boolean, prefixWith?: string): string;
22
+ export declare function getRestBaseUrl(useTestnet: boolean, restInverseOptions: RestClientOptions): string;
23
+ export declare function isWsPong(msg: any): boolean;
24
+ /**
25
+ * Used to switch how authentication/requests work under the hood (primarily for SPOT since it's different there)
26
+ */
27
+ export declare const REST_CLIENT_TYPE_ENUM: {
28
+ readonly spot: "spot";
29
+ readonly futures: "futures";
30
+ readonly broker: "broker";
31
+ };
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REST_CLIENT_TYPE_ENUM = exports.isWsPong = exports.getRestBaseUrl = exports.serializeParams = void 0;
4
+ function serializeParams(params, strict_validation = false, prefixWith = '') {
5
+ if (!params) {
6
+ return '';
7
+ }
8
+ const queryString = Object.keys(params)
9
+ .sort()
10
+ .map((key) => {
11
+ const value = params[key];
12
+ if (strict_validation === true && typeof value === 'undefined') {
13
+ throw new Error('Failed to sign API request due to undefined parameter');
14
+ }
15
+ return `${key}=${value}`;
16
+ })
17
+ .join('&');
18
+ // Only prefix if there's a value
19
+ return queryString ? prefixWith + queryString : queryString;
20
+ }
21
+ exports.serializeParams = serializeParams;
22
+ function getRestBaseUrl(useTestnet, restInverseOptions) {
23
+ const exchangeBaseUrls = {
24
+ livenet: 'https://api.bitget.com',
25
+ livenet2: 'https://capi.bitget.com',
26
+ testnet: 'https://noTestnet',
27
+ };
28
+ if (restInverseOptions.baseUrl) {
29
+ return restInverseOptions.baseUrl;
30
+ }
31
+ if (useTestnet) {
32
+ return exchangeBaseUrls.testnet;
33
+ }
34
+ return exchangeBaseUrls.livenet;
35
+ }
36
+ exports.getRestBaseUrl = getRestBaseUrl;
37
+ function isWsPong(msg) {
38
+ // bitget
39
+ if ((msg === null || msg === void 0 ? void 0 : msg.data) === 'pong') {
40
+ return true;
41
+ }
42
+ return false;
43
+ }
44
+ exports.isWsPong = isWsPong;
45
+ /**
46
+ * Used to switch how authentication/requests work under the hood (primarily for SPOT since it's different there)
47
+ */
48
+ exports.REST_CLIENT_TYPE_ENUM = {
49
+ spot: 'spot',
50
+ futures: 'futures',
51
+ broker: 'broker',
52
+ };
53
+ //# sourceMappingURL=requestUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestUtils.js","sourceRoot":"","sources":["../../src/util/requestUtils.ts"],"names":[],"mappings":";;;AA6BA,SAAgB,eAAe,CAC7B,MAAS,EACT,iBAAiB,GAAG,KAAK,EACzB,aAAqB,EAAE;IAEvB,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IAED,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;SACpC,IAAI,EAAE;SACN,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;QACX,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,IAAI,iBAAiB,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;YAC9D,MAAM,IAAI,KAAK,CACb,uDAAuD,CACxD,CAAC;SACH;QACD,OAAO,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC;IAC3B,CAAC,CAAC;SACD,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,iCAAiC;IACjC,OAAO,WAAW,CAAC,CAAC,CAAC,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC;AAC9D,CAAC;AAxBD,0CAwBC;AAED,SAAgB,cAAc,CAC5B,UAAmB,EACnB,kBAAqC;IAErC,MAAM,gBAAgB,GAAG;QACvB,OAAO,EAAE,wBAAwB;QACjC,QAAQ,EAAE,yBAAyB;QACnC,OAAO,EAAE,mBAAmB;KAC7B,CAAC;IAEF,IAAI,kBAAkB,CAAC,OAAO,EAAE;QAC9B,OAAO,kBAAkB,CAAC,OAAO,CAAC;KACnC;IAED,IAAI,UAAU,EAAE;QACd,OAAO,gBAAgB,CAAC,OAAO,CAAC;KACjC;IAED,OAAO,gBAAgB,CAAC,OAAO,CAAC;AAClC,CAAC;AAnBD,wCAmBC;AAED,SAAgB,QAAQ,CAAC,GAAQ;IAC/B,SAAS;IACT,IAAI,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,IAAI,MAAK,MAAM,EAAE;QACxB,OAAO,IAAI,CAAC;KACb;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAND,4BAMC;AAED;;GAEG;AACU,QAAA,qBAAqB,GAAG;IACnC,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;CACR,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { WsAccountSnapshotUMCBL, WSPositionSnapshotUMCBL, WsSnapshotAccountEvent, WsSnapshotPositionsEvent } from '../types';
2
+ /** TypeGuard: event is an account update (balance) */
3
+ export declare function isWsAccountSnapshotEvent(event: unknown): event is WsSnapshotAccountEvent;
4
+ /** TypeGuard: event is a positions update */
5
+ export declare function isWsPositionsSnapshotEvent(event: unknown): event is WsSnapshotPositionsEvent;
6
+ /** TypeGuard: event is a UMCBL account update (balance) */
7
+ export declare function isWsFuturesAccountSnapshotEvent(event: unknown): event is WsAccountSnapshotUMCBL;
8
+ /** TypeGuard: event is a UMCBL positions update */
9
+ export declare function isWsFuturesPositionsSnapshotEvent(event: unknown): event is WSPositionSnapshotUMCBL;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isWsFuturesPositionsSnapshotEvent = exports.isWsFuturesAccountSnapshotEvent = exports.isWsPositionsSnapshotEvent = exports.isWsAccountSnapshotEvent = void 0;
4
+ /** TypeGuard: event has a string "action" property */
5
+ function isWsEvent(event) {
6
+ return (typeof event === 'object' &&
7
+ event &&
8
+ typeof event['action'] === 'string' &&
9
+ event['data']);
10
+ }
11
+ /** TypeGuard: event has "action === snapshot" */
12
+ function isWsSnapshotEvent(event) {
13
+ return isWsEvent(event) && event.action === 'snapshot';
14
+ }
15
+ /** TypeGuard: event has a string channel name */
16
+ function isWsChannelEvent(event) {
17
+ if (typeof event['arg'] === 'object' &&
18
+ event.arg &&
19
+ typeof (event === null || event === void 0 ? void 0 : event.arg['channel']) === 'string') {
20
+ return true;
21
+ }
22
+ return false;
23
+ }
24
+ /** TypeGuard: event is an account update (balance) */
25
+ function isWsAccountSnapshotEvent(event) {
26
+ return (isWsSnapshotEvent(event) &&
27
+ isWsChannelEvent(event) &&
28
+ event.arg.channel === 'account' &&
29
+ Array.isArray(event.data));
30
+ }
31
+ exports.isWsAccountSnapshotEvent = isWsAccountSnapshotEvent;
32
+ /** TypeGuard: event is a positions update */
33
+ function isWsPositionsSnapshotEvent(event) {
34
+ return (isWsSnapshotEvent(event) &&
35
+ isWsChannelEvent(event) &&
36
+ event.arg.channel === 'positions' &&
37
+ Array.isArray(event.data));
38
+ }
39
+ exports.isWsPositionsSnapshotEvent = isWsPositionsSnapshotEvent;
40
+ /** TypeGuard: event is a UMCBL account update (balance) */
41
+ function isWsFuturesAccountSnapshotEvent(event) {
42
+ return isWsAccountSnapshotEvent(event) && event.arg.instType === 'umcbl';
43
+ }
44
+ exports.isWsFuturesAccountSnapshotEvent = isWsFuturesAccountSnapshotEvent;
45
+ /** TypeGuard: event is a UMCBL positions update */
46
+ function isWsFuturesPositionsSnapshotEvent(event) {
47
+ return isWsPositionsSnapshotEvent(event) && event.arg.instType === 'umcbl';
48
+ }
49
+ exports.isWsFuturesPositionsSnapshotEvent = isWsFuturesPositionsSnapshotEvent;
50
+ //# sourceMappingURL=type-guards.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type-guards.js","sourceRoot":"","sources":["../../src/util/type-guards.ts"],"names":[],"mappings":";;;AASA,sDAAsD;AACtD,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK;QACL,OAAO,KAAK,CAAC,QAAQ,CA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,KAAc;IAEd,OAAO,0BAA0B,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC;AAC7E,CAAC;AAJD,8EAIC"}
@@ -0,0 +1,38 @@
1
+ import { WsKey } from '../types';
2
+ import { WsTopicSubscribeEventArgs } from './WsStore';
3
+ /**
4
+ * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges.
5
+ * Examples:
6
+ * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'>
7
+ * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'>
8
+ * - Only one livenet, no other networks: NetworkMap<'livenet'>
9
+ */
10
+ declare type NetworkMap<TRequiredKeys extends string, TOptionalKeys extends string | undefined = undefined> = Record<TRequiredKeys, string> & (TOptionalKeys extends string ? Record<TOptionalKeys, string | undefined> : Record<TRequiredKeys, string>);
11
+ export declare const WS_BASE_URL_MAP: Record<WsKey, Record<'all', NetworkMap<'livenet'>>>;
12
+ /** Should be one WS key per unique URL */
13
+ export declare const WS_KEY_MAP: {
14
+ readonly spotv1: "spotv1";
15
+ readonly mixv1: "mixv1";
16
+ };
17
+ /** Any WS keys in this list will trigger auth on connect, if credentials are available */
18
+ export declare const WS_AUTH_ON_CONNECT_KEYS: WsKey[];
19
+ /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */
20
+ export declare const PUBLIC_WS_KEYS: WsKey[];
21
+ /**
22
+ * Used to automatically determine if a sub request should be to a public or private ws (when there's two separate connections).
23
+ * Unnecessary if there's only one connection to handle both public & private topics.
24
+ */
25
+ export declare const PRIVATE_TOPICS: string[];
26
+ export declare function isPrivateChannel<TChannel extends string>(channel: TChannel): boolean;
27
+ export declare function getWsKeyForTopic(subscribeEvent: WsTopicSubscribeEventArgs, isPrivate?: boolean): WsKey;
28
+ /** Force subscription requests to be sent in smaller batches, if a number is returned */
29
+ export declare function getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null;
30
+ export declare const WS_ERROR_ENUM: {
31
+ INVALID_ACCESS_KEY: number;
32
+ };
33
+ export declare function neverGuard(x: never, msg: string): Error;
34
+ export declare function getWsAuthSignature(apiKey: string | undefined, apiSecret: string | undefined, apiPass: string | undefined, recvWindow?: number): Promise<{
35
+ expiresAt: number;
36
+ signature: string;
37
+ }>;
38
+ export {};
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.getWsAuthSignature = exports.neverGuard = exports.WS_ERROR_ENUM = exports.getMaxTopicsPerSubscribeEvent = exports.getWsKeyForTopic = exports.isPrivateChannel = exports.PRIVATE_TOPICS = exports.PUBLIC_WS_KEYS = exports.WS_AUTH_ON_CONNECT_KEYS = exports.WS_KEY_MAP = exports.WS_BASE_URL_MAP = void 0;
13
+ const node_support_1 = require("./node-support");
14
+ exports.WS_BASE_URL_MAP = {
15
+ mixv1: {
16
+ all: {
17
+ livenet: 'wss://ws.bitget.com/mix/v1/stream',
18
+ },
19
+ },
20
+ spotv1: {
21
+ all: {
22
+ livenet: 'wss://ws.bitget.com/spot/v1/stream',
23
+ },
24
+ },
25
+ };
26
+ /** Should be one WS key per unique URL */
27
+ exports.WS_KEY_MAP = {
28
+ spotv1: 'spotv1',
29
+ mixv1: 'mixv1',
30
+ };
31
+ /** Any WS keys in this list will trigger auth on connect, if credentials are available */
32
+ exports.WS_AUTH_ON_CONNECT_KEYS = [
33
+ exports.WS_KEY_MAP.spotv1,
34
+ exports.WS_KEY_MAP.mixv1,
35
+ ];
36
+ /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */
37
+ exports.PUBLIC_WS_KEYS = [];
38
+ /**
39
+ * Used to automatically determine if a sub request should be to a public or private ws (when there's two separate connections).
40
+ * Unnecessary if there's only one connection to handle both public & private topics.
41
+ */
42
+ exports.PRIVATE_TOPICS = ['account', 'orders', 'positions', 'ordersAlgo'];
43
+ function isPrivateChannel(channel) {
44
+ return exports.PRIVATE_TOPICS.includes(channel);
45
+ }
46
+ exports.isPrivateChannel = isPrivateChannel;
47
+ function getWsKeyForTopic(subscribeEvent, isPrivate) {
48
+ const instType = subscribeEvent.instType.toUpperCase();
49
+ switch (instType) {
50
+ case 'SP':
51
+ case 'SPBL': {
52
+ return exports.WS_KEY_MAP.spotv1;
53
+ }
54
+ case 'MC':
55
+ case 'UMCBL':
56
+ case 'DMCBL': {
57
+ return exports.WS_KEY_MAP.mixv1;
58
+ }
59
+ default: {
60
+ throw neverGuard(instType, `getWsKeyForTopic(): Unhandled market ${'instrumentId'}`);
61
+ }
62
+ }
63
+ }
64
+ exports.getWsKeyForTopic = getWsKeyForTopic;
65
+ /** Force subscription requests to be sent in smaller batches, if a number is returned */
66
+ function getMaxTopicsPerSubscribeEvent(wsKey) {
67
+ switch (wsKey) {
68
+ case 'mixv1':
69
+ case 'spotv1': {
70
+ // Technically there doesn't seem to be a documented cap, but there is a size limit per request. Doesn't hurt to batch requests.
71
+ return 15;
72
+ }
73
+ default: {
74
+ throw neverGuard(wsKey, `getWsKeyForTopic(): Unhandled wsKey`);
75
+ }
76
+ }
77
+ }
78
+ exports.getMaxTopicsPerSubscribeEvent = getMaxTopicsPerSubscribeEvent;
79
+ exports.WS_ERROR_ENUM = {
80
+ INVALID_ACCESS_KEY: 30011,
81
+ };
82
+ function neverGuard(x, msg) {
83
+ return new Error(`Unhandled value exception "${x}", ${msg}`);
84
+ }
85
+ exports.neverGuard = neverGuard;
86
+ function getWsAuthSignature(apiKey, apiSecret, apiPass, recvWindow = 0) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ if (!apiKey || !apiSecret || !apiPass) {
89
+ throw new Error(`Cannot auth - missing api key, secret or passcode in config`);
90
+ }
91
+ const signatureExpiresAt = ((Date.now() + recvWindow) / 1000).toFixed(0);
92
+ const signature = yield (0, node_support_1.signMessage)(signatureExpiresAt + 'GET' + '/user/verify', apiSecret, 'base64');
93
+ return {
94
+ expiresAt: Number(signatureExpiresAt),
95
+ signature,
96
+ };
97
+ });
98
+ }
99
+ exports.getWsAuthSignature = getWsAuthSignature;
100
+ //# sourceMappingURL=websocket-util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket-util.js","sourceRoot":"","sources":["../../src/util/websocket-util.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iDAA6C;AAkBhC,QAAA,eAAe,GAGxB;IACF,KAAK,EAAE;QACL,GAAG,EAAE;YACH,OAAO,EAAE,mCAAmC;SAC7C;KACF;IACD,MAAM,EAAE;QACN,GAAG,EAAE;YACH,OAAO,EAAE,oCAAoC;SAC9C;KACF;CACF,CAAC;AAEF,0CAA0C;AAC7B,QAAA,UAAU,GAAG;IACxB,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACN,CAAC;AAEX,0FAA0F;AAC7E,QAAA,uBAAuB,GAAY;IAC9C,kBAAU,CAAC,MAAM;IACjB,kBAAU,CAAC,KAAK;CACjB,CAAC;AAEF,8GAA8G;AACjG,QAAA,cAAc,GAAG,EAAa,CAAC;AAE5C;;;GAGG;AACU,QAAA,cAAc,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC;AAE/E,SAAgB,gBAAgB,CAC9B,OAAiB;IAEjB,OAAO,sBAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAC1C,CAAC;AAJD,4CAIC;AAED,SAAgB,gBAAgB,CAC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,CAAC,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;QAEzE,MAAM,SAAS,GAAG,MAAM,IAAA,0BAAW,EACjC,kBAAkB,GAAG,KAAK,GAAG,cAAc,EAC3C,SAAS,EACT,QAAQ,CACT,CAAC;QAEF,OAAO;YACL,SAAS,EAAE,MAAM,CAAC,kBAAkB,CAAC;YACrC,SAAS;SACV,CAAC;IACJ,CAAC;CAAA;AA1BD,gDA0BC"}
@@ -0,0 +1,121 @@
1
+ /// <reference types="node" />
2
+ import { EventEmitter } from 'events';
3
+ import WebSocket from 'isomorphic-ws';
4
+ import { BitgetInstType, WsTopicSubscribeEventArgs } from './util/WsStore';
5
+ import { WSClientConfigurableOptions, WsKey, WsTopic } from './types';
6
+ import { DefaultLogger } from './util';
7
+ export declare type WsClientEvent = 'open' | 'update' | 'close' | 'exception' | 'reconnect' | 'reconnected' | 'response';
8
+ interface WebsocketClientEvents {
9
+ /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
10
+ open: (evt: {
11
+ wsKey: WsKey;
12
+ event: any;
13
+ }) => void;
14
+ /** Reconnecting a dropped connection */
15
+ reconnect: (evt: {
16
+ wsKey: WsKey;
17
+ event: any;
18
+ }) => void;
19
+ /** Successfully reconnected a connection that dropped */
20
+ reconnected: (evt: {
21
+ wsKey: WsKey;
22
+ event: any;
23
+ }) => void;
24
+ /** Connection closed */
25
+ close: (evt: {
26
+ wsKey: WsKey;
27
+ event: any;
28
+ }) => void;
29
+ /** Received reply to websocket command (e.g. after subscribing to topics) */
30
+ response: (response: any & {
31
+ wsKey: WsKey;
32
+ }) => void;
33
+ /** Received data for topic */
34
+ update: (response: any & {
35
+ wsKey: WsKey;
36
+ }) => void;
37
+ /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */
38
+ exception: (response: any & {
39
+ wsKey: WsKey;
40
+ }) => void;
41
+ /** Confirmation that a connection successfully authenticated */
42
+ authenticated: (event: {
43
+ wsKey: WsKey;
44
+ event: any;
45
+ }) => void;
46
+ }
47
+ export declare interface WebsocketClient {
48
+ on<U extends keyof WebsocketClientEvents>(event: U, listener: WebsocketClientEvents[U]): this;
49
+ emit<U extends keyof WebsocketClientEvents>(event: U, ...args: Parameters<WebsocketClientEvents[U]>): boolean;
50
+ }
51
+ export declare class WebsocketClient extends EventEmitter {
52
+ private logger;
53
+ private options;
54
+ private wsStore;
55
+ constructor(options: WSClientConfigurableOptions, logger?: typeof DefaultLogger);
56
+ /**
57
+ * Subscribe to topics & track/persist them. They will be automatically resubscribed to if the connection drops/reconnects.
58
+ * @param wsTopics topic or list of topics
59
+ * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
60
+ */
61
+ subscribe(wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, isPrivateTopic?: boolean): void;
62
+ /**
63
+ * Unsubscribe from topics & remove them from memory. They won't be re-subscribed to if the connection reconnects.
64
+ * @param wsTopics topic or list of topics
65
+ * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)
66
+ */
67
+ unsubscribe(wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, isPrivateTopic?: boolean): void;
68
+ /** Get the WsStore that tracks websockets & topics */
69
+ getWsStore(): typeof this.wsStore;
70
+ close(wsKey: WsKey, force?: boolean): void;
71
+ closeAll(force?: boolean): void;
72
+ /**
73
+ * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
74
+ */
75
+ connectAll(): Promise<WebSocket | undefined>[];
76
+ /**
77
+ * Request connection to a specific websocket, instead of waiting for automatic connection.
78
+ */
79
+ private connect;
80
+ private parseWsError;
81
+ /** Get a signature, build the auth request and send it */
82
+ private sendAuthRequest;
83
+ private reconnectWithDelay;
84
+ private ping;
85
+ private clearTimers;
86
+ private clearPingTimer;
87
+ private clearPongTimer;
88
+ /**
89
+ * @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics.
90
+ */
91
+ private requestSubscribeTopics;
92
+ /**
93
+ * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
94
+ */
95
+ private requestUnsubscribeTopics;
96
+ tryWsSend(wsKey: WsKey, wsMessage: string): void;
97
+ private connectToWsUrl;
98
+ private onWsOpen;
99
+ /** Handle subscription to private topics _after_ authentication successfully completes asynchronously */
100
+ private onWsAuthenticated;
101
+ private onWsMessage;
102
+ private onWsClose;
103
+ private getWs;
104
+ private setWsState;
105
+ private getWsUrl;
106
+ /**
107
+ * Subscribe to a topic
108
+ * @param instType instrument type (refer to API docs).
109
+ * @param topic topic name (e.g. "ticker").
110
+ * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics.
111
+ */
112
+ subscribeTopic(instType: BitgetInstType, topic: WsTopic, instId?: string): void;
113
+ /**
114
+ * Unsubscribe from a topic
115
+ * @param instType instrument type (refer to API docs).
116
+ * @param topic topic name (e.g. "ticker").
117
+ * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols.
118
+ */
119
+ unsubscribeTopic(instType: BitgetInstType, topic: WsTopic, instId?: string): void;
120
+ }
121
+ export {};