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