@adaptic/utils 0.0.383 → 0.1.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 (75) hide show
  1. package/dist/index.cjs +48504 -341
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +48321 -341
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/types/alpaca/client.d.ts +95 -0
  6. package/dist/types/alpaca/client.d.ts.map +1 -0
  7. package/dist/types/alpaca/crypto/data.d.ts +281 -0
  8. package/dist/types/alpaca/crypto/data.d.ts.map +1 -0
  9. package/dist/types/alpaca/crypto/index.d.ts +75 -0
  10. package/dist/types/alpaca/crypto/index.d.ts.map +1 -0
  11. package/dist/types/alpaca/crypto/orders.d.ts +221 -0
  12. package/dist/types/alpaca/crypto/orders.d.ts.map +1 -0
  13. package/dist/types/alpaca/index.d.ts +201 -0
  14. package/dist/types/alpaca/index.d.ts.map +1 -0
  15. package/dist/types/alpaca/market-data/bars.d.ts +142 -0
  16. package/dist/types/alpaca/market-data/bars.d.ts.map +1 -0
  17. package/dist/types/alpaca/market-data/index.d.ts +13 -0
  18. package/dist/types/alpaca/market-data/index.d.ts.map +1 -0
  19. package/dist/types/alpaca/market-data/news.d.ts +87 -0
  20. package/dist/types/alpaca/market-data/news.d.ts.map +1 -0
  21. package/dist/types/alpaca/market-data/quotes.d.ts +85 -0
  22. package/dist/types/alpaca/market-data/quotes.d.ts.map +1 -0
  23. package/dist/types/alpaca/market-data/trades.d.ts +98 -0
  24. package/dist/types/alpaca/market-data/trades.d.ts.map +1 -0
  25. package/dist/types/alpaca/options/contracts.d.ts +279 -0
  26. package/dist/types/alpaca/options/contracts.d.ts.map +1 -0
  27. package/dist/types/alpaca/options/data.d.ts +126 -0
  28. package/dist/types/alpaca/options/data.d.ts.map +1 -0
  29. package/dist/types/alpaca/options/index.d.ts +17 -0
  30. package/dist/types/alpaca/options/index.d.ts.map +1 -0
  31. package/dist/types/alpaca/options/orders.d.ts +366 -0
  32. package/dist/types/alpaca/options/orders.d.ts.map +1 -0
  33. package/dist/types/alpaca/options/strategies.d.ts +224 -0
  34. package/dist/types/alpaca/options/strategies.d.ts.map +1 -0
  35. package/dist/types/alpaca/streams/base-stream.d.ts +143 -0
  36. package/dist/types/alpaca/streams/base-stream.d.ts.map +1 -0
  37. package/dist/types/alpaca/streams/crypto-stream.d.ts +173 -0
  38. package/dist/types/alpaca/streams/crypto-stream.d.ts.map +1 -0
  39. package/dist/types/alpaca/streams/index.d.ts +54 -0
  40. package/dist/types/alpaca/streams/index.d.ts.map +1 -0
  41. package/dist/types/alpaca/streams/option-stream.d.ts +167 -0
  42. package/dist/types/alpaca/streams/option-stream.d.ts.map +1 -0
  43. package/dist/types/alpaca/streams/stock-stream.d.ts +176 -0
  44. package/dist/types/alpaca/streams/stock-stream.d.ts.map +1 -0
  45. package/dist/types/alpaca/streams/stream-manager.d.ts +277 -0
  46. package/dist/types/alpaca/streams/stream-manager.d.ts.map +1 -0
  47. package/dist/types/alpaca/streams/trading-stream.d.ts +186 -0
  48. package/dist/types/alpaca/streams/trading-stream.d.ts.map +1 -0
  49. package/dist/types/alpaca/streams.d.ts +88 -0
  50. package/dist/types/alpaca/streams.d.ts.map +1 -0
  51. package/dist/types/alpaca/test-imports.d.ts +7 -0
  52. package/dist/types/alpaca/test-imports.d.ts.map +1 -0
  53. package/dist/types/alpaca/trading/account.d.ts +198 -0
  54. package/dist/types/alpaca/trading/account.d.ts.map +1 -0
  55. package/dist/types/alpaca/trading/bracket-orders.d.ts +162 -0
  56. package/dist/types/alpaca/trading/bracket-orders.d.ts.map +1 -0
  57. package/dist/types/alpaca/trading/index.d.ts +13 -0
  58. package/dist/types/alpaca/trading/index.d.ts.map +1 -0
  59. package/dist/types/alpaca/trading/oco-orders.d.ts +203 -0
  60. package/dist/types/alpaca/trading/oco-orders.d.ts.map +1 -0
  61. package/dist/types/alpaca/trading/order-utils.d.ts +404 -0
  62. package/dist/types/alpaca/trading/order-utils.d.ts.map +1 -0
  63. package/dist/types/alpaca/trading/orders.d.ts +199 -0
  64. package/dist/types/alpaca/trading/orders.d.ts.map +1 -0
  65. package/dist/types/alpaca/trading/oto-orders.d.ts +282 -0
  66. package/dist/types/alpaca/trading/oto-orders.d.ts.map +1 -0
  67. package/dist/types/alpaca/trading/positions.d.ts +389 -0
  68. package/dist/types/alpaca/trading/positions.d.ts.map +1 -0
  69. package/dist/types/alpaca/trading/smart-orders.d.ts +301 -0
  70. package/dist/types/alpaca/trading/smart-orders.d.ts.map +1 -0
  71. package/dist/types/alpaca/trading/trailing-stops.d.ts +240 -0
  72. package/dist/types/alpaca/trading/trailing-stops.d.ts.map +1 -0
  73. package/dist/types/index.d.ts +353 -6
  74. package/dist/types/index.d.ts.map +1 -1
  75. package/package.json +4 -4
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Position Management Module
3
+ * Handles all position-related operations using Alpaca SDK
4
+ */
5
+ import { AlpacaClient } from '../client';
6
+ import { AlpacaPosition, AssetClass, AlpacaOrder } from '../../types/alpaca-types';
7
+ /**
8
+ * P&L summary for a single position
9
+ */
10
+ export interface PositionPnLSummary {
11
+ /** Trading symbol */
12
+ symbol: string;
13
+ /** Number of shares/contracts held */
14
+ qty: number;
15
+ /** Average entry price per share */
16
+ avgEntryPrice: number;
17
+ /** Current market price per share */
18
+ currentPrice: number;
19
+ /** Total market value of the position */
20
+ marketValue: number;
21
+ /** Total cost basis of the position */
22
+ costBasis: number;
23
+ /** Unrealized profit/loss in dollars */
24
+ unrealizedPL: number;
25
+ /** Unrealized profit/loss as a percentage */
26
+ unrealizedPLPercent: number;
27
+ /** Today's profit/loss in dollars */
28
+ todayPL: number;
29
+ /** Today's profit/loss as a percentage */
30
+ todayPLPercent: number;
31
+ }
32
+ /**
33
+ * P&L summary for the entire portfolio
34
+ */
35
+ export interface PortfolioPnLSummary {
36
+ /** Total market value of all positions */
37
+ totalMarketValue: number;
38
+ /** Total cost basis of all positions */
39
+ totalCostBasis: number;
40
+ /** Total unrealized profit/loss in dollars */
41
+ totalUnrealizedPL: number;
42
+ /** Total unrealized profit/loss as a percentage */
43
+ totalUnrealizedPLPercent: number;
44
+ /** Today's total profit/loss in dollars */
45
+ todayPL: number;
46
+ /** Today's total profit/loss as a percentage */
47
+ todayPLPercent: number;
48
+ /** Individual position summaries */
49
+ positions: PositionPnLSummary[];
50
+ }
51
+ /**
52
+ * Options for closing a single position
53
+ */
54
+ export interface ClosePositionOptions {
55
+ /** Percentage of position to close (0-100) */
56
+ percentage?: number;
57
+ /** Specific quantity to close */
58
+ qty?: number;
59
+ }
60
+ /**
61
+ * Options for closing all positions
62
+ */
63
+ export interface CloseAllPositionsOptions {
64
+ /** Whether to cancel open orders first */
65
+ cancelOrders?: boolean;
66
+ }
67
+ /**
68
+ * Options for closing positions during after-hours
69
+ */
70
+ export interface ClosePositionsAfterHoursOptions {
71
+ /** Percentage offset from current price for limit orders (default: 0.5) */
72
+ limitPriceOffset?: number;
73
+ }
74
+ /**
75
+ * Get all open positions for the account
76
+ *
77
+ * @param client - The Alpaca client instance
78
+ * @returns Array of all open positions
79
+ *
80
+ * @example
81
+ * const client = createAlpacaClient(config);
82
+ * const positions = await getPositions(client);
83
+ * console.log(`Found ${positions.length} open positions`);
84
+ */
85
+ export declare function getPositions(client: AlpacaClient): Promise<AlpacaPosition[]>;
86
+ /**
87
+ * Get positions filtered by asset class
88
+ *
89
+ * @param client - The Alpaca client instance
90
+ * @param assetClass - The asset class to filter by ('us_equity', 'us_option', 'crypto')
91
+ * @returns Array of positions matching the asset class
92
+ *
93
+ * @example
94
+ * const equityPositions = await getPositionsByAssetClass(client, 'us_equity');
95
+ * const optionPositions = await getPositionsByAssetClass(client, 'us_option');
96
+ */
97
+ export declare function getPositionsByAssetClass(client: AlpacaClient, assetClass: AssetClass): Promise<AlpacaPosition[]>;
98
+ /**
99
+ * Get a specific position by symbol
100
+ *
101
+ * @param client - The Alpaca client instance
102
+ * @param symbol - The trading symbol to look up
103
+ * @returns The position if found, null otherwise
104
+ *
105
+ * @example
106
+ * const applePosition = await getPosition(client, 'AAPL');
107
+ * if (applePosition) {
108
+ * console.log(`Holding ${applePosition.qty} shares of AAPL`);
109
+ * }
110
+ */
111
+ export declare function getPosition(client: AlpacaClient, symbol: string): Promise<AlpacaPosition | null>;
112
+ /**
113
+ * Check if a position exists for a given symbol
114
+ *
115
+ * @param client - The Alpaca client instance
116
+ * @param symbol - The trading symbol to check
117
+ * @returns True if a position exists, false otherwise
118
+ *
119
+ * @example
120
+ * if (await hasPosition(client, 'AAPL')) {
121
+ * console.log('Already have AAPL position');
122
+ * }
123
+ */
124
+ export declare function hasPosition(client: AlpacaClient, symbol: string): Promise<boolean>;
125
+ /**
126
+ * Get the quantity of shares held for a symbol
127
+ *
128
+ * @param client - The Alpaca client instance
129
+ * @param symbol - The trading symbol
130
+ * @returns The quantity held (positive for long, negative for short), 0 if no position
131
+ *
132
+ * @example
133
+ * const qty = await getPositionQty(client, 'AAPL');
134
+ * console.log(`Holding ${qty} shares of AAPL`);
135
+ */
136
+ export declare function getPositionQty(client: AlpacaClient, symbol: string): Promise<number>;
137
+ /**
138
+ * Get the market value of a position
139
+ *
140
+ * @param client - The Alpaca client instance
141
+ * @param symbol - The trading symbol
142
+ * @returns The market value in dollars, 0 if no position
143
+ *
144
+ * @example
145
+ * const value = await getPositionValue(client, 'AAPL');
146
+ * console.log(`AAPL position worth $${value.toFixed(2)}`);
147
+ */
148
+ export declare function getPositionValue(client: AlpacaClient, symbol: string): Promise<number>;
149
+ /**
150
+ * Get the side of a position (long or short)
151
+ *
152
+ * @param client - The Alpaca client instance
153
+ * @param symbol - The trading symbol
154
+ * @returns 'long', 'short', or null if no position
155
+ *
156
+ * @example
157
+ * const side = await getPositionSide(client, 'AAPL');
158
+ * if (side === 'long') {
159
+ * console.log('Long position in AAPL');
160
+ * }
161
+ */
162
+ export declare function getPositionSide(client: AlpacaClient, symbol: string): Promise<'long' | 'short' | null>;
163
+ /**
164
+ * Close a specific position
165
+ *
166
+ * @param client - The Alpaca client instance
167
+ * @param symbol - The trading symbol to close
168
+ * @param options - Optional parameters for partial closes
169
+ * @returns The resulting close order
170
+ * @throws Error if no position exists or close fails
171
+ *
172
+ * @example
173
+ * // Close entire position
174
+ * const order = await closePosition(client, 'AAPL');
175
+ *
176
+ * // Close 50% of position
177
+ * const order = await closePosition(client, 'AAPL', { percentage: 50 });
178
+ *
179
+ * // Close specific quantity
180
+ * const order = await closePosition(client, 'AAPL', { qty: 10 });
181
+ */
182
+ export declare function closePosition(client: AlpacaClient, symbol: string, options?: ClosePositionOptions): Promise<AlpacaOrder>;
183
+ /**
184
+ * Close all open positions
185
+ *
186
+ * @param client - The Alpaca client instance
187
+ * @param options - Optional parameters
188
+ * @returns Array of close orders
189
+ *
190
+ * @example
191
+ * // Close all positions and cancel orders
192
+ * const orders = await closeAllPositions(client, { cancelOrders: true });
193
+ *
194
+ * // Close all positions without canceling orders
195
+ * const orders = await closeAllPositions(client, { cancelOrders: false });
196
+ */
197
+ export declare function closeAllPositions(client: AlpacaClient, options?: CloseAllPositionsOptions): Promise<AlpacaOrder[]>;
198
+ /**
199
+ * Close all positions with limit orders (for after-hours trading)
200
+ * Sets limit price slightly below current price for sells, above for buys
201
+ *
202
+ * @param client - The Alpaca client instance
203
+ * @param options - Optional parameters
204
+ * @returns Array of limit orders created
205
+ *
206
+ * @example
207
+ * // Close positions after hours with 0.5% price offset
208
+ * const orders = await closeAllPositionsAfterHours(client, { limitPriceOffset: 0.5 });
209
+ */
210
+ export declare function closeAllPositionsAfterHours(client: AlpacaClient, options?: ClosePositionsAfterHoursOptions): Promise<AlpacaOrder[]>;
211
+ /**
212
+ * Get P&L summary for a specific position
213
+ *
214
+ * @param client - The Alpaca client instance
215
+ * @param symbol - The trading symbol
216
+ * @returns P&L summary for the position, null if no position exists
217
+ *
218
+ * @example
219
+ * const pnl = await getPositionPnL(client, 'AAPL');
220
+ * if (pnl) {
221
+ * console.log(`AAPL unrealized P&L: $${pnl.unrealizedPL.toFixed(2)} (${pnl.unrealizedPLPercent.toFixed(2)}%)`);
222
+ * }
223
+ */
224
+ export declare function getPositionPnL(client: AlpacaClient, symbol: string): Promise<PositionPnLSummary | null>;
225
+ /**
226
+ * Get total portfolio P&L summary
227
+ *
228
+ * @param client - The Alpaca client instance
229
+ * @returns Portfolio-level P&L summary including all positions
230
+ *
231
+ * @example
232
+ * const portfolio = await getPortfolioPnL(client);
233
+ * console.log(`Total unrealized P&L: $${portfolio.totalUnrealizedPL.toFixed(2)}`);
234
+ * console.log(`Today's P&L: $${portfolio.todayPL.toFixed(2)}`);
235
+ */
236
+ export declare function getPortfolioPnL(client: AlpacaClient): Promise<PortfolioPnLSummary>;
237
+ /**
238
+ * Get all equity positions (us_equity asset class)
239
+ *
240
+ * @param client - The Alpaca client instance
241
+ * @returns Array of equity positions
242
+ *
243
+ * @example
244
+ * const equities = await getEquityPositions(client);
245
+ */
246
+ export declare function getEquityPositions(client: AlpacaClient): Promise<AlpacaPosition[]>;
247
+ /**
248
+ * Get all option positions (us_option asset class)
249
+ *
250
+ * @param client - The Alpaca client instance
251
+ * @returns Array of option positions
252
+ *
253
+ * @example
254
+ * const options = await getOptionPositions(client);
255
+ */
256
+ export declare function getOptionPositions(client: AlpacaClient): Promise<AlpacaPosition[]>;
257
+ /**
258
+ * Get all crypto positions
259
+ *
260
+ * @param client - The Alpaca client instance
261
+ * @returns Array of crypto positions
262
+ *
263
+ * @example
264
+ * const crypto = await getCryptoPositions(client);
265
+ */
266
+ export declare function getCryptoPositions(client: AlpacaClient): Promise<AlpacaPosition[]>;
267
+ /**
268
+ * Get count of open positions
269
+ *
270
+ * @param client - The Alpaca client instance
271
+ * @param assetClass - Optional asset class filter
272
+ * @returns Number of open positions
273
+ *
274
+ * @example
275
+ * const totalPositions = await getPositionCount(client);
276
+ * const equityPositions = await getPositionCount(client, 'us_equity');
277
+ */
278
+ export declare function getPositionCount(client: AlpacaClient, assetClass?: AssetClass): Promise<number>;
279
+ /**
280
+ * Get symbols of all open positions
281
+ *
282
+ * @param client - The Alpaca client instance
283
+ * @param assetClass - Optional asset class filter
284
+ * @returns Array of position symbols
285
+ *
286
+ * @example
287
+ * const symbols = await getPositionSymbols(client);
288
+ * console.log(`Holding positions in: ${symbols.join(', ')}`);
289
+ */
290
+ export declare function getPositionSymbols(client: AlpacaClient, assetClass?: AssetClass): Promise<string[]>;
291
+ /**
292
+ * Get total market value of all positions
293
+ *
294
+ * @param client - The Alpaca client instance
295
+ * @param assetClass - Optional asset class filter
296
+ * @returns Total market value in dollars
297
+ *
298
+ * @example
299
+ * const totalValue = await getTotalMarketValue(client);
300
+ * const equityValue = await getTotalMarketValue(client, 'us_equity');
301
+ */
302
+ export declare function getTotalMarketValue(client: AlpacaClient, assetClass?: AssetClass): Promise<number>;
303
+ /**
304
+ * Check if there are any open positions
305
+ *
306
+ * @param client - The Alpaca client instance
307
+ * @param assetClass - Optional asset class filter
308
+ * @returns True if there are open positions
309
+ *
310
+ * @example
311
+ * if (await hasAnyPositions(client)) {
312
+ * console.log('Portfolio has open positions');
313
+ * }
314
+ */
315
+ export declare function hasAnyPositions(client: AlpacaClient, assetClass?: AssetClass): Promise<boolean>;
316
+ /**
317
+ * Get positions sorted by market value (descending)
318
+ *
319
+ * @param client - The Alpaca client instance
320
+ * @param assetClass - Optional asset class filter
321
+ * @returns Positions sorted by market value (largest first)
322
+ *
323
+ * @example
324
+ * const sortedPositions = await getPositionsByValue(client);
325
+ * console.log(`Largest position: ${sortedPositions[0]?.symbol}`);
326
+ */
327
+ export declare function getPositionsByValue(client: AlpacaClient, assetClass?: AssetClass): Promise<AlpacaPosition[]>;
328
+ /**
329
+ * Get positions sorted by unrealized P&L (descending - best performers first)
330
+ *
331
+ * @param client - The Alpaca client instance
332
+ * @param assetClass - Optional asset class filter
333
+ * @returns Positions sorted by unrealized P&L
334
+ *
335
+ * @example
336
+ * const sortedPositions = await getPositionsByPnL(client);
337
+ * const winners = sortedPositions.filter(p => parseFloat(p.unrealized_pl) > 0);
338
+ * const losers = sortedPositions.filter(p => parseFloat(p.unrealized_pl) < 0);
339
+ */
340
+ export declare function getPositionsByPnL(client: AlpacaClient, assetClass?: AssetClass): Promise<AlpacaPosition[]>;
341
+ /**
342
+ * Get winning positions (positive unrealized P&L)
343
+ *
344
+ * @param client - The Alpaca client instance
345
+ * @param assetClass - Optional asset class filter
346
+ * @returns Positions with positive unrealized P&L
347
+ *
348
+ * @example
349
+ * const winners = await getWinningPositions(client);
350
+ */
351
+ export declare function getWinningPositions(client: AlpacaClient, assetClass?: AssetClass): Promise<AlpacaPosition[]>;
352
+ /**
353
+ * Get losing positions (negative unrealized P&L)
354
+ *
355
+ * @param client - The Alpaca client instance
356
+ * @param assetClass - Optional asset class filter
357
+ * @returns Positions with negative unrealized P&L
358
+ *
359
+ * @example
360
+ * const losers = await getLosingPositions(client);
361
+ */
362
+ export declare function getLosingPositions(client: AlpacaClient, assetClass?: AssetClass): Promise<AlpacaPosition[]>;
363
+ declare const _default: {
364
+ getPositions: typeof getPositions;
365
+ getPositionsByAssetClass: typeof getPositionsByAssetClass;
366
+ getPosition: typeof getPosition;
367
+ hasPosition: typeof hasPosition;
368
+ getPositionQty: typeof getPositionQty;
369
+ getPositionValue: typeof getPositionValue;
370
+ getPositionSide: typeof getPositionSide;
371
+ closePosition: typeof closePosition;
372
+ closeAllPositions: typeof closeAllPositions;
373
+ closeAllPositionsAfterHours: typeof closeAllPositionsAfterHours;
374
+ getPositionPnL: typeof getPositionPnL;
375
+ getPortfolioPnL: typeof getPortfolioPnL;
376
+ getEquityPositions: typeof getEquityPositions;
377
+ getOptionPositions: typeof getOptionPositions;
378
+ getCryptoPositions: typeof getCryptoPositions;
379
+ getPositionCount: typeof getPositionCount;
380
+ getPositionSymbols: typeof getPositionSymbols;
381
+ getTotalMarketValue: typeof getTotalMarketValue;
382
+ hasAnyPositions: typeof hasAnyPositions;
383
+ getPositionsByValue: typeof getPositionsByValue;
384
+ getPositionsByPnL: typeof getPositionsByPnL;
385
+ getWinningPositions: typeof getWinningPositions;
386
+ getLosingPositions: typeof getLosingPositions;
387
+ };
388
+ export default _default;
389
+ //# sourceMappingURL=positions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"positions.d.ts","sourceRoot":"","sources":["../../../../src/alpaca/trading/positions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAUnF;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,qBAAqB;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ,oCAAoC;IACpC,aAAa,EAAE,MAAM,CAAC;IACtB,qCAAqC;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,yCAAyC;IACzC,WAAW,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,SAAS,EAAE,MAAM,CAAC;IAClB,wCAAwC;IACxC,YAAY,EAAE,MAAM,CAAC;IACrB,6CAA6C;IAC7C,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,0CAA0C;IAC1C,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,0CAA0C;IAC1C,gBAAgB,EAAE,MAAM,CAAC;IACzB,wCAAwC;IACxC,cAAc,EAAE,MAAM,CAAC;IACvB,8CAA8C;IAC9C,iBAAiB,EAAE,MAAM,CAAC;IAC1B,mDAAmD;IACnD,wBAAwB,EAAE,MAAM,CAAC;IACjC,2CAA2C;IAC3C,OAAO,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,cAAc,EAAE,MAAM,CAAC;IACvB,oCAAoC;IACpC,SAAS,EAAE,kBAAkB,EAAE,CAAC;CACjC;AAED;;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AAkB,CACtC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,MAAM,EAAE,CAAC,CAKnB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,MAAM,CAAC,CAMjB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,OAAO,CAAC,CAGlB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,cAAc,EAAE,CAAC,CAU3B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,cAAc,EAAE,CAAC,CAU3B;AAED;;;;;;;;;GASG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,cAAc,EAAE,CAAC,CAM3B;AAED;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,YAAY,EACpB,UAAU,CAAC,EAAE,UAAU,GACtB,OAAO,CAAC,cAAc,EAAE,CAAC,CAM3B;;;;;;;;;;;;;;;;;;;;;;;;;;AAMD,wBA+BE"}
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Smart Orders Module
3
+ * Unified interface for bracket, OCO, OTO, and trailing stop orders
4
+ *
5
+ * This module aggregates all advanced order types and provides:
6
+ * - Automatic order type selection based on parameters
7
+ * - Convenience functions for common trading strategies
8
+ * - Risk-managed position creation with automatic sizing
9
+ * - Percentage-based bracket orders
10
+ *
11
+ * @module smart-orders
12
+ */
13
+ import { AlpacaClient } from '../client';
14
+ import { AlpacaOrder, OrderSide, TimeInForce } from '../../types/alpaca-types';
15
+ import { createBracketOrder, createProtectiveBracket, BracketOrderResult, createExecutorFromTradingAPI } from './bracket-orders';
16
+ import { createOCOOrder, OCOOrderResult } from './oco-orders';
17
+ import { createOTOOrder, OTOOrderResult } from './oto-orders';
18
+ import { createTrailingStop, updateTrailingStop } from './trailing-stops';
19
+ export * from './bracket-orders';
20
+ export * from './oco-orders';
21
+ export * from './oto-orders';
22
+ export * from './trailing-stops';
23
+ /**
24
+ * Unified smart order creation parameters
25
+ * Allows specifying entry, take profit, stop loss, and trailing stop in a single interface
26
+ */
27
+ export interface SmartOrderParams {
28
+ /** Trading symbol (e.g., 'AAPL') */
29
+ symbol: string;
30
+ /** Number of shares */
31
+ qty: number;
32
+ /** Order side: 'buy' or 'sell' */
33
+ side: OrderSide;
34
+ /** Entry configuration (optional - if omitted, assumes existing position) */
35
+ entry?: {
36
+ /** Entry order type */
37
+ type: 'market' | 'limit';
38
+ /** Limit price for entry (required if type is 'limit') */
39
+ limitPrice?: number;
40
+ };
41
+ /** Take profit configuration (optional) */
42
+ takeProfit?: {
43
+ /** Limit price for take profit */
44
+ limitPrice: number;
45
+ };
46
+ /** Stop loss configuration (optional) */
47
+ stopLoss?: {
48
+ /** Stop price to trigger stop loss */
49
+ stopPrice: number;
50
+ /** Optional limit price for stop-limit orders */
51
+ limitPrice?: number;
52
+ };
53
+ /** Trailing stop configuration (alternative to fixed stop loss) */
54
+ trailingStop?: {
55
+ /** Trail by percentage (e.g., 5 = 5%) */
56
+ trailPercent?: number;
57
+ /** Trail by fixed dollar amount */
58
+ trailPrice?: number;
59
+ };
60
+ /** Time in force for the order */
61
+ timeInForce?: TimeInForce;
62
+ /** Allow extended hours trading */
63
+ extendedHours?: boolean;
64
+ }
65
+ /**
66
+ * Type of order determined by smart order analysis
67
+ */
68
+ export type SmartOrderType = 'bracket' | 'oco' | 'oto' | 'trailing_stop' | 'simple';
69
+ /**
70
+ * Result of smart order creation - union of all possible result types
71
+ */
72
+ export type SmartOrderResult = BracketOrderResult | OCOOrderResult | OTOOrderResult | AlpacaOrder;
73
+ /**
74
+ * Analyze parameters and determine the best order type
75
+ *
76
+ * Decision logic:
77
+ * - Bracket: Entry + Take Profit + Stop Loss
78
+ * - OCO: Take Profit + Stop Loss (no entry - for existing position)
79
+ * - OTO: Entry + single exit (either TP or SL, not both)
80
+ * - Trailing Stop: Only trailing stop specified
81
+ * - Simple: None of the above
82
+ *
83
+ * @param params - Smart order parameters
84
+ * @returns The recommended order type
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const orderType = determineOrderType({
89
+ * symbol: 'AAPL',
90
+ * qty: 100,
91
+ * side: 'buy',
92
+ * entry: { type: 'limit', limitPrice: 150 },
93
+ * takeProfit: { limitPrice: 160 },
94
+ * stopLoss: { stopPrice: 145 },
95
+ * });
96
+ * // Returns: 'bracket'
97
+ * ```
98
+ */
99
+ export declare function determineOrderType(params: SmartOrderParams): SmartOrderType;
100
+ /**
101
+ * Create a smart order based on parameters
102
+ * Automatically selects the appropriate order type based on provided configuration
103
+ *
104
+ * @param client - AlpacaClient instance
105
+ * @param params - Smart order parameters
106
+ * @returns The created order(s) based on the determined order type
107
+ * @throws Error if parameters result in 'simple' order type (use createOrder directly)
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * // Full bracket order with entry, take profit, and stop loss
112
+ * const result = await createSmartOrder(client, {
113
+ * symbol: 'AAPL',
114
+ * qty: 100,
115
+ * side: 'buy',
116
+ * entry: { type: 'limit', limitPrice: 150 },
117
+ * takeProfit: { limitPrice: 160 },
118
+ * stopLoss: { stopPrice: 145 },
119
+ * timeInForce: 'gtc',
120
+ * });
121
+ *
122
+ * // OCO for existing position (no entry)
123
+ * const result = await createSmartOrder(client, {
124
+ * symbol: 'AAPL',
125
+ * qty: 100,
126
+ * side: 'sell',
127
+ * takeProfit: { limitPrice: 160 },
128
+ * stopLoss: { stopPrice: 145 },
129
+ * });
130
+ *
131
+ * // OTO with entry and stop loss only
132
+ * const result = await createSmartOrder(client, {
133
+ * symbol: 'AAPL',
134
+ * qty: 100,
135
+ * side: 'buy',
136
+ * entry: { type: 'limit', limitPrice: 150 },
137
+ * stopLoss: { stopPrice: 145 },
138
+ * });
139
+ *
140
+ * // Trailing stop
141
+ * const result = await createSmartOrder(client, {
142
+ * symbol: 'AAPL',
143
+ * qty: 100,
144
+ * side: 'sell',
145
+ * trailingStop: { trailPercent: 5 },
146
+ * });
147
+ * ```
148
+ */
149
+ export declare function createSmartOrder(client: AlpacaClient, params: SmartOrderParams): Promise<SmartOrderResult>;
150
+ /**
151
+ * Parameters for percentage-based bracket order
152
+ */
153
+ export interface PercentageBracketParams {
154
+ /** Trading symbol */
155
+ symbol: string;
156
+ /** Number of shares */
157
+ qty: number;
158
+ /** Order side: 'buy' or 'sell' */
159
+ side: OrderSide;
160
+ /** Entry price (limit order) */
161
+ entryPrice: number;
162
+ /** Take profit percentage above/below entry (e.g., 5 = 5% profit target) */
163
+ takeProfitPercent: number;
164
+ /** Stop loss percentage above/below entry (e.g., 2 = 2% risk) */
165
+ stopLossPercent: number;
166
+ /** Time in force for the order */
167
+ timeInForce?: TimeInForce;
168
+ }
169
+ /**
170
+ * Quick bracket order with percentage-based take profit and stop loss
171
+ * Calculates TP and SL prices based on percentages from entry price
172
+ *
173
+ * For buy orders:
174
+ * - Take profit is entryPrice + takeProfitPercent
175
+ * - Stop loss is entryPrice - stopLossPercent
176
+ *
177
+ * For sell (short) orders:
178
+ * - Take profit is entryPrice - takeProfitPercent
179
+ * - Stop loss is entryPrice + stopLossPercent
180
+ *
181
+ * @param client - AlpacaClient instance
182
+ * @param params - Percentage bracket parameters
183
+ * @returns The created bracket order result
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * // Buy AAPL at $150 with 5% take profit ($157.50) and 2% stop loss ($147)
188
+ * const result = await createPercentageBracket(client, {
189
+ * symbol: 'AAPL',
190
+ * qty: 100,
191
+ * side: 'buy',
192
+ * entryPrice: 150.00,
193
+ * takeProfitPercent: 5, // Take profit at $157.50
194
+ * stopLossPercent: 2, // Stop loss at $147.00
195
+ * timeInForce: 'gtc',
196
+ * });
197
+ * ```
198
+ */
199
+ export declare function createPercentageBracket(client: AlpacaClient, params: PercentageBracketParams): Promise<BracketOrderResult>;
200
+ /**
201
+ * Parameters for risk-managed position
202
+ */
203
+ export interface RiskManagedPositionParams {
204
+ /** Trading symbol */
205
+ symbol: string;
206
+ /** Order side: 'buy' or 'sell' */
207
+ side: OrderSide;
208
+ /** Entry price (limit order) */
209
+ entryPrice: number;
210
+ /** Stop loss price */
211
+ stopPrice: number;
212
+ /** Dollar amount willing to risk */
213
+ riskAmount: number;
214
+ /** Optional take profit price */
215
+ takeProfitPrice?: number;
216
+ /** Time in force for the order */
217
+ timeInForce?: TimeInForce;
218
+ }
219
+ /**
220
+ * Create a risk-managed position
221
+ * Calculates position size based on risk amount and stop distance
222
+ *
223
+ * Position size formula: riskAmount / abs(entryPrice - stopPrice)
224
+ *
225
+ * @param client - AlpacaClient instance
226
+ * @param params - Risk-managed position parameters
227
+ * @returns The created bracket or OTO order result
228
+ * @throws Error if risk amount is too small for the stop distance
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * // Risk $500 on AAPL trade with entry at $150 and stop at $145
233
+ * // Position size = $500 / ($150 - $145) = 100 shares
234
+ * const result = await createRiskManagedPosition(client, {
235
+ * symbol: 'AAPL',
236
+ * side: 'buy',
237
+ * entryPrice: 150.00,
238
+ * stopPrice: 145.00,
239
+ * riskAmount: 500,
240
+ * takeProfitPrice: 160.00, // Optional
241
+ * timeInForce: 'gtc',
242
+ * });
243
+ *
244
+ * // Actual risk: 100 shares * $5 stop distance = $500
245
+ * ```
246
+ */
247
+ export declare function createRiskManagedPosition(client: AlpacaClient, params: RiskManagedPositionParams): Promise<BracketOrderResult | OTOOrderResult>;
248
+ /**
249
+ * Calculate reward-to-risk ratio for a trade setup
250
+ *
251
+ * @param entryPrice - Entry price
252
+ * @param takeProfitPrice - Take profit price
253
+ * @param stopLossPrice - Stop loss price
254
+ * @param side - Order side ('buy' or 'sell')
255
+ * @returns Reward-to-risk ratio (e.g., 2.5 means 2.5:1 reward:risk)
256
+ *
257
+ * @example
258
+ * ```typescript
259
+ * // Buy at $150, TP at $160, SL at $145
260
+ * const rr = calculateRewardRiskRatio(150, 160, 145, 'buy');
261
+ * // Returns: 2.0 (reward: $10 / risk: $5 = 2:1)
262
+ * ```
263
+ */
264
+ export declare function calculateRewardRiskRatio(entryPrice: number, takeProfitPrice: number, stopLossPrice: number, side: OrderSide): number;
265
+ /**
266
+ * Calculate position size based on account risk percentage
267
+ *
268
+ * @param accountValue - Total account value
269
+ * @param riskPercent - Percentage of account to risk (e.g., 1 = 1%)
270
+ * @param entryPrice - Entry price
271
+ * @param stopPrice - Stop loss price
272
+ * @returns Recommended position size in shares
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * // $100,000 account, risk 1%, entry at $150, stop at $145
277
+ * const shares = calculatePositionSize(100000, 1, 150, 145);
278
+ * // Returns: 200 (risk $1,000 / $5 per share = 200 shares)
279
+ * ```
280
+ */
281
+ export declare function calculatePositionSize(accountValue: number, riskPercent: number, entryPrice: number, stopPrice: number): number;
282
+ /**
283
+ * Default export with all smart order functions
284
+ */
285
+ declare const _default: {
286
+ createSmartOrder: typeof createSmartOrder;
287
+ determineOrderType: typeof determineOrderType;
288
+ createPercentageBracket: typeof createPercentageBracket;
289
+ createRiskManagedPosition: typeof createRiskManagedPosition;
290
+ calculateRewardRiskRatio: typeof calculateRewardRiskRatio;
291
+ calculatePositionSize: typeof calculatePositionSize;
292
+ createBracketOrder: typeof createBracketOrder;
293
+ createProtectiveBracket: typeof createProtectiveBracket;
294
+ createExecutorFromTradingAPI: typeof createExecutorFromTradingAPI;
295
+ createOCOOrder: typeof createOCOOrder;
296
+ createOTOOrder: typeof createOTOOrder;
297
+ createTrailingStop: typeof createTrailingStop;
298
+ updateTrailingStop: typeof updateTrailingStop;
299
+ };
300
+ export default _default;
301
+ //# sourceMappingURL=smart-orders.d.ts.map