@discomedia/utils 1.0.30 → 1.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index-frontend.cjs.map +1 -1
- package/dist/index-frontend.mjs.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/package.json +1 -1
- package/dist/test.js +689 -81
- package/dist/test.js.map +1 -1
- package/dist/types/market-time.d.ts.map +1 -1
- package/dist/types-frontend/market-time.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/alpaca-trading-api-CPaXTnjf.js +0 -1412
- package/dist/alpaca-trading-api-CPaXTnjf.js.map +0 -1
|
@@ -1,1412 +0,0 @@
|
|
|
1
|
-
import { l as log, W as WebSocket, m as marketDataAPI } from './test.js';
|
|
2
|
-
import 'events';
|
|
3
|
-
import 'https';
|
|
4
|
-
import 'http';
|
|
5
|
-
import 'net';
|
|
6
|
-
import 'tls';
|
|
7
|
-
import 'crypto';
|
|
8
|
-
import 'stream';
|
|
9
|
-
import 'url';
|
|
10
|
-
import 'zlib';
|
|
11
|
-
import 'buffer';
|
|
12
|
-
import 'fs';
|
|
13
|
-
import 'path';
|
|
14
|
-
import 'os';
|
|
15
|
-
|
|
16
|
-
const limitPriceSlippagePercent100 = 0.1; // 0.1%
|
|
17
|
-
/**
|
|
18
|
-
Websocket example
|
|
19
|
-
const alpacaAPI = createAlpacaTradingAPI(credentials); // type AlpacaCredentials
|
|
20
|
-
alpacaAPI.onTradeUpdate((update: TradeUpdate) => {
|
|
21
|
-
this.log(`Received trade update: event ${update.event} for an order to ${update.order.side} ${update.order.qty} of ${update.order.symbol}`);
|
|
22
|
-
});
|
|
23
|
-
alpacaAPI.connectWebsocket(); // necessary to connect to the WebSocket
|
|
24
|
-
|
|
25
|
-
Portfolio History examples
|
|
26
|
-
// Get standard portfolio history
|
|
27
|
-
const portfolioHistory = await alpacaAPI.getPortfolioHistory({
|
|
28
|
-
timeframe: '1D',
|
|
29
|
-
period: '1M'
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
// Get daily portfolio history with current day included (if available from hourly data)
|
|
33
|
-
const dailyHistory = await alpacaAPI.getPortfolioDailyHistory({
|
|
34
|
-
period: '1M'
|
|
35
|
-
});
|
|
36
|
-
*/
|
|
37
|
-
class AlpacaTradingAPI {
|
|
38
|
-
static new(credentials) {
|
|
39
|
-
return new AlpacaTradingAPI(credentials);
|
|
40
|
-
}
|
|
41
|
-
static getInstance(credentials) {
|
|
42
|
-
return new AlpacaTradingAPI(credentials);
|
|
43
|
-
}
|
|
44
|
-
ws = null;
|
|
45
|
-
headers;
|
|
46
|
-
tradeUpdateCallback = null;
|
|
47
|
-
credentials;
|
|
48
|
-
apiBaseUrl;
|
|
49
|
-
wsUrl;
|
|
50
|
-
authenticated = false;
|
|
51
|
-
connecting = false;
|
|
52
|
-
reconnectDelay = 10000; // 10 seconds between reconnection attempts
|
|
53
|
-
reconnectTimeout = null;
|
|
54
|
-
messageHandlers = new Map();
|
|
55
|
-
debugLogging = false;
|
|
56
|
-
/**
|
|
57
|
-
* Constructor for AlpacaTradingAPI
|
|
58
|
-
* @param credentials - Alpaca credentials,
|
|
59
|
-
* accountName: string; // The account identifier used inthis.logs and tracking
|
|
60
|
-
* apiKey: string; // Alpaca API key
|
|
61
|
-
* apiSecret: string; // Alpaca API secret
|
|
62
|
-
* type: AlpacaAccountType;
|
|
63
|
-
* orderType: AlpacaOrderType;
|
|
64
|
-
* @param options - Optional options
|
|
65
|
-
* debugLogging: boolean; // Whether to log messages of type 'debug'
|
|
66
|
-
*/
|
|
67
|
-
constructor(credentials, options) {
|
|
68
|
-
this.credentials = credentials;
|
|
69
|
-
// Set URLs based on account type
|
|
70
|
-
this.apiBaseUrl =
|
|
71
|
-
credentials.type === 'PAPER' ? 'https://paper-api.alpaca.markets/v2' : 'https://api.alpaca.markets/v2';
|
|
72
|
-
this.wsUrl =
|
|
73
|
-
credentials.type === 'PAPER' ? 'wss://paper-api.alpaca.markets/stream' : 'wss://api.alpaca.markets/stream';
|
|
74
|
-
this.headers = {
|
|
75
|
-
'APCA-API-KEY-ID': credentials.apiKey,
|
|
76
|
-
'APCA-API-SECRET-KEY': credentials.apiSecret,
|
|
77
|
-
'Content-Type': 'application/json',
|
|
78
|
-
};
|
|
79
|
-
// Initialize message handlers
|
|
80
|
-
this.messageHandlers.set('authorization', this.handleAuthMessage.bind(this));
|
|
81
|
-
this.messageHandlers.set('listening', this.handleListenMessage.bind(this));
|
|
82
|
-
this.messageHandlers.set('trade_updates', this.handleTradeUpdate.bind(this));
|
|
83
|
-
this.debugLogging = options?.debugLogging || false;
|
|
84
|
-
}
|
|
85
|
-
log(message, options = { type: 'info' }) {
|
|
86
|
-
if (this.debugLogging && options.type === 'debug') {
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
log(message, { ...options, source: 'AlpacaTradingAPI', account: this.credentials.accountName });
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* Round a price to the nearest 2 decimal places for Alpaca, or 4 decimal places for prices less than $1
|
|
93
|
-
* @param price - The price to round
|
|
94
|
-
* @returns The rounded price
|
|
95
|
-
*/
|
|
96
|
-
roundPriceForAlpaca = (price) => {
|
|
97
|
-
return price >= 1 ? Math.round(price * 100) / 100 : Math.round(price * 10000) / 10000;
|
|
98
|
-
};
|
|
99
|
-
handleAuthMessage(data) {
|
|
100
|
-
if (data.status === 'authorized') {
|
|
101
|
-
this.authenticated = true;
|
|
102
|
-
this.log('WebSocket authenticated');
|
|
103
|
-
}
|
|
104
|
-
else {
|
|
105
|
-
this.log(`Authentication failed: ${data.message || 'Unknown error'}`, {
|
|
106
|
-
type: 'error',
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
handleListenMessage(data) {
|
|
111
|
-
if (data.streams?.includes('trade_updates')) {
|
|
112
|
-
this.log('Successfully subscribed to trade updates');
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
handleTradeUpdate(data) {
|
|
116
|
-
if (this.tradeUpdateCallback) {
|
|
117
|
-
this.log(`Trade update: ${data.event} to ${data.order.side} ${data.order.qty} shares, type ${data.order.type}`, {
|
|
118
|
-
symbol: data.order.symbol,
|
|
119
|
-
type: 'debug',
|
|
120
|
-
});
|
|
121
|
-
this.tradeUpdateCallback(data);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
handleMessage(message) {
|
|
125
|
-
try {
|
|
126
|
-
const data = JSON.parse(message);
|
|
127
|
-
const handler = this.messageHandlers.get(data.stream);
|
|
128
|
-
if (handler) {
|
|
129
|
-
handler(data.data);
|
|
130
|
-
}
|
|
131
|
-
else {
|
|
132
|
-
this.log(`Received message for unknown stream: ${data.stream}`, {
|
|
133
|
-
type: 'warn',
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
catch (error) {
|
|
138
|
-
this.log('Failed to parse WebSocket message', {
|
|
139
|
-
type: 'error',
|
|
140
|
-
metadata: { error: error instanceof Error ? error.message : 'Unknown error' },
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
connectWebsocket() {
|
|
145
|
-
if (this.connecting) {
|
|
146
|
-
this.log('Connection attempt skipped - already connecting');
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
149
|
-
if (this.ws?.readyState === WebSocket.OPEN) {
|
|
150
|
-
this.log('Connection attempt skipped - already connected');
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
this.connecting = true;
|
|
154
|
-
if (this.ws) {
|
|
155
|
-
this.ws.removeAllListeners();
|
|
156
|
-
this.ws.terminate();
|
|
157
|
-
this.ws = null;
|
|
158
|
-
}
|
|
159
|
-
this.log(`Connecting to WebSocket at ${this.wsUrl}...`);
|
|
160
|
-
this.ws = new WebSocket(this.wsUrl);
|
|
161
|
-
this.ws.on('open', async () => {
|
|
162
|
-
try {
|
|
163
|
-
this.log('WebSocket connected');
|
|
164
|
-
await this.authenticate();
|
|
165
|
-
await this.subscribeToTradeUpdates();
|
|
166
|
-
this.connecting = false;
|
|
167
|
-
}
|
|
168
|
-
catch (error) {
|
|
169
|
-
this.log('Failed to setup WebSocket connection', {
|
|
170
|
-
type: 'error',
|
|
171
|
-
metadata: { error: error instanceof Error ? error.message : 'Unknown error' },
|
|
172
|
-
});
|
|
173
|
-
this.ws?.close();
|
|
174
|
-
}
|
|
175
|
-
});
|
|
176
|
-
this.ws.on('message', (data) => {
|
|
177
|
-
this.handleMessage(data.toString());
|
|
178
|
-
});
|
|
179
|
-
this.ws.on('error', (error) => {
|
|
180
|
-
this.log('WebSocket error', {
|
|
181
|
-
type: 'error',
|
|
182
|
-
metadata: { error: error instanceof Error ? error.message : 'Unknown error' },
|
|
183
|
-
});
|
|
184
|
-
this.connecting = false;
|
|
185
|
-
});
|
|
186
|
-
this.ws.on('close', () => {
|
|
187
|
-
this.log('WebSocket connection closed');
|
|
188
|
-
this.authenticated = false;
|
|
189
|
-
this.connecting = false;
|
|
190
|
-
// Clear any existing reconnect timeout
|
|
191
|
-
if (this.reconnectTimeout) {
|
|
192
|
-
clearTimeout(this.reconnectTimeout);
|
|
193
|
-
this.reconnectTimeout = null;
|
|
194
|
-
}
|
|
195
|
-
// Schedule reconnection
|
|
196
|
-
this.reconnectTimeout = setTimeout(() => {
|
|
197
|
-
this.log('Attempting to reconnect...');
|
|
198
|
-
this.connectWebsocket();
|
|
199
|
-
}, this.reconnectDelay);
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
async authenticate() {
|
|
203
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
204
|
-
throw new Error('WebSocket not ready for authentication');
|
|
205
|
-
}
|
|
206
|
-
const authMessage = {
|
|
207
|
-
action: 'auth',
|
|
208
|
-
key: this.credentials.apiKey,
|
|
209
|
-
secret: this.credentials.apiSecret,
|
|
210
|
-
};
|
|
211
|
-
this.ws.send(JSON.stringify(authMessage));
|
|
212
|
-
return new Promise((resolve, reject) => {
|
|
213
|
-
const authTimeout = setTimeout(() => {
|
|
214
|
-
this.log('Authentication timeout', { type: 'error' });
|
|
215
|
-
reject(new Error('Authentication timed out'));
|
|
216
|
-
}, 10000);
|
|
217
|
-
const handleAuthResponse = (data) => {
|
|
218
|
-
try {
|
|
219
|
-
const message = JSON.parse(data.toString());
|
|
220
|
-
if (message.stream === 'authorization') {
|
|
221
|
-
this.ws?.removeListener('message', handleAuthResponse);
|
|
222
|
-
clearTimeout(authTimeout);
|
|
223
|
-
if (message.data?.status === 'authorized') {
|
|
224
|
-
this.authenticated = true;
|
|
225
|
-
resolve();
|
|
226
|
-
}
|
|
227
|
-
else {
|
|
228
|
-
const error = `Authentication failed: ${message.data?.message || 'Unknown error'}`;
|
|
229
|
-
this.log(error, { type: 'error' });
|
|
230
|
-
reject(new Error(error));
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
catch (error) {
|
|
235
|
-
this.log('Failed to parse auth response', {
|
|
236
|
-
type: 'error',
|
|
237
|
-
metadata: { error: error instanceof Error ? error.message : 'Unknown error' },
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
};
|
|
241
|
-
this.ws?.on('message', handleAuthResponse);
|
|
242
|
-
});
|
|
243
|
-
}
|
|
244
|
-
async subscribeToTradeUpdates() {
|
|
245
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.authenticated) {
|
|
246
|
-
throw new Error('WebSocket not ready for subscription');
|
|
247
|
-
}
|
|
248
|
-
const listenMessage = {
|
|
249
|
-
action: 'listen',
|
|
250
|
-
data: {
|
|
251
|
-
streams: ['trade_updates'],
|
|
252
|
-
},
|
|
253
|
-
};
|
|
254
|
-
this.ws.send(JSON.stringify(listenMessage));
|
|
255
|
-
return new Promise((resolve, reject) => {
|
|
256
|
-
const listenTimeout = setTimeout(() => {
|
|
257
|
-
reject(new Error('Subscribe timeout'));
|
|
258
|
-
}, 10000);
|
|
259
|
-
const handleListenResponse = (data) => {
|
|
260
|
-
try {
|
|
261
|
-
const message = JSON.parse(data.toString());
|
|
262
|
-
if (message.stream === 'listening') {
|
|
263
|
-
this.ws?.removeListener('message', handleListenResponse);
|
|
264
|
-
clearTimeout(listenTimeout);
|
|
265
|
-
if (message.data?.streams?.includes('trade_updates')) {
|
|
266
|
-
resolve();
|
|
267
|
-
}
|
|
268
|
-
else {
|
|
269
|
-
reject(new Error('Failed to subscribe to trade updates'));
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
catch (error) {
|
|
274
|
-
this.log('Failed to parse listen response', {
|
|
275
|
-
type: 'error',
|
|
276
|
-
metadata: { error: error instanceof Error ? error.message : 'Unknown error' },
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
};
|
|
280
|
-
this.ws?.on('message', handleListenResponse);
|
|
281
|
-
});
|
|
282
|
-
}
|
|
283
|
-
async makeRequest(endpoint, method = 'GET', body, queryString = '') {
|
|
284
|
-
const url = `${this.apiBaseUrl}${endpoint}${queryString}`;
|
|
285
|
-
try {
|
|
286
|
-
const response = await fetch(url, {
|
|
287
|
-
method,
|
|
288
|
-
headers: this.headers,
|
|
289
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
290
|
-
});
|
|
291
|
-
if (!response.ok) {
|
|
292
|
-
const errorText = await response.text();
|
|
293
|
-
this.log(`Alpaca API error (${response.status}): ${errorText}`, { type: 'error' });
|
|
294
|
-
throw new Error(`Alpaca API error (${response.status}): ${errorText}`);
|
|
295
|
-
}
|
|
296
|
-
// Handle responses with no content (e.g., 204 No Content)
|
|
297
|
-
if (response.status === 204 || response.headers.get('content-length') === '0') {
|
|
298
|
-
return null;
|
|
299
|
-
}
|
|
300
|
-
const contentType = response.headers.get('content-type');
|
|
301
|
-
if (contentType && contentType.includes('application/json')) {
|
|
302
|
-
return await response.json();
|
|
303
|
-
}
|
|
304
|
-
// For non-JSON responses, return the text content
|
|
305
|
-
const textContent = await response.text();
|
|
306
|
-
return textContent || null;
|
|
307
|
-
}
|
|
308
|
-
catch (err) {
|
|
309
|
-
const error = err;
|
|
310
|
-
this.log(`Error in makeRequest: ${error.message}. Url: ${url}`, {
|
|
311
|
-
source: 'AlpacaAPI',
|
|
312
|
-
type: 'error',
|
|
313
|
-
});
|
|
314
|
-
throw error;
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
async getPositions(assetClass) {
|
|
318
|
-
const positions = (await this.makeRequest('/positions'));
|
|
319
|
-
if (assetClass) {
|
|
320
|
-
return positions.filter((position) => position.asset_class === assetClass);
|
|
321
|
-
}
|
|
322
|
-
return positions;
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
|
-
* Get all orders
|
|
326
|
-
* @param params (GetOrdersParams) - optional parameters to filter the orders
|
|
327
|
-
* - status: 'open' | 'closed' | 'all'
|
|
328
|
-
* - limit: number
|
|
329
|
-
* - after: string
|
|
330
|
-
* - until: string
|
|
331
|
-
* - direction: 'asc' | 'desc'
|
|
332
|
-
* - nested: boolean
|
|
333
|
-
* - symbols: string[], an array of all the symbols
|
|
334
|
-
* - side: 'buy' | 'sell'
|
|
335
|
-
* @returns all orders
|
|
336
|
-
*/
|
|
337
|
-
async getOrders(params = {}) {
|
|
338
|
-
const queryParams = new URLSearchParams();
|
|
339
|
-
if (params.status)
|
|
340
|
-
queryParams.append('status', params.status);
|
|
341
|
-
if (params.limit)
|
|
342
|
-
queryParams.append('limit', params.limit.toString());
|
|
343
|
-
if (params.after)
|
|
344
|
-
queryParams.append('after', params.after);
|
|
345
|
-
if (params.until)
|
|
346
|
-
queryParams.append('until', params.until);
|
|
347
|
-
if (params.direction)
|
|
348
|
-
queryParams.append('direction', params.direction);
|
|
349
|
-
if (params.nested)
|
|
350
|
-
queryParams.append('nested', params.nested.toString());
|
|
351
|
-
if (params.symbols)
|
|
352
|
-
queryParams.append('symbols', params.symbols.join(','));
|
|
353
|
-
if (params.side)
|
|
354
|
-
queryParams.append('side', params.side);
|
|
355
|
-
const endpoint = `/orders${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;
|
|
356
|
-
try {
|
|
357
|
-
return await this.makeRequest(endpoint);
|
|
358
|
-
}
|
|
359
|
-
catch (error) {
|
|
360
|
-
this.log(`Error getting orders: ${error}`, { type: 'error' });
|
|
361
|
-
throw error;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
async getAccountDetails() {
|
|
365
|
-
try {
|
|
366
|
-
return await this.makeRequest('/account');
|
|
367
|
-
}
|
|
368
|
-
catch (error) {
|
|
369
|
-
this.log(`Error getting account details: ${error}`, { type: 'error' });
|
|
370
|
-
throw error;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Create a trailing stop order
|
|
375
|
-
* @param symbol (string) - the symbol of the order
|
|
376
|
-
* @param qty (number) - the quantity of the order
|
|
377
|
-
* @param side (string) - the side of the order
|
|
378
|
-
* @param trailPercent100 (number) - the trail percent of the order (scale 100, i.e. 0.5 = 0.5%)
|
|
379
|
-
* @param position_intent (string) - the position intent of the order
|
|
380
|
-
*/
|
|
381
|
-
async createTrailingStop(symbol, qty, side, trailPercent100, position_intent) {
|
|
382
|
-
this.log(`Creating trailing stop ${side.toUpperCase()} ${qty} shares for ${symbol} with trail percent ${trailPercent100}%`, {
|
|
383
|
-
symbol,
|
|
384
|
-
});
|
|
385
|
-
try {
|
|
386
|
-
await this.makeRequest(`/orders`, 'POST', {
|
|
387
|
-
symbol,
|
|
388
|
-
qty: Math.abs(qty),
|
|
389
|
-
side,
|
|
390
|
-
position_intent,
|
|
391
|
-
order_class: 'simple',
|
|
392
|
-
type: 'trailing_stop',
|
|
393
|
-
trail_percent: trailPercent100, // Already in decimal form (e.g., 4 for 4%)
|
|
394
|
-
time_in_force: 'gtc',
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
catch (error) {
|
|
398
|
-
this.log(`Error creating trailing stop: ${error}`, {
|
|
399
|
-
symbol,
|
|
400
|
-
type: 'error',
|
|
401
|
-
});
|
|
402
|
-
throw error;
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* Create a market order
|
|
407
|
-
* @param symbol (string) - the symbol of the order
|
|
408
|
-
* @param qty (number) - the quantity of the order
|
|
409
|
-
* @param side (string) - the side of the order
|
|
410
|
-
* @param position_intent (string) - the position intent of the order. Important for knowing if a position needs a trailing stop.
|
|
411
|
-
*/
|
|
412
|
-
async createMarketOrder(symbol, qty, side, position_intent, client_order_id) {
|
|
413
|
-
this.log(`Creating market order for ${symbol}: ${side} ${qty} shares (${position_intent})`, {
|
|
414
|
-
symbol,
|
|
415
|
-
});
|
|
416
|
-
const body = {
|
|
417
|
-
symbol,
|
|
418
|
-
qty: Math.abs(qty).toString(),
|
|
419
|
-
side,
|
|
420
|
-
position_intent,
|
|
421
|
-
type: 'market',
|
|
422
|
-
time_in_force: 'day',
|
|
423
|
-
order_class: 'simple',
|
|
424
|
-
};
|
|
425
|
-
if (client_order_id !== undefined) {
|
|
426
|
-
body.client_order_id = client_order_id;
|
|
427
|
-
}
|
|
428
|
-
try {
|
|
429
|
-
return await this.makeRequest('/orders', 'POST', body);
|
|
430
|
-
}
|
|
431
|
-
catch (error) {
|
|
432
|
-
this.log(`Error creating market order: ${error}`, { type: 'error' });
|
|
433
|
-
throw error;
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
/**
|
|
437
|
-
* Get the current trail percent for a symbol, assuming that it has an open position and a trailing stop order to close it. Because this relies on an orders request for one symbol, you can't do it too often.
|
|
438
|
-
* @param symbol (string) - the symbol of the order
|
|
439
|
-
* @returns the current trail percent
|
|
440
|
-
*/
|
|
441
|
-
async getCurrentTrailPercent(symbol) {
|
|
442
|
-
try {
|
|
443
|
-
const orders = await this.getOrders({
|
|
444
|
-
status: 'open',
|
|
445
|
-
symbols: [symbol],
|
|
446
|
-
});
|
|
447
|
-
const trailingStopOrder = orders.find((order) => order.type === 'trailing_stop' &&
|
|
448
|
-
(order.position_intent === 'sell_to_close' || order.position_intent === 'buy_to_close'));
|
|
449
|
-
if (!trailingStopOrder) {
|
|
450
|
-
this.log(`No closing trailing stop order found for ${symbol}`, {
|
|
451
|
-
symbol,
|
|
452
|
-
});
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
if (!trailingStopOrder.trail_percent) {
|
|
456
|
-
this.log(`Trailing stop order found for ${symbol} but no trail_percent value`, {
|
|
457
|
-
symbol,
|
|
458
|
-
});
|
|
459
|
-
return null;
|
|
460
|
-
}
|
|
461
|
-
const trailPercent = parseFloat(trailingStopOrder.trail_percent);
|
|
462
|
-
return trailPercent;
|
|
463
|
-
}
|
|
464
|
-
catch (error) {
|
|
465
|
-
this.log(`Error getting current trail percent: ${error}`, {
|
|
466
|
-
symbol,
|
|
467
|
-
type: 'error',
|
|
468
|
-
});
|
|
469
|
-
throw error;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
/**
|
|
473
|
-
* Update the trail percent for a trailing stop order
|
|
474
|
-
* @param symbol (string) - the symbol of the order
|
|
475
|
-
* @param trailPercent100 (number) - the trail percent of the order (scale 100, i.e. 0.5 = 0.5%)
|
|
476
|
-
*/
|
|
477
|
-
async updateTrailingStop(symbol, trailPercent100) {
|
|
478
|
-
// First get all open orders for this symbol
|
|
479
|
-
const orders = await this.getOrders({
|
|
480
|
-
status: 'open',
|
|
481
|
-
symbols: [symbol],
|
|
482
|
-
});
|
|
483
|
-
// Find the trailing stop order
|
|
484
|
-
const trailingStopOrder = orders.find((order) => order.type === 'trailing_stop');
|
|
485
|
-
if (!trailingStopOrder) {
|
|
486
|
-
this.log(`No open trailing stop order found for ${symbol}`, { type: 'error', symbol });
|
|
487
|
-
return;
|
|
488
|
-
}
|
|
489
|
-
// Check if the trail_percent is already set to the desired value
|
|
490
|
-
const currentTrailPercent = trailingStopOrder.trail_percent ? parseFloat(trailingStopOrder.trail_percent) : null;
|
|
491
|
-
// Compare with a small epsilon to handle floating point precision
|
|
492
|
-
const epsilon = 0.0001;
|
|
493
|
-
if (currentTrailPercent !== null && Math.abs(currentTrailPercent - trailPercent100) < epsilon) {
|
|
494
|
-
this.log(`Trailing stop for ${symbol} already set to ${trailPercent100}% (current: ${currentTrailPercent}%), skipping update`, {
|
|
495
|
-
symbol,
|
|
496
|
-
});
|
|
497
|
-
return;
|
|
498
|
-
}
|
|
499
|
-
this.log(`Updating trailing stop for ${symbol} from ${currentTrailPercent}% to ${trailPercent100}%`, {
|
|
500
|
-
symbol,
|
|
501
|
-
});
|
|
502
|
-
try {
|
|
503
|
-
await this.makeRequest(`/orders/${trailingStopOrder.id}`, 'PATCH', {
|
|
504
|
-
trail: trailPercent100.toString(), // Changed from trail_percent to trail
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
catch (error) {
|
|
508
|
-
this.log(`Error updating trailing stop: ${error}`, {
|
|
509
|
-
symbol,
|
|
510
|
-
type: 'error',
|
|
511
|
-
});
|
|
512
|
-
throw error;
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Cancel all open orders
|
|
517
|
-
*/
|
|
518
|
-
async cancelAllOrders() {
|
|
519
|
-
this.log(`Canceling all open orders`);
|
|
520
|
-
try {
|
|
521
|
-
await this.makeRequest('/orders', 'DELETE');
|
|
522
|
-
}
|
|
523
|
-
catch (error) {
|
|
524
|
-
this.log(`Error canceling all orders: ${error}`, { type: 'error' });
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
/**
|
|
528
|
-
* Cancel a specific order by its ID
|
|
529
|
-
* @param orderId The id of the order to cancel
|
|
530
|
-
* @throws Error if the order is not cancelable (status 422) or if the order doesn't exist
|
|
531
|
-
* @returns Promise that resolves when the order is successfully canceled
|
|
532
|
-
*/
|
|
533
|
-
async cancelOrder(orderId) {
|
|
534
|
-
this.log(`Attempting to cancel order ${orderId}`);
|
|
535
|
-
try {
|
|
536
|
-
await this.makeRequest(`/orders/${orderId}`, 'DELETE');
|
|
537
|
-
this.log(`Successfully canceled order ${orderId}`);
|
|
538
|
-
}
|
|
539
|
-
catch (error) {
|
|
540
|
-
// If the error is a 422, it means the order is not cancelable
|
|
541
|
-
if (error instanceof Error && error.message.includes('422')) {
|
|
542
|
-
this.log(`Order ${orderId} is not cancelable`, {
|
|
543
|
-
type: 'error',
|
|
544
|
-
});
|
|
545
|
-
throw new Error(`Order ${orderId} is not cancelable`);
|
|
546
|
-
}
|
|
547
|
-
// Re-throw other errors
|
|
548
|
-
throw error;
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
/**
|
|
552
|
-
* Create a limit order
|
|
553
|
-
* @param symbol (string) - the symbol of the order
|
|
554
|
-
* @param qty (number) - the quantity of the order
|
|
555
|
-
* @param side (string) - the side of the order
|
|
556
|
-
* @param limitPrice (number) - the limit price of the order
|
|
557
|
-
* @param position_intent (string) - the position intent of the order
|
|
558
|
-
* @param extended_hours (boolean) - whether the order is in extended hours
|
|
559
|
-
* @param client_order_id (string) - the client order id of the order
|
|
560
|
-
*/
|
|
561
|
-
async createLimitOrder(symbol, qty, side, limitPrice, position_intent, extended_hours = false, client_order_id) {
|
|
562
|
-
this.log(`Creating limit order for ${symbol}: ${side} ${qty} shares at $${limitPrice.toFixed(2)} (${position_intent})`, {
|
|
563
|
-
symbol,
|
|
564
|
-
});
|
|
565
|
-
const body = {
|
|
566
|
-
symbol,
|
|
567
|
-
qty: Math.abs(qty).toString(),
|
|
568
|
-
side,
|
|
569
|
-
position_intent,
|
|
570
|
-
type: 'limit',
|
|
571
|
-
limit_price: this.roundPriceForAlpaca(limitPrice).toString(),
|
|
572
|
-
time_in_force: 'day',
|
|
573
|
-
order_class: 'simple',
|
|
574
|
-
extended_hours,
|
|
575
|
-
};
|
|
576
|
-
if (client_order_id !== undefined) {
|
|
577
|
-
body.client_order_id = client_order_id;
|
|
578
|
-
}
|
|
579
|
-
try {
|
|
580
|
-
return await this.makeRequest('/orders', 'POST', body);
|
|
581
|
-
}
|
|
582
|
-
catch (error) {
|
|
583
|
-
this.log(`Error creating limit order: ${error}`, { type: 'error' });
|
|
584
|
-
throw error;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
/**
|
|
588
|
-
* Close all equities positions
|
|
589
|
-
* @param options (object) - the options for closing the positions
|
|
590
|
-
* - cancel_orders (boolean) - whether to cancel related orders
|
|
591
|
-
* - useLimitOrders (boolean) - whether to use limit orders to close the positions
|
|
592
|
-
*/
|
|
593
|
-
async closeAllPositions(options = { cancel_orders: true, useLimitOrders: false }) {
|
|
594
|
-
this.log(`Closing all positions${options.useLimitOrders ? ' using limit orders' : ''}${options.cancel_orders ? ' and canceling open orders' : ''}`);
|
|
595
|
-
if (options.useLimitOrders) {
|
|
596
|
-
// Get all positions
|
|
597
|
-
const positions = await this.getPositions('us_equity');
|
|
598
|
-
if (positions.length === 0) {
|
|
599
|
-
this.log('No positions to close');
|
|
600
|
-
return;
|
|
601
|
-
}
|
|
602
|
-
this.log(`Found ${positions.length} positions to close`);
|
|
603
|
-
// Get latest quotes for all positions
|
|
604
|
-
const symbols = positions.map((position) => position.symbol);
|
|
605
|
-
const quotesResponse = await marketDataAPI.getLatestQuotes(symbols);
|
|
606
|
-
const lengthOfQuotes = Object.keys(quotesResponse.quotes).length;
|
|
607
|
-
if (lengthOfQuotes === 0) {
|
|
608
|
-
this.log('No quotes available for positions, received 0 quotes', {
|
|
609
|
-
type: 'error',
|
|
610
|
-
});
|
|
611
|
-
return;
|
|
612
|
-
}
|
|
613
|
-
if (lengthOfQuotes !== positions.length) {
|
|
614
|
-
this.log(`Received ${lengthOfQuotes} quotes for ${positions.length} positions, expected ${positions.length} quotes`, { type: 'warn' });
|
|
615
|
-
return;
|
|
616
|
-
}
|
|
617
|
-
// Create limit orders to close each position
|
|
618
|
-
for (const position of positions) {
|
|
619
|
-
const quote = quotesResponse.quotes[position.symbol];
|
|
620
|
-
if (!quote) {
|
|
621
|
-
this.log(`No quote available for ${position.symbol}, skipping limit order`, {
|
|
622
|
-
symbol: position.symbol,
|
|
623
|
-
type: 'warn',
|
|
624
|
-
});
|
|
625
|
-
continue;
|
|
626
|
-
}
|
|
627
|
-
const qty = Math.abs(parseFloat(position.qty));
|
|
628
|
-
const side = position.side === 'long' ? 'sell' : 'buy';
|
|
629
|
-
const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';
|
|
630
|
-
// Get the current price from the quote
|
|
631
|
-
const currentPrice = side === 'sell' ? quote.bp : quote.ap; // Use bid for sells, ask for buys
|
|
632
|
-
if (!currentPrice) {
|
|
633
|
-
this.log(`No valid price available for ${position.symbol}, skipping limit order`, {
|
|
634
|
-
symbol: position.symbol,
|
|
635
|
-
type: 'warn',
|
|
636
|
-
});
|
|
637
|
-
continue;
|
|
638
|
-
}
|
|
639
|
-
// Apply slippage from config
|
|
640
|
-
const limitSlippagePercent1 = limitPriceSlippagePercent100 / 100;
|
|
641
|
-
const limitPrice = side === 'sell'
|
|
642
|
-
? this.roundPriceForAlpaca(currentPrice * (1 - limitSlippagePercent1)) // Sell slightly lower
|
|
643
|
-
: this.roundPriceForAlpaca(currentPrice * (1 + limitSlippagePercent1)); // Buy slightly higher
|
|
644
|
-
this.log(`Creating limit order to close ${position.symbol} position: ${side} ${qty} shares at $${limitPrice.toFixed(2)}`, {
|
|
645
|
-
symbol: position.symbol,
|
|
646
|
-
});
|
|
647
|
-
await this.createLimitOrder(position.symbol, qty, side, limitPrice, positionIntent);
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
else {
|
|
651
|
-
await this.makeRequest('/positions', 'DELETE', undefined, options.cancel_orders ? '?cancel_orders=true' : '');
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
/**
|
|
655
|
-
* Close all equities positions using limit orders during extended hours trading
|
|
656
|
-
* @param cancelOrders Whether to cancel related orders (default: true)
|
|
657
|
-
* @returns Promise that resolves when all positions are closed
|
|
658
|
-
*/
|
|
659
|
-
async closeAllPositionsAfterHours() {
|
|
660
|
-
this.log('Closing all positions using limit orders during extended hours trading');
|
|
661
|
-
// Get all positions
|
|
662
|
-
const positions = await this.getPositions();
|
|
663
|
-
this.log(`Found ${positions.length} positions to close`);
|
|
664
|
-
if (positions.length === 0) {
|
|
665
|
-
this.log('No positions to close');
|
|
666
|
-
return;
|
|
667
|
-
}
|
|
668
|
-
await this.cancelAllOrders();
|
|
669
|
-
this.log(`Cancelled all open orders`);
|
|
670
|
-
// Get latest quotes for all positions
|
|
671
|
-
const symbols = positions.map((position) => position.symbol);
|
|
672
|
-
const quotesResponse = await marketDataAPI.getLatestQuotes(symbols);
|
|
673
|
-
// Create limit orders to close each position
|
|
674
|
-
for (const position of positions) {
|
|
675
|
-
const quote = quotesResponse.quotes[position.symbol];
|
|
676
|
-
if (!quote) {
|
|
677
|
-
this.log(`No quote available for ${position.symbol}, skipping limit order`, {
|
|
678
|
-
symbol: position.symbol,
|
|
679
|
-
type: 'warn',
|
|
680
|
-
});
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
const qty = Math.abs(parseFloat(position.qty));
|
|
684
|
-
const side = position.side === 'long' ? 'sell' : 'buy';
|
|
685
|
-
const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';
|
|
686
|
-
// Get the current price from the quote
|
|
687
|
-
const currentPrice = side === 'sell' ? quote.bp : quote.ap; // Use bid for sells, ask for buys
|
|
688
|
-
if (!currentPrice) {
|
|
689
|
-
this.log(`No valid price available for ${position.symbol}, skipping limit order`, {
|
|
690
|
-
symbol: position.symbol,
|
|
691
|
-
type: 'warn',
|
|
692
|
-
});
|
|
693
|
-
continue;
|
|
694
|
-
}
|
|
695
|
-
// Apply slippage from config
|
|
696
|
-
const limitSlippagePercent1 = limitPriceSlippagePercent100 / 100;
|
|
697
|
-
const limitPrice = side === 'sell'
|
|
698
|
-
? this.roundPriceForAlpaca(currentPrice * (1 - limitSlippagePercent1)) // Sell slightly lower
|
|
699
|
-
: this.roundPriceForAlpaca(currentPrice * (1 + limitSlippagePercent1)); // Buy slightly higher
|
|
700
|
-
this.log(`Creating extended hours limit order to close ${position.symbol} position: ${side} ${qty} shares at $${limitPrice.toFixed(2)}`, {
|
|
701
|
-
symbol: position.symbol,
|
|
702
|
-
});
|
|
703
|
-
await this.createLimitOrder(position.symbol, qty, side, limitPrice, positionIntent, true // Enable extended hours trading
|
|
704
|
-
);
|
|
705
|
-
}
|
|
706
|
-
this.log(`All positions closed: ${positions.map((p) => p.symbol).join(', ')}`);
|
|
707
|
-
}
|
|
708
|
-
onTradeUpdate(callback) {
|
|
709
|
-
this.tradeUpdateCallback = callback;
|
|
710
|
-
}
|
|
711
|
-
/**
|
|
712
|
-
* Get portfolio history for the account
|
|
713
|
-
* @param params Parameters for the portfolio history request
|
|
714
|
-
* @returns Portfolio history data
|
|
715
|
-
*/
|
|
716
|
-
async getPortfolioHistory(params) {
|
|
717
|
-
const queryParams = new URLSearchParams();
|
|
718
|
-
if (params.timeframe)
|
|
719
|
-
queryParams.append('timeframe', params.timeframe);
|
|
720
|
-
if (params.period)
|
|
721
|
-
queryParams.append('period', params.period);
|
|
722
|
-
if (params.extended_hours !== undefined)
|
|
723
|
-
queryParams.append('extended_hours', params.extended_hours.toString());
|
|
724
|
-
if (params.start)
|
|
725
|
-
queryParams.append('start', params.start);
|
|
726
|
-
if (params.end)
|
|
727
|
-
queryParams.append('end', params.end);
|
|
728
|
-
if (params.date_end)
|
|
729
|
-
queryParams.append('date_end', params.date_end);
|
|
730
|
-
const response = await this.makeRequest(`/account/portfolio/history?${queryParams.toString()}`);
|
|
731
|
-
return response;
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* Get portfolio daily history for the account, ensuring the most recent day is included
|
|
735
|
-
* by combining daily and hourly history if needed.
|
|
736
|
-
*
|
|
737
|
-
* This function performs two API calls:
|
|
738
|
-
* 1. Retrieves daily portfolio history
|
|
739
|
-
* 2. Retrieves hourly portfolio history to check for more recent data
|
|
740
|
-
*
|
|
741
|
-
* If hourly history has timestamps more recent than the last timestamp in daily history,
|
|
742
|
-
* it appends one additional day to the daily history using the most recent hourly values.
|
|
743
|
-
*
|
|
744
|
-
* @param params Parameters for the portfolio history request (same as getPortfolioHistory except timeframe is forced to '1D')
|
|
745
|
-
* @returns Portfolio history data with daily timeframe, including the most recent day if available from hourly data
|
|
746
|
-
*/
|
|
747
|
-
async getPortfolioDailyHistory(params) {
|
|
748
|
-
// Get daily and hourly history in parallel
|
|
749
|
-
const dailyParams = { ...params, timeframe: '1D' };
|
|
750
|
-
const hourlyParams = { timeframe: '1Min', period: '1D' };
|
|
751
|
-
const [dailyHistory, hourlyHistory] = await Promise.all([
|
|
752
|
-
this.getPortfolioHistory(dailyParams),
|
|
753
|
-
this.getPortfolioHistory(hourlyParams)
|
|
754
|
-
]);
|
|
755
|
-
// If no hourly history, return daily as-is
|
|
756
|
-
if (!hourlyHistory.timestamp || hourlyHistory.timestamp.length === 0) {
|
|
757
|
-
return dailyHistory;
|
|
758
|
-
}
|
|
759
|
-
// Get the last timestamp from daily history
|
|
760
|
-
const lastDailyTimestamp = dailyHistory.timestamp[dailyHistory.timestamp.length - 1];
|
|
761
|
-
// Check if hourly history has more recent data
|
|
762
|
-
const recentHourlyData = hourlyHistory.timestamp
|
|
763
|
-
.map((timestamp, index) => ({ timestamp, index }))
|
|
764
|
-
.filter(({ timestamp }) => timestamp > lastDailyTimestamp);
|
|
765
|
-
// If no more recent hourly data, return daily history as-is
|
|
766
|
-
if (recentHourlyData.length === 0) {
|
|
767
|
-
return dailyHistory;
|
|
768
|
-
}
|
|
769
|
-
// Get the most recent hourly data point
|
|
770
|
-
const mostRecentHourly = recentHourlyData[recentHourlyData.length - 1];
|
|
771
|
-
const mostRecentIndex = mostRecentHourly.index;
|
|
772
|
-
// Calculate the timestamp for the new daily entry (most recent day + 1 day worth of seconds)
|
|
773
|
-
const oneDayInSeconds = 24 * 60 * 60;
|
|
774
|
-
const newDailyTimestamp = mostRecentHourly.timestamp + oneDayInSeconds;
|
|
775
|
-
// Create a new daily history entry with the most recent hourly values
|
|
776
|
-
const updatedDailyHistory = {
|
|
777
|
-
...dailyHistory,
|
|
778
|
-
timestamp: [...dailyHistory.timestamp, newDailyTimestamp],
|
|
779
|
-
equity: [...dailyHistory.equity, hourlyHistory.equity[mostRecentIndex]],
|
|
780
|
-
profit_loss: [...dailyHistory.profit_loss, hourlyHistory.profit_loss[mostRecentIndex]],
|
|
781
|
-
profit_loss_pct: [...dailyHistory.profit_loss_pct, hourlyHistory.profit_loss_pct[mostRecentIndex]],
|
|
782
|
-
};
|
|
783
|
-
return updatedDailyHistory;
|
|
784
|
-
}
|
|
785
|
-
/**
|
|
786
|
-
* Get option contracts based on specified parameters
|
|
787
|
-
* @param params Parameters to filter option contracts
|
|
788
|
-
* @returns Option contracts matching the criteria
|
|
789
|
-
*/
|
|
790
|
-
async getOptionContracts(params) {
|
|
791
|
-
const queryParams = new URLSearchParams();
|
|
792
|
-
queryParams.append('underlying_symbols', params.underlying_symbols.join(','));
|
|
793
|
-
if (params.expiration_date_gte)
|
|
794
|
-
queryParams.append('expiration_date_gte', params.expiration_date_gte);
|
|
795
|
-
if (params.expiration_date_lte)
|
|
796
|
-
queryParams.append('expiration_date_lte', params.expiration_date_lte);
|
|
797
|
-
if (params.strike_price_gte)
|
|
798
|
-
queryParams.append('strike_price_gte', params.strike_price_gte);
|
|
799
|
-
if (params.strike_price_lte)
|
|
800
|
-
queryParams.append('strike_price_lte', params.strike_price_lte);
|
|
801
|
-
if (params.type)
|
|
802
|
-
queryParams.append('type', params.type);
|
|
803
|
-
if (params.status)
|
|
804
|
-
queryParams.append('status', params.status);
|
|
805
|
-
if (params.limit)
|
|
806
|
-
queryParams.append('limit', params.limit.toString());
|
|
807
|
-
if (params.page_token)
|
|
808
|
-
queryParams.append('page_token', params.page_token);
|
|
809
|
-
this.log(`Fetching option contracts for ${params.underlying_symbols.join(', ')}`, {
|
|
810
|
-
symbol: params.underlying_symbols.join(', '),
|
|
811
|
-
});
|
|
812
|
-
const response = (await this.makeRequest(`/options/contracts?${queryParams.toString()}`));
|
|
813
|
-
this.log(`Found ${response.option_contracts.length} option contracts`, {
|
|
814
|
-
symbol: params.underlying_symbols.join(', '),
|
|
815
|
-
});
|
|
816
|
-
return response;
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* Get a specific option contract by symbol or ID
|
|
820
|
-
* @param symbolOrId The symbol or ID of the option contract
|
|
821
|
-
* @returns The option contract details
|
|
822
|
-
*/
|
|
823
|
-
async getOptionContract(symbolOrId) {
|
|
824
|
-
this.log(`Fetching option contract details for ${symbolOrId}`, {
|
|
825
|
-
symbol: symbolOrId,
|
|
826
|
-
});
|
|
827
|
-
const response = (await this.makeRequest(`/options/contracts/${symbolOrId}`));
|
|
828
|
-
this.log(`Found option contract details for ${symbolOrId}: ${response.name}`, {
|
|
829
|
-
symbol: symbolOrId,
|
|
830
|
-
});
|
|
831
|
-
return response;
|
|
832
|
-
}
|
|
833
|
-
/**
|
|
834
|
-
* Create a simple option order (market or limit)
|
|
835
|
-
* @param symbol Option contract symbol
|
|
836
|
-
* @param qty Quantity of contracts (must be a whole number)
|
|
837
|
-
* @param side Buy or sell
|
|
838
|
-
* @param position_intent Position intent (buy_to_open, buy_to_close, sell_to_open, sell_to_close)
|
|
839
|
-
* @param type Order type (market or limit)
|
|
840
|
-
* @param limitPrice Limit price (required for limit orders)
|
|
841
|
-
* @returns The created order
|
|
842
|
-
*/
|
|
843
|
-
async createOptionOrder(symbol, qty, side, position_intent, type, limitPrice) {
|
|
844
|
-
if (!Number.isInteger(qty) || qty <= 0) {
|
|
845
|
-
this.log('Quantity must be a positive whole number for option orders', { type: 'error' });
|
|
846
|
-
}
|
|
847
|
-
if (type === 'limit' && limitPrice === undefined) {
|
|
848
|
-
this.log('Limit price is required for limit orders', { type: 'error' });
|
|
849
|
-
}
|
|
850
|
-
this.log(`Creating ${type} option order for ${symbol}: ${side} ${qty} contracts (${position_intent})${type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''}`, {
|
|
851
|
-
symbol,
|
|
852
|
-
});
|
|
853
|
-
const orderData = {
|
|
854
|
-
symbol,
|
|
855
|
-
qty: qty.toString(),
|
|
856
|
-
side,
|
|
857
|
-
position_intent,
|
|
858
|
-
type,
|
|
859
|
-
time_in_force: 'day',
|
|
860
|
-
order_class: 'simple',
|
|
861
|
-
extended_hours: false,
|
|
862
|
-
};
|
|
863
|
-
if (type === 'limit' && limitPrice !== undefined) {
|
|
864
|
-
orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();
|
|
865
|
-
}
|
|
866
|
-
return this.makeRequest('/orders', 'POST', orderData);
|
|
867
|
-
}
|
|
868
|
-
/**
|
|
869
|
-
* Create a multi-leg option order
|
|
870
|
-
* @param legs Array of order legs
|
|
871
|
-
* @param qty Quantity of the multi-leg order (must be a whole number)
|
|
872
|
-
* @param type Order type (market or limit)
|
|
873
|
-
* @param limitPrice Limit price (required for limit orders)
|
|
874
|
-
* @returns The created multi-leg order
|
|
875
|
-
*/
|
|
876
|
-
async createMultiLegOptionOrder(legs, qty, type, limitPrice) {
|
|
877
|
-
if (!Number.isInteger(qty) || qty <= 0) {
|
|
878
|
-
this.log('Quantity must be a positive whole number for option orders', { type: 'error' });
|
|
879
|
-
}
|
|
880
|
-
if (type === 'limit' && limitPrice === undefined) {
|
|
881
|
-
this.log('Limit price is required for limit orders', { type: 'error' });
|
|
882
|
-
}
|
|
883
|
-
if (legs.length < 2) {
|
|
884
|
-
this.log('Multi-leg orders require at least 2 legs', { type: 'error' });
|
|
885
|
-
}
|
|
886
|
-
const legSymbols = legs.map((leg) => leg.symbol).join(', ');
|
|
887
|
-
this.log(`Creating multi-leg ${type} option order with ${legs.length} legs (${legSymbols})${type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''}`, {
|
|
888
|
-
symbol: legSymbols,
|
|
889
|
-
});
|
|
890
|
-
const orderData = {
|
|
891
|
-
order_class: 'mleg',
|
|
892
|
-
qty: qty.toString(),
|
|
893
|
-
type,
|
|
894
|
-
time_in_force: 'day',
|
|
895
|
-
legs,
|
|
896
|
-
};
|
|
897
|
-
if (type === 'limit' && limitPrice !== undefined) {
|
|
898
|
-
orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();
|
|
899
|
-
}
|
|
900
|
-
return this.makeRequest('/orders', 'POST', orderData);
|
|
901
|
-
}
|
|
902
|
-
/**
|
|
903
|
-
* Exercise an option contract
|
|
904
|
-
* @param symbolOrContractId The symbol or ID of the option contract to exercise
|
|
905
|
-
* @returns Response from the exercise request
|
|
906
|
-
*/
|
|
907
|
-
async exerciseOption(symbolOrContractId) {
|
|
908
|
-
this.log(`Exercising option contract ${symbolOrContractId}`, {
|
|
909
|
-
symbol: symbolOrContractId,
|
|
910
|
-
});
|
|
911
|
-
return this.makeRequest(`/positions/${symbolOrContractId}/exercise`, 'POST');
|
|
912
|
-
}
|
|
913
|
-
/**
|
|
914
|
-
* Get option positions
|
|
915
|
-
* @returns Array of option positions
|
|
916
|
-
*/
|
|
917
|
-
async getOptionPositions() {
|
|
918
|
-
this.log('Fetching option positions');
|
|
919
|
-
const positions = await this.getPositions('us_option');
|
|
920
|
-
return positions;
|
|
921
|
-
}
|
|
922
|
-
async getOptionsOpenSpreadTrades() {
|
|
923
|
-
this.log('Fetching option open trades');
|
|
924
|
-
// this function will get all open positions, extract the symbol and see when they were created.
|
|
925
|
-
// figures out when the earliest date was (should be today)
|
|
926
|
-
// then it pulls all orders after the earliest date that were closed and that were of class 'mleg'
|
|
927
|
-
// Each of these contains two orders. they look like this:
|
|
928
|
-
}
|
|
929
|
-
/**
|
|
930
|
-
* Get option account activities (exercises, assignments, expirations)
|
|
931
|
-
* @param activityType Type of option activity to filter by
|
|
932
|
-
* @param date Date to filter activities (YYYY-MM-DD format)
|
|
933
|
-
* @returns Array of option account activities
|
|
934
|
-
*/
|
|
935
|
-
async getOptionActivities(activityType, date) {
|
|
936
|
-
const queryParams = new URLSearchParams();
|
|
937
|
-
if (activityType) {
|
|
938
|
-
queryParams.append('activity_types', activityType);
|
|
939
|
-
}
|
|
940
|
-
else {
|
|
941
|
-
queryParams.append('activity_types', 'OPEXC,OPASN,OPEXP');
|
|
942
|
-
}
|
|
943
|
-
if (date) {
|
|
944
|
-
queryParams.append('date', date);
|
|
945
|
-
}
|
|
946
|
-
this.log(`Fetching option activities${activityType ? ` of type ${activityType}` : ''}${date ? ` for date ${date}` : ''}`);
|
|
947
|
-
return this.makeRequest(`/account/activities?${queryParams.toString()}`);
|
|
948
|
-
}
|
|
949
|
-
/**
|
|
950
|
-
* Create a long call spread (buy lower strike call, sell higher strike call)
|
|
951
|
-
* @param lowerStrikeCallSymbol Symbol of the lower strike call option
|
|
952
|
-
* @param higherStrikeCallSymbol Symbol of the higher strike call option
|
|
953
|
-
* @param qty Quantity of spreads to create (must be a whole number)
|
|
954
|
-
* @param limitPrice Limit price for the spread
|
|
955
|
-
* @returns The created multi-leg order
|
|
956
|
-
*/
|
|
957
|
-
async createLongCallSpread(lowerStrikeCallSymbol, higherStrikeCallSymbol, qty, limitPrice) {
|
|
958
|
-
this.log(`Creating long call spread: Buy ${lowerStrikeCallSymbol}, Sell ${higherStrikeCallSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(2)}`, {
|
|
959
|
-
symbol: `${lowerStrikeCallSymbol},${higherStrikeCallSymbol}`,
|
|
960
|
-
});
|
|
961
|
-
const legs = [
|
|
962
|
-
{
|
|
963
|
-
symbol: lowerStrikeCallSymbol,
|
|
964
|
-
ratio_qty: '1',
|
|
965
|
-
side: 'buy',
|
|
966
|
-
position_intent: 'buy_to_open',
|
|
967
|
-
},
|
|
968
|
-
{
|
|
969
|
-
symbol: higherStrikeCallSymbol,
|
|
970
|
-
ratio_qty: '1',
|
|
971
|
-
side: 'sell',
|
|
972
|
-
position_intent: 'sell_to_open',
|
|
973
|
-
},
|
|
974
|
-
];
|
|
975
|
-
return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);
|
|
976
|
-
}
|
|
977
|
-
/**
|
|
978
|
-
* Create a long put spread (buy higher strike put, sell lower strike put)
|
|
979
|
-
* @param higherStrikePutSymbol Symbol of the higher strike put option
|
|
980
|
-
* @param lowerStrikePutSymbol Symbol of the lower strike put option
|
|
981
|
-
* @param qty Quantity of spreads to create (must be a whole number)
|
|
982
|
-
* @param limitPrice Limit price for the spread
|
|
983
|
-
* @returns The created multi-leg order
|
|
984
|
-
*/
|
|
985
|
-
async createLongPutSpread(higherStrikePutSymbol, lowerStrikePutSymbol, qty, limitPrice) {
|
|
986
|
-
this.log(`Creating long put spread: Buy ${higherStrikePutSymbol}, Sell ${lowerStrikePutSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(2)}`, {
|
|
987
|
-
symbol: `${higherStrikePutSymbol},${lowerStrikePutSymbol}`,
|
|
988
|
-
});
|
|
989
|
-
const legs = [
|
|
990
|
-
{
|
|
991
|
-
symbol: higherStrikePutSymbol,
|
|
992
|
-
ratio_qty: '1',
|
|
993
|
-
side: 'buy',
|
|
994
|
-
position_intent: 'buy_to_open',
|
|
995
|
-
},
|
|
996
|
-
{
|
|
997
|
-
symbol: lowerStrikePutSymbol,
|
|
998
|
-
ratio_qty: '1',
|
|
999
|
-
side: 'sell',
|
|
1000
|
-
position_intent: 'sell_to_open',
|
|
1001
|
-
},
|
|
1002
|
-
];
|
|
1003
|
-
return this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);
|
|
1004
|
-
}
|
|
1005
|
-
/**
|
|
1006
|
-
* Create an iron condor (sell call spread and put spread)
|
|
1007
|
-
* @param longPutSymbol Symbol of the lower strike put (long)
|
|
1008
|
-
* @param shortPutSymbol Symbol of the higher strike put (short)
|
|
1009
|
-
* @param shortCallSymbol Symbol of the lower strike call (short)
|
|
1010
|
-
* @param longCallSymbol Symbol of the higher strike call (long)
|
|
1011
|
-
* @param qty Quantity of iron condors to create (must be a whole number)
|
|
1012
|
-
* @param limitPrice Limit price for the iron condor (credit)
|
|
1013
|
-
* @returns The created multi-leg order
|
|
1014
|
-
*/
|
|
1015
|
-
async createIronCondor(longPutSymbol, shortPutSymbol, shortCallSymbol, longCallSymbol, qty, limitPrice) {
|
|
1016
|
-
this.log(`Creating iron condor with ${qty} contracts at $${limitPrice.toFixed(2)}`, {
|
|
1017
|
-
symbol: `${longPutSymbol},${shortPutSymbol},${shortCallSymbol},${longCallSymbol}`,
|
|
1018
|
-
});
|
|
1019
|
-
const legs = [
|
|
1020
|
-
{
|
|
1021
|
-
symbol: longPutSymbol,
|
|
1022
|
-
ratio_qty: '1',
|
|
1023
|
-
side: 'buy',
|
|
1024
|
-
position_intent: 'buy_to_open',
|
|
1025
|
-
},
|
|
1026
|
-
{
|
|
1027
|
-
symbol: shortPutSymbol,
|
|
1028
|
-
ratio_qty: '1',
|
|
1029
|
-
side: 'sell',
|
|
1030
|
-
position_intent: 'sell_to_open',
|
|
1031
|
-
},
|
|
1032
|
-
{
|
|
1033
|
-
symbol: shortCallSymbol,
|
|
1034
|
-
ratio_qty: '1',
|
|
1035
|
-
side: 'sell',
|
|
1036
|
-
position_intent: 'sell_to_open',
|
|
1037
|
-
},
|
|
1038
|
-
{
|
|
1039
|
-
symbol: longCallSymbol,
|
|
1040
|
-
ratio_qty: '1',
|
|
1041
|
-
side: 'buy',
|
|
1042
|
-
position_intent: 'buy_to_open',
|
|
1043
|
-
},
|
|
1044
|
-
];
|
|
1045
|
-
try {
|
|
1046
|
-
return await this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);
|
|
1047
|
-
}
|
|
1048
|
-
catch (error) {
|
|
1049
|
-
this.log(`Error creating iron condor: ${error}`, { type: 'error' });
|
|
1050
|
-
throw error;
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
/**
|
|
1054
|
-
* Create a covered call (sell call option against owned stock)
|
|
1055
|
-
* @param stockSymbol Symbol of the underlying stock
|
|
1056
|
-
* @param callOptionSymbol Symbol of the call option to sell
|
|
1057
|
-
* @param qty Quantity of covered calls to create (must be a whole number)
|
|
1058
|
-
* @param limitPrice Limit price for the call option
|
|
1059
|
-
* @returns The created order
|
|
1060
|
-
*/
|
|
1061
|
-
async createCoveredCall(stockSymbol, callOptionSymbol, qty, limitPrice) {
|
|
1062
|
-
this.log(`Creating covered call: Sell ${callOptionSymbol} against ${stockSymbol}, Qty: ${qty}, Price: $${limitPrice.toFixed(2)}`, {
|
|
1063
|
-
symbol: `${stockSymbol},${callOptionSymbol}`,
|
|
1064
|
-
});
|
|
1065
|
-
// For covered calls, we don't need to include the stock leg if we already own the shares
|
|
1066
|
-
// We just create a simple sell order for the call option
|
|
1067
|
-
try {
|
|
1068
|
-
return await this.createOptionOrder(callOptionSymbol, qty, 'sell', 'sell_to_open', 'limit', limitPrice);
|
|
1069
|
-
}
|
|
1070
|
-
catch (error) {
|
|
1071
|
-
this.log(`Error creating covered call: ${error}`, { type: 'error' });
|
|
1072
|
-
throw error;
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
/**
|
|
1076
|
-
* Roll an option position to a new expiration or strike
|
|
1077
|
-
* @param currentOptionSymbol Symbol of the current option position
|
|
1078
|
-
* @param newOptionSymbol Symbol of the new option to roll to
|
|
1079
|
-
* @param qty Quantity of options to roll (must be a whole number)
|
|
1080
|
-
* @param currentPositionSide Side of the current position ('buy' or 'sell')
|
|
1081
|
-
* @param limitPrice Net limit price for the roll
|
|
1082
|
-
* @returns The created multi-leg order
|
|
1083
|
-
*/
|
|
1084
|
-
async rollOptionPosition(currentOptionSymbol, newOptionSymbol, qty, currentPositionSide, limitPrice) {
|
|
1085
|
-
this.log(`Rolling ${qty} ${currentOptionSymbol} to ${newOptionSymbol} at net price $${limitPrice.toFixed(2)}`, {
|
|
1086
|
-
symbol: `${currentOptionSymbol},${newOptionSymbol}`,
|
|
1087
|
-
});
|
|
1088
|
-
// If current position is long, we need to sell to close and buy to open
|
|
1089
|
-
// If current position is short, we need to buy to close and sell to open
|
|
1090
|
-
const closePositionSide = currentPositionSide === 'buy' ? 'sell' : 'buy';
|
|
1091
|
-
const openPositionSide = currentPositionSide;
|
|
1092
|
-
const closePositionIntent = closePositionSide === 'buy' ? 'buy_to_close' : 'sell_to_close';
|
|
1093
|
-
const openPositionIntent = openPositionSide === 'buy' ? 'buy_to_open' : 'sell_to_open';
|
|
1094
|
-
const legs = [
|
|
1095
|
-
{
|
|
1096
|
-
symbol: currentOptionSymbol,
|
|
1097
|
-
ratio_qty: '1',
|
|
1098
|
-
side: closePositionSide,
|
|
1099
|
-
position_intent: closePositionIntent,
|
|
1100
|
-
},
|
|
1101
|
-
{
|
|
1102
|
-
symbol: newOptionSymbol,
|
|
1103
|
-
ratio_qty: '1',
|
|
1104
|
-
side: openPositionSide,
|
|
1105
|
-
position_intent: openPositionIntent,
|
|
1106
|
-
},
|
|
1107
|
-
];
|
|
1108
|
-
try {
|
|
1109
|
-
return await this.createMultiLegOptionOrder(legs, qty, 'limit', limitPrice);
|
|
1110
|
-
}
|
|
1111
|
-
catch (error) {
|
|
1112
|
-
this.log(`Error rolling option position: ${error}`, { type: 'error' });
|
|
1113
|
-
throw error;
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
/**
|
|
1117
|
-
* Get option chain for a specific underlying symbol and expiration date
|
|
1118
|
-
* @param underlyingSymbol The underlying stock symbol
|
|
1119
|
-
* @param expirationDate The expiration date (YYYY-MM-DD format)
|
|
1120
|
-
* @returns Option contracts for the specified symbol and expiration date
|
|
1121
|
-
*/
|
|
1122
|
-
async getOptionChain(underlyingSymbol, expirationDate) {
|
|
1123
|
-
this.log(`Fetching option chain for ${underlyingSymbol} with expiration date ${expirationDate}`, {
|
|
1124
|
-
symbol: underlyingSymbol,
|
|
1125
|
-
});
|
|
1126
|
-
try {
|
|
1127
|
-
const params = {
|
|
1128
|
-
underlying_symbols: [underlyingSymbol],
|
|
1129
|
-
expiration_date_gte: expirationDate,
|
|
1130
|
-
expiration_date_lte: expirationDate,
|
|
1131
|
-
status: 'active',
|
|
1132
|
-
limit: 500, // Get a large number to ensure we get all strikes
|
|
1133
|
-
};
|
|
1134
|
-
const response = await this.getOptionContracts(params);
|
|
1135
|
-
return response.option_contracts || [];
|
|
1136
|
-
}
|
|
1137
|
-
catch (error) {
|
|
1138
|
-
this.log(`Failed to fetch option chain for ${underlyingSymbol}: ${error instanceof Error ? error.message : 'Unknown error'}`, {
|
|
1139
|
-
type: 'error',
|
|
1140
|
-
symbol: underlyingSymbol,
|
|
1141
|
-
});
|
|
1142
|
-
return [];
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
/**
|
|
1146
|
-
* Get all available expiration dates for a specific underlying symbol
|
|
1147
|
-
* @param underlyingSymbol The underlying stock symbol
|
|
1148
|
-
* @returns Array of available expiration dates
|
|
1149
|
-
*/
|
|
1150
|
-
async getOptionExpirationDates(underlyingSymbol) {
|
|
1151
|
-
this.log(`Fetching available expiration dates for ${underlyingSymbol}`, {
|
|
1152
|
-
symbol: underlyingSymbol,
|
|
1153
|
-
});
|
|
1154
|
-
try {
|
|
1155
|
-
const params = {
|
|
1156
|
-
underlying_symbols: [underlyingSymbol],
|
|
1157
|
-
status: 'active',
|
|
1158
|
-
limit: 1000, // Get a large number to ensure we get contracts with all expiration dates
|
|
1159
|
-
};
|
|
1160
|
-
const response = await this.getOptionContracts(params);
|
|
1161
|
-
// Extract unique expiration dates
|
|
1162
|
-
const expirationDates = new Set();
|
|
1163
|
-
if (response.option_contracts) {
|
|
1164
|
-
response.option_contracts.forEach((contract) => {
|
|
1165
|
-
expirationDates.add(contract.expiration_date);
|
|
1166
|
-
});
|
|
1167
|
-
}
|
|
1168
|
-
// Convert to array and sort
|
|
1169
|
-
return Array.from(expirationDates).sort();
|
|
1170
|
-
}
|
|
1171
|
-
catch (error) {
|
|
1172
|
-
this.log(`Failed to fetch expiration dates for ${underlyingSymbol}: ${error instanceof Error ? error.message : 'Unknown error'}`, {
|
|
1173
|
-
type: 'error',
|
|
1174
|
-
symbol: underlyingSymbol,
|
|
1175
|
-
});
|
|
1176
|
-
return [];
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
/**
|
|
1180
|
-
* Get the current options trading level for the account
|
|
1181
|
-
* @returns The options trading level (0-3)
|
|
1182
|
-
*/
|
|
1183
|
-
async getOptionsTradingLevel() {
|
|
1184
|
-
this.log('Fetching options trading level');
|
|
1185
|
-
const accountDetails = await this.getAccountDetails();
|
|
1186
|
-
return accountDetails.options_trading_level || 0;
|
|
1187
|
-
}
|
|
1188
|
-
/**
|
|
1189
|
-
* Check if the account has options trading enabled
|
|
1190
|
-
* @returns Boolean indicating if options trading is enabled
|
|
1191
|
-
*/
|
|
1192
|
-
async isOptionsEnabled() {
|
|
1193
|
-
this.log('Checking if options trading is enabled');
|
|
1194
|
-
const accountDetails = await this.getAccountDetails();
|
|
1195
|
-
// Check if options trading level is 2 or higher (Level 2+ allows buying calls/puts)
|
|
1196
|
-
// Level 0: Options disabled
|
|
1197
|
-
// Level 1: Only covered calls and cash-secured puts
|
|
1198
|
-
// Level 2+: Can buy calls and puts (required for executeOptionsOrder)
|
|
1199
|
-
const optionsLevel = accountDetails.options_trading_level || 0;
|
|
1200
|
-
const isEnabled = optionsLevel >= 2;
|
|
1201
|
-
this.log(`Options trading level: ${optionsLevel}, enabled: ${isEnabled}`);
|
|
1202
|
-
return isEnabled;
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Close all option positions
|
|
1206
|
-
* @param cancelOrders Whether to cancel related orders (default: true)
|
|
1207
|
-
* @returns Response from the close positions request
|
|
1208
|
-
*/
|
|
1209
|
-
async closeAllOptionPositions(cancelOrders = true) {
|
|
1210
|
-
this.log(`Closing all option positions${cancelOrders ? ' and canceling related orders' : ''}`);
|
|
1211
|
-
const optionPositions = await this.getOptionPositions();
|
|
1212
|
-
if (optionPositions.length === 0) {
|
|
1213
|
-
this.log('No option positions to close');
|
|
1214
|
-
return;
|
|
1215
|
-
}
|
|
1216
|
-
// Create market orders to close each position
|
|
1217
|
-
for (const position of optionPositions) {
|
|
1218
|
-
const side = position.side === 'long' ? 'sell' : 'buy';
|
|
1219
|
-
const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';
|
|
1220
|
-
this.log(`Closing ${position.side} position of ${position.qty} contracts for ${position.symbol}`, {
|
|
1221
|
-
symbol: position.symbol,
|
|
1222
|
-
});
|
|
1223
|
-
await this.createOptionOrder(position.symbol, parseInt(position.qty), side, positionIntent, 'market');
|
|
1224
|
-
}
|
|
1225
|
-
if (cancelOrders) {
|
|
1226
|
-
// Get all open option orders
|
|
1227
|
-
const orders = await this.getOrders({ status: 'open' });
|
|
1228
|
-
const optionOrders = orders.filter((order) => order.asset_class === 'us_option');
|
|
1229
|
-
// Cancel each open option order
|
|
1230
|
-
for (const order of optionOrders) {
|
|
1231
|
-
this.log(`Canceling open order for ${order.symbol}`, {
|
|
1232
|
-
symbol: order.symbol,
|
|
1233
|
-
});
|
|
1234
|
-
await this.makeRequest(`/orders/${order.id}`, 'DELETE');
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
/**
|
|
1239
|
-
* Close a specific option position
|
|
1240
|
-
* @param symbol The option contract symbol
|
|
1241
|
-
* @param qty Optional quantity to close (defaults to entire position)
|
|
1242
|
-
* @returns The created order
|
|
1243
|
-
*/
|
|
1244
|
-
async closeOptionPosition(symbol, qty) {
|
|
1245
|
-
this.log(`Closing option position for ${symbol}${qty ? ` (${qty} contracts)` : ''}`, {
|
|
1246
|
-
symbol,
|
|
1247
|
-
});
|
|
1248
|
-
// Get the position details
|
|
1249
|
-
const positions = await this.getOptionPositions();
|
|
1250
|
-
const position = positions.find((p) => p.symbol === symbol);
|
|
1251
|
-
if (!position) {
|
|
1252
|
-
throw new Error(`No position found for option contract ${symbol}`);
|
|
1253
|
-
}
|
|
1254
|
-
const quantityToClose = qty || parseInt(position.qty);
|
|
1255
|
-
const side = position.side === 'long' ? 'sell' : 'buy';
|
|
1256
|
-
const positionIntent = side === 'sell' ? 'sell_to_close' : 'buy_to_close';
|
|
1257
|
-
try {
|
|
1258
|
-
return await this.createOptionOrder(symbol, quantityToClose, side, positionIntent, 'market');
|
|
1259
|
-
}
|
|
1260
|
-
catch (error) {
|
|
1261
|
-
this.log(`Error closing option position: ${error}`, { type: 'error' });
|
|
1262
|
-
throw error;
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
/**
|
|
1266
|
-
* Create a complete equities trade with optional stop loss and take profit
|
|
1267
|
-
* @param params Trade parameters including symbol, qty, side, and optional referencePrice
|
|
1268
|
-
* @param options Trade options including order type, extended hours, stop loss, and take profit settings
|
|
1269
|
-
* @returns The created order
|
|
1270
|
-
*/
|
|
1271
|
-
async createEquitiesTrade(params, options) {
|
|
1272
|
-
const { symbol, qty, side, referencePrice } = params;
|
|
1273
|
-
const { type = 'market', limitPrice, extendedHours = false, useStopLoss = false, stopPrice, stopPercent100, useTakeProfit = false, takeProfitPrice, takeProfitPercent100, clientOrderId, } = options || {};
|
|
1274
|
-
// Validation: Extended hours + market order is not allowed
|
|
1275
|
-
if (extendedHours && type === 'market') {
|
|
1276
|
-
this.log('Cannot create market order with extended hours enabled', {
|
|
1277
|
-
symbol,
|
|
1278
|
-
type: 'error',
|
|
1279
|
-
});
|
|
1280
|
-
throw new Error('Cannot create market order with extended hours enabled');
|
|
1281
|
-
}
|
|
1282
|
-
// Validation: Limit orders require limit price
|
|
1283
|
-
if (type === 'limit' && limitPrice === undefined) {
|
|
1284
|
-
this.log('Limit price is required for limit orders', {
|
|
1285
|
-
symbol,
|
|
1286
|
-
type: 'error',
|
|
1287
|
-
});
|
|
1288
|
-
throw new Error('Limit price is required for limit orders');
|
|
1289
|
-
}
|
|
1290
|
-
let calculatedStopPrice;
|
|
1291
|
-
let calculatedTakeProfitPrice;
|
|
1292
|
-
// Handle stop loss validation and calculation
|
|
1293
|
-
if (useStopLoss) {
|
|
1294
|
-
if (stopPrice === undefined && stopPercent100 === undefined) {
|
|
1295
|
-
this.log('Either stopPrice or stopPercent100 must be provided when useStopLoss is true', {
|
|
1296
|
-
symbol,
|
|
1297
|
-
type: 'error',
|
|
1298
|
-
});
|
|
1299
|
-
throw new Error('Either stopPrice or stopPercent100 must be provided when useStopLoss is true');
|
|
1300
|
-
}
|
|
1301
|
-
if (stopPercent100 !== undefined) {
|
|
1302
|
-
if (referencePrice === undefined) {
|
|
1303
|
-
this.log('referencePrice is required when using stopPercent100', {
|
|
1304
|
-
symbol,
|
|
1305
|
-
type: 'error',
|
|
1306
|
-
});
|
|
1307
|
-
throw new Error('referencePrice is required when using stopPercent100');
|
|
1308
|
-
}
|
|
1309
|
-
// Calculate stop price based on percentage and side
|
|
1310
|
-
const stopPercentDecimal = stopPercent100 / 100;
|
|
1311
|
-
if (side === 'buy') {
|
|
1312
|
-
// For buy orders, stop loss is below the reference price
|
|
1313
|
-
calculatedStopPrice = referencePrice * (1 - stopPercentDecimal);
|
|
1314
|
-
}
|
|
1315
|
-
else {
|
|
1316
|
-
// For sell orders, stop loss is above the reference price
|
|
1317
|
-
calculatedStopPrice = referencePrice * (1 + stopPercentDecimal);
|
|
1318
|
-
}
|
|
1319
|
-
}
|
|
1320
|
-
else {
|
|
1321
|
-
calculatedStopPrice = stopPrice;
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
// Handle take profit validation and calculation
|
|
1325
|
-
if (useTakeProfit) {
|
|
1326
|
-
if (takeProfitPrice === undefined && takeProfitPercent100 === undefined) {
|
|
1327
|
-
this.log('Either takeProfitPrice or takeProfitPercent100 must be provided when useTakeProfit is true', {
|
|
1328
|
-
symbol,
|
|
1329
|
-
type: 'error',
|
|
1330
|
-
});
|
|
1331
|
-
throw new Error('Either takeProfitPrice or takeProfitPercent100 must be provided when useTakeProfit is true');
|
|
1332
|
-
}
|
|
1333
|
-
if (takeProfitPercent100 !== undefined) {
|
|
1334
|
-
if (referencePrice === undefined) {
|
|
1335
|
-
this.log('referencePrice is required when using takeProfitPercent100', {
|
|
1336
|
-
symbol,
|
|
1337
|
-
type: 'error',
|
|
1338
|
-
});
|
|
1339
|
-
throw new Error('referencePrice is required when using takeProfitPercent100');
|
|
1340
|
-
}
|
|
1341
|
-
// Calculate take profit price based on percentage and side
|
|
1342
|
-
const takeProfitPercentDecimal = takeProfitPercent100 / 100;
|
|
1343
|
-
if (side === 'buy') {
|
|
1344
|
-
// For buy orders, take profit is above the reference price
|
|
1345
|
-
calculatedTakeProfitPrice = referencePrice * (1 + takeProfitPercentDecimal);
|
|
1346
|
-
}
|
|
1347
|
-
else {
|
|
1348
|
-
// For sell orders, take profit is below the reference price
|
|
1349
|
-
calculatedTakeProfitPrice = referencePrice * (1 - takeProfitPercentDecimal);
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
else {
|
|
1353
|
-
calculatedTakeProfitPrice = takeProfitPrice;
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
// Determine order class based on what's enabled
|
|
1357
|
-
let orderClass = 'simple';
|
|
1358
|
-
if (useStopLoss && useTakeProfit) {
|
|
1359
|
-
orderClass = 'bracket';
|
|
1360
|
-
}
|
|
1361
|
-
else if (useStopLoss || useTakeProfit) {
|
|
1362
|
-
orderClass = 'oto';
|
|
1363
|
-
}
|
|
1364
|
-
// Build the order request
|
|
1365
|
-
const orderData = {
|
|
1366
|
-
symbol,
|
|
1367
|
-
qty: Math.abs(qty).toString(),
|
|
1368
|
-
side,
|
|
1369
|
-
type,
|
|
1370
|
-
time_in_force: 'day',
|
|
1371
|
-
order_class: orderClass,
|
|
1372
|
-
extended_hours: extendedHours,
|
|
1373
|
-
position_intent: side === 'buy' ? 'buy_to_open' : 'sell_to_open',
|
|
1374
|
-
};
|
|
1375
|
-
if (clientOrderId) {
|
|
1376
|
-
orderData.client_order_id = clientOrderId;
|
|
1377
|
-
}
|
|
1378
|
-
// Add limit price for limit orders
|
|
1379
|
-
if (type === 'limit' && limitPrice !== undefined) {
|
|
1380
|
-
orderData.limit_price = this.roundPriceForAlpaca(limitPrice).toString();
|
|
1381
|
-
}
|
|
1382
|
-
// Add stop loss if enabled
|
|
1383
|
-
if (useStopLoss && calculatedStopPrice !== undefined) {
|
|
1384
|
-
orderData.stop_loss = {
|
|
1385
|
-
stop_price: this.roundPriceForAlpaca(calculatedStopPrice).toString(),
|
|
1386
|
-
};
|
|
1387
|
-
}
|
|
1388
|
-
// Add take profit if enabled
|
|
1389
|
-
if (useTakeProfit && calculatedTakeProfitPrice !== undefined) {
|
|
1390
|
-
orderData.take_profit = {
|
|
1391
|
-
limit_price: this.roundPriceForAlpaca(calculatedTakeProfitPrice).toString(),
|
|
1392
|
-
};
|
|
1393
|
-
}
|
|
1394
|
-
const logMessage = `Creating ${orderClass} ${type} ${side} order for ${symbol}: ${qty} shares${type === 'limit' ? ` at $${limitPrice?.toFixed(2)}` : ''}${useStopLoss ? ` with stop loss at $${calculatedStopPrice?.toFixed(2)}` : ''}${useTakeProfit ? ` with take profit at $${calculatedTakeProfitPrice?.toFixed(2)}` : ''}${extendedHours ? ' (extended hours)' : ''}`;
|
|
1395
|
-
this.log(logMessage, {
|
|
1396
|
-
symbol,
|
|
1397
|
-
});
|
|
1398
|
-
try {
|
|
1399
|
-
return await this.makeRequest('/orders', 'POST', orderData);
|
|
1400
|
-
}
|
|
1401
|
-
catch (error) {
|
|
1402
|
-
this.log(`Error creating equities trade: ${error}`, {
|
|
1403
|
-
symbol,
|
|
1404
|
-
type: 'error',
|
|
1405
|
-
});
|
|
1406
|
-
throw error;
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
|
|
1411
|
-
export { AlpacaTradingAPI };
|
|
1412
|
-
//# sourceMappingURL=alpaca-trading-api-CPaXTnjf.js.map
|