@adaptic/utils 0.0.99

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 (238) hide show
  1. package/README.md +916 -0
  2. package/dist/index.cjs +71971 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.mjs +71677 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/dist/test.js +7799 -0
  7. package/dist/test.js.map +1 -0
  8. package/dist/types/__tests__/alpaca-functions.test.d.ts +2 -0
  9. package/dist/types/__tests__/alpaca-functions.test.d.ts.map +1 -0
  10. package/dist/types/__tests__/api-endpoints.test.d.ts +2 -0
  11. package/dist/types/__tests__/api-endpoints.test.d.ts.map +1 -0
  12. package/dist/types/__tests__/asset-allocation.test.d.ts +2 -0
  13. package/dist/types/__tests__/asset-allocation.test.d.ts.map +1 -0
  14. package/dist/types/__tests__/auth-validator.test.d.ts +2 -0
  15. package/dist/types/__tests__/auth-validator.test.d.ts.map +1 -0
  16. package/dist/types/__tests__/cache.test.d.ts +2 -0
  17. package/dist/types/__tests__/cache.test.d.ts.map +1 -0
  18. package/dist/types/__tests__/errors.test.d.ts +2 -0
  19. package/dist/types/__tests__/errors.test.d.ts.map +1 -0
  20. package/dist/types/__tests__/financial-regression.test.d.ts +2 -0
  21. package/dist/types/__tests__/financial-regression.test.d.ts.map +1 -0
  22. package/dist/types/__tests__/format-tools.test.d.ts +2 -0
  23. package/dist/types/__tests__/format-tools.test.d.ts.map +1 -0
  24. package/dist/types/__tests__/http-keep-alive.test.d.ts +2 -0
  25. package/dist/types/__tests__/http-keep-alive.test.d.ts.map +1 -0
  26. package/dist/types/__tests__/http-timeout.test.d.ts +2 -0
  27. package/dist/types/__tests__/http-timeout.test.d.ts.map +1 -0
  28. package/dist/types/__tests__/logger.test.d.ts +2 -0
  29. package/dist/types/__tests__/logger.test.d.ts.map +1 -0
  30. package/dist/types/__tests__/market-time.test.d.ts +2 -0
  31. package/dist/types/__tests__/market-time.test.d.ts.map +1 -0
  32. package/dist/types/__tests__/misc-utils.test.d.ts +2 -0
  33. package/dist/types/__tests__/misc-utils.test.d.ts.map +1 -0
  34. package/dist/types/__tests__/paginator.test.d.ts +2 -0
  35. package/dist/types/__tests__/paginator.test.d.ts.map +1 -0
  36. package/dist/types/__tests__/performance-metrics.test.d.ts +2 -0
  37. package/dist/types/__tests__/performance-metrics.test.d.ts.map +1 -0
  38. package/dist/types/__tests__/polygon.test.d.ts +2 -0
  39. package/dist/types/__tests__/polygon.test.d.ts.map +1 -0
  40. package/dist/types/__tests__/price-utils.test.d.ts +2 -0
  41. package/dist/types/__tests__/price-utils.test.d.ts.map +1 -0
  42. package/dist/types/__tests__/property-based-financial.test.d.ts +2 -0
  43. package/dist/types/__tests__/property-based-financial.test.d.ts.map +1 -0
  44. package/dist/types/__tests__/rate-limiter.test.d.ts +2 -0
  45. package/dist/types/__tests__/rate-limiter.test.d.ts.map +1 -0
  46. package/dist/types/__tests__/schema-validation.test.d.ts +2 -0
  47. package/dist/types/__tests__/schema-validation.test.d.ts.map +1 -0
  48. package/dist/types/__tests__/technical-analysis.test.d.ts +2 -0
  49. package/dist/types/__tests__/technical-analysis.test.d.ts.map +1 -0
  50. package/dist/types/__tests__/time-utils.test.d.ts +2 -0
  51. package/dist/types/__tests__/time-utils.test.d.ts.map +1 -0
  52. package/dist/types/adaptic.d.ts +52 -0
  53. package/dist/types/adaptic.d.ts.map +1 -0
  54. package/dist/types/alpaca/client.d.ts +95 -0
  55. package/dist/types/alpaca/client.d.ts.map +1 -0
  56. package/dist/types/alpaca/crypto/data.d.ts +281 -0
  57. package/dist/types/alpaca/crypto/data.d.ts.map +1 -0
  58. package/dist/types/alpaca/crypto/index.d.ts +75 -0
  59. package/dist/types/alpaca/crypto/index.d.ts.map +1 -0
  60. package/dist/types/alpaca/crypto/orders.d.ts +221 -0
  61. package/dist/types/alpaca/crypto/orders.d.ts.map +1 -0
  62. package/dist/types/alpaca/index.d.ts +205 -0
  63. package/dist/types/alpaca/index.d.ts.map +1 -0
  64. package/dist/types/alpaca/legacy/account.d.ts +34 -0
  65. package/dist/types/alpaca/legacy/account.d.ts.map +1 -0
  66. package/dist/types/alpaca/legacy/assets.d.ts +13 -0
  67. package/dist/types/alpaca/legacy/assets.d.ts.map +1 -0
  68. package/dist/types/alpaca/legacy/auth.d.ts +18 -0
  69. package/dist/types/alpaca/legacy/auth.d.ts.map +1 -0
  70. package/dist/types/alpaca/legacy/index.d.ts +15 -0
  71. package/dist/types/alpaca/legacy/index.d.ts.map +1 -0
  72. package/dist/types/alpaca/legacy/market-data.d.ts +32 -0
  73. package/dist/types/alpaca/legacy/market-data.d.ts.map +1 -0
  74. package/dist/types/alpaca/legacy/orders.d.ts +84 -0
  75. package/dist/types/alpaca/legacy/orders.d.ts.map +1 -0
  76. package/dist/types/alpaca/legacy/positions.d.ts +66 -0
  77. package/dist/types/alpaca/legacy/positions.d.ts.map +1 -0
  78. package/dist/types/alpaca/legacy/utils.d.ts +18 -0
  79. package/dist/types/alpaca/legacy/utils.d.ts.map +1 -0
  80. package/dist/types/alpaca/market-data/bars.d.ts +142 -0
  81. package/dist/types/alpaca/market-data/bars.d.ts.map +1 -0
  82. package/dist/types/alpaca/market-data/index.d.ts +13 -0
  83. package/dist/types/alpaca/market-data/index.d.ts.map +1 -0
  84. package/dist/types/alpaca/market-data/news.d.ts +87 -0
  85. package/dist/types/alpaca/market-data/news.d.ts.map +1 -0
  86. package/dist/types/alpaca/market-data/quotes.d.ts +85 -0
  87. package/dist/types/alpaca/market-data/quotes.d.ts.map +1 -0
  88. package/dist/types/alpaca/market-data/trades.d.ts +98 -0
  89. package/dist/types/alpaca/market-data/trades.d.ts.map +1 -0
  90. package/dist/types/alpaca/options/contracts.d.ts +279 -0
  91. package/dist/types/alpaca/options/contracts.d.ts.map +1 -0
  92. package/dist/types/alpaca/options/data.d.ts +126 -0
  93. package/dist/types/alpaca/options/data.d.ts.map +1 -0
  94. package/dist/types/alpaca/options/index.d.ts +17 -0
  95. package/dist/types/alpaca/options/index.d.ts.map +1 -0
  96. package/dist/types/alpaca/options/orders.d.ts +366 -0
  97. package/dist/types/alpaca/options/orders.d.ts.map +1 -0
  98. package/dist/types/alpaca/options/strategies.d.ts +224 -0
  99. package/dist/types/alpaca/options/strategies.d.ts.map +1 -0
  100. package/dist/types/alpaca/streams/base-stream.d.ts +143 -0
  101. package/dist/types/alpaca/streams/base-stream.d.ts.map +1 -0
  102. package/dist/types/alpaca/streams/crypto-stream.d.ts +173 -0
  103. package/dist/types/alpaca/streams/crypto-stream.d.ts.map +1 -0
  104. package/dist/types/alpaca/streams/index.d.ts +54 -0
  105. package/dist/types/alpaca/streams/index.d.ts.map +1 -0
  106. package/dist/types/alpaca/streams/option-stream.d.ts +167 -0
  107. package/dist/types/alpaca/streams/option-stream.d.ts.map +1 -0
  108. package/dist/types/alpaca/streams/stock-stream.d.ts +176 -0
  109. package/dist/types/alpaca/streams/stock-stream.d.ts.map +1 -0
  110. package/dist/types/alpaca/streams/stream-manager.d.ts +277 -0
  111. package/dist/types/alpaca/streams/stream-manager.d.ts.map +1 -0
  112. package/dist/types/alpaca/streams/trading-stream.d.ts +186 -0
  113. package/dist/types/alpaca/streams/trading-stream.d.ts.map +1 -0
  114. package/dist/types/alpaca/streams.d.ts +88 -0
  115. package/dist/types/alpaca/streams.d.ts.map +1 -0
  116. package/dist/types/alpaca/test-imports.d.ts +7 -0
  117. package/dist/types/alpaca/test-imports.d.ts.map +1 -0
  118. package/dist/types/alpaca/trading/account.d.ts +198 -0
  119. package/dist/types/alpaca/trading/account.d.ts.map +1 -0
  120. package/dist/types/alpaca/trading/bracket-orders.d.ts +162 -0
  121. package/dist/types/alpaca/trading/bracket-orders.d.ts.map +1 -0
  122. package/dist/types/alpaca/trading/clock.d.ts +99 -0
  123. package/dist/types/alpaca/trading/clock.d.ts.map +1 -0
  124. package/dist/types/alpaca/trading/index.d.ts +15 -0
  125. package/dist/types/alpaca/trading/index.d.ts.map +1 -0
  126. package/dist/types/alpaca/trading/oco-orders.d.ts +203 -0
  127. package/dist/types/alpaca/trading/oco-orders.d.ts.map +1 -0
  128. package/dist/types/alpaca/trading/order-utils.d.ts +404 -0
  129. package/dist/types/alpaca/trading/order-utils.d.ts.map +1 -0
  130. package/dist/types/alpaca/trading/orders.d.ts +199 -0
  131. package/dist/types/alpaca/trading/orders.d.ts.map +1 -0
  132. package/dist/types/alpaca/trading/oto-orders.d.ts +282 -0
  133. package/dist/types/alpaca/trading/oto-orders.d.ts.map +1 -0
  134. package/dist/types/alpaca/trading/positions.d.ts +389 -0
  135. package/dist/types/alpaca/trading/positions.d.ts.map +1 -0
  136. package/dist/types/alpaca/trading/smart-orders.d.ts +301 -0
  137. package/dist/types/alpaca/trading/smart-orders.d.ts.map +1 -0
  138. package/dist/types/alpaca/trading/trailing-stops.d.ts +240 -0
  139. package/dist/types/alpaca/trading/trailing-stops.d.ts.map +1 -0
  140. package/dist/types/alpaca-market-data-api.d.ts +386 -0
  141. package/dist/types/alpaca-market-data-api.d.ts.map +1 -0
  142. package/dist/types/alpaca-trading-api.d.ts +315 -0
  143. package/dist/types/alpaca-trading-api.d.ts.map +1 -0
  144. package/dist/types/alphavantage.d.ts +44 -0
  145. package/dist/types/alphavantage.d.ts.map +1 -0
  146. package/dist/types/asset-allocation-algorithm.d.ts +143 -0
  147. package/dist/types/asset-allocation-algorithm.d.ts.map +1 -0
  148. package/dist/types/cache/stampede-protected-cache.d.ts +565 -0
  149. package/dist/types/cache/stampede-protected-cache.d.ts.map +1 -0
  150. package/dist/types/config/api-endpoints.d.ts +94 -0
  151. package/dist/types/config/api-endpoints.d.ts.map +1 -0
  152. package/dist/types/crypto.d.ts +76 -0
  153. package/dist/types/crypto.d.ts.map +1 -0
  154. package/dist/types/display-manager.d.ts +24 -0
  155. package/dist/types/display-manager.d.ts.map +1 -0
  156. package/dist/types/errors/index.d.ts +130 -0
  157. package/dist/types/errors/index.d.ts.map +1 -0
  158. package/dist/types/examples/asset-allocation-example.d.ts +36 -0
  159. package/dist/types/examples/asset-allocation-example.d.ts.map +1 -0
  160. package/dist/types/examples/rate-limiter-example.d.ts +7 -0
  161. package/dist/types/examples/rate-limiter-example.d.ts.map +1 -0
  162. package/dist/types/format-tools.d.ts +54 -0
  163. package/dist/types/format-tools.d.ts.map +1 -0
  164. package/dist/types/http-timeout.d.ts +37 -0
  165. package/dist/types/http-timeout.d.ts.map +1 -0
  166. package/dist/types/index.d.ts +766 -0
  167. package/dist/types/index.d.ts.map +1 -0
  168. package/dist/types/logger.d.ts +56 -0
  169. package/dist/types/logger.d.ts.map +1 -0
  170. package/dist/types/logging.d.ts +12 -0
  171. package/dist/types/logging.d.ts.map +1 -0
  172. package/dist/types/market-hours.d.ts +24 -0
  173. package/dist/types/market-hours.d.ts.map +1 -0
  174. package/dist/types/market-time.d.ts +246 -0
  175. package/dist/types/market-time.d.ts.map +1 -0
  176. package/dist/types/metrics-calcs.d.ts +6 -0
  177. package/dist/types/metrics-calcs.d.ts.map +1 -0
  178. package/dist/types/misc-utils.d.ts +52 -0
  179. package/dist/types/misc-utils.d.ts.map +1 -0
  180. package/dist/types/performance-metrics.d.ts +88 -0
  181. package/dist/types/performance-metrics.d.ts.map +1 -0
  182. package/dist/types/polygon-indices.d.ts +85 -0
  183. package/dist/types/polygon-indices.d.ts.map +1 -0
  184. package/dist/types/polygon.d.ts +126 -0
  185. package/dist/types/polygon.d.ts.map +1 -0
  186. package/dist/types/price-utils.d.ts +26 -0
  187. package/dist/types/price-utils.d.ts.map +1 -0
  188. package/dist/types/rate-limiter.d.ts +171 -0
  189. package/dist/types/rate-limiter.d.ts.map +1 -0
  190. package/dist/types/schemas/alpaca-schemas.d.ts +779 -0
  191. package/dist/types/schemas/alpaca-schemas.d.ts.map +1 -0
  192. package/dist/types/schemas/alphavantage-schemas.d.ts +255 -0
  193. package/dist/types/schemas/alphavantage-schemas.d.ts.map +1 -0
  194. package/dist/types/schemas/index.d.ts +21 -0
  195. package/dist/types/schemas/index.d.ts.map +1 -0
  196. package/dist/types/schemas/polygon-schemas.d.ts +551 -0
  197. package/dist/types/schemas/polygon-schemas.d.ts.map +1 -0
  198. package/dist/types/schemas/validate-response.d.ts +88 -0
  199. package/dist/types/schemas/validate-response.d.ts.map +1 -0
  200. package/dist/types/technical-analysis.d.ts +90 -0
  201. package/dist/types/technical-analysis.d.ts.map +1 -0
  202. package/dist/types/test.d.ts +2 -0
  203. package/dist/types/test.d.ts.map +1 -0
  204. package/dist/types/testing/options-ws.d.ts +2 -0
  205. package/dist/types/testing/options-ws.d.ts.map +1 -0
  206. package/dist/types/time-utils.d.ts +17 -0
  207. package/dist/types/time-utils.d.ts.map +1 -0
  208. package/dist/types/types/adaptic-types.d.ts +11 -0
  209. package/dist/types/types/adaptic-types.d.ts.map +1 -0
  210. package/dist/types/types/alpaca-types.d.ts +1165 -0
  211. package/dist/types/types/alpaca-types.d.ts.map +1 -0
  212. package/dist/types/types/alphavantage-types.d.ts +66 -0
  213. package/dist/types/types/alphavantage-types.d.ts.map +1 -0
  214. package/dist/types/types/asset-allocation-types.d.ts +328 -0
  215. package/dist/types/types/asset-allocation-types.d.ts.map +1 -0
  216. package/dist/types/types/index.d.ts +21 -0
  217. package/dist/types/types/index.d.ts.map +1 -0
  218. package/dist/types/types/logging-types.d.ts +10 -0
  219. package/dist/types/types/logging-types.d.ts.map +1 -0
  220. package/dist/types/types/market-time-types.d.ts +59 -0
  221. package/dist/types/types/market-time-types.d.ts.map +1 -0
  222. package/dist/types/types/metrics-types.d.ts +33 -0
  223. package/dist/types/types/metrics-types.d.ts.map +1 -0
  224. package/dist/types/types/polygon-indices-types.d.ts +190 -0
  225. package/dist/types/types/polygon-indices-types.d.ts.map +1 -0
  226. package/dist/types/types/polygon-types.d.ts +204 -0
  227. package/dist/types/types/polygon-types.d.ts.map +1 -0
  228. package/dist/types/types/ta-types.d.ts +89 -0
  229. package/dist/types/types/ta-types.d.ts.map +1 -0
  230. package/dist/types/utils/auth-validator.d.ts +32 -0
  231. package/dist/types/utils/auth-validator.d.ts.map +1 -0
  232. package/dist/types/utils/http-keep-alive.d.ts +110 -0
  233. package/dist/types/utils/http-keep-alive.d.ts.map +1 -0
  234. package/dist/types/utils/paginator.d.ts +154 -0
  235. package/dist/types/utils/paginator.d.ts.map +1 -0
  236. package/dist/types/utils/retry.d.ts +78 -0
  237. package/dist/types/utils/retry.d.ts.map +1 -0
  238. package/package.json +78 -0
package/README.md ADDED
@@ -0,0 +1,916 @@
1
+ # @adaptic/utils
2
+
3
+ Last updated: 20 Feb 2025
4
+
5
+ A comprehensive utility library for financial data processing, time manipulation, and formatting.
6
+
7
+ NPM repo: https://www.npmjs.com/package/@adaptic/utils
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @adaptic/utils
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ Import the functions from the library:
18
+
19
+ ```typescript
20
+ import { adaptic } from "@adaptic/utils";
21
+ ```
22
+
23
+ ## Environment Variables
24
+
25
+ - `POLYGON_API_KEY`
26
+ - `ALPHA_VANTAGE_API_KEY`
27
+ - `ALPACA_API_KEY` - Required for crypto data and news
28
+ - `ALPACA_API_SECRET` - Required for crypto data and news
29
+ - `GOOGLE_SHEETS_CLIENT_EMAIL` - Required for Google Sheets operations
30
+ - `GOOGLE_SHEETS_PRIVATE_KEY` - Required for Google Sheets operations (with newlines preserved)
31
+ - `BACKEND_HTTPS_URL`= for the backend functions
32
+ - `NODE_ENV`='production' for backend functions to work with a remote server
33
+
34
+ ## Alpaca Functions
35
+
36
+ ### `fetchAccountDetails(accountId: string): Promise<AccountDetails>`
37
+
38
+ Asynchronously retrieves detailed information about a specific Alpaca trading account.
39
+
40
+ **Parameters:**
41
+
42
+ - `accountId: string` - The Alpaca account ID
43
+
44
+ **Returns:**
45
+
46
+ - `Promise<AccountDetails>` - Comprehensive account details including:
47
+ ```typescript
48
+ {
49
+ id: string;
50
+ account_number: string;
51
+ status: "ONBOARDING" |
52
+ "SUBMISSION_FAILED" |
53
+ "SUBMITTED" |
54
+ "ACCOUNT_UPDATED" |
55
+ "APPROVAL_PENDING" |
56
+ "ACTIVE" |
57
+ "REJECTED";
58
+ currency: string;
59
+ cash: string;
60
+ portfolio_value: string; // deprecated, equivalent to equity
61
+ equity: string;
62
+ buying_power: string;
63
+ initial_margin: string;
64
+ maintenance_margin: string;
65
+ daytrade_count: number;
66
+ daytrading_buying_power: string;
67
+ options_buying_power: string;
68
+ options_approved_level: 0 | 1 | 2 | 3;
69
+ // ... and more fields available
70
+ }
71
+ ```
72
+
73
+ **Example:**
74
+
75
+ ```typescript
76
+ const accountDetails =
77
+ await adaptic.alpaca.fetchAccountDetails("your-account-id");
78
+ console.log(`Account equity: ${accountDetails.equity}`);
79
+ ```
80
+
81
+ ### `fetchPortfolioHistory({ params, accountId, client, alpacaAccount }: FetchPortfolioHistoryProps): Promise<PortfolioHistoryResponse>`
82
+
83
+ Asynchronously retrieves historical portfolio data including equity and profit/loss information from either the Adaptic backend or directly from an Alpaca account.
84
+
85
+ **Parameters:**
86
+
87
+ - `FetchPortfolioHistoryProps`:
88
+ ```typescript
89
+ {
90
+ params: PortfolioHistoryParams; // Portfolio history query parameters
91
+ accountId?: string; // The Alpaca account ID (required if alpacaAccount not provided)
92
+ client?: ApolloClientType<NormalizedCacheObject>; // Optional Apollo client for backend queries
93
+ alpacaAccount?: types.AlpacaAccount;// Optional Alpaca account object (if provided, accountId not required)
94
+ }
95
+ ```
96
+ - `PortfolioHistoryParams`:
97
+ ```typescript
98
+ {
99
+ period?: string; // e.g., '1D', '1W', '1M', '1A', 'YTD' (YTD will be converted to '1A')
100
+ timeframe?: '1Min' | '5Min' | '15Min' | '1H' | '1D';
101
+ intraday_reporting?: 'market_hours' | 'extended_hours' | 'continuous';
102
+ start?: string; // RFC3339 format (if specified with period, period will be ignored)
103
+ end?: string; // RFC3339 format
104
+ pnl_reset?: 'per_day' | 'no_reset';
105
+ }
106
+ ```
107
+
108
+ **Returns:**
109
+
110
+ - `Promise<PortfolioHistoryResponse>`:
111
+ ```typescript
112
+ {
113
+ timestamp: number[]; // UNIX epoch format
114
+ equity: number[];
115
+ profit_loss: number[];
116
+ profit_loss_pct: number[];
117
+ base_value: number;
118
+ base_value_asof?: string;
119
+ timeframe: string;
120
+ cashflow?: Record<string, number>;
121
+ }
122
+ ```
123
+
124
+ **Example:**
125
+
126
+ ```typescript
127
+ // Using accountId
128
+ const history = await adaptic.alpaca.fetchPortfolioHistory({
129
+ accountId: "your-account-id",
130
+ params: {
131
+ period: "1M",
132
+ timeframe: "1D",
133
+ },
134
+ });
135
+
136
+ // Using direct Alpaca account object
137
+ const history = await adaptic.alpaca.fetchPortfolioHistory({
138
+ alpacaAccount: yourAlpacaAccount,
139
+ params: {
140
+ start: "2025-01-01T00:00:00Z",
141
+ end: "2025-01-31T00:00:00Z",
142
+ timeframe: "1D",
143
+ },
144
+ });
145
+ ```
146
+
147
+ ### `adaptic.position.fetchAll(auth: AlpacaAuth): Promise<Position[]>`
148
+
149
+ Asynchronously fetches all current open positions for an Alpaca trading account.
150
+
151
+ **Parameters:**
152
+
153
+ - `auth: AlpacaAuth` - Authentication details:
154
+ ```typescript
155
+ {
156
+ adapticAccountId?: string; // Either this
157
+ alpacaApiKey?: string; // Or these two
158
+ alpacaApiSecret?: string;
159
+ }
160
+ ```
161
+
162
+ **Returns:**
163
+
164
+ - `Promise<Position[]>` - Array of positions with the following type:
165
+ ```typescript
166
+ {
167
+ asset_id: string;
168
+ symbol: string;
169
+ exchange: string;
170
+ asset_class: string;
171
+ asset_marginable: boolean;
172
+ qty: string;
173
+ qty_available: string;
174
+ avg_entry_price: string;
175
+ side: "long" | "short";
176
+ market_value: string;
177
+ cost_basis: string;
178
+ unrealized_pl: string;
179
+ unrealized_plpc: string;
180
+ unrealized_intraday_pl: string;
181
+ unrealized_intraday_plpc: string;
182
+ current_price: string;
183
+ lastday_price: string;
184
+ change_today: string;
185
+ }
186
+ ```
187
+
188
+ **Example:**
189
+
190
+ ```typescript
191
+ // Using adapticAccountId
192
+ const positions = await adaptic.position.fetchAll({
193
+ adapticAccountId: "your-account-id",
194
+ });
195
+
196
+ // Using direct API keys
197
+ const positions = await adaptic.position.fetchAll({
198
+ alpacaApiKey: "your-api-key",
199
+ alpacaApiSecret: "your-api-secret",
200
+ });
201
+ ```
202
+
203
+ ### `adaptic.position.fetch(symbolOrAssetId: string, auth: AlpacaAuth): Promise<Position>`
204
+
205
+ Asynchronously fetches a specific position for an Alpaca trading account.
206
+
207
+ **Parameters:**
208
+
209
+ - `symbolOrAssetId: string` - The symbol or asset ID to fetch the position for
210
+ - `auth: AlpacaAuth` - Authentication details (same as above)
211
+
212
+ **Returns:**
213
+
214
+ - `Promise<Position>` - Single position details with the same type as in `fetchAll`
215
+
216
+ **Example:**
217
+
218
+ ```typescript
219
+ const position = await adaptic.position.fetch("AAPL", {
220
+ adapticAccountId: "your-account-id",
221
+ });
222
+ ```
223
+
224
+ ### `adaptic.position.close(symbolOrAssetId: string, auth: AlpacaAuth, params?: ClosePositionParams): Promise<Order>`
225
+
226
+ Closes a specific position in an Alpaca trading account.
227
+
228
+ **Parameters:**
229
+
230
+ - `symbolOrAssetId: string` - The symbol or asset ID of the position to close
231
+ - `auth: AlpacaAuth` - Authentication details (same as above)
232
+ - `params?: ClosePositionParams` - Optional closing parameters:
233
+ ```typescript
234
+ {
235
+ qty?: number; // Quantity of shares to close (up to 9 decimal places)
236
+ percentage?: number; // Percentage of position to close (0-100, up to 9 decimal places)
237
+ }
238
+ ```
239
+
240
+ **Returns:**
241
+
242
+ - `Promise<Order>` - The order created to close the position
243
+
244
+ **Example:**
245
+
246
+ ```typescript
247
+ // Close entire position
248
+ const order = await adaptic.position.close("AAPL", {
249
+ adapticAccountId: "your-account-id",
250
+ });
251
+
252
+ // Close 50% of position
253
+ const order = await adaptic.position.close(
254
+ "AAPL",
255
+ {
256
+ adapticAccountId: "your-account-id",
257
+ },
258
+ {
259
+ percentage: 50,
260
+ },
261
+ );
262
+ ```
263
+
264
+ ### `adaptic.position.closeAll(auth: AlpacaAuth, params?: CloseAllPositionsParams): Promise<Array<{ symbol: string; status: number; body?: Order }>>`
265
+
266
+ Closes all positions in an Alpaca trading account.
267
+
268
+ **Parameters:**
269
+
270
+ - `auth: AlpacaAuth` - Authentication details (same as above)
271
+ - `params?: CloseAllPositionsParams` - Optional parameters:
272
+ ```typescript
273
+ {
274
+ cancelOrders?: boolean; // If true, cancels all open orders before closing positions
275
+ }
276
+ ```
277
+
278
+ **Returns:**
279
+
280
+ - `Promise<Array<{ symbol: string; status: number; body?: Order }>>` - Status of each position closure attempt:
281
+ - `symbol: string` - The symbol of the position
282
+ - `status: number` - HTTP status code for the attempt
283
+ - `body?: Order` - The order created to close the position (if successful)
284
+
285
+ **Example:**
286
+
287
+ ```typescript
288
+ // Close all positions
289
+ const results = await adaptic.position.closeAll({
290
+ adapticAccountId: "your-account-id",
291
+ });
292
+
293
+ // Close all positions and cancel pending orders
294
+ const results = await adaptic.position.closeAll(
295
+ {
296
+ adapticAccountId: "your-account-id",
297
+ },
298
+ {
299
+ cancelOrders: true,
300
+ },
301
+ );
302
+ ```
303
+
304
+ ### `createOrder(params: CreateOrderParams): Promise<Order>`
305
+
306
+ Creates a new order for trading.
307
+
308
+ **Parameters:**
309
+
310
+ - `params: CreateOrderParams`:
311
+ ```typescript
312
+ {
313
+ symbol: string;
314
+ qty?: string;
315
+ notional?: string;
316
+ side: 'buy' | 'sell';
317
+ type: 'market' | 'limit' | 'stop' | 'stop_limit' | 'trailing_stop';
318
+ time_in_force: 'day' | 'gtc' | 'opg' | 'cls' | 'ioc' | 'fok';
319
+ limit_price?: string;
320
+ stop_price?: string;
321
+ trail_price?: string;
322
+ trail_percent?: string;
323
+ extended_hours?: boolean;
324
+ client_order_id?: string;
325
+ order_class?: 'simple' | 'oco' | 'oto' | 'bracket';
326
+ take_profit?: {
327
+ limit_price: string;
328
+ stop_price?: string;
329
+ order_class?: OrderClass;
330
+ };
331
+ stop_loss?: {
332
+ stop_price: string;
333
+ limit_price?: string;
334
+ order_class?: OrderClass;
335
+ };
336
+ position_intent?: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close';
337
+ }
338
+ ```
339
+
340
+ **Returns:**
341
+
342
+ - `Promise<Order>` - Created order details with full order type information
343
+
344
+ ## Crypto Functions
345
+
346
+ ### `fetchBars(params: CryptoBarsParams): Promise<CryptoBarsResponse>`
347
+
348
+ Fetches historical bar data for crypto trading pairs.
349
+
350
+ **Parameters:**
351
+
352
+ - `params: CryptoBarsParams`:
353
+ ```typescript
354
+ {
355
+ symbols: CryptoPair[];
356
+ timeframe: CryptoTimeframe; // '1Min' | '5Min' | '15Min' | '1Hour' | '1Day' | '1Week' | '1Month'
357
+ start?: Date;
358
+ end?: Date;
359
+ limit?: number;
360
+ page_token?: string;
361
+ sort?: 'asc' | 'desc';
362
+ }
363
+ ```
364
+
365
+ **Returns:**
366
+
367
+ - `Promise<CryptoBarsResponse>`:
368
+ ```typescript
369
+ {
370
+ bars: {
371
+ [symbol: string]: CryptoBar[];
372
+ };
373
+ next_page_token?: string;
374
+ }
375
+ ```
376
+ where `CryptoBar` is:
377
+ ```typescript
378
+ {
379
+ t: number; // timestamp
380
+ o: number; // open
381
+ h: number; // high
382
+ l: number; // low
383
+ c: number; // close
384
+ v: number; // volume
385
+ }
386
+ ```
387
+
388
+ ## Market Data Functions
389
+
390
+ ### `fetchPolygonPrices(symbol: string, params: object): Promise<PolygonPriceData[]>`
391
+
392
+ Fetches historical price data from Polygon.io.
393
+
394
+ **Parameters:**
395
+
396
+ - `symbol: string` - The trading symbol
397
+ - `params: object` - Query parameters for the data fetch
398
+
399
+ **Returns:**
400
+
401
+ - `Promise<PolygonPriceData[]>`:
402
+ ```typescript
403
+ {
404
+ date: string;
405
+ timeStamp: number;
406
+ open: number;
407
+ high: number;
408
+ low: number;
409
+ close: number;
410
+ vol: number;
411
+ vwap: number;
412
+ }
413
+ [];
414
+ ```
415
+
416
+ ## Performance Metrics
417
+
418
+ ### `calculateBeta(returns: number[], benchmarkReturns: number[]): CalculateBetaResult`
419
+
420
+ Calculates beta and related statistics for a portfolio against a benchmark.
421
+
422
+ **Parameters:**
423
+
424
+ - `returns: number[]` - Array of portfolio returns
425
+ - `benchmarkReturns: number[]` - Array of benchmark returns
426
+
427
+ **Returns:**
428
+
429
+ - `CalculateBetaResult`:
430
+ ```typescript
431
+ {
432
+ beta: number;
433
+ covariance: number;
434
+ variance: number;
435
+ averagePortfolioReturn: number;
436
+ averageBenchmarkReturn: number;
437
+ }
438
+ ```
439
+
440
+ ### `calculateMaxDrawdown(portfolioValues: number[]): number`
441
+
442
+ Calculates the maximum drawdown from peak for a series of portfolio values.
443
+
444
+ **Parameters:**
445
+
446
+ - `portfolioValues: number[]` - Array of portfolio values over time
447
+
448
+ **Returns:**
449
+
450
+ - `number` - Maximum drawdown as a decimal (e.g., 0.25 for 25% drawdown)
451
+
452
+ ### `calculateDailyReturns(portfolioValues: number[]): number[]`
453
+
454
+ Computes daily returns from a series of portfolio values.
455
+
456
+ **Parameters:**
457
+
458
+ - `portfolioValues: number[]` - Array of portfolio values
459
+
460
+ **Returns:**
461
+
462
+ - `number[]` - Array of daily returns as decimals
463
+
464
+ ## News Functions
465
+
466
+ ### `fetchNews(params: NewsParams): Promise<NewsResponse>`
467
+
468
+ Fetches financial news articles.
469
+
470
+ **Parameters:**
471
+
472
+ - `params: NewsParams`:
473
+ ```typescript
474
+ {
475
+ start?: Date | string;
476
+ end?: Date | string;
477
+ symbols?: string | string[];
478
+ limit?: number;
479
+ sort?: 'asc' | 'desc';
480
+ page_token?: string;
481
+ }
482
+ ```
483
+
484
+ **Returns:**
485
+
486
+ - `Promise<NewsResponse>`:
487
+ ```typescript
488
+ {
489
+ news: {
490
+ id: number;
491
+ author: string;
492
+ content: string;
493
+ created_at: string;
494
+ updated_at: string;
495
+ headline: string;
496
+ source: string;
497
+ summary: string;
498
+ url: string;
499
+ symbols: string[];
500
+ images: {
501
+ size: 'large' | 'small' | 'thumb';
502
+ url: string;
503
+ }[];
504
+ }[];
505
+ next_page_token?: string;
506
+ }
507
+ ```
508
+
509
+ ## Time Utilities
510
+
511
+ ### Market Time Types
512
+
513
+ The following types are used throughout the market time utilities:
514
+
515
+ ```typescript
516
+ type Period = "1D" | "3D" | "1W" | "1M" | "3M" | "6M" | "1Y" | "YTD";
517
+ type Timeframe = "1Min" | "5Min" | "15Min" | "1H" | "1D";
518
+ type IntradayReporting = "market_hours" | "extended_hours" | "continuous";
519
+ type OutputFormat = "iso" | "unix-seconds" | "unix-ms";
520
+
521
+ interface MarketTimeParams {
522
+ period?: Period;
523
+ start?: Date;
524
+ end?: Date;
525
+ timezone?: string;
526
+ intraday_reporting?: IntradayReporting;
527
+ outputFormat?: OutputFormat;
528
+ }
529
+
530
+ interface PeriodDates {
531
+ start: string | number;
532
+ end: string | number;
533
+ }
534
+
535
+ interface MarketOpenCloseOptions {
536
+ date?: Date;
537
+ }
538
+
539
+ interface MarketOpenCloseResult {
540
+ marketOpen: boolean;
541
+ open: Date | null;
542
+ close: Date | null;
543
+ openExt: Date | null;
544
+ closeExt: Date | null;
545
+ }
546
+ ```
547
+
548
+ ### `createMarketTimeUtil(timezone?: string, intraday_reporting?: IntradayReporting): MarketTimeUtil`
549
+
550
+ Creates a utility for market time-related operations.
551
+
552
+ **Parameters:**
553
+
554
+ - `timezone?: string` - Optional timezone (default: 'America/New_York')
555
+ - `intraday_reporting?: IntradayReporting` - Optional intraday reporting mode:
556
+ - `'market_hours'` - Regular market hours (9:30 AM - 4:00 PM ET)
557
+ - `'extended_hours'` - Extended market hours (4:00 AM - 8:00 PM ET)
558
+ - `'continuous'` - All day, 24/7
559
+
560
+ **Returns:**
561
+
562
+ - `MarketTimeUtil` - Market time utility object
563
+
564
+ ### `getMarketOpenClose(options?: MarketOpenCloseOptions): MarketOpenCloseResult`
565
+
566
+ Gets market open/close times for both regular and extended hours for a given date.
567
+
568
+ **Parameters:**
569
+
570
+ - `options?: MarketOpenCloseOptions` - Optional parameters:
571
+ - `date?: Date` - The date to check (default: current date)
572
+
573
+ **Returns:**
574
+
575
+ - `MarketOpenCloseResult`:
576
+ ```typescript
577
+ {
578
+ marketOpen: boolean; // Whether the market is open on this date
579
+ open: Date | null; // Regular market hours open time
580
+ close: Date | null; // Regular market hours close time
581
+ openExt: Date | null; // Extended hours open time
582
+ closeExt: Date | null; // Extended hours close time
583
+ }
584
+ ```
585
+
586
+ **Example:**
587
+
588
+ ```typescript
589
+ const { marketOpen, open, close, openExt, closeExt } =
590
+ adaptic.time.getMarketOpenClose({
591
+ date: new Date("2024-12-24"),
592
+ });
593
+ ```
594
+
595
+ ### `getMarketStatus(options?: { date?: Date }): MarketStatus`
596
+
597
+ Gets the current market status and detailed information about market periods.
598
+
599
+ **Parameters:**
600
+
601
+ - `options?: object` - Optional parameters:
602
+ - `date?: Date` - The date to check (default: current date)
603
+
604
+ **Returns:**
605
+
606
+ - `MarketStatus`:
607
+ ```typescript
608
+ {
609
+ time: Date; // Current time
610
+ timeString: string; // Formatted time string
611
+ status: "closed" | "extended hours" | "open"; // Current market status
612
+ nextStatus: "closed" | "extended hours" | "open"; // Next market status
613
+ marketPeriod: "preMarket" |
614
+ "earlyMarket" |
615
+ "regularMarket" |
616
+ "afterMarket" |
617
+ "closed"; // Detailed market period
618
+ nextStatusTime: Date; // Time when next status begins
619
+ nextStatusTimeDifference: number; // Milliseconds until next status
620
+ nextStatusTimeString: string; // Formatted next status time
621
+ }
622
+ ```
623
+
624
+ The `marketPeriod` field indicates the specific trading period:
625
+
626
+ - `preMarket`: 4:00 AM - 9:30 AM ET
627
+ - `earlyMarket`: 9:30 AM - 10:00 AM ET
628
+ - `regularMarket`: 10:00 AM - Market Close (typically 4:00 PM ET)
629
+ - `afterMarket`: Market Close - 8:00 PM ET
630
+ - `closed`: Outside of all trading hours
631
+
632
+ **Example:**
633
+
634
+ ```typescript
635
+ const status = adaptic.time.getMarketStatus();
636
+ console.log(`Current market period: ${status.marketPeriod}`);
637
+ ```
638
+
639
+ ### `toUnixTimestamp(date: Date): number`
640
+
641
+ Converts a date to Unix timestamp.
642
+
643
+ **Parameters:**
644
+
645
+ - `date: Date` - The date to convert
646
+
647
+ **Returns:**
648
+
649
+ - `number` - Unix timestamp
650
+
651
+ ### `getTimeAgo(date: Date): string`
652
+
653
+ Returns a human-readable time difference from now.
654
+
655
+ **Parameters:**
656
+
657
+ - `date: Date` - The date to calculate from
658
+
659
+ **Returns:**
660
+
661
+ - `string` - Human-readable time difference (e.g., '1 minute ago')
662
+
663
+ ### `normalizeDate(date: Date): string`
664
+
665
+ Standardizes a date to a consistent format.
666
+
667
+ **Parameters:**
668
+
669
+ - `date: Date` - The date to standardize
670
+
671
+ **Returns:**
672
+
673
+ - `string` - Standardized date string (e.g., '2024-11-09')
674
+
675
+ ### `getDateInNY(time: number | string | { year: number; month: number; day: number }): Date`
676
+
677
+ Returns the current date in New York timezone.
678
+
679
+ **Parameters:**
680
+
681
+ - `time: number | string | { year: number; month: number; day: number }` - The time or date to convert
682
+
683
+ **Returns:**
684
+
685
+ - `Date` - Date in New York timezone
686
+
687
+ ### `getStartAndEndTimestamps(params: MarketTimeParams = {}): PeriodDates`
688
+
689
+ Generates start and end timestamps for a given period.
690
+
691
+ **Parameters:**
692
+
693
+ - `params: MarketTimeParams` - Optional parameters for the period
694
+
695
+ **Returns:**
696
+
697
+ - `PeriodDates` - Start and end timestamps for the period
698
+
699
+ ### `getStartAndEndDates(params: MarketTimeParams = {}): { start: Date; end: Date }`
700
+
701
+ Gets the start and end dates for a given period.
702
+
703
+ **Parameters:**
704
+
705
+ - `params: MarketTimeParams` - Optional parameters for the period
706
+
707
+ **Returns:**
708
+
709
+ - `{ start: Date; end: Date }` - Start and end dates for the period
710
+
711
+ ### `getLastTradingDateYYYYMMDD(): string`
712
+
713
+ Gets the last trading date in YYYY-MM-DD format.
714
+
715
+ **Returns:**
716
+
717
+ - `string` - Last trading date in YYYY-MM-DD format
718
+
719
+ ### `getLastFullTradingDate(currentDate?: Date): { date: Date; YYYYMMDD: string }`
720
+
721
+ Gets the last full trading date, considering market hours and holidays.
722
+
723
+ **Parameters:**
724
+
725
+ - `currentDate?: Date` - Optional reference date (defaults to current date)
726
+
727
+ **Returns:**
728
+
729
+ - Object containing:
730
+ - `date: Date` - The last full trading date
731
+ - `YYYYMMDD: string` - The date formatted as YYYY-MM-DD
732
+
733
+ ### `getNextMarketDay({ referenceDate?: Date }): { date: Date; yyyymmdd: string; dateISOString: string }`
734
+
735
+ Gets the next market day from a reference date.
736
+
737
+ **Parameters:**
738
+
739
+ - `referenceDate?: Date` - Optional reference date (defaults to current date)
740
+
741
+ **Returns:**
742
+
743
+ - Object containing:
744
+ - `date: Date` - The next market day (start of day in NY time)
745
+ - `yyyymmdd: string` - The date formatted as YYYY-MM-DD
746
+ - `dateISOString: string` - Full ISO date string
747
+
748
+ **Example:**
749
+
750
+ ```typescript
751
+ const nextMarketDay = adaptic.time.getNextMarketDay();
752
+ console.log(`Next market day: ${nextMarketDay.yyyymmdd}`);
753
+
754
+ // With reference date
755
+ const nextMarketDay = adaptic.time.getNextMarketDay({
756
+ referenceDate: new Date("2025-01-01"),
757
+ });
758
+ ```
759
+
760
+ ### `currentTimeET(): Date`
761
+
762
+ Gets the current time in Eastern Time.
763
+
764
+ **Returns:**
765
+
766
+ - `Date` - Current time in Eastern Time
767
+
768
+ ## Formatting Utilities
769
+
770
+ ### `capitalize(string: string): string`
771
+
772
+ Capitalizes the first letter of a string.
773
+
774
+ **Parameters:**
775
+
776
+ - `string: string` - The string to capitalize
777
+
778
+ **Returns:**
779
+
780
+ - `string` - Capitalized string
781
+
782
+ ### `formatEnum(enumValue: any): string`
783
+
784
+ Formats an enum value for display.
785
+
786
+ **Parameters:**
787
+
788
+ - `enumValue: any` - The enum value to format
789
+
790
+ **Returns:**
791
+
792
+ - `string` - Formatted enum value
793
+
794
+ ### `formatCurrency(value: number): string`
795
+
796
+ Formats a number as currency.
797
+
798
+ **Parameters:**
799
+
800
+ - `value: number` - The number to format
801
+
802
+ **Returns:**
803
+
804
+ - `string` - Formatted currency string
805
+
806
+ ### `formatPercentage(value: number): string`
807
+
808
+ Formats a number as a percentage.
809
+
810
+ **Parameters:**
811
+
812
+ - `value: number` - The number to format
813
+
814
+ **Returns:**
815
+
816
+ - `string` - Formatted percentage string
817
+
818
+ ## Misc utilities
819
+
820
+ ### `logIfDebug(message: string, data?: unknown, type: LogType = 'info' | 'warn' | 'error' | 'debug' | 'trace'): void`
821
+
822
+ Debug logging utility that respects environment debug flags.
823
+
824
+ **Parameters:**
825
+
826
+ - `message: string` - The log message
827
+ - `data?: unknown` - Optional data to log
828
+ - `type: LogType` - Optional log type (default: 'info')
829
+
830
+ ### `fetchWithRetry(url: string, options: RequestInit): Promise<Response>`
831
+
832
+ Fetches data from a URL with retry logic.
833
+
834
+ **Parameters:**
835
+
836
+ - `url: string` - The URL to fetch
837
+ - `options: RequestInit` - Optional fetch options
838
+
839
+ **Returns:**
840
+
841
+ - `Promise<Response>` - Fetched response
842
+
843
+ ## Alpaca API Utilities
844
+
845
+ This module provides several utility functions to interact with the Alpaca API, including fetching account details, placing orders, and retrieving market news.
846
+
847
+ ### Fetching News Articles
848
+
849
+ The `fetchNews` function retrieves news articles for specified symbols from the Alpaca API. It supports pagination and accepts various optional parameters to customize the query.
850
+
851
+ #### Usage
852
+
853
+ ```typescript
854
+ import { fetchNews } from "./alpaca";
855
+
856
+ // Example: Fetch news for a single symbol or multiple symbols (comma-separated)
857
+ const symbols = "AAPL,MSFT,GOOG"; // For multiple symbols, use a comma-separated string
858
+
859
+ (async () => {
860
+ try {
861
+ // Option 1: Pass Alpaca API credentials via the auth parameter
862
+ const newsData = await fetchNews(symbols, {
863
+ auth: {
864
+ alpacaApiKey: "YOUR_API_KEY",
865
+ alpacaApiSecret: "YOUR_API_SECRET",
866
+ },
867
+ start: new Date(Date.now() - 24 * 60 * 60 * 1000), // Default: last 24 hours
868
+ end: new Date(),
869
+ limit: 10,
870
+ sort: "desc",
871
+ });
872
+ console.log(newsData.news);
873
+
874
+ // Option 2: Rely on environment variables ALPACA_API_KEY and ALPACA_API_SECRET
875
+ const newsDataEnv = await fetchNews(symbols, {
876
+ start: new Date(Date.now() - 24 * 60 * 60 * 1000),
877
+ end: new Date(),
878
+ limit: 10,
879
+ sort: "desc",
880
+ });
881
+ console.log(newsDataEnv.news);
882
+
883
+ // Pagination
884
+ // fetchNews automatically fetches all pages if a next_page_token is provided by the API.
885
+ // The final returned result contains all aggregated news articles along with a `nextPageToken` (if any remain).
886
+ } catch (error) {
887
+ console.error(`Error fetching news: ${error}`);
888
+ }
889
+ })();
890
+ ```
891
+
892
+ #### Parameter Details
893
+
894
+ - **symbols**: A required string listing the symbols to fetch news for. For multiple symbols, separate them with commas (e.g., "AAPL,MSFT,GOOG").
895
+ - **params.auth**: (Optional) An object of type `AlpacaAuth` containing either:
896
+ - `alpacaApiKey` and `alpacaApiSecret` for direct authentication, or
897
+ - `adapticAccountId` to look up credentials from your backend via Adaptic.
898
+
899
+ If the `auth` parameter is not provided, the function will fallback to using the environment variables `ALPACA_API_KEY` and `ALPACA_API_SECRET`.
900
+
901
+ - **params.start** and **params.end**: Specify the date range (as a Date object or string) for the news articles. Defaults to the last 24 hours if not provided.
902
+ - **params.limit**: The maximum number of articles to return per page (default is 10).
903
+ - **params.sort**: The sort order for articles. Use `'asc'` for ascending order or `'desc'` for descending order (default is `'desc'`).
904
+ - **params.page_token**: A token for pagination. This is automatically handled by `fetchNews` if more results are available.
905
+
906
+ The function consolidates all pages of results and returns an object with a `news` array (of type `SimpleNews[]`) and an optional `nextPageToken`.
907
+
908
+ ## Contributing to the Repository
909
+
910
+ Contributions are welcome! Please submit a pull request or open an issue for any enhancements or bug fixes.
911
+
912
+ ## Author
913
+
914
+ This project is a product of [Lumic.ai](https://lumic.ai).
915
+
916
+ Thanks for reading this far! Why did the trader bring a ladder to the bar? Because they heard the drinks were on the house!