@typedtrader/exchange 0.2.5 → 0.3.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 (153) hide show
  1. package/README.md +89 -0
  2. package/dist/broker/Broker.d.ts +152 -0
  3. package/dist/broker/Broker.js +124 -0
  4. package/dist/broker/Broker.js.map +1 -0
  5. package/dist/broker/BrokerMock.d.ts +51 -0
  6. package/dist/broker/BrokerMock.js +333 -0
  7. package/dist/broker/BrokerMock.js.map +1 -0
  8. package/dist/broker/MarketDataSource.d.ts +11 -0
  9. package/dist/broker/MarketDataSource.js +26 -0
  10. package/dist/broker/MarketDataSource.js.map +1 -0
  11. package/dist/broker/TradingPair.d.ts +12 -0
  12. package/dist/broker/TradingPair.js +22 -0
  13. package/dist/broker/TradingPair.js.map +1 -0
  14. package/dist/broker/alpaca/AlpacaBroker.d.ts +49 -0
  15. package/dist/broker/alpaca/AlpacaBroker.js +258 -0
  16. package/dist/broker/alpaca/AlpacaBroker.js.map +1 -0
  17. package/dist/broker/alpaca/AlpacaBrokerMapper.d.ts +12 -0
  18. package/dist/broker/alpaca/AlpacaBrokerMapper.js +96 -0
  19. package/dist/broker/alpaca/AlpacaBrokerMapper.js.map +1 -0
  20. package/dist/broker/alpaca/AlpacaBrokerMock.d.ts +15 -0
  21. package/dist/broker/alpaca/AlpacaBrokerMock.js +29 -0
  22. package/dist/broker/alpaca/AlpacaBrokerMock.js.map +1 -0
  23. package/dist/broker/alpaca/AlpacaMarketData.d.ts +19 -0
  24. package/dist/broker/alpaca/AlpacaMarketData.js +130 -0
  25. package/dist/broker/alpaca/AlpacaMarketData.js.map +1 -0
  26. package/dist/broker/alpaca/AlpacaTradingWebSocket.d.ts +15 -0
  27. package/dist/broker/alpaca/AlpacaTradingWebSocket.js +95 -0
  28. package/dist/broker/alpaca/AlpacaTradingWebSocket.js.map +1 -0
  29. package/dist/broker/alpaca/AlpacaWebSocket.d.ts +14 -0
  30. package/dist/broker/alpaca/AlpacaWebSocket.js +93 -0
  31. package/dist/broker/alpaca/AlpacaWebSocket.js.map +1 -0
  32. package/dist/broker/alpaca/alpacaSymbol.d.ts +4 -0
  33. package/dist/broker/alpaca/alpacaSymbol.js +20 -0
  34. package/dist/broker/alpaca/alpacaSymbol.js.map +1 -0
  35. package/dist/broker/alpaca/api/AlpacaAPI.d.ts +277 -0
  36. package/dist/broker/alpaca/api/AlpacaAPI.js +108 -0
  37. package/dist/broker/alpaca/api/AlpacaAPI.js.map +1 -0
  38. package/dist/broker/alpaca/api/AlpacaStream.d.ts +13 -0
  39. package/dist/broker/alpaca/api/AlpacaStream.js +61 -0
  40. package/dist/broker/alpaca/api/AlpacaStream.js.map +1 -0
  41. package/dist/broker/alpaca/api/AlpacaTradingStream.d.ts +12 -0
  42. package/dist/broker/alpaca/api/AlpacaTradingStream.js +59 -0
  43. package/dist/broker/alpaca/api/AlpacaTradingStream.js.map +1 -0
  44. package/dist/broker/alpaca/api/schema/AccountSchema.d.ts +26 -0
  45. package/dist/broker/alpaca/api/schema/AccountSchema.js +26 -0
  46. package/dist/broker/alpaca/api/schema/AccountSchema.js.map +1 -0
  47. package/dist/broker/alpaca/api/schema/AssetSchema.d.ts +19 -0
  48. package/dist/broker/alpaca/api/schema/AssetSchema.js +19 -0
  49. package/dist/broker/alpaca/api/schema/AssetSchema.js.map +1 -0
  50. package/dist/broker/alpaca/api/schema/BarSchema.d.ts +37 -0
  51. package/dist/broker/alpaca/api/schema/BarSchema.js +19 -0
  52. package/dist/broker/alpaca/api/schema/BarSchema.js.map +1 -0
  53. package/dist/broker/alpaca/api/schema/ClockSchema.d.ts +7 -0
  54. package/dist/broker/alpaca/api/schema/ClockSchema.js +8 -0
  55. package/dist/broker/alpaca/api/schema/ClockSchema.js.map +1 -0
  56. package/dist/broker/alpaca/api/schema/OrderSchema.d.ts +78 -0
  57. package/dist/broker/alpaca/api/schema/OrderSchema.js +73 -0
  58. package/dist/broker/alpaca/api/schema/OrderSchema.js.map +1 -0
  59. package/dist/broker/alpaca/api/schema/PositionSchema.d.ts +31 -0
  60. package/dist/broker/alpaca/api/schema/PositionSchema.js +23 -0
  61. package/dist/broker/alpaca/api/schema/PositionSchema.js.map +1 -0
  62. package/dist/broker/alpaca/api/schema/SnapshotSchema.d.ts +82 -0
  63. package/dist/broker/alpaca/api/schema/SnapshotSchema.js +15 -0
  64. package/dist/broker/alpaca/api/schema/SnapshotSchema.js.map +1 -0
  65. package/dist/broker/alpaca/api/schema/StreamSchema.d.ts +48 -0
  66. package/dist/broker/alpaca/api/schema/StreamSchema.js +32 -0
  67. package/dist/broker/alpaca/api/schema/StreamSchema.js.map +1 -0
  68. package/dist/broker/alpaca/api/schema/TradingStreamSchema.d.ts +61 -0
  69. package/dist/broker/alpaca/api/schema/TradingStreamSchema.js +30 -0
  70. package/dist/broker/alpaca/api/schema/TradingStreamSchema.js.map +1 -0
  71. package/dist/broker/alpaca/getAlpacaClient.d.ts +8 -0
  72. package/dist/broker/alpaca/getAlpacaClient.js +29 -0
  73. package/dist/broker/alpaca/getAlpacaClient.js.map +1 -0
  74. package/dist/broker/alpaca/getAlpacaMarketData.d.ts +2 -0
  75. package/dist/broker/alpaca/getAlpacaMarketData.js +12 -0
  76. package/dist/broker/alpaca/getAlpacaMarketData.js.map +1 -0
  77. package/dist/broker/alpaca/getAlpacaRules.d.ts +11 -0
  78. package/dist/broker/alpaca/getAlpacaRules.js +17 -0
  79. package/dist/broker/alpaca/getAlpacaRules.js.map +1 -0
  80. package/dist/broker/alpaca/index.d.ts +17 -0
  81. package/dist/broker/alpaca/index.js +18 -0
  82. package/dist/broker/alpaca/index.js.map +1 -0
  83. package/dist/broker/getAuthenticatedBrokerClient.d.ts +4 -0
  84. package/dist/broker/getAuthenticatedBrokerClient.js +7 -0
  85. package/dist/broker/getAuthenticatedBrokerClient.js.map +1 -0
  86. package/dist/broker/getBrokerClient.d.ts +10 -0
  87. package/dist/broker/getBrokerClient.js +29 -0
  88. package/dist/broker/getBrokerClient.js.map +1 -0
  89. package/dist/broker/index.d.ts +6 -0
  90. package/dist/broker/index.js +7 -0
  91. package/dist/broker/index.js.map +1 -0
  92. package/dist/broker/trading212/Trading212Broker.d.ts +41 -0
  93. package/dist/broker/trading212/Trading212Broker.js +249 -0
  94. package/dist/broker/trading212/Trading212Broker.js.map +1 -0
  95. package/dist/broker/trading212/Trading212BrokerMapper.d.ts +10 -0
  96. package/dist/broker/trading212/Trading212BrokerMapper.js +84 -0
  97. package/dist/broker/trading212/Trading212BrokerMapper.js.map +1 -0
  98. package/dist/broker/trading212/api/Trading212API.d.ts +202 -0
  99. package/dist/broker/trading212/api/Trading212API.js +143 -0
  100. package/dist/broker/trading212/api/Trading212API.js.map +1 -0
  101. package/dist/broker/trading212/api/schema/AccountSchema.d.ts +16 -0
  102. package/dist/broker/trading212/api/schema/AccountSchema.js +15 -0
  103. package/dist/broker/trading212/api/schema/AccountSchema.js.map +1 -0
  104. package/dist/broker/trading212/api/schema/HistoryOrderSchema.d.ts +136 -0
  105. package/dist/broker/trading212/api/schema/HistoryOrderSchema.js +57 -0
  106. package/dist/broker/trading212/api/schema/HistoryOrderSchema.js.map +1 -0
  107. package/dist/broker/trading212/api/schema/InstrumentSchema.d.ts +37 -0
  108. package/dist/broker/trading212/api/schema/InstrumentSchema.js +26 -0
  109. package/dist/broker/trading212/api/schema/InstrumentSchema.js.map +1 -0
  110. package/dist/broker/trading212/api/schema/OrderSchema.d.ts +97 -0
  111. package/dist/broker/trading212/api/schema/OrderSchema.js +61 -0
  112. package/dist/broker/trading212/api/schema/OrderSchema.js.map +1 -0
  113. package/dist/broker/trading212/api/schema/PositionSchema.d.ts +14 -0
  114. package/dist/broker/trading212/api/schema/PositionSchema.js +14 -0
  115. package/dist/broker/trading212/api/schema/PositionSchema.js.map +1 -0
  116. package/dist/broker/trading212/getTrading212Client.d.ts +8 -0
  117. package/dist/broker/trading212/getTrading212Client.js +6 -0
  118. package/dist/broker/trading212/getTrading212Client.js.map +1 -0
  119. package/dist/broker/trading212/index.d.ts +4 -0
  120. package/dist/broker/trading212/index.js +5 -0
  121. package/dist/broker/trading212/index.js.map +1 -0
  122. package/dist/candle/BatchedCandle.d.ts +24 -0
  123. package/dist/candle/BatchedCandle.js +4 -0
  124. package/dist/candle/BatchedCandle.js.map +1 -0
  125. package/dist/candle/CandleBatcher.d.ts +35 -0
  126. package/dist/candle/CandleBatcher.js +233 -0
  127. package/dist/candle/CandleBatcher.js.map +1 -0
  128. package/dist/candle/index.d.ts +2 -0
  129. package/dist/candle/index.js +3 -0
  130. package/dist/candle/index.js.map +1 -0
  131. package/dist/candle/writeCandles.d.ts +2 -0
  132. package/dist/candle/writeCandles.js +5 -0
  133. package/dist/candle/writeCandles.js.map +1 -0
  134. package/dist/index.d.ts +5 -0
  135. package/dist/index.js +6 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/util/SimplifiedHttpError.d.ts +11 -0
  138. package/dist/util/SimplifiedHttpError.js +17 -0
  139. package/dist/util/SimplifiedHttpError.js.map +1 -0
  140. package/dist/util/index.d.ts +1 -0
  141. package/dist/util/index.js +2 -0
  142. package/dist/util/index.js.map +1 -0
  143. package/dist/util/isEarningsDay.d.ts +15 -0
  144. package/dist/util/isEarningsDay.js +39 -0
  145. package/dist/util/isEarningsDay.js.map +1 -0
  146. package/dist/util/simplifyError.d.ts +2 -0
  147. package/dist/util/simplifyError.js +16 -0
  148. package/dist/util/simplifyError.js.map +1 -0
  149. package/package.json +23 -28
  150. package/dist/index.cjs +0 -966
  151. package/dist/index.d.cts +0 -361
  152. package/dist/index.d.mts +0 -361
  153. package/dist/index.mjs +0 -919
package/dist/index.cjs DELETED
@@ -1,966 +0,0 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
- let zod = require("zod");
29
- let node_events = require("node:events");
30
- let ms = require("ms");
31
- let jsonabc = require("jsonabc");
32
- jsonabc = __toESM(jsonabc);
33
- let _master_chief_alpaca_ts = require("@master-chief/alpaca-ts");
34
- let ts_retry_promise = require("ts-retry-promise");
35
-
36
- //#region src/candle/BatchedCandle.ts
37
- const BasicCandlePrice = zod.z.union([
38
- zod.z.literal("open"),
39
- zod.z.literal("high"),
40
- zod.z.literal("low"),
41
- zod.z.literal("close")
42
- ]);
43
-
44
- //#endregion
45
- //#region ../../node_modules/big.js/big.mjs
46
- /************************************** EDITABLE DEFAULTS *****************************************/
47
- var DP = 20, RM = 1, MAX_DP = 1e6, MAX_POWER = 1e6, NE = -7, PE = 21, STRICT = false, NAME = "[big.js] ", INVALID = NAME + "Invalid ", INVALID_DP = INVALID + "decimal places", INVALID_RM = INVALID + "rounding mode", DIV_BY_ZERO = NAME + "Division by zero", P = {}, UNDEFINED = void 0, NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
48
- function _Big_() {
49
- function Big$1(n) {
50
- var x = this;
51
- if (!(x instanceof Big$1)) return n === UNDEFINED && arguments.length === 0 ? _Big_() : new Big$1(n);
52
- if (n instanceof Big$1) {
53
- x.s = n.s;
54
- x.e = n.e;
55
- x.c = n.c.slice();
56
- } else {
57
- if (typeof n !== "string") {
58
- if (Big$1.strict === true && typeof n !== "bigint") throw TypeError(INVALID + "value");
59
- n = n === 0 && 1 / n < 0 ? "-0" : String(n);
60
- }
61
- parse(x, n);
62
- }
63
- x.constructor = Big$1;
64
- }
65
- Big$1.prototype = P;
66
- Big$1.DP = DP;
67
- Big$1.RM = RM;
68
- Big$1.NE = NE;
69
- Big$1.PE = PE;
70
- Big$1.strict = STRICT;
71
- Big$1.roundDown = 0;
72
- Big$1.roundHalfUp = 1;
73
- Big$1.roundHalfEven = 2;
74
- Big$1.roundUp = 3;
75
- return Big$1;
76
- }
77
- function parse(x, n) {
78
- var e, i, nl;
79
- if (!NUMERIC.test(n)) throw Error(INVALID + "number");
80
- x.s = n.charAt(0) == "-" ? (n = n.slice(1), -1) : 1;
81
- if ((e = n.indexOf(".")) > -1) n = n.replace(".", "");
82
- if ((i = n.search(/e/i)) > 0) {
83
- if (e < 0) e = i;
84
- e += +n.slice(i + 1);
85
- n = n.substring(0, i);
86
- } else if (e < 0) e = n.length;
87
- nl = n.length;
88
- for (i = 0; i < nl && n.charAt(i) == "0";) ++i;
89
- if (i == nl) x.c = [x.e = 0];
90
- else {
91
- for (; nl > 0 && n.charAt(--nl) == "0";);
92
- x.e = e - i - 1;
93
- x.c = [];
94
- for (e = 0; i <= nl;) x.c[e++] = +n.charAt(i++);
95
- }
96
- return x;
97
- }
98
- function round(x, sd, rm, more) {
99
- var xc = x.c;
100
- if (rm === UNDEFINED) rm = x.constructor.RM;
101
- if (rm !== 0 && rm !== 1 && rm !== 2 && rm !== 3) throw Error(INVALID_RM);
102
- if (sd < 1) {
103
- more = rm === 3 && (more || !!xc[0]) || sd === 0 && (rm === 1 && xc[0] >= 5 || rm === 2 && (xc[0] > 5 || xc[0] === 5 && (more || xc[1] !== UNDEFINED)));
104
- xc.length = 1;
105
- if (more) {
106
- x.e = x.e - sd + 1;
107
- xc[0] = 1;
108
- } else xc[0] = x.e = 0;
109
- } else if (sd < xc.length) {
110
- more = rm === 1 && xc[sd] >= 5 || rm === 2 && (xc[sd] > 5 || xc[sd] === 5 && (more || xc[sd + 1] !== UNDEFINED || xc[sd - 1] & 1)) || rm === 3 && (more || !!xc[0]);
111
- xc.length = sd;
112
- if (more) for (; ++xc[--sd] > 9;) {
113
- xc[sd] = 0;
114
- if (sd === 0) {
115
- ++x.e;
116
- xc.unshift(1);
117
- break;
118
- }
119
- }
120
- for (sd = xc.length; !xc[--sd];) xc.pop();
121
- }
122
- return x;
123
- }
124
- function stringify(x, doExponential, isNonzero) {
125
- var e = x.e, s = x.c.join(""), n = s.length;
126
- if (doExponential) s = s.charAt(0) + (n > 1 ? "." + s.slice(1) : "") + (e < 0 ? "e" : "e+") + e;
127
- else if (e < 0) {
128
- for (; ++e;) s = "0" + s;
129
- s = "0." + s;
130
- } else if (e > 0) {
131
- if (++e > n) for (e -= n; e--;) s += "0";
132
- else if (e < n) s = s.slice(0, e) + "." + s.slice(e);
133
- } else if (n > 1) s = s.charAt(0) + "." + s.slice(1);
134
- return x.s < 0 && isNonzero ? "-" + s : s;
135
- }
136
- P.abs = function() {
137
- var x = new this.constructor(this);
138
- x.s = 1;
139
- return x;
140
- };
141
- P.cmp = function(y) {
142
- var isneg, x = this, xc = x.c, yc = (y = new x.constructor(y)).c, i = x.s, j = y.s, k = x.e, l = y.e;
143
- if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i;
144
- if (i != j) return i;
145
- isneg = i < 0;
146
- if (k != l) return k > l ^ isneg ? 1 : -1;
147
- j = (k = xc.length) < (l = yc.length) ? k : l;
148
- for (i = -1; ++i < j;) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1;
149
- return k == l ? 0 : k > l ^ isneg ? 1 : -1;
150
- };
151
- P.div = function(y) {
152
- var x = this, Big$1 = x.constructor, a = x.c, b = (y = new Big$1(y)).c, k = x.s == y.s ? 1 : -1, dp = Big$1.DP;
153
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP);
154
- if (!b[0]) throw Error(DIV_BY_ZERO);
155
- if (!a[0]) {
156
- y.s = k;
157
- y.c = [y.e = 0];
158
- return y;
159
- }
160
- var bl, bt, n, cmp, ri, bz = b.slice(), ai = bl = b.length, al = a.length, r = a.slice(0, bl), rl = r.length, q = y, qc = q.c = [], qi = 0, p = dp + (q.e = x.e - y.e) + 1;
161
- q.s = k;
162
- k = p < 0 ? 0 : p;
163
- bz.unshift(0);
164
- for (; rl++ < bl;) r.push(0);
165
- do {
166
- for (n = 0; n < 10; n++) {
167
- if (bl != (rl = r.length)) cmp = bl > rl ? 1 : -1;
168
- else for (ri = -1, cmp = 0; ++ri < bl;) if (b[ri] != r[ri]) {
169
- cmp = b[ri] > r[ri] ? 1 : -1;
170
- break;
171
- }
172
- if (cmp < 0) {
173
- for (bt = rl == bl ? b : bz; rl;) {
174
- if (r[--rl] < bt[rl]) {
175
- ri = rl;
176
- for (; ri && !r[--ri];) r[ri] = 9;
177
- --r[ri];
178
- r[rl] += 10;
179
- }
180
- r[rl] -= bt[rl];
181
- }
182
- for (; !r[0];) r.shift();
183
- } else break;
184
- }
185
- qc[qi++] = cmp ? n : ++n;
186
- if (r[0] && cmp) r[rl] = a[ai] || 0;
187
- else r = [a[ai]];
188
- } while ((ai++ < al || r[0] !== UNDEFINED) && k--);
189
- if (!qc[0] && qi != 1) {
190
- qc.shift();
191
- q.e--;
192
- p--;
193
- }
194
- if (qi > p) round(q, p, Big$1.RM, r[0] !== UNDEFINED);
195
- return q;
196
- };
197
- P.eq = function(y) {
198
- return this.cmp(y) === 0;
199
- };
200
- P.gt = function(y) {
201
- return this.cmp(y) > 0;
202
- };
203
- P.gte = function(y) {
204
- return this.cmp(y) > -1;
205
- };
206
- P.lt = function(y) {
207
- return this.cmp(y) < 0;
208
- };
209
- P.lte = function(y) {
210
- return this.cmp(y) < 1;
211
- };
212
- P.minus = P.sub = function(y) {
213
- var i, j, t, xlty, x = this, Big$1 = x.constructor, a = x.s, b = (y = new Big$1(y)).s;
214
- if (a != b) {
215
- y.s = -b;
216
- return x.plus(y);
217
- }
218
- var xc = x.c.slice(), xe = x.e, yc = y.c, ye = y.e;
219
- if (!xc[0] || !yc[0]) {
220
- if (yc[0]) y.s = -b;
221
- else if (xc[0]) y = new Big$1(x);
222
- else y.s = 1;
223
- return y;
224
- }
225
- if (a = xe - ye) {
226
- if (xlty = a < 0) {
227
- a = -a;
228
- t = xc;
229
- } else {
230
- ye = xe;
231
- t = yc;
232
- }
233
- t.reverse();
234
- for (b = a; b--;) t.push(0);
235
- t.reverse();
236
- } else {
237
- j = ((xlty = xc.length < yc.length) ? xc : yc).length;
238
- for (a = b = 0; b < j; b++) if (xc[b] != yc[b]) {
239
- xlty = xc[b] < yc[b];
240
- break;
241
- }
242
- }
243
- if (xlty) {
244
- t = xc;
245
- xc = yc;
246
- yc = t;
247
- y.s = -y.s;
248
- }
249
- if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--;) xc[i++] = 0;
250
- for (b = i; j > a;) {
251
- if (xc[--j] < yc[j]) {
252
- for (i = j; i && !xc[--i];) xc[i] = 9;
253
- --xc[i];
254
- xc[j] += 10;
255
- }
256
- xc[j] -= yc[j];
257
- }
258
- for (; xc[--b] === 0;) xc.pop();
259
- for (; xc[0] === 0;) {
260
- xc.shift();
261
- --ye;
262
- }
263
- if (!xc[0]) {
264
- y.s = 1;
265
- xc = [ye = 0];
266
- }
267
- y.c = xc;
268
- y.e = ye;
269
- return y;
270
- };
271
- P.mod = function(y) {
272
- var ygtx, x = this, Big$1 = x.constructor, a = x.s, b = (y = new Big$1(y)).s;
273
- if (!y.c[0]) throw Error(DIV_BY_ZERO);
274
- x.s = y.s = 1;
275
- ygtx = y.cmp(x) == 1;
276
- x.s = a;
277
- y.s = b;
278
- if (ygtx) return new Big$1(x);
279
- a = Big$1.DP;
280
- b = Big$1.RM;
281
- Big$1.DP = Big$1.RM = 0;
282
- x = x.div(y);
283
- Big$1.DP = a;
284
- Big$1.RM = b;
285
- return this.minus(x.times(y));
286
- };
287
- P.neg = function() {
288
- var x = new this.constructor(this);
289
- x.s = -x.s;
290
- return x;
291
- };
292
- P.plus = P.add = function(y) {
293
- var e, k, t, x = this, Big$1 = x.constructor;
294
- y = new Big$1(y);
295
- if (x.s != y.s) {
296
- y.s = -y.s;
297
- return x.minus(y);
298
- }
299
- var xe = x.e, xc = x.c, ye = y.e, yc = y.c;
300
- if (!xc[0] || !yc[0]) {
301
- if (!yc[0]) if (xc[0]) y = new Big$1(x);
302
- else y.s = x.s;
303
- return y;
304
- }
305
- xc = xc.slice();
306
- if (e = xe - ye) {
307
- if (e > 0) {
308
- ye = xe;
309
- t = yc;
310
- } else {
311
- e = -e;
312
- t = xc;
313
- }
314
- t.reverse();
315
- for (; e--;) t.push(0);
316
- t.reverse();
317
- }
318
- if (xc.length - yc.length < 0) {
319
- t = yc;
320
- yc = xc;
321
- xc = t;
322
- }
323
- e = yc.length;
324
- for (k = 0; e; xc[e] %= 10) k = (xc[--e] = xc[e] + yc[e] + k) / 10 | 0;
325
- if (k) {
326
- xc.unshift(k);
327
- ++ye;
328
- }
329
- for (e = xc.length; xc[--e] === 0;) xc.pop();
330
- y.c = xc;
331
- y.e = ye;
332
- return y;
333
- };
334
- P.pow = function(n) {
335
- var x = this, one = new x.constructor("1"), y = one, isneg = n < 0;
336
- if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) throw Error(INVALID + "exponent");
337
- if (isneg) n = -n;
338
- for (;;) {
339
- if (n & 1) y = y.times(x);
340
- n >>= 1;
341
- if (!n) break;
342
- x = x.times(x);
343
- }
344
- return isneg ? one.div(y) : y;
345
- };
346
- P.prec = function(sd, rm) {
347
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) throw Error(INVALID + "precision");
348
- return round(new this.constructor(this), sd, rm);
349
- };
350
- P.round = function(dp, rm) {
351
- if (dp === UNDEFINED) dp = 0;
352
- else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) throw Error(INVALID_DP);
353
- return round(new this.constructor(this), dp + this.e + 1, rm);
354
- };
355
- P.sqrt = function() {
356
- var r, c, t, x = this, Big$1 = x.constructor, s = x.s, e = x.e, half = new Big$1("0.5");
357
- if (!x.c[0]) return new Big$1(x);
358
- if (s < 0) throw Error(NAME + "No square root");
359
- s = Math.sqrt(+stringify(x, true, true));
360
- if (s === 0 || s === Infinity) {
361
- c = x.c.join("");
362
- if (!(c.length + e & 1)) c += "0";
363
- s = Math.sqrt(c);
364
- e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
365
- r = new Big$1((s == Infinity ? "5e" : (s = s.toExponential()).slice(0, s.indexOf("e") + 1)) + e);
366
- } else r = new Big$1(s + "");
367
- e = r.e + (Big$1.DP += 4);
368
- do {
369
- t = r;
370
- r = half.times(t.plus(x.div(t)));
371
- } while (t.c.slice(0, e).join("") !== r.c.slice(0, e).join(""));
372
- return round(r, (Big$1.DP -= 4) + r.e + 1, Big$1.RM);
373
- };
374
- P.times = P.mul = function(y) {
375
- var c, x = this, Big$1 = x.constructor, xc = x.c, yc = (y = new Big$1(y)).c, a = xc.length, b = yc.length, i = x.e, j = y.e;
376
- y.s = x.s == y.s ? 1 : -1;
377
- if (!xc[0] || !yc[0]) {
378
- y.c = [y.e = 0];
379
- return y;
380
- }
381
- y.e = i + j;
382
- if (a < b) {
383
- c = xc;
384
- xc = yc;
385
- yc = c;
386
- j = a;
387
- a = b;
388
- b = j;
389
- }
390
- for (c = new Array(j = a + b); j--;) c[j] = 0;
391
- for (i = b; i--;) {
392
- b = 0;
393
- for (j = a + i; j > i;) {
394
- b = c[j] + yc[i] * xc[j - i - 1] + b;
395
- c[j--] = b % 10;
396
- b = b / 10 | 0;
397
- }
398
- c[j] = b;
399
- }
400
- if (b) ++y.e;
401
- else c.shift();
402
- for (i = c.length; !c[--i];) c.pop();
403
- y.c = c;
404
- return y;
405
- };
406
- P.toExponential = function(dp, rm) {
407
- var x = this, n = x.c[0];
408
- if (dp !== UNDEFINED) {
409
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP);
410
- x = round(new x.constructor(x), ++dp, rm);
411
- for (; x.c.length < dp;) x.c.push(0);
412
- }
413
- return stringify(x, true, !!n);
414
- };
415
- P.toFixed = function(dp, rm) {
416
- var x = this, n = x.c[0];
417
- if (dp !== UNDEFINED) {
418
- if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP);
419
- x = round(new x.constructor(x), dp + x.e + 1, rm);
420
- for (dp = dp + x.e + 1; x.c.length < dp;) x.c.push(0);
421
- }
422
- return stringify(x, false, !!n);
423
- };
424
- P.toJSON = P.toString = function() {
425
- var x = this, Big$1 = x.constructor;
426
- return stringify(x, x.e <= Big$1.NE || x.e >= Big$1.PE, !!x.c[0]);
427
- };
428
- if (typeof Symbol !== "undefined") P[Symbol.for("nodejs.util.inspect.custom")] = P.toJSON;
429
- P.toNumber = function() {
430
- var n = +stringify(this, true, true);
431
- if (this.constructor.strict === true && !this.eq(n.toString())) throw Error(NAME + "Imprecise conversion");
432
- return n;
433
- };
434
- P.toPrecision = function(sd, rm) {
435
- var x = this, Big$1 = x.constructor, n = x.c[0];
436
- if (sd !== UNDEFINED) {
437
- if (sd !== ~~sd || sd < 1 || sd > MAX_DP) throw Error(INVALID + "precision");
438
- x = round(new Big$1(x), sd, rm);
439
- for (; x.c.length < sd;) x.c.push(0);
440
- }
441
- return stringify(x, sd <= x.e || x.e <= Big$1.NE || x.e >= Big$1.PE, !!n);
442
- };
443
- P.valueOf = function() {
444
- var x = this, Big$1 = x.constructor;
445
- if (Big$1.strict === true) throw Error(NAME + "valueOf disallowed");
446
- return stringify(x, x.e <= Big$1.NE || x.e >= Big$1.PE, true);
447
- };
448
- var Big = _Big_();
449
-
450
- //#endregion
451
- //#region src/candle/CandleBatcher.ts
452
- var CandleBatcher = class CandleBatcher extends node_events.EventEmitter {
453
- batch = [];
454
- desiredIntervalInMillis;
455
- constructor(desiredIntervalInMillis) {
456
- super();
457
- this.desiredIntervalInMillis = desiredIntervalInMillis;
458
- }
459
- get present() {
460
- return this.batch.length;
461
- }
462
- static amountOfCandles(intervalInMillis, timespanInMillis) {
463
- const interval = typeof intervalInMillis === "number" ? intervalInMillis : (0, ms.ms)(intervalInMillis);
464
- return (typeof timespanInMillis === "number" ? timespanInMillis : (0, ms.ms)(timespanInMillis)) / interval;
465
- }
466
- static isBatchedCandle(candle) {
467
- return typeof candle.open !== "string";
468
- }
469
- static createBatchedCandle(batch, desiredIntervalInMillis) {
470
- const openTimesArray = batch.map((candle) => candle.openTimeInMillis);
471
- batch = batch.filter((candle, index) => index === openTimesArray.indexOf(candle.openTimeInMillis));
472
- const firstCandle = batch[0];
473
- const lastCandle = batch[batch.length - 1];
474
- const isPositive = new Big(lastCandle.close).gt(firstCandle.open);
475
- const accumulator = {
476
- base: firstCandle.base,
477
- change: new Big(1).minus(new Big(firstCandle.open).div(lastCandle.close)).times(100),
478
- close: new Big(lastCandle.close),
479
- closeAsk: new Big(lastCandle.closeAsk || lastCandle.close),
480
- counter: firstCandle.counter,
481
- high: new Big(firstCandle.high),
482
- highAsk: new Big(firstCandle.highAsk || firstCandle.high),
483
- isLatest: lastCandle.isLatest,
484
- isNegative: !isPositive,
485
- isPositive,
486
- low: new Big(firstCandle.low),
487
- lowAsk: new Big(firstCandle.lowAsk || firstCandle.low),
488
- medianPrice: new Big(0),
489
- open: new Big(firstCandle.open),
490
- openAsk: new Big(firstCandle.openAsk || firstCandle.open),
491
- openTimeInISO: firstCandle.openTimeInISO,
492
- openTimeInMillis: firstCandle.openTimeInMillis,
493
- sizeInMillis: desiredIntervalInMillis,
494
- volume: new Big(0),
495
- weightedMedianPrice: new Big(0)
496
- };
497
- const reducer = (accumulator$1, candle) => {
498
- const { high, highAsk, low, lowAsk } = accumulator$1;
499
- candle.lowAsk ??= candle.low;
500
- candle.highAsk ??= candle.high;
501
- return {
502
- base: accumulator$1.base,
503
- change: accumulator$1.change,
504
- close: accumulator$1.close,
505
- closeAsk: accumulator$1.closeAsk,
506
- counter: accumulator$1.counter,
507
- high: high.gte(candle.high) ? high : new Big(candle.high),
508
- highAsk: highAsk.gte(candle.highAsk) ? highAsk : new Big(candle.highAsk),
509
- isLatest: accumulator$1.isLatest,
510
- isNegative: accumulator$1.isNegative,
511
- isPositive: accumulator$1.isPositive,
512
- low: low.lte(candle.low) ? low : new Big(candle.low),
513
- lowAsk: lowAsk.lte(candle.lowAsk) ? lowAsk : new Big(candle.lowAsk),
514
- medianPrice: accumulator$1.medianPrice,
515
- open: accumulator$1.open,
516
- openAsk: accumulator$1.openAsk,
517
- openTimeInISO: accumulator$1.openTimeInISO,
518
- openTimeInMillis: accumulator$1.openTimeInMillis,
519
- sizeInMillis: accumulator$1.sizeInMillis,
520
- volume: accumulator$1.volume.plus(candle.volume),
521
- weightedMedianPrice: accumulator$1.weightedMedianPrice
522
- };
523
- };
524
- const batchedCandle = batch.reduce(reducer, accumulator);
525
- const weightedMedianPrice = batchedCandle.volume.eq(0) ? batchedCandle.close : batch.map((candle) => {
526
- const medianPrice = new Big(candle.low).plus(candle.high).div(2);
527
- return new Big(candle.volume).mul(medianPrice);
528
- }).reduce((medianSum1, medianSum2) => medianSum1.plus(medianSum2)).div(batchedCandle.volume);
529
- batchedCandle.medianPrice = new Big(batchedCandle.high).plus(batchedCandle.low).div(2);
530
- batchedCandle.weightedMedianPrice = weightedMedianPrice;
531
- return batchedCandle;
532
- }
533
- /**
534
- * Add candles that should be batched. Once enough candles have been added, the function will return a batched
535
- * candle.
536
- *
537
- * Example: If you aim for a 1-hour batch, and you include 15-minute candles, this function will produce a 1-hour
538
- * candle once you've added four sets of 15-minute candles.
539
- */
540
- addToBatch(candle) {
541
- const exchangeCandle = CandleBatcher.isBatchedCandle(candle) ? CandleBatcher.toExchangeCandle(candle) : candle;
542
- const { currentBatchArray, newBatch } = CandleBatcher.add(exchangeCandle, this.batch, this.desiredIntervalInMillis);
543
- this.batch = currentBatchArray;
544
- if (newBatch) this.emit("batchedCandle", newBatch);
545
- return newBatch;
546
- }
547
- static batchMany(candles, desiredIntervalInMillis) {
548
- if (candles.length === 0) return [];
549
- const batchesArray = [];
550
- let currentBatchArray = [];
551
- for (const candle of candles) {
552
- const addCandle = CandleBatcher.add(candle, currentBatchArray, desiredIntervalInMillis);
553
- if (addCandle.newBatch !== void 0) batchesArray.push(addCandle.newBatch);
554
- currentBatchArray = addCandle.currentBatchArray;
555
- }
556
- if (currentBatchArray.length !== 0) batchesArray.push(CandleBatcher.createBatchedCandle(currentBatchArray, desiredIntervalInMillis));
557
- return batchesArray;
558
- }
559
- /**
560
- * Create a new candle which starts at the beginning of the desired interval (even when beginning candles have been
561
- * missed). Because of this fix, we won't get a shifted chart when candles are missing within an interval.
562
- */
563
- static adjustCandle(candle, desiredIntervalInMillis) {
564
- const newCandle = { ...candle };
565
- newCandle.openTimeInMillis = candle.openTimeInMillis - candle.openTimeInMillis % desiredIntervalInMillis;
566
- newCandle.openTimeInISO = new Date(newCandle.openTimeInMillis).toISOString();
567
- return newCandle;
568
- }
569
- static add(candle, currentBatchArray, desiredIntervalInMillis) {
570
- if (new Big(candle.volume).eq(0)) return {
571
- currentBatchArray,
572
- newBatch: void 0
573
- };
574
- if (currentBatchArray.length === 0) {
575
- const adjustedCandle = CandleBatcher.adjustCandle(candle, desiredIntervalInMillis);
576
- currentBatchArray.push(adjustedCandle);
577
- if (adjustedCandle.sizeInMillis === desiredIntervalInMillis) return {
578
- currentBatchArray: [],
579
- newBatch: CandleBatcher.createBatchedCandle(currentBatchArray, desiredIntervalInMillis)
580
- };
581
- } else {
582
- const firstCandle = currentBatchArray[0];
583
- const isNextInterval = candle.openTimeInMillis + candle.sizeInMillis - firstCandle.openTimeInMillis > desiredIntervalInMillis;
584
- const isEndOfCurrentInterval = candle.openTimeInMillis + candle.sizeInMillis - firstCandle.openTimeInMillis === desiredIntervalInMillis;
585
- if (isNextInterval || isEndOfCurrentInterval) {
586
- if (isEndOfCurrentInterval) currentBatchArray.push(candle);
587
- const newBatch = CandleBatcher.createBatchedCandle(currentBatchArray, desiredIntervalInMillis);
588
- if (isEndOfCurrentInterval) currentBatchArray = [];
589
- else currentBatchArray = [CandleBatcher.adjustCandle(candle, desiredIntervalInMillis)];
590
- return {
591
- currentBatchArray,
592
- newBatch
593
- };
594
- }
595
- currentBatchArray.push(candle);
596
- }
597
- return {
598
- currentBatchArray,
599
- newBatch: void 0
600
- };
601
- }
602
- static toBatchedCandles(candles) {
603
- return CandleBatcher.batchMany(candles, candles[0].sizeInMillis);
604
- }
605
- static toBatchedCandle(candle) {
606
- return CandleBatcher.batchMany([candle], candle.sizeInMillis)[0];
607
- }
608
- static toExchangeCandles(candles) {
609
- return candles.map(CandleBatcher.toExchangeCandle);
610
- }
611
- static toExchangeCandle(candle) {
612
- return {
613
- base: candle.base,
614
- close: candle.close.valueOf(),
615
- counter: candle.counter,
616
- high: candle.high.valueOf(),
617
- low: candle.low.valueOf(),
618
- open: candle.open.valueOf(),
619
- openTimeInISO: candle.openTimeInISO,
620
- openTimeInMillis: candle.openTimeInMillis,
621
- sizeInMillis: candle.sizeInMillis,
622
- volume: candle.volume.valueOf()
623
- };
624
- }
625
- static toString(candle) {
626
- return JSON.stringify(jsonabc.default.sortObj({
627
- base: candle.base,
628
- close: candle.close.valueOf(),
629
- counter: candle.counter,
630
- high: candle.high.valueOf(),
631
- low: candle.low.valueOf(),
632
- medianPrice: candle.medianPrice.valueOf(),
633
- open: candle.open.valueOf(),
634
- openTimeInISO: candle.openTimeInISO,
635
- openTimeInMillis: candle.openTimeInMillis,
636
- sizeInMillis: candle.sizeInMillis,
637
- volume: candle.volume.valueOf(),
638
- weightedMedianPrice: candle.weightedMedianPrice.valueOf()
639
- }), null, 2);
640
- }
641
- static getHighAndLow(candles) {
642
- const reducer = (accumulator, candle) => {
643
- const { high, low } = accumulator;
644
- return {
645
- high: high.gte(candle.high) ? high : new Big(candle.high),
646
- low: low.lte(candle.low) ? low : new Big(candle.low)
647
- };
648
- };
649
- const [firstCandle] = candles;
650
- return candles.reduce(reducer, {
651
- high: new Big(firstCandle.high),
652
- low: new Big(firstCandle.low)
653
- });
654
- }
655
- };
656
-
657
- //#endregion
658
- //#region src/core/CurrencyPair.ts
659
- /**
660
- * A currency pair symbolizes an asset and the currency that you are trading the asset with.
661
- *
662
- * Examples:
663
- * Base: TSLA, Counter: EUR
664
- * Base: BTC, Counter: USDT
665
- */
666
- var CurrencyPair = class CurrencyPair {
667
- /**
668
- * Constructs a currency pair.
669
- *
670
- * @param base - Symbol of the base asset (i.e. TSLA)
671
- * @param counter - Symbol of the counter asset (i.e. EUR)
672
- */
673
- constructor(base, counter) {
674
- this.base = base;
675
- this.counter = counter;
676
- }
677
- isEqual(other) {
678
- return this.base === other.base && this.counter === other.counter;
679
- }
680
- asString(delimiter) {
681
- return `${this.base}${delimiter}${this.counter}`;
682
- }
683
- static fromString(symbol, delimiter) {
684
- const [base, counter] = symbol.split(delimiter);
685
- if (base && counter) return new CurrencyPair(base, counter);
686
- throw new Error(`Symbol "${symbol}" cannot be split with delimiter "${delimiter}".`);
687
- }
688
- };
689
-
690
- //#endregion
691
- //#region src/core/Exchange.ts
692
- let ExchangeOrderSide = /* @__PURE__ */ function(ExchangeOrderSide$1) {
693
- ExchangeOrderSide$1["BUY"] = "BUY";
694
- ExchangeOrderSide$1["SELL"] = "SELL";
695
- return ExchangeOrderSide$1;
696
- }({});
697
- const ExchangeCandleBaseSchema = zod.z.object({
698
- base: zod.z.string(),
699
- counter: zod.z.string(),
700
- isLatest: zod.z.boolean().optional(),
701
- openTimeInISO: zod.z.string(),
702
- openTimeInMillis: zod.z.number(),
703
- sizeInMillis: zod.z.number()
704
- });
705
- let ExchangeOrderType = /* @__PURE__ */ function(ExchangeOrderType$1) {
706
- /** Maker */
707
- ExchangeOrderType$1["LIMIT"] = "LIMIT";
708
- /** Taker */
709
- ExchangeOrderType$1["MARKET"] = "MARKET";
710
- return ExchangeOrderType$1;
711
- }({});
712
- const ExchangeCandleSchema = zod.z.object({
713
- close: zod.z.string(),
714
- closeAsk: zod.z.string().optional(),
715
- high: zod.z.string(),
716
- highAsk: zod.z.string().optional(),
717
- low: zod.z.string(),
718
- lowAsk: zod.z.string().optional(),
719
- open: zod.z.string(),
720
- openAsk: zod.z.string().optional(),
721
- volume: zod.z.string()
722
- }).merge(ExchangeCandleBaseSchema);
723
- let ExchangeOrderPosition = /* @__PURE__ */ function(ExchangeOrderPosition$1) {
724
- ExchangeOrderPosition$1["LONG"] = "LONG";
725
- ExchangeOrderPosition$1["SHORT"] = "SHORT";
726
- return ExchangeOrderPosition$1;
727
- }({});
728
- var Exchange = class {
729
- constructor(loggerName) {
730
- this.loggerName = loggerName;
731
- }
732
- /**
733
- * Get the most recent candle with data by searching backwards in time.
734
- * Useful when markets are closed or data hasn't been published yet for the latest interval.
735
- */
736
- async getLatestAvailableCandle(pair, intervalInMillis) {
737
- let endTime = Math.floor(Date.now() / intervalInMillis) * intervalInMillis;
738
- let startTime = endTime - intervalInMillis;
739
- let candles = await this.getCandles(pair, {
740
- intervalInMillis,
741
- startTimeFirstCandle: new Date(startTime).toISOString(),
742
- startTimeLastCandle: new Date(endTime).toISOString()
743
- });
744
- while (candles.length === 0) {
745
- endTime = startTime;
746
- startTime -= intervalInMillis;
747
- candles = await this.getCandles(pair, {
748
- intervalInMillis,
749
- startTimeFirstCandle: new Date(startTime).toISOString(),
750
- startTimeLastCandle: new Date(endTime).toISOString()
751
- });
752
- }
753
- return candles[0];
754
- }
755
- };
756
-
757
- //#endregion
758
- //#region src/exchange-alpaca/AlpacaExchangeMapper.ts
759
- var AlpacaExchangeMapper = class {
760
- static mapInterval(intervalInMillis) {
761
- if (intervalInMillis < (0, ms.ms)("1m")) throw new Error(`Timeframes below 1 minute are not supported.`);
762
- if (intervalInMillis > (0, ms.ms)("1d")) throw new Error(`Timeframes above 1 day are not supported.`);
763
- return (0, ms.ms)(intervalInMillis).replace("m", "Min").replace("h", "Hour").replace("d", "Day");
764
- }
765
- static toExchangeCandle(candle, pair, sizeInMillis) {
766
- const date = new Date(candle.t);
767
- return {
768
- base: pair.base,
769
- close: candle.c + "",
770
- counter: pair.counter,
771
- high: candle.h + "",
772
- low: candle.l + "",
773
- open: candle.o + "",
774
- openTimeInISO: date.toISOString(),
775
- openTimeInMillis: date.getTime(),
776
- sizeInMillis,
777
- volume: candle.v + ""
778
- };
779
- }
780
- static toExchangePendingOrder(order, pair, options) {
781
- if (order.type === "market") return {
782
- id: order.id,
783
- pair,
784
- side: options.side,
785
- size: order.notional ? `${order.notional}` : `${order.qty}`,
786
- type: ExchangeOrderType.MARKET
787
- };
788
- return {
789
- id: order.id,
790
- pair,
791
- price: `${order.limit_price}`,
792
- side: options.side,
793
- size: `${order.qty}`,
794
- type: ExchangeOrderType.LIMIT
795
- };
796
- }
797
- static toFilledOrder(order, pair) {
798
- if (order.status !== _master_chief_alpaca_ts.OrderStatus.FILLED) throw new Error(`Order ID "${order.id}" is not filled.`);
799
- return {
800
- created_at: `${order.created_at}`,
801
- fee: "0",
802
- feeAsset: pair.counter,
803
- order_id: `${order.id}`,
804
- pair,
805
- position: ExchangeOrderPosition.LONG,
806
- price: `${order.filled_avg_price}`,
807
- side: order.side === "buy" ? ExchangeOrderSide.BUY : ExchangeOrderSide.SELL,
808
- size: `${order.filled_qty}`
809
- };
810
- }
811
- };
812
-
813
- //#endregion
814
- //#region src/exchange-alpaca/AlpacaExchange.ts
815
- const ms$2 = (timeString) => {
816
- const units = {
817
- s: 1e3,
818
- m: 6e4
819
- };
820
- const match = timeString.match(/^(\d+)([sm])$/);
821
- if (!match) throw new Error(`Invalid time string: ${timeString}`);
822
- return parseInt(match[1]) * units[match[2]];
823
- };
824
- const hasErrorCode = (error) => {
825
- return !!error && typeof error === "object" && "code" in error;
826
- };
827
- const hasErrorStatus = (error) => {
828
- return !!error && typeof error === "object" && "status" in error && typeof error.status === "number";
829
- };
830
- var AlpacaExchange = class AlpacaExchange extends Exchange {
831
- stream = void 0;
832
- client;
833
- SUBSCRIPTION_PLAN = "iex";
834
- retryConfig = {
835
- delay: ms$2("10s"),
836
- retries: "INFINITELY",
837
- retryIf: (error) => {
838
- if (hasErrorCode(error)) switch (error.code) {
839
- case 40310100: return false;
840
- default: return true;
841
- }
842
- else if (hasErrorStatus(error)) {
843
- if (error.status === 429) return true;
844
- }
845
- return false;
846
- },
847
- timeout: ms$2("5m")
848
- };
849
- constructor(options) {
850
- super(AlpacaExchange.NAME);
851
- this.client = new _master_chief_alpaca_ts.Client({
852
- credentials: {
853
- key: options.apiKey,
854
- secret: options.apiSecret
855
- },
856
- paper: options.usePaperTrading
857
- });
858
- }
859
- static NAME = "Alpaca";
860
- createSymbol(pair, isCrypto) {
861
- if (isCrypto ?? pair.counter !== "USD") return `${pair.base}/${pair.counter}`;
862
- return pair.base;
863
- }
864
- async fetchLatestCryptoBars(pair) {
865
- return (0, ts_retry_promise.retry)(() => this.client.v1beta3.getCryptoBarsLatest({ symbols: this.createSymbol(pair, true) }), this.retryConfig);
866
- }
867
- async isCryptoSymbol(pair) {
868
- try {
869
- const response = await this.fetchLatestCryptoBars(pair);
870
- return Object.keys(response.bars).length > 0;
871
- } catch (error) {
872
- if (error instanceof _master_chief_alpaca_ts.ApiError && error.status === 400) return false;
873
- throw error;
874
- }
875
- }
876
- async fetchCryptoBars(pair, request, pageToken) {
877
- return (0, ts_retry_promise.retry)(() => this.client.v1beta3.getCryptoBars({
878
- end: request.startTimeLastCandle,
879
- limit: 1e4,
880
- pageToken,
881
- start: request.startTimeFirstCandle,
882
- symbols: this.createSymbol(pair, true),
883
- timeframe: AlpacaExchangeMapper.mapInterval(request.intervalInMillis)
884
- }), this.retryConfig);
885
- }
886
- fetchStockBars(pair, request, pageToken) {
887
- if (pair.counter !== "USD") throw new Error(`Cannot use "${pair.counter}". Stock "${pair.base}" can only be traded in USD on ${AlpacaExchange.NAME}.`);
888
- return (0, ts_retry_promise.retry)(() => this.client.v2.getStockBars({
889
- end: request.startTimeLastCandle,
890
- feed: this.SUBSCRIPTION_PLAN,
891
- limit: 1e4,
892
- pageToken,
893
- start: request.startTimeFirstCandle,
894
- symbols: this.createSymbol(pair, false),
895
- timeframe: AlpacaExchangeMapper.mapInterval(request.intervalInMillis)
896
- }), this.retryConfig);
897
- }
898
- async getCandles(pair, request) {
899
- const candles = [];
900
- let pageToken = void 0;
901
- const fetchBars = await this.isCryptoSymbol(pair) ? this.fetchCryptoBars.bind(this) : this.fetchStockBars.bind(this);
902
- do {
903
- const { bars, next_page_token } = await fetchBars(pair, request, pageToken);
904
- const entries = Object.values(bars);
905
- for (const bars$1 of entries) bars$1.forEach((bar) => {
906
- const candle = AlpacaExchangeMapper.toExchangeCandle(bar, pair, request.intervalInMillis);
907
- candles.push(candle);
908
- });
909
- pageToken = next_page_token;
910
- } while (pageToken);
911
- return candles;
912
- }
913
- getName() {
914
- return AlpacaExchange.NAME;
915
- }
916
- /**
917
- * Original time format from Alpaca is "RFC 3339" (i.e. "2023-08-08T18:58:27.26720022-04:00"),
918
- * we convert it to "ISO 8601 UTC" (i.e. "2023-08-08T22:58:27.267Z").
919
- */
920
- async getTime() {
921
- const clock = await (0, ts_retry_promise.retry)(() => this.client.v2.getClock(), this.retryConfig);
922
- return new Date(clock.timestamp).toISOString();
923
- }
924
- disconnect() {
925
- this.stream?.getConnection().close();
926
- }
927
- };
928
-
929
- //#endregion
930
- //#region src/exchange-alpaca/getAlpacaClient.ts
931
- function getAlpacaClient({ apiKey, apiSecret, usePaperTrading }) {
932
- process.on("SIGINT", () => {
933
- console.log("Received signal interrupt...");
934
- exchange.disconnect();
935
- console.log(`Sent WebSocket disconnect.`);
936
- process.exit(0);
937
- });
938
- const exchange = new AlpacaExchange({
939
- apiKey,
940
- apiSecret,
941
- usePaperTrading
942
- });
943
- return exchange;
944
- }
945
-
946
- //#endregion
947
- exports.AlpacaExchange = AlpacaExchange;
948
- exports.AlpacaExchangeMapper = AlpacaExchangeMapper;
949
- exports.BasicCandlePrice = BasicCandlePrice;
950
- exports.CandleBatcher = CandleBatcher;
951
- exports.CurrencyPair = CurrencyPair;
952
- exports.Exchange = Exchange;
953
- exports.ExchangeCandleBaseSchema = ExchangeCandleBaseSchema;
954
- exports.ExchangeCandleSchema = ExchangeCandleSchema;
955
- exports.ExchangeOrderPosition = ExchangeOrderPosition;
956
- exports.ExchangeOrderSide = ExchangeOrderSide;
957
- exports.ExchangeOrderType = ExchangeOrderType;
958
- exports.getAlpacaClient = getAlpacaClient;
959
- exports.hasErrorCode = hasErrorCode;
960
- exports.hasErrorStatus = hasErrorStatus;
961
- Object.defineProperty(exports, 'ms', {
962
- enumerable: true,
963
- get: function () {
964
- return ms.parse;
965
- }
966
- });