37 lines
1.4 KiB
JavaScript
37 lines
1.4 KiB
JavaScript
const PAPER_BASE_URL = 'https://paper-api.alpaca.markets';
|
|
|
|
function createAlpacaPaperClient({ keyId, secretKey } = {}) {
|
|
if (!keyId || !secretKey) throw new Error('Alpaca paper credentials are required');
|
|
async function request(path, options = {}) {
|
|
const response = await fetch(`${PAPER_BASE_URL}${path}`, {
|
|
...options,
|
|
headers: {
|
|
'APCA-API-KEY-ID': keyId,
|
|
'APCA-API-SECRET-KEY': secretKey,
|
|
'Content-Type': 'application/json',
|
|
...(options.headers || {}),
|
|
},
|
|
});
|
|
const text = await response.text();
|
|
let body = null;
|
|
try { body = text ? JSON.parse(text) : null; } catch (_) { body = { raw: text }; }
|
|
if (!response.ok) {
|
|
const error = new Error(body?.message || `Alpaca paper API returned ${response.status}`);
|
|
error.status = response.status;
|
|
error.body = body;
|
|
throw error;
|
|
}
|
|
return body;
|
|
}
|
|
return {
|
|
getAccount: () => request('/v2/account'),
|
|
getAssets: () => request('/v2/assets?status=active&asset_class=us_equity'),
|
|
getOrders: () => request('/v2/orders?status=all&limit=500&direction=desc'),
|
|
getPositions: () => request('/v2/positions'),
|
|
getOrderByClientId: (clientOrderId) => request(`/v2/orders:by_client_order_id?client_order_id=${encodeURIComponent(clientOrderId)}`),
|
|
submitOrder: (order) => request('/v2/orders', { method: 'POST', body: JSON.stringify(order) }),
|
|
};
|
|
}
|
|
|
|
module.exports = { PAPER_BASE_URL, createAlpacaPaperClient };
|