topstepx-api 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.
package/dist/index.mjs ADDED
@@ -0,0 +1,776 @@
1
+ import { HubConnectionBuilder, HttpTransportType, HubConnectionState } from '@microsoft/signalr';
2
+
3
+ // src/errors/base-error.ts
4
+ var TopstepXError = class extends Error {
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.code = code;
8
+ this.name = this.constructor.name;
9
+ this.timestamp = /* @__PURE__ */ new Date();
10
+ Error.captureStackTrace?.(this, this.constructor);
11
+ }
12
+ timestamp;
13
+ toJSON() {
14
+ return {
15
+ name: this.name,
16
+ message: this.message,
17
+ code: this.code,
18
+ timestamp: this.timestamp.toISOString()
19
+ };
20
+ }
21
+ };
22
+
23
+ // src/errors/auth-error.ts
24
+ var AuthenticationError = class extends TopstepXError {
25
+ constructor(message, code) {
26
+ super(message, code);
27
+ }
28
+ };
29
+
30
+ // src/errors/api-error.ts
31
+ var ApiError = class extends TopstepXError {
32
+ constructor(message, code, endpoint) {
33
+ super(message, code);
34
+ this.endpoint = endpoint;
35
+ }
36
+ toJSON() {
37
+ return {
38
+ ...super.toJSON(),
39
+ endpoint: this.endpoint
40
+ };
41
+ }
42
+ };
43
+
44
+ // src/errors/connection-error.ts
45
+ var ConnectionError = class extends TopstepXError {
46
+ constructor(message) {
47
+ super(message);
48
+ }
49
+ };
50
+
51
+ // src/auth/auth.service.ts
52
+ var AuthService = class {
53
+ sessionToken = null;
54
+ tokenExpiration = null;
55
+ refreshTimer;
56
+ config;
57
+ constructor(config) {
58
+ this.config = {
59
+ username: config.username,
60
+ apiKey: config.apiKey,
61
+ baseUrl: config.baseUrl ?? "https://api.topstepx.com",
62
+ autoRefresh: config.autoRefresh ?? true,
63
+ tokenValidityHours: config.tokenValidityHours ?? 24
64
+ };
65
+ }
66
+ async login() {
67
+ const request = {
68
+ userName: this.config.username,
69
+ apiKey: this.config.apiKey
70
+ };
71
+ const response = await fetch(`${this.config.baseUrl}/api/Auth/loginKey`, {
72
+ method: "POST",
73
+ headers: {
74
+ "Content-Type": "application/json",
75
+ Accept: "text/plain"
76
+ },
77
+ body: JSON.stringify(request)
78
+ });
79
+ if (!response.ok) {
80
+ throw new AuthenticationError(
81
+ `HTTP error during login: ${response.status}`,
82
+ response.status
83
+ );
84
+ }
85
+ const data = await response.json();
86
+ if (!data.success || data.errorCode !== 0) {
87
+ throw new AuthenticationError(
88
+ data.errorMessage ?? "Login failed",
89
+ data.errorCode
90
+ );
91
+ }
92
+ this.sessionToken = data.token;
93
+ this.setTokenExpiration();
94
+ if (this.config.autoRefresh) {
95
+ this.scheduleTokenRefresh();
96
+ }
97
+ }
98
+ async validate() {
99
+ if (!this.sessionToken) return false;
100
+ try {
101
+ const response = await fetch(`${this.config.baseUrl}/api/Auth/validate`, {
102
+ method: "POST",
103
+ headers: {
104
+ "Content-Type": "application/json",
105
+ Accept: "text/plain",
106
+ Authorization: `Bearer ${this.sessionToken}`
107
+ }
108
+ });
109
+ if (response.ok) {
110
+ this.setTokenExpiration();
111
+ return true;
112
+ }
113
+ return false;
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+ async getSessionToken() {
119
+ if (!this.sessionToken || this.isTokenExpired()) {
120
+ const isValid = await this.validate();
121
+ if (!isValid) {
122
+ await this.login();
123
+ }
124
+ }
125
+ if (!this.sessionToken) {
126
+ throw new AuthenticationError("No active session token available");
127
+ }
128
+ return this.sessionToken;
129
+ }
130
+ get baseUrl() {
131
+ return this.config.baseUrl;
132
+ }
133
+ setTokenExpiration() {
134
+ const expiration = /* @__PURE__ */ new Date();
135
+ expiration.setHours(
136
+ expiration.getHours() + this.config.tokenValidityHours
137
+ );
138
+ this.tokenExpiration = expiration;
139
+ }
140
+ isTokenExpired() {
141
+ if (!this.tokenExpiration) return true;
142
+ const buffer = 5 * 60 * 1e3;
143
+ return Date.now() >= this.tokenExpiration.getTime() - buffer;
144
+ }
145
+ scheduleTokenRefresh() {
146
+ if (this.refreshTimer) {
147
+ clearTimeout(this.refreshTimer);
148
+ }
149
+ if (!this.tokenExpiration) return;
150
+ const refreshTime = this.tokenExpiration.getTime() - Date.now() - 10 * 60 * 1e3;
151
+ if (refreshTime > 0) {
152
+ this.refreshTimer = setTimeout(async () => {
153
+ try {
154
+ const isValid = await this.validate();
155
+ if (!isValid) {
156
+ await this.login();
157
+ }
158
+ this.scheduleTokenRefresh();
159
+ } catch (error) {
160
+ console.error("Token refresh failed:", error);
161
+ }
162
+ }, refreshTime);
163
+ }
164
+ }
165
+ destroy() {
166
+ if (this.refreshTimer) {
167
+ clearTimeout(this.refreshTimer);
168
+ }
169
+ this.sessionToken = null;
170
+ this.tokenExpiration = null;
171
+ }
172
+ };
173
+
174
+ // src/rest/http-client.ts
175
+ var HttpClient = class {
176
+ config;
177
+ constructor(config) {
178
+ this.config = {
179
+ baseUrl: config.baseUrl,
180
+ getToken: config.getToken,
181
+ timeout: config.timeout ?? 3e4
182
+ };
183
+ }
184
+ async post(endpoint, data) {
185
+ const token = await this.config.getToken();
186
+ const controller = new AbortController();
187
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
188
+ try {
189
+ const response = await fetch(`${this.config.baseUrl}${endpoint}`, {
190
+ method: "POST",
191
+ headers: {
192
+ "Content-Type": "application/json",
193
+ Accept: "application/json",
194
+ Authorization: `Bearer ${token}`
195
+ },
196
+ body: JSON.stringify(data),
197
+ signal: controller.signal
198
+ });
199
+ clearTimeout(timeoutId);
200
+ if (!response.ok) {
201
+ throw new ApiError(
202
+ `HTTP error: ${response.status} ${response.statusText}`,
203
+ response.status,
204
+ endpoint
205
+ );
206
+ }
207
+ const result = await response.json();
208
+ if (!result.success || result.errorCode !== 0) {
209
+ throw new ApiError(
210
+ result.errorMessage ?? "API request failed",
211
+ result.errorCode,
212
+ endpoint
213
+ );
214
+ }
215
+ return result;
216
+ } catch (error) {
217
+ clearTimeout(timeoutId);
218
+ if (error instanceof ApiError) throw error;
219
+ if (error instanceof Error && error.name === "AbortError") {
220
+ throw new ApiError("Request timeout", -1, endpoint);
221
+ }
222
+ throw new ApiError(
223
+ error instanceof Error ? error.message : "Unknown error",
224
+ -1,
225
+ endpoint
226
+ );
227
+ }
228
+ }
229
+ };
230
+
231
+ // src/rest/account/account.api.ts
232
+ var AccountApi = class {
233
+ constructor(http) {
234
+ this.http = http;
235
+ }
236
+ async search(request) {
237
+ const response = await this.http.post("/api/Account/search", request);
238
+ return response.accounts;
239
+ }
240
+ };
241
+
242
+ // src/rest/order/order.api.ts
243
+ var OrderApi = class {
244
+ /** @internal */
245
+ constructor(http) {
246
+ this.http = http;
247
+ }
248
+ /**
249
+ * Search historical orders within a date range.
250
+ * @param request - Search parameters including accountId and optional date range
251
+ * @returns Array of orders matching the search criteria
252
+ */
253
+ async search(request) {
254
+ const response = await this.http.post("/api/Order/search", request);
255
+ return response.orders;
256
+ }
257
+ /**
258
+ * Get all currently open (working) orders for an account.
259
+ * @param request - Request containing the accountId
260
+ * @returns Array of open orders
261
+ */
262
+ async searchOpen(request) {
263
+ const response = await this.http.post("/api/Order/searchOpen", request);
264
+ return response.orders;
265
+ }
266
+ /**
267
+ * Place a new order.
268
+ * @param request - Order details including type, side, size, and prices
269
+ * @returns Response containing the new orderId
270
+ *
271
+ * @example
272
+ * ```typescript
273
+ * // Market order
274
+ * await client.orders.place({
275
+ * accountId: 123,
276
+ * contractId: 'CON.F.US.ENQ.M25',
277
+ * type: OrderType.Market,
278
+ * side: OrderSide.Buy,
279
+ * size: 1,
280
+ * });
281
+ *
282
+ * // Limit order
283
+ * await client.orders.place({
284
+ * accountId: 123,
285
+ * contractId: 'CON.F.US.ENQ.M25',
286
+ * type: OrderType.Limit,
287
+ * side: OrderSide.Buy,
288
+ * size: 1,
289
+ * limitPrice: 5000.00,
290
+ * });
291
+ * ```
292
+ */
293
+ async place(request) {
294
+ return this.http.post(
295
+ "/api/Order/place",
296
+ request
297
+ );
298
+ }
299
+ /**
300
+ * Cancel an existing order.
301
+ * @param request - Request containing accountId and orderId to cancel
302
+ * @returns Response indicating success or failure
303
+ */
304
+ async cancel(request) {
305
+ return this.http.post(
306
+ "/api/Order/cancel",
307
+ request
308
+ );
309
+ }
310
+ /**
311
+ * Modify an existing order's size or price.
312
+ * @param request - Request containing orderId and fields to modify
313
+ * @returns Response indicating success or failure
314
+ */
315
+ async modify(request) {
316
+ return this.http.post(
317
+ "/api/Order/modify",
318
+ request
319
+ );
320
+ }
321
+ };
322
+
323
+ // src/rest/position/position.api.ts
324
+ var PositionApi = class {
325
+ constructor(http) {
326
+ this.http = http;
327
+ }
328
+ async searchOpen(request) {
329
+ const response = await this.http.post("/api/Position/searchOpen", request);
330
+ return response.positions;
331
+ }
332
+ async close(request) {
333
+ return this.http.post(
334
+ "/api/Position/closeContract",
335
+ request
336
+ );
337
+ }
338
+ async partialClose(request) {
339
+ return this.http.post("/api/Position/partialCloseContract", request);
340
+ }
341
+ };
342
+
343
+ // src/rest/trade/trade.api.ts
344
+ var TradeApi = class {
345
+ constructor(http) {
346
+ this.http = http;
347
+ }
348
+ async search(request) {
349
+ const response = await this.http.post("/api/Trade/search", request);
350
+ return response.trades;
351
+ }
352
+ };
353
+
354
+ // src/rest/contract/contract.api.ts
355
+ var ContractApi = class {
356
+ constructor(http) {
357
+ this.http = http;
358
+ }
359
+ async search(request) {
360
+ const response = await this.http.post("/api/Contract/search", request);
361
+ return response.contracts;
362
+ }
363
+ async searchById(request) {
364
+ const response = await this.http.post("/api/Contract/searchById", request);
365
+ return response.contract;
366
+ }
367
+ };
368
+
369
+ // src/rest/history/history.api.ts
370
+ var HistoryApi = class {
371
+ constructor(http) {
372
+ this.http = http;
373
+ }
374
+ async retrieveBars(request) {
375
+ const response = await this.http.post("/api/History/retrieveBars", request);
376
+ return response.bars;
377
+ }
378
+ };
379
+ var ConnectionManager = class {
380
+ marketConn = null;
381
+ userConn = null;
382
+ config;
383
+ marketConnectionCallbacks = [];
384
+ userConnectionCallbacks = [];
385
+ constructor(config) {
386
+ this.config = {
387
+ marketHubUrl: config.marketHubUrl,
388
+ userHubUrl: config.userHubUrl,
389
+ auth: config.auth,
390
+ reconnectDelays: config.reconnectDelays ?? [0, 2e3, 5e3, 1e4, 3e4]
391
+ };
392
+ }
393
+ async connect() {
394
+ const token = await this.config.auth.getSessionToken();
395
+ this.marketConn = new HubConnectionBuilder().withUrl(`${this.config.marketHubUrl}?access_token=${token}`, {
396
+ skipNegotiation: true,
397
+ transport: HttpTransportType.WebSockets,
398
+ accessTokenFactory: () => this.config.auth.getSessionToken()
399
+ }).withAutomaticReconnect(this.config.reconnectDelays).build();
400
+ this.userConn = new HubConnectionBuilder().withUrl(`${this.config.userHubUrl}?access_token=${token}`, {
401
+ skipNegotiation: true,
402
+ transport: HttpTransportType.WebSockets,
403
+ accessTokenFactory: () => this.config.auth.getSessionToken()
404
+ }).withAutomaticReconnect(this.config.reconnectDelays).build();
405
+ this.marketConnectionCallbacks.forEach((cb) => cb(this.marketConn));
406
+ this.userConnectionCallbacks.forEach((cb) => cb(this.userConn));
407
+ try {
408
+ await this.marketConn.start();
409
+ await this.userConn.start();
410
+ } catch (error) {
411
+ throw new ConnectionError(
412
+ `Failed to establish WebSocket connections: ${error instanceof Error ? error.message : "Unknown error"}`
413
+ );
414
+ }
415
+ }
416
+ async disconnect() {
417
+ await Promise.all([this.marketConn?.stop(), this.userConn?.stop()]);
418
+ this.marketConn = null;
419
+ this.userConn = null;
420
+ }
421
+ get isConnected() {
422
+ return this.marketConn?.state === HubConnectionState.Connected && this.userConn?.state === HubConnectionState.Connected;
423
+ }
424
+ get marketConnection() {
425
+ if (!this.marketConn) {
426
+ throw new ConnectionError("Market connection not initialized");
427
+ }
428
+ return this.marketConn;
429
+ }
430
+ get userConnection() {
431
+ if (!this.userConn) {
432
+ throw new ConnectionError("User connection not initialized");
433
+ }
434
+ return this.userConn;
435
+ }
436
+ onMarketConnection(callback) {
437
+ this.marketConnectionCallbacks.push(callback);
438
+ if (this.marketConn) callback(this.marketConn);
439
+ }
440
+ onUserConnection(callback) {
441
+ this.userConnectionCallbacks.push(callback);
442
+ if (this.userConn) callback(this.userConn);
443
+ }
444
+ };
445
+
446
+ // src/utils/event-emitter.ts
447
+ var TypedEventEmitter = class {
448
+ listeners = /* @__PURE__ */ new Map();
449
+ on(event, callback) {
450
+ if (!this.listeners.has(event)) {
451
+ this.listeners.set(event, /* @__PURE__ */ new Set());
452
+ }
453
+ this.listeners.get(event).add(callback);
454
+ return this;
455
+ }
456
+ off(event, callback) {
457
+ this.listeners.get(event)?.delete(callback);
458
+ return this;
459
+ }
460
+ once(event, callback) {
461
+ const onceCallback = ((data) => {
462
+ this.off(event, onceCallback);
463
+ callback(data);
464
+ });
465
+ return this.on(event, onceCallback);
466
+ }
467
+ emit(event, ...args) {
468
+ const callbacks = this.listeners.get(event);
469
+ if (!callbacks || callbacks.size === 0) return false;
470
+ callbacks.forEach((callback) => {
471
+ try {
472
+ if (args.length > 0) {
473
+ callback(args[0]);
474
+ } else {
475
+ callback();
476
+ }
477
+ } catch (error) {
478
+ console.error(`Error in event listener for ${String(event)}:`, error);
479
+ }
480
+ });
481
+ return true;
482
+ }
483
+ removeAllListeners(event) {
484
+ if (event) {
485
+ this.listeners.delete(event);
486
+ } else {
487
+ this.listeners.clear();
488
+ }
489
+ return this;
490
+ }
491
+ };
492
+
493
+ // src/realtime/market/market-hub.ts
494
+ var MarketHub = class extends TypedEventEmitter {
495
+ constructor(connectionManager) {
496
+ super();
497
+ this.connectionManager = connectionManager;
498
+ this.setupEventHandlers();
499
+ }
500
+ subscribedQuotes = /* @__PURE__ */ new Set();
501
+ subscribedTrades = /* @__PURE__ */ new Set();
502
+ subscribedDepth = /* @__PURE__ */ new Set();
503
+ setupEventHandlers() {
504
+ this.connectionManager.onMarketConnection((connection) => {
505
+ connection.on("GatewayQuote", (contractId, data) => {
506
+ this.emit("quote", { contractId, data });
507
+ });
508
+ connection.on(
509
+ "GatewayTrade",
510
+ (contractId, data) => {
511
+ this.emit("trade", { contractId, data });
512
+ }
513
+ );
514
+ connection.on(
515
+ "GatewayDepth",
516
+ (contractId, data) => {
517
+ this.emit("depth", { contractId, data });
518
+ }
519
+ );
520
+ });
521
+ }
522
+ async subscribe(contractId) {
523
+ await Promise.all([
524
+ this.subscribeQuotes(contractId),
525
+ this.subscribeTrades(contractId),
526
+ this.subscribeDepth(contractId)
527
+ ]);
528
+ }
529
+ async unsubscribe(contractId) {
530
+ await Promise.all([
531
+ this.unsubscribeQuotes(contractId),
532
+ this.unsubscribeTrades(contractId),
533
+ this.unsubscribeDepth(contractId)
534
+ ]);
535
+ }
536
+ async subscribeQuotes(contractId) {
537
+ if (this.subscribedQuotes.has(contractId)) return;
538
+ const connection = this.connectionManager.marketConnection;
539
+ await connection.invoke("SubscribeContractQuotes", contractId);
540
+ this.subscribedQuotes.add(contractId);
541
+ }
542
+ async unsubscribeQuotes(contractId) {
543
+ if (!this.subscribedQuotes.has(contractId)) return;
544
+ const connection = this.connectionManager.marketConnection;
545
+ await connection.invoke("UnsubscribeContractQuotes", contractId);
546
+ this.subscribedQuotes.delete(contractId);
547
+ }
548
+ async subscribeTrades(contractId) {
549
+ if (this.subscribedTrades.has(contractId)) return;
550
+ const connection = this.connectionManager.marketConnection;
551
+ await connection.invoke("SubscribeContractTrades", contractId);
552
+ this.subscribedTrades.add(contractId);
553
+ }
554
+ async unsubscribeTrades(contractId) {
555
+ if (!this.subscribedTrades.has(contractId)) return;
556
+ const connection = this.connectionManager.marketConnection;
557
+ await connection.invoke("UnsubscribeContractTrades", contractId);
558
+ this.subscribedTrades.delete(contractId);
559
+ }
560
+ async subscribeDepth(contractId) {
561
+ if (this.subscribedDepth.has(contractId)) return;
562
+ const connection = this.connectionManager.marketConnection;
563
+ await connection.invoke("SubscribeContractMarketDepth", contractId);
564
+ this.subscribedDepth.add(contractId);
565
+ }
566
+ async unsubscribeDepth(contractId) {
567
+ if (!this.subscribedDepth.has(contractId)) return;
568
+ const connection = this.connectionManager.marketConnection;
569
+ await connection.invoke("UnsubscribeContractMarketDepth", contractId);
570
+ this.subscribedDepth.delete(contractId);
571
+ }
572
+ };
573
+
574
+ // src/realtime/user/user-hub.ts
575
+ var UserHub = class extends TypedEventEmitter {
576
+ constructor(connectionManager) {
577
+ super();
578
+ this.connectionManager = connectionManager;
579
+ this.setupEventHandlers();
580
+ }
581
+ subscribedOrders = /* @__PURE__ */ new Set();
582
+ subscribedPositions = /* @__PURE__ */ new Set();
583
+ subscribedTrades = /* @__PURE__ */ new Set();
584
+ setupEventHandlers() {
585
+ this.connectionManager.onUserConnection((connection) => {
586
+ connection.on("GatewayUserAccount", (data) => {
587
+ this.emit("account", data);
588
+ });
589
+ connection.on("GatewayUserOrder", (data) => {
590
+ this.emit("order", data);
591
+ });
592
+ connection.on("GatewayUserPosition", (data) => {
593
+ this.emit("position", data);
594
+ });
595
+ connection.on("GatewayUserTrade", (data) => {
596
+ this.emit("trade", data);
597
+ });
598
+ });
599
+ }
600
+ async subscribe(accountId) {
601
+ await Promise.all([
602
+ this.subscribeOrders(accountId),
603
+ this.subscribePositions(accountId),
604
+ this.subscribeTrades(accountId)
605
+ ]);
606
+ }
607
+ async unsubscribe(accountId) {
608
+ await Promise.all([
609
+ this.unsubscribeOrders(accountId),
610
+ this.unsubscribePositions(accountId),
611
+ this.unsubscribeTrades(accountId)
612
+ ]);
613
+ }
614
+ async subscribeOrders(accountId) {
615
+ if (this.subscribedOrders.has(accountId)) return;
616
+ const connection = this.connectionManager.userConnection;
617
+ await connection.invoke("SubscribeOrders", accountId);
618
+ this.subscribedOrders.add(accountId);
619
+ }
620
+ async unsubscribeOrders(accountId) {
621
+ if (!this.subscribedOrders.has(accountId)) return;
622
+ const connection = this.connectionManager.userConnection;
623
+ await connection.invoke("UnsubscribeOrders", accountId);
624
+ this.subscribedOrders.delete(accountId);
625
+ }
626
+ async subscribePositions(accountId) {
627
+ if (this.subscribedPositions.has(accountId)) return;
628
+ const connection = this.connectionManager.userConnection;
629
+ await connection.invoke("SubscribePositions", accountId);
630
+ this.subscribedPositions.add(accountId);
631
+ }
632
+ async unsubscribePositions(accountId) {
633
+ if (!this.subscribedPositions.has(accountId)) return;
634
+ const connection = this.connectionManager.userConnection;
635
+ await connection.invoke("UnsubscribePositions", accountId);
636
+ this.subscribedPositions.delete(accountId);
637
+ }
638
+ async subscribeTrades(accountId) {
639
+ if (this.subscribedTrades.has(accountId)) return;
640
+ const connection = this.connectionManager.userConnection;
641
+ await connection.invoke("SubscribeTrades", accountId);
642
+ this.subscribedTrades.add(accountId);
643
+ }
644
+ async unsubscribeTrades(accountId) {
645
+ if (!this.subscribedTrades.has(accountId)) return;
646
+ const connection = this.connectionManager.userConnection;
647
+ await connection.invoke("UnsubscribeTrades", accountId);
648
+ this.subscribedTrades.delete(accountId);
649
+ }
650
+ };
651
+
652
+ // src/client.ts
653
+ var TopstepXClient = class extends TypedEventEmitter {
654
+ auth;
655
+ connectionManager;
656
+ httpClient;
657
+ /** Account management API */
658
+ accounts;
659
+ /** Order management API (place, cancel, modify, search) */
660
+ orders;
661
+ /** Position management API (search, close) */
662
+ positions;
663
+ /** Trade history API */
664
+ trades;
665
+ /** Contract/symbol search API */
666
+ contracts;
667
+ /** Historical bars/candles API */
668
+ history;
669
+ /** Real-time market data hub (quotes, trades, depth) */
670
+ marketHub;
671
+ /** Real-time account data hub (orders, positions, trades) */
672
+ userHub;
673
+ constructor(config) {
674
+ super();
675
+ const baseUrl = config.baseUrl ?? "https://api.topstepx.com";
676
+ this.auth = new AuthService({
677
+ username: config.username,
678
+ apiKey: config.apiKey,
679
+ baseUrl,
680
+ autoRefresh: config.autoRefresh ?? true,
681
+ tokenValidityHours: config.tokenValidityHours ?? 24
682
+ });
683
+ this.httpClient = new HttpClient({
684
+ baseUrl,
685
+ getToken: () => this.auth.getSessionToken()
686
+ });
687
+ this.accounts = new AccountApi(this.httpClient);
688
+ this.orders = new OrderApi(this.httpClient);
689
+ this.positions = new PositionApi(this.httpClient);
690
+ this.trades = new TradeApi(this.httpClient);
691
+ this.contracts = new ContractApi(this.httpClient);
692
+ this.history = new HistoryApi(this.httpClient);
693
+ this.connectionManager = new ConnectionManager({
694
+ marketHubUrl: config.marketHubUrl ?? "https://rtc.topstepx.com/hubs/market",
695
+ userHubUrl: config.userHubUrl ?? "https://rtc.topstepx.com/hubs/user",
696
+ auth: this.auth
697
+ });
698
+ this.marketHub = new MarketHub(this.connectionManager);
699
+ this.userHub = new UserHub(this.connectionManager);
700
+ }
701
+ /**
702
+ * Connect to the TopstepX API.
703
+ * Authenticates and establishes WebSocket connections.
704
+ */
705
+ async connect() {
706
+ await this.auth.login();
707
+ await this.connectionManager.connect();
708
+ this.emit("connected");
709
+ }
710
+ /**
711
+ * Disconnect from all services.
712
+ */
713
+ async disconnect() {
714
+ await this.connectionManager.disconnect();
715
+ this.auth.destroy();
716
+ this.emit("disconnected");
717
+ }
718
+ /**
719
+ * Check if client is connected.
720
+ */
721
+ get isConnected() {
722
+ return this.connectionManager.isConnected;
723
+ }
724
+ /**
725
+ * Get the current auth token (for advanced use cases).
726
+ */
727
+ async getToken() {
728
+ return this.auth.getSessionToken();
729
+ }
730
+ };
731
+
732
+ // src/types/enums.ts
733
+ var OrderType = /* @__PURE__ */ ((OrderType2) => {
734
+ OrderType2[OrderType2["Limit"] = 1] = "Limit";
735
+ OrderType2[OrderType2["Market"] = 2] = "Market";
736
+ OrderType2[OrderType2["Stop"] = 3] = "Stop";
737
+ OrderType2[OrderType2["StopLimit"] = 4] = "StopLimit";
738
+ return OrderType2;
739
+ })(OrderType || {});
740
+ var OrderSide = /* @__PURE__ */ ((OrderSide2) => {
741
+ OrderSide2[OrderSide2["Buy"] = 0] = "Buy";
742
+ OrderSide2[OrderSide2["Sell"] = 1] = "Sell";
743
+ return OrderSide2;
744
+ })(OrderSide || {});
745
+ var OrderStatus = /* @__PURE__ */ ((OrderStatus2) => {
746
+ OrderStatus2[OrderStatus2["Pending"] = 0] = "Pending";
747
+ OrderStatus2[OrderStatus2["Working"] = 1] = "Working";
748
+ OrderStatus2[OrderStatus2["Filled"] = 2] = "Filled";
749
+ OrderStatus2[OrderStatus2["Cancelled"] = 3] = "Cancelled";
750
+ OrderStatus2[OrderStatus2["Rejected"] = 4] = "Rejected";
751
+ OrderStatus2[OrderStatus2["PartiallyFilled"] = 5] = "PartiallyFilled";
752
+ return OrderStatus2;
753
+ })(OrderStatus || {});
754
+ var BarUnit = /* @__PURE__ */ ((BarUnit2) => {
755
+ BarUnit2[BarUnit2["Second"] = 1] = "Second";
756
+ BarUnit2[BarUnit2["Minute"] = 2] = "Minute";
757
+ BarUnit2[BarUnit2["Hour"] = 3] = "Hour";
758
+ BarUnit2[BarUnit2["Day"] = 4] = "Day";
759
+ BarUnit2[BarUnit2["Week"] = 5] = "Week";
760
+ BarUnit2[BarUnit2["Month"] = 6] = "Month";
761
+ return BarUnit2;
762
+ })(BarUnit || {});
763
+ var PositionType = /* @__PURE__ */ ((PositionType2) => {
764
+ PositionType2[PositionType2["Long"] = 0] = "Long";
765
+ PositionType2[PositionType2["Short"] = 1] = "Short";
766
+ return PositionType2;
767
+ })(PositionType || {});
768
+ var TradeType = /* @__PURE__ */ ((TradeType2) => {
769
+ TradeType2[TradeType2["Bid"] = 0] = "Bid";
770
+ TradeType2[TradeType2["Ask"] = 1] = "Ask";
771
+ return TradeType2;
772
+ })(TradeType || {});
773
+
774
+ export { AccountApi, ApiError, AuthService, AuthenticationError, BarUnit, ConnectionError, ConnectionManager, ContractApi, HistoryApi, HttpClient, MarketHub, OrderApi, OrderSide, OrderStatus, OrderType, PositionApi, PositionType, TopstepXClient, TopstepXError, TradeApi, TradeType, TypedEventEmitter, UserHub };
775
+ //# sourceMappingURL=index.mjs.map
776
+ //# sourceMappingURL=index.mjs.map