@finatic/client 0.0.142 → 0.9.1

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 (64) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +39 -0
  3. package/README.md +54 -425
  4. package/dist/index.d.ts +7329 -1579
  5. package/dist/index.js +8110 -6114
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +8047 -6085
  8. package/dist/index.mjs.map +1 -1
  9. package/package.json +77 -33
  10. package/dist/types/core/client/ApiClient.d.ts +0 -270
  11. package/dist/types/core/client/FinaticConnect.d.ts +0 -332
  12. package/dist/types/core/portal/PortalUI.d.ts +0 -37
  13. package/dist/types/index.d.ts +0 -12
  14. package/dist/types/lib/logger/index.d.ts +0 -2
  15. package/dist/types/lib/logger/logger.d.ts +0 -4
  16. package/dist/types/lib/logger/logger.types.d.ts +0 -28
  17. package/dist/types/mocks/MockApiClient.d.ts +0 -171
  18. package/dist/types/mocks/MockDataProvider.d.ts +0 -139
  19. package/dist/types/mocks/MockFactory.d.ts +0 -53
  20. package/dist/types/mocks/utils.d.ts +0 -24
  21. package/dist/types/themes/portalPresets.d.ts +0 -9
  22. package/dist/types/types/api/auth.d.ts +0 -93
  23. package/dist/types/types/api/broker.d.ts +0 -421
  24. package/dist/types/types/api/core.d.ts +0 -46
  25. package/dist/types/types/api/errors.d.ts +0 -31
  26. package/dist/types/types/api/orders.d.ts +0 -39
  27. package/dist/types/types/api/portfolio.d.ts +0 -55
  28. package/dist/types/types/common/pagination.d.ts +0 -33
  29. package/dist/types/types/connect.d.ts +0 -58
  30. package/dist/types/types/index.d.ts +0 -13
  31. package/dist/types/types/portal.d.ts +0 -204
  32. package/dist/types/types/ui/theme.d.ts +0 -104
  33. package/dist/types/utils/brokerUtils.d.ts +0 -30
  34. package/dist/types/utils/errors.d.ts +0 -45
  35. package/dist/types/utils/events.d.ts +0 -12
  36. package/dist/types/utils/themeUtils.d.ts +0 -34
  37. package/src/core/client/ApiClient.ts +0 -2004
  38. package/src/core/client/FinaticConnect.ts +0 -1606
  39. package/src/core/portal/PortalUI.ts +0 -335
  40. package/src/index.d.ts +0 -23
  41. package/src/index.ts +0 -100
  42. package/src/lib/logger/index.ts +0 -3
  43. package/src/lib/logger/logger.ts +0 -332
  44. package/src/lib/logger/logger.types.ts +0 -34
  45. package/src/mocks/MockApiClient.ts +0 -1058
  46. package/src/mocks/MockDataProvider.ts +0 -986
  47. package/src/mocks/MockFactory.ts +0 -97
  48. package/src/mocks/utils.ts +0 -133
  49. package/src/themes/portalPresets.ts +0 -1307
  50. package/src/types/api/auth.ts +0 -112
  51. package/src/types/api/broker.ts +0 -461
  52. package/src/types/api/core.ts +0 -53
  53. package/src/types/api/errors.ts +0 -35
  54. package/src/types/api/orders.ts +0 -45
  55. package/src/types/api/portfolio.ts +0 -59
  56. package/src/types/common/pagination.ts +0 -164
  57. package/src/types/connect.ts +0 -56
  58. package/src/types/index.ts +0 -25
  59. package/src/types/portal.ts +0 -214
  60. package/src/types/ui/theme.ts +0 -105
  61. package/src/utils/brokerUtils.ts +0 -104
  62. package/src/utils/errors.ts +0 -104
  63. package/src/utils/events.ts +0 -66
  64. package/src/utils/themeUtils.ts +0 -165
@@ -1,332 +0,0 @@
1
- import { EventEmitter } from '../../utils/events';
2
- import { PaginatedResult } from '../../types/common/pagination';
3
- import { OrderResponse } from '../../types/api/orders';
4
- import { BrokerDataOptions, BrokerBalance, BrokerInfo, BrokerOrderParams, BrokerConnection, OrdersFilter, PositionsFilter, AccountsFilter, BalancesFilter, BrokerDataOrder, BrokerDataPosition, BrokerDataAccount, DisconnectCompanyResponse } from '../../types/api/broker';
5
- import { FinaticConnectOptions, PortalOptions } from '../../types/connect';
6
- interface DeviceInfo {
7
- ip_address: string;
8
- user_agent: string;
9
- fingerprint: string;
10
- }
11
- export declare class FinaticConnect extends EventEmitter {
12
- private static instance;
13
- private apiClient;
14
- private portalUI;
15
- private options;
16
- private userToken;
17
- private sessionId;
18
- private companyId;
19
- private baseUrl;
20
- private readonly BROKER_LIST_CACHE_KEY;
21
- private readonly BROKER_LIST_CACHE_VERSION;
22
- private readonly BROKER_LIST_CACHE_DURATION;
23
- private readonly deviceInfo?;
24
- private currentSessionState;
25
- private sessionKeepAliveInterval;
26
- private readonly SESSION_KEEP_ALIVE_INTERVAL;
27
- private readonly SESSION_VALIDATION_TIMEOUT;
28
- private readonly SESSION_REFRESH_BUFFER_HOURS;
29
- private sessionStartTime;
30
- private readonly logger;
31
- private buildLoggerExtra;
32
- constructor(options: FinaticConnectOptions, deviceInfo?: DeviceInfo);
33
- private linkUserToSession;
34
- /**
35
- * Store user ID for authentication state persistence
36
- * @param userId - The user ID to store
37
- */
38
- private storeUserId;
39
- /**
40
- * Check if the user is fully authenticated (has userId in session context)
41
- * @returns True if the user is fully authenticated and ready for API calls
42
- */
43
- isAuthenticated(): Promise<boolean>;
44
- /**
45
- * Get user's orders with pagination and optional filtering
46
- * @param params - Query parameters including page, perPage, and filters
47
- * @returns Promise with paginated result that supports navigation
48
- */
49
- getOrders(page?: number, perPage?: number, options?: BrokerDataOptions, filters?: OrdersFilter): Promise<PaginatedResult<BrokerDataOrder[]>>;
50
- /**
51
- * Get user's positions with pagination and optional filtering
52
- * @param params - Query parameters including page, perPage, and filters
53
- * @returns Promise with paginated result that supports navigation
54
- */
55
- getPositions(page?: number, perPage?: number, options?: BrokerDataOptions, filters?: PositionsFilter): Promise<PaginatedResult<BrokerDataPosition[]>>;
56
- /**
57
- * Get user's accounts with pagination and optional filtering
58
- * @param params - Query parameters including page, perPage, and filters
59
- * @returns Promise with paginated result that supports navigation
60
- */
61
- getAccounts(page?: number, perPage?: number, options?: BrokerDataOptions, filters?: AccountsFilter): Promise<PaginatedResult<BrokerDataAccount[]>>;
62
- /**
63
- * Get user's balances with pagination and optional filtering
64
- * @param params - Query parameters including page, perPage, and filters
65
- * @returns Promise with paginated result that supports navigation
66
- */
67
- getBalances(page?: number, perPage?: number, options?: BrokerDataOptions, filters?: BalancesFilter): Promise<PaginatedResult<BrokerBalance[]>>;
68
- /**
69
- * Initialize the Finatic Connect SDK
70
- * @param token - The portal token from your backend
71
- * @param userId - Optional: The user ID if you have it from a previous session
72
- * @param options - Optional configuration including baseUrl
73
- * @returns FinaticConnect instance
74
- */
75
- static init(token: string, userId?: string | null | undefined, options?: {
76
- baseUrl?: string;
77
- } | undefined): Promise<FinaticConnect>;
78
- /**
79
- * Initialize the SDK with a user ID
80
- * @param userId - The user ID from a previous session
81
- */
82
- setUserId(userId: string): Promise<void>;
83
- /**
84
- * Get the user and tokens for a completed session
85
- * @returns Promise with user information and tokens
86
- */
87
- private initializeWithUser;
88
- /**
89
- * Handle company access error by opening the portal
90
- * @param error The company access error
91
- * @param options Optional configuration for the portal
92
- */
93
- private handleCompanyAccessError;
94
- /**
95
- * Open the portal for user authentication
96
- * @param options Optional configuration for the portal
97
- */
98
- openPortal(options?: PortalOptions): Promise<void>;
99
- /**
100
- * Close the Finatic Connect Portal
101
- */
102
- closePortal(): void;
103
- /**
104
- * Initialize a new session
105
- * @param oneTimeToken - The one-time token from initSession
106
- */
107
- protected startSession(oneTimeToken: string): Promise<void>;
108
- /**
109
- * Place a new order using the broker order API
110
- * @param order - Order details with broker context
111
- */
112
- placeOrder(order: BrokerOrderParams, extras?: BrokerExtras): Promise<OrderResponse>;
113
- /**
114
- * Cancel a broker order
115
- * @param orderId - The order ID to cancel
116
- * @param broker - Optional broker override
117
- * @param connection_id - Optional connection ID for testing bypass
118
- */
119
- cancelOrder(orderId: string, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', connection_id?: string): Promise<OrderResponse>;
120
- /**
121
- * Modify a broker order
122
- * @param orderId - The order ID to modify
123
- * @param modifications - The modifications to apply
124
- * @param broker - Optional broker override
125
- * @param connection_id - Optional connection ID for testing bypass
126
- */
127
- modifyOrder(orderId: string, modifications: Partial<{
128
- symbol?: string;
129
- quantity?: number;
130
- price?: number;
131
- stopPrice?: number;
132
- timeInForce?: 'day' | 'gtc' | 'gtd' | 'ioc' | 'fok';
133
- orderType?: 'Market' | 'Limit' | 'Stop' | 'StopLimit';
134
- side?: 'Buy' | 'Sell';
135
- order_id?: string;
136
- }>, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', connection_id?: string): Promise<OrderResponse>;
137
- /**
138
- * Place a stock market order (convenience method)
139
- */
140
- placeStockMarketOrder(symbol: string, quantity: number, side: 'buy' | 'sell', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string): Promise<OrderResponse>;
141
- /**
142
- * Place a stock limit order (convenience method)
143
- */
144
- placeStockLimitOrder(symbol: string, quantity: number, side: 'buy' | 'sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string): Promise<OrderResponse>;
145
- /**
146
- * Place a stock stop order (convenience method)
147
- */
148
- placeStockStopOrder(symbol: string, quantity: number, side: 'buy' | 'sell', stopPrice: number, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string): Promise<OrderResponse>;
149
- /**
150
- * Place a crypto market order (convenience method)
151
- */
152
- placeCryptoMarketOrder(symbol: string, quantity: number, side: 'buy' | 'sell', broker?: 'coinbase' | 'binance' | 'kraken', accountNumber?: string): Promise<OrderResponse>;
153
- /**
154
- * Place a crypto limit order (convenience method)
155
- */
156
- placeCryptoLimitOrder(symbol: string, quantity: number, side: 'buy' | 'sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'coinbase' | 'binance' | 'kraken', accountNumber?: string): Promise<OrderResponse>;
157
- /**
158
- * Place an options market order (convenience method)
159
- */
160
- placeOptionsMarketOrder(symbol: string, quantity: number, side: 'buy' | 'sell', broker?: 'tasty_trade' | 'robinhood' | 'ninja_trader', accountNumber?: string): Promise<OrderResponse>;
161
- /**
162
- * Place an options limit order (convenience method)
163
- */
164
- placeOptionsLimitOrder(symbol: string, quantity: number, side: 'buy' | 'sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'tasty_trade' | 'robinhood' | 'ninja_trader', accountNumber?: string): Promise<OrderResponse>;
165
- /**
166
- * Place a futures market order (convenience method)
167
- */
168
- placeFuturesMarketOrder(symbol: string, quantity: number, side: 'buy' | 'sell', broker?: 'ninja_trader' | 'tasty_trade', accountNumber?: string): Promise<OrderResponse>;
169
- /**
170
- * Place a futures limit order (convenience method)
171
- */
172
- placeFuturesLimitOrder(symbol: string, quantity: number, side: 'buy' | 'sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'ninja_trader' | 'tasty_trade', accountNumber?: string): Promise<OrderResponse>;
173
- /**
174
- * Get the current user ID
175
- * @returns The current user ID or undefined if not authenticated
176
- * @throws AuthenticationError if user is not authenticated
177
- */
178
- getUserId(): Promise<string | null>;
179
- /**
180
- * Get list of supported brokers
181
- * @returns Promise with array of broker information
182
- */
183
- getBrokerList(): Promise<BrokerInfo[]>;
184
- /**
185
- * Get broker connections
186
- * @returns Promise with array of broker connections
187
- * @throws AuthenticationError if user is not authenticated
188
- */
189
- getBrokerConnections(): Promise<BrokerConnection[]>;
190
- /**
191
- * Get only open positions
192
- * @returns Promise with array of open positions
193
- */
194
- getOpenPositions(): Promise<BrokerDataPosition[]>;
195
- /**
196
- * Get only filled orders
197
- * @returns Promise with array of filled orders
198
- */
199
- getFilledOrders(): Promise<BrokerDataOrder[]>;
200
- /**
201
- * Get only pending orders
202
- * @returns Promise with array of pending orders
203
- */
204
- getPendingOrders(): Promise<BrokerDataOrder[]>;
205
- /**
206
- * Get only active accounts
207
- * @returns Promise with array of active accounts
208
- */
209
- getActiveAccounts(): Promise<BrokerDataAccount[]>;
210
- /**
211
- * Get orders for a specific symbol
212
- * @param symbol - The symbol to filter by
213
- * @returns Promise with array of orders for the symbol
214
- */
215
- getOrdersBySymbol(symbol: string): Promise<BrokerDataOrder[]>;
216
- /**
217
- * Get positions for a specific symbol
218
- * @param symbol - The symbol to filter by
219
- * @returns Promise with array of positions for the symbol
220
- */
221
- getPositionsBySymbol(symbol: string): Promise<BrokerDataPosition[]>;
222
- /**
223
- * Get orders for a specific broker
224
- * @param brokerId - The broker ID to filter by
225
- * @returns Promise with array of orders for the broker
226
- */
227
- getOrdersByBroker(brokerId: string): Promise<BrokerDataOrder[]>;
228
- /**
229
- * Get positions for a specific broker
230
- * @param brokerId - The broker ID to filter by
231
- * @returns Promise with array of positions for the broker
232
- */
233
- getPositionsByBroker(brokerId: string): Promise<BrokerDataPosition[]>;
234
- /**
235
- * Get all orders across all pages (convenience method)
236
- * @param filter - Optional filter parameters
237
- * @returns Promise with all orders
238
- */
239
- getAllOrders(filter?: OrdersFilter): Promise<BrokerDataOrder[]>;
240
- /**
241
- * Get all positions across all pages (convenience method)
242
- * @param filter - Optional filter parameters
243
- * @returns Promise with all positions
244
- */
245
- getAllPositions(filter?: PositionsFilter): Promise<BrokerDataPosition[]>;
246
- /**
247
- * Get all accounts across all pages (convenience method)
248
- * @param filter - Optional filter parameters
249
- * @returns Promise with all accounts
250
- */
251
- getAllAccounts(filter?: AccountsFilter): Promise<BrokerDataAccount[]>;
252
- getAllBalances(filter?: BalancesFilter): Promise<BrokerBalance[]>;
253
- /**
254
- * Register session management (but don't auto-cleanup for 24-hour sessions)
255
- */
256
- private registerSessionCleanup;
257
- /**
258
- * Start the session keep-alive mechanism
259
- */
260
- private startSessionKeepAlive;
261
- /**
262
- * Stop the session keep-alive mechanism
263
- */
264
- private stopSessionKeepAlive;
265
- /**
266
- * Validate session for keep-alive purposes and handle automatic refresh
267
- */
268
- private validateSessionKeepAlive;
269
- /**
270
- * Check if the session should be refreshed (after 16 hours)
271
- */
272
- private shouldRefreshSession;
273
- /**
274
- * Automatically refresh the session to extend its lifetime
275
- */
276
- private refreshSessionAutomatically;
277
- /**
278
- * Handle session cleanup when page is unloading
279
- */
280
- private handleSessionCleanup;
281
- /**
282
- * Handle visibility change (mobile browsers)
283
- * Note: We don't complete sessions on visibility change for 24-hour sessions
284
- */
285
- private handleVisibilityChange;
286
- /**
287
- * Complete the session by calling the API
288
- * @param sessionId - The session ID to complete
289
- */
290
- private completeSession;
291
- /**
292
- * Disconnect a company from a broker connection
293
- * @param connectionId - The connection ID to disconnect
294
- * @returns Promise with disconnect response
295
- * @throws AuthenticationError if user is not authenticated
296
- */
297
- disconnectCompany(connectionId: string): Promise<DisconnectCompanyResponse>;
298
- /**
299
- * Get order fills for a specific order
300
- * @param orderId - The order ID
301
- * @param filter - Optional filter parameters
302
- * @returns Promise with order fills response
303
- */
304
- getOrderFills(orderId: string, filter?: import('../../types/api/broker').OrderFillsFilter): Promise<import('../../types/api/broker').OrderFill[]>;
305
- /**
306
- * Get order events for a specific order
307
- * @param orderId - The order ID
308
- * @param filter - Optional filter parameters
309
- * @returns Promise with order events response
310
- */
311
- getOrderEvents(orderId: string, filter?: import('../../types/api/broker').OrderEventsFilter): Promise<import('../../types/api/broker').OrderEvent[]>;
312
- /**
313
- * Get order groups
314
- * @param filter - Optional filter parameters
315
- * @returns Promise with order groups response
316
- */
317
- getOrderGroups(filter?: import('../../types/api/broker').OrderGroupsFilter): Promise<import('../../types/api/broker').OrderGroup[]>;
318
- /**
319
- * Get position lots (tax lots for positions)
320
- * @param filter - Optional filter parameters
321
- * @returns Promise with position lots response
322
- */
323
- getPositionLots(filter?: import('../../types/api/broker').PositionLotsFilter): Promise<import('../../types/api/broker').PositionLot[]>;
324
- /**
325
- * Get position lot fills for a specific lot
326
- * @param lotId - The position lot ID
327
- * @param filter - Optional filter parameters
328
- * @returns Promise with position lot fills response
329
- */
330
- getPositionLotFills(lotId: string, filter?: import('../../types/api/broker').PositionLotFillsFilter): Promise<import('../../types/api/broker').PositionLotFill[]>;
331
- }
332
- export {};
@@ -1,37 +0,0 @@
1
- export declare class PortalUI {
2
- private iframe;
3
- private container;
4
- private messageHandler;
5
- private sessionId;
6
- private portalOrigin;
7
- private options?;
8
- private originalBodyStyle;
9
- private readonly logger;
10
- constructor(portalUrl: string);
11
- private buildLoggerExtra;
12
- private createContainer;
13
- /**
14
- * Lock background scrolling by setting overflow: hidden on body
15
- */
16
- private lockScroll;
17
- /**
18
- * Unlock background scrolling by restoring original body style
19
- */
20
- private unlockScroll;
21
- show(url: string, sessionId: string, options?: {
22
- onSuccess?: (userId: string) => void;
23
- onError?: (error: Error) => void;
24
- onClose?: () => void;
25
- onEvent?: (type: string, data: any) => void;
26
- }): void;
27
- hide(): void;
28
- private handleMessage;
29
- private handlePortalSuccess;
30
- private handlePortalError;
31
- private handlePortalClose;
32
- private handleGenericEvent;
33
- private handleSuccess;
34
- private handleError;
35
- private handleClose;
36
- private handleResize;
37
- }
@@ -1,12 +0,0 @@
1
- export type { ApiConfig, ApiResponse, Order, OptionsOrder, BrokerAccount, PortfolioSnapshot, PerformanceMetrics, UserToken, Holding, Portfolio, PortalResponse, SessionInitResponse, SessionResponse, OtpRequestResponse, OtpVerifyResponse, PortalUrlResponse, SessionValidationResponse, SessionAuthenticateResponse, RequestHeaders, SessionStatus, BrokerOrderParams, BrokerExtras, CryptoOrderOptions, OptionsOrderOptions, OrderResponse, TradingContext, DeviceInfo, BrokerOrder, BrokerPosition, BrokerBalance, BrokerDataOptions, BrokerInfo, TokenInfo, RefreshTokenRequest, RefreshTokenResponse, AccountsFilter, OrdersFilter, PositionsFilter, BalancesFilter, BrokerDataOrder, BrokerDataPosition, BrokerDataAccount, FilteredOrdersResponse, FilteredPositionsResponse, FilteredAccountsResponse, FilteredBalancesResponse, BrokerConnection, OrderFill, OrderEvent, OrderLeg, OrderGroup, OrderGroupOrder, PositionLot, PositionLotFill, OrderFillsFilter, OrderEventsFilter, OrderGroupsFilter, PositionLotsFilter, PositionLotFillsFilter, } from './types';
2
- export type { FinaticConnectOptions, FinaticUserToken, PortalMessage } from './types/connect';
3
- export type { PortalProps, PortalTheme, PortalThemeConfig, PortalThemePreset, } from './types/portal';
4
- export type { TradeAccessDeniedError, OrderNotFoundError, ValidationError, } from './types/api/errors';
5
- export { ApiClient } from './core/client/ApiClient';
6
- export { FinaticConnect } from './core/client/FinaticConnect';
7
- export { PaginatedResult } from './types/common/pagination';
8
- export * from './utils/errors';
9
- export * from './utils/events';
10
- export * from './utils/themeUtils';
11
- export * from './lib/logger';
12
- export { portalThemePresets } from './themes/portalPresets';
@@ -1,2 +0,0 @@
1
- export * from './logger';
2
- export * from './logger.types';
@@ -1,4 +0,0 @@
1
- import { Logger, LoggerExtra, LoggerMetadata, LoggerOptions, LogLevel } from './logger.types';
2
- export declare const setupLogger: (nameOrOptions: string | LoggerOptions, level?: LogLevel, defaultMetadata?: LoggerMetadata) => Logger;
3
- export declare const buildLoggerExtra: (metadata: LoggerMetadata) => LoggerExtra;
4
- export declare const logStartEnd: (logger: Logger) => <Args extends unknown[], ReturnType>(fn: (...args: Args) => ReturnType | Promise<ReturnType>) => (...args: Args) => Promise<ReturnType>;
@@ -1,28 +0,0 @@
1
- export type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
2
- export interface LoggerMetadata {
3
- [key: string]: unknown;
4
- }
5
- export interface LoggerExtra {
6
- metadata?: LoggerMetadata;
7
- module?: string;
8
- function?: string;
9
- event?: string;
10
- duration_ms?: number;
11
- error?: unknown;
12
- [key: string]: unknown;
13
- }
14
- export interface LoggerOptions {
15
- name: string;
16
- level?: LogLevel;
17
- defaultMetadata?: LoggerMetadata;
18
- }
19
- export interface Logger {
20
- getLevel: () => LogLevel;
21
- setLevel: (level: LogLevel) => void;
22
- debug: (message: string, extra?: LoggerExtra) => void;
23
- info: (message: string, extra?: LoggerExtra) => void;
24
- warn: (message: string, extra?: LoggerExtra) => void;
25
- error: (message: string, extra?: LoggerExtra) => void;
26
- exception: (message: string, error: unknown, extra?: LoggerExtra) => void;
27
- }
28
- export type LogVerbosity = 0 | 1 | 2 | 3;
@@ -1,171 +0,0 @@
1
- import { SessionResponse, OtpRequestResponse, OtpVerifyResponse, PortalUrlResponse, SessionValidationResponse, SessionAuthenticateResponse, UserToken, Order, BrokerInfo, BrokerAccount, BrokerOrder, BrokerPosition, BrokerBalance, BrokerConnection, BrokerDataOptions, BrokerOrderParams, BrokerExtras, CryptoOrderOptions, OptionsOrderOptions, OrderResponse, OrdersFilter, PositionsFilter, AccountsFilter, BalancesFilter, BrokerDataOrder, BrokerDataPosition, DisconnectCompanyResponse } from '../types';
2
- import { PaginatedResult } from '../types';
3
- import { DeviceInfo, SessionState, TokenInfo } from '../types/api/auth';
4
- import { MockDataProvider, MockConfig } from './MockDataProvider';
5
- /**
6
- * Mock API Client that implements the same interface as the real ApiClient
7
- * but returns mock data instead of making HTTP requests
8
- */
9
- export declare class MockApiClient {
10
- private readonly baseUrl;
11
- protected readonly deviceInfo?: DeviceInfo;
12
- protected currentSessionState: SessionState | null;
13
- protected currentSessionId: string | null;
14
- private tradingContext;
15
- private tokenInfo;
16
- private refreshPromise;
17
- private readonly REFRESH_BUFFER_MINUTES;
18
- private companyId;
19
- private csrfToken;
20
- private mockDataProvider;
21
- private readonly mockApiOnly;
22
- private readonly logger;
23
- private buildLoggerExtra;
24
- constructor(baseUrl: string, deviceInfo?: DeviceInfo, mockConfig?: MockConfig);
25
- /**
26
- * Store tokens after successful authentication
27
- */
28
- setTokens(accessToken: string, refreshToken: string, expiresAt: string, userId?: string): void;
29
- /**
30
- * Get the current access token, refreshing if necessary
31
- */
32
- getValidAccessToken(): Promise<string>;
33
- /**
34
- * Check if the current token is expired or about to expire
35
- */
36
- private isTokenExpired;
37
- /**
38
- * Refresh the access token using the refresh token
39
- */
40
- private refreshTokens;
41
- /**
42
- * Perform the actual token refresh request
43
- */
44
- private performTokenRefresh;
45
- /**
46
- * Clear stored tokens (useful for logout)
47
- */
48
- clearTokens(): void;
49
- /**
50
- * Get current token info (for debugging/testing)
51
- */
52
- getTokenInfo(): TokenInfo | null;
53
- /**
54
- * Set session context (session ID, company ID, CSRF token)
55
- */
56
- setSessionContext(sessionId: string, companyId: string, csrfToken?: string): void;
57
- /**
58
- * Get the current session ID
59
- */
60
- getCurrentSessionId(): string | null;
61
- /**
62
- * Get the current company ID
63
- */
64
- getCurrentCompanyId(): string | null;
65
- /**
66
- * Get the current CSRF token
67
- */
68
- getCurrentCsrfToken(): string | null;
69
- startSession(token: string, userId?: string): Promise<SessionResponse>;
70
- requestOtp(sessionId: string, email: string): Promise<OtpRequestResponse>;
71
- verifyOtp(sessionId: string, otp: string): Promise<OtpVerifyResponse>;
72
- authenticateDirectly(sessionId: string, userId: string): Promise<SessionAuthenticateResponse>;
73
- getPortalUrl(sessionId: string): Promise<PortalUrlResponse>;
74
- validatePortalSession(sessionId: string, signature: string): Promise<SessionValidationResponse>;
75
- completePortalSession(sessionId: string): Promise<PortalUrlResponse>;
76
- getOrders(filter?: OrdersFilter): Promise<{
77
- data: Order[];
78
- }>;
79
- placeOrder(order: BrokerOrderParams): Promise<void>;
80
- placeBrokerOrder(params: Partial<BrokerOrderParams> & {
81
- symbol: string;
82
- orderQty: number;
83
- action: 'Buy' | 'Sell';
84
- orderType: 'Market' | 'Limit' | 'Stop' | 'StopLimit';
85
- assetType: 'equity' | 'equity_option' | 'crypto' | 'forex' | 'future' | 'future_option';
86
- }, extras?: BrokerExtras, connection_id?: string): Promise<OrderResponse>;
87
- cancelBrokerOrder(orderId: string, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', extras?: any, connection_id?: string): Promise<OrderResponse>;
88
- modifyBrokerOrder(orderId: string, params: Partial<BrokerOrderParams>, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', extras?: any, connection_id?: string): Promise<OrderResponse>;
89
- setBroker(broker: 'robinhood' | 'tasty_trade' | 'ninja_trader'): void;
90
- setAccount(accountNumber: string, accountId?: string): void;
91
- placeStockMarketOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
92
- placeStockLimitOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
93
- placeStockStopOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', stopPrice: number, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
94
- placeCryptoMarketOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', options?: CryptoOrderOptions, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
95
- placeCryptoLimitOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', price: number, timeInForce?: 'day' | 'gtc', options?: CryptoOrderOptions, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
96
- placeOptionsMarketOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', options: OptionsOrderOptions, broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
97
- placeOptionsLimitOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', price: number, options: OptionsOrderOptions, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
98
- placeFuturesMarketOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
99
- placeFuturesLimitOrder(symbol: string, orderQty: number, action: 'Buy' | 'Sell', price: number, timeInForce?: 'day' | 'gtc', broker?: 'robinhood' | 'tasty_trade' | 'ninja_trader', accountNumber?: string, extras?: BrokerExtras): Promise<OrderResponse>;
100
- getUserToken(sessionId: string): Promise<UserToken>;
101
- getCurrentSessionState(): SessionState | null;
102
- getBrokerList(): Promise<{
103
- _id: string;
104
- response_data: BrokerInfo[];
105
- message: string;
106
- status_code: number;
107
- warnings: null;
108
- errors: null;
109
- }>;
110
- getBrokerAccounts(options?: BrokerDataOptions): Promise<{
111
- _id: string;
112
- response_data: BrokerAccount[];
113
- message: string;
114
- status_code: number;
115
- warnings: null;
116
- errors: null;
117
- }>;
118
- getBrokerOrders(options?: BrokerDataOptions): Promise<{
119
- _id: string;
120
- response_data: BrokerOrder[];
121
- message: string;
122
- status_code: number;
123
- warnings: null;
124
- errors: null;
125
- }>;
126
- getBrokerPositions(options?: BrokerDataOptions): Promise<{
127
- _id: string;
128
- response_data: BrokerPosition[];
129
- message: string;
130
- status_code: number;
131
- warnings: null;
132
- errors: null;
133
- }>;
134
- getBrokerOrdersWithFilter(filter?: OrdersFilter): Promise<{
135
- data: BrokerDataOrder[];
136
- }>;
137
- getBrokerPositionsWithFilter(filter?: PositionsFilter): Promise<{
138
- data: BrokerDataPosition[];
139
- }>;
140
- getBrokerBalancesWithFilter(filter?: BalancesFilter): Promise<{
141
- data: BrokerBalance[];
142
- }>;
143
- getBrokerDataAccountsWithFilter(filter?: AccountsFilter): Promise<{
144
- data: BrokerAccount[];
145
- }>;
146
- getBrokerOrdersPage(page?: number, perPage?: number, filters?: OrdersFilter): Promise<PaginatedResult<BrokerDataOrder[]>>;
147
- getBrokerAccountsPage(page?: number, perPage?: number, filters?: AccountsFilter): Promise<PaginatedResult<BrokerAccount[]>>;
148
- getBrokerPositionsPage(page?: number, perPage?: number, filters?: PositionsFilter): Promise<PaginatedResult<BrokerDataPosition[]>>;
149
- getBrokerBalancesPage(page?: number, perPage?: number, filters?: BalancesFilter): Promise<PaginatedResult<BrokerBalance[]>>;
150
- getBrokerConnections(): Promise<{
151
- _id: string;
152
- response_data: BrokerConnection[];
153
- message: string;
154
- status_code: number;
155
- warnings: null;
156
- errors: null;
157
- }>;
158
- /**
159
- * Mock disconnect company method
160
- * @param connectionId - The connection ID to disconnect
161
- * @returns Promise with mock disconnect response
162
- */
163
- disconnectCompany(connectionId: string): Promise<DisconnectCompanyResponse>;
164
- getMockDataProvider(): MockDataProvider;
165
- clearMockData(): void;
166
- /**
167
- * Check if this is a mock client
168
- * @returns true if this is a mock client
169
- */
170
- isMockClient(): boolean;
171
- }