### Example: Get Latest Quote Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-stocks.md Demonstrates how to fetch and log the latest quote details for a given symbol. ```javascript const quote = await alpaca.getLatestQuote('AAPL'); console.log(`Bid: $${quote.BidPrice} @ ${quote.BidSize}`); console.log(`Ask: $${quote.AskPrice} @ ${quote.AskSize}`); ``` -------------------------------- ### Example: Get All Open Orders Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md Fetches all currently open orders. This is a common use case for monitoring active trades. ```javascript // Get all open orders const orders = await alpaca.getOrders({ status: 'open' }); ``` -------------------------------- ### Example: Get Latest Bar Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-stocks.md Fetches and logs the latest bar data, including close price and volume, for a specified symbol. ```javascript const bar = await alpaca.getLatestBar('AAPL'); console.log(`Close: $${bar.ClosePrice}, Volume: ${bar.Volume}`); ``` -------------------------------- ### Stock WebSocket Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/websockets.md Connect to the stock data stream, subscribe to specific symbols and data types, and handle incoming trade, quote, and bar data. Ensure to call connect() to start streaming. ```javascript const ws = alpaca.data_stream_v2; // Handle connection ws.onConnect(() => { console.log('Connected to stock data stream'); ws.subscribeForTrades(['AAPL', 'GOOGL']); ws.subscribeForQuotes(['MSFT']); ws.subscribeForBars(['TSLA']); }); // Handle state changes ws.onStateChange((status) => { console.log(`Status: ${status}`); }); // Handle errors ws.onError((error) => { console.error(`WebSocket error: ${error.message}`); }); // Handle incoming trades ws.onStockTrade((trade) => { console.log(`Trade: ${trade.Symbol} @ $${trade.Price} (size: ${trade.Size})`); }); // Handle incoming quotes ws.onStockQuote((quote) => { console.log(`Quote: ${quote.Symbol} - Bid: $${quote.BidPrice}, Ask: $${quote.AskPrice}`); }); // Handle incoming bars ws.onStockBar((bar) => { console.log(`Bar: ${bar.Symbol} - Close: $${bar.ClosePrice}, Volume: ${bar.Volume}`); }); // Connect and start streaming ws.connect(); // Later: disconnect // ws.disconnect(); ``` -------------------------------- ### Crypto WebSocket Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/websockets.md An example demonstrating how to connect to the Crypto WebSocket, subscribe to trade and quote streams, and handle incoming trade and quote data. ```APIDOC ### Example: Crypto WebSocket ```javascript const ws = alpaca.crypto_stream_v1beta3; ws.onConnect(() => { console.log('Connected to crypto stream'); ws.subscribeForTrades(['BTC/USD', 'ETH/USD']); ws.subscribeForQuotes(['BTC/USD']); }); ws.onCryptoTrade((trade) => { console.log(`Crypto Trade: ${trade.Symbol} @ $${trade.Price}`); }); ws.onCryptoQuote((quote) => { console.log(`Crypto Quote: Bid: $${quote.BidPrice}, Ask: $${quote.AskPrice}`); }); ws.connect(); ``` ``` -------------------------------- ### Example: Get Orders for Specific Symbols Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md Fetches all orders (regardless of status) for a specified list of stock symbols. This helps in analyzing activity for particular assets. ```javascript // Get orders for specific symbols const orders = await alpaca.getOrders({ status: 'all', symbols: ['AAPL', 'GOOGL'], }); ``` -------------------------------- ### News WebSocket Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/news.md A comprehensive example demonstrating how to connect, subscribe to news for specific symbols, handle incoming news data, and manage errors. ```APIDOC ## Example: News WebSocket ```javascript const newsWS = alpaca.news_stream; newsWS.onConnect(() => { console.log('Connected to news stream'); // Subscribe to news for specific symbols newsWS.subscribeForNews(['AAPL', 'GOOGL', 'MSFT', 'TSLA']); }); newsWS.onNews((news) => { console.log(`${new Date().toISOString()} - News Update:`); console.log(`Headline: ${news.Headline}`); console.log(`Symbols: ${news.Symbols.join(', ')}`); console.log(`Source: ${news.Source}`); if (news.Summary) { console.log(`Summary: ${news.Summary}`); } if (news.Images && news.Images.length > 0) { console.log(`Images: ${news.Images.length}`); } }); newsWS.onError((error) => { console.error(`WebSocket error: ${error.message}`); }); // Connect and start receiving news newsWS.connect(); // Later: add more symbols // newsWS.subscribeForNews(['NVDA']); // Later: disconnect // newsWS.disconnect(); ``` ``` -------------------------------- ### Install Alpaca Trade API JS Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Install the library using npm. Ensure you have Node.js v16.9 or newer and npm version 6 or above. ```sh npm install --save @alpacahq/alpaca-trade-api ``` -------------------------------- ### Get Account Information Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Call methods on the instantiated API object to interact with the Alpaca API. This example retrieves current account information. ```js alpaca.getAccount().then((account) => { console.log('Current Account:', account) }) ``` -------------------------------- ### Get Account Configurations Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /account/configurations and returns the current account configurations. ```APIDOC ## GET /account/configurations ### Description Retrieves the current account configurations. ### Method GET ### Endpoint /account/configurations ### Response #### Success Response (200) - **AccountConfigurations** (object) - The account configurations. ``` -------------------------------- ### Example: Get Historical Bars (V2) Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-stocks.md Fetches and iterates through historical bars for a symbol within a specified timeframe and date range. Requires setting up timeframe and date parameters. ```javascript const bars = await alpaca.getBarsV2('AAPL', { timeframe: alpaca.newTimeframe(30, alpaca.timeframeUnit.MIN), start: '2024-01-01T00:00:00Z', end: '2024-01-02T00:00:00Z', limit: 100, adjustment: 'all', }); for await (const bar of bars) { console.log(`${bar.Timestamp}: O:${bar.OpenPrice} H:${bar.HighPrice} L:${bar.LowPrice} C:${bar.ClosePrice} V:${bar.Volume}`); } ``` -------------------------------- ### GET /account/configurations Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/endpoints.md Fetches the current configuration settings for the account. ```APIDOC ## GET /account/configurations ### Description Retrieve account configuration settings. ### Method GET ### Endpoint /account/configurations ### Parameters None ### Response #### Success Response (200) - `AccountConfigurations` object ``` -------------------------------- ### Get Account Activities Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /account/activities and returns account activities. ```APIDOC ## GET /account/activities ### Description Retrieves a list of account activities. ### Method GET ### Endpoint /account/activities ### Parameters #### Query Parameters - **activityTypes** (string | string[]) - Optional - Any valid activity type. - **until** (Date) - Optional - Filter activities until this date. - **after** (Date) - Optional - Filter activities after this date. - **direction** (string) - Optional - The direction of sorting. - **date** (Date) - Optional - Filter activities for a specific date. - **pageSize** (number) - Optional - The number of activities to return per page. - **pageToken** (string) - Optional - The token for the next page of activities. ### Response #### Success Response (200) - **AccountActivity[]** (array) - An array of account activities. ``` -------------------------------- ### Get All Positions Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches all currently open positions. This method calls `GET /positions`. ```typescript getPositions() => Promise ``` -------------------------------- ### Get Account Configurations Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches the current account configurations. This method corresponds to the `GET /account/configurations` API endpoint. ```typescript getAccountConfigurations() => Promise ``` -------------------------------- ### Get All Watchlists Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches all the watchlists associated with your account. ```APIDOC ## Get All Watchlists ### Description Retrieves all watchlists. ### Method `getWatchlists()` ### Request Example ```js alpaca.getWatchlists().then((response) => { console.log(response) }) ``` ``` -------------------------------- ### Get Bars Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches historical bar data for a symbol within a date range and timeframe. This example iterates through the async generator to collect bars. ```typescript const bars = alpaca.getBarsV2("AAPL", { start: "2022-04-01", end: "2022-04-02", timeframe: alpaca.newTimeframe(30, alpaca.timeframeUnit.MIN), limit: 2, }); const got = []; for await (let b of bars) { got.push(b); } console.log(got); ``` -------------------------------- ### Instantiate Alpaca Client with Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/alpaca-client.md This example shows how to initialize the Alpaca client using environment variables for authentication and configuration. Ensure `APCA_API_KEY_ID` and `APCA_API_SECRET_KEY` are set. ```javascript // Using environment variables const alpaca = new Alpaca({ paper: true, }); ``` -------------------------------- ### GET /assets Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/endpoints.md Retrieves a list of all available assets. Use the `alpaca.getAssets(options)` JavaScript method for this. ```APIDOC ## GET /assets ### Description List all assets. ### Method GET ### Endpoint /assets ### Parameters #### Query Parameters - **status** (string) - Optional - Asset status (active, inactive) - **asset_class** (string) - Optional - Asset class (us_equity, crypto) ### Response #### Success Response (200) Array of `Asset` objects ``` -------------------------------- ### Get Latest Trade Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches the most recent trade for a given symbol. This is useful for real-time price checks. ```typescript const trade = await alpaca.getLatestTrade('AAPL'); console.log(trade); ``` -------------------------------- ### Place Market Order and Monitor Execution Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/README.md Demonstrates how to create a market order and then monitor its status until it is filled. Use this for immediate trade execution. ```javascript const order = await alpaca.createOrder({ symbol: 'AAPL', qty: 100, side: 'buy', type: 'market', }); const checkOrder = setInterval(async () => { const o = await alpaca.getOrder(order.id); console.log(`Order status: ${o.status}`); if (o.status === 'filled') { clearInterval(checkOrder); console.log(`Filled ${o.filled_qty} shares at avg price $${o.limit_price}`); } }, 1000); ``` -------------------------------- ### Live Trading Setup Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/README.md Configure the Alpaca client for live trading by setting the 'paper' option to false or omitting it, as false is the default. ```javascript const alpaca = new Alpaca({ // ... credentials ... paper: false, // or omit (default) }); ``` -------------------------------- ### Example: News WebSocket Streaming Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/news.md Demonstrates how to connect to the news stream, subscribe to specific stock symbols, and process incoming news data. Includes handling connection events, news updates, and errors. ```javascript const newsWS = alpaca.news_stream; newsWS.onConnect(() => { console.log('Connected to news stream'); // Subscribe to news for specific symbols newsWS.subscribeForNews(['AAPL', 'GOOGL', 'MSFT', 'TSLA']); }); newsWS.onNews((news) => { console.log(`${new Date().toISOString()} - News Update:`); console.log(`Headline: ${news.Headline}`); console.log(`Symbols: ${news.Symbols.join(', ')}`); console.log(`Source: ${news.Source}`); if (news.Summary) { console.log(`Summary: ${news.Summary}`); } if (news.Images && news.Images.length > 0) { console.log(`Images: ${news.Images.length}`); } }); newsWS.onError((error) => { console.error(`WebSocket error: ${error.message}`); }); // Connect and start receiving news newsWS.connect(); // Later: add more symbols // newsWS.subscribeForNews(['NVDA']); // Later: disconnect // newsWS.disconnect(); ``` -------------------------------- ### Client Initialization Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/QUICK-REFERENCE.md Initialize the Alpaca client for paper or live trading by providing your API keys. ```APIDOC ## Client Initialization ```javascript const Alpaca = require('@alpacahq/alpaca-trade-api'); // Paper trading const alpaca = new Alpaca({ keyId: 'YOUR_KEY', secretKey: 'YOUR_SECRET', paper: true, }); // Live trading const alpaca = new Alpaca({ keyId: 'YOUR_KEY', secretKey: 'YOUR_SECRET', // paper defaults to false }); ``` ``` -------------------------------- ### Example: Get Filled Orders from Past 7 Days Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md Retrieves all closed (filled or canceled) orders from the last week. Useful for reviewing recent trade history. ```javascript // Get filled orders from past 7 days const orders = await alpaca.getOrders({ status: 'closed', after: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), }); ``` -------------------------------- ### Get Multi Trades Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves trades for multiple symbols within a specified time range and limit. The result is a map where keys are symbols and values are arrays of trades. ```typescript const trades = await alpaca.getMultiTradesV2(["PFE", "SPY"], { start: "2022-04-18T08:30:00Z", end: "2022-04-18T08:31:00Z", limit: 2, }); console.log(trades); ``` -------------------------------- ### Configure Paper Trading with `paper` Parameter Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Use the `paper: true` option during instantiation to connect to the paper trading environment. Ensure your API keys are for paper trading. ```javascript const alpaca = new Alpaca({ keyId: 'your_paper_key', secretKey: 'your_paper_secret', paper: true, }); ``` -------------------------------- ### Get Historical Trades for a Symbol Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-stocks.md Retrieves historical trade data for a single stock symbol as an async generator. Specify start and end times, limit, and other options. Use `for await...of` to iterate through the results. ```typescript getTradesV2( symbol: string, options: { start?: string; end?: string; limit?: number; pageLimit?: number; feed?: string; asof?: string; sort?: 'asc' | 'desc'; }, config?: any ): AsyncGenerator ``` ```javascript // Iterate through trades const trades = await alpaca.getTradesV2('AAPL', { start: '2024-01-01T00:00:00Z', end: '2024-01-02T00:00:00Z', limit: 100, }); const tradeList = []; for await (const trade of trades) { tradeList.push(trade); } console.log(`Retrieved ${tradeList.length} trades`); ``` -------------------------------- ### Crypto WebSocket Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/websockets.md Connects to the crypto stream, subscribes to trades and quotes for specified symbols, and logs incoming trade and quote data. Ensure the Alpaca SDK is initialized before use. ```javascript const ws = alpaca.crypto_stream_v1beta3; ws.onConnect(() => { console.log('Connected to crypto stream'); ws.subscribeForTrades(['BTC/USD', 'ETH/USD']); ws.subscribeForQuotes(['BTC/USD']); }); ws.onCryptoTrade((trade) => { console.log(`Crypto Trade: ${trade.Symbol} @ $${trade.Price}`); }); ws.onCryptoQuote((quote) => { console.log(`Crypto Quote: Bid: $${quote.BidPrice}, Ask: $${quote.AskPrice}`); }); ws.connect(); ``` -------------------------------- ### Initialize Alpaca Client with API Keys Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Instantiate the Alpaca client using your API key ID and secret key for authentication. Ensure these are kept secure and not committed to version control. ```javascript const alpaca1 = new Alpaca({ keyId: 'KEY', secretKey: 'SECRET', }); ``` -------------------------------- ### Get Orders Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /orders and returns a list of orders. ```APIDOC ## GET /orders ### Description Retrieves a list of orders. ### Method GET ### Endpoint /orders ### Parameters #### Query Parameters - **status** ('open' | 'closed' | 'all') - Optional - The status of the orders to retrieve. - **after** (Date) - Optional - Filter orders after this date. - **until** (Date) - Optional - Filter orders until this date. - **limit** (number) - Optional - The maximum number of orders to return. - **direction** ('asc' | 'desc') - Optional - The direction of sorting. ### Response #### Success Response (200) - **Order[]** (array) - An array of order objects. ``` -------------------------------- ### Configuration Properties Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/alpaca-client.md After instantiation, the client's configuration details are available through the `configuration` property. ```APIDOC ### Configuration Properties After instantiation, configuration is available at `alpaca.configuration`: ```javascript alpaca.configuration.baseUrl // REST API URL alpaca.configuration.dataBaseUrl // Data API URL alpaca.configuration.keyId // API key alpaca.configuration.feed // Market data feed type alpaca.configuration.optionFeed // Options feed type ``` ``` -------------------------------- ### Get All Positions Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /positions and returns all current open positions. ```APIDOC ## GET /positions ### Description Retrieves a list of all currently open positions. ### Method GET ### Endpoint /positions ### Response #### Success Response (200) - **Position[]** (array) - An array of position objects. ``` -------------------------------- ### Initialize Alpaca Client Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/QUICK-REFERENCE.md Initialize the Alpaca client for paper or live trading. Ensure you have your API keys and secret keys. ```javascript const Alpaca = require('@alpacahq/alpaca-trade-api'); // Paper trading const alpaca = new Alpaca({ keyId: 'YOUR_KEY', secretKey: 'YOUR_SECRET', paper: true, }); // Live trading const alpaca = new Alpaca({ keyId: 'YOUR_KEY', secretKey: 'YOUR_SECRET', // paper defaults to false }); ``` -------------------------------- ### Get Portfolio History Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /account/portfolio/history and returns portfolio history. ```APIDOC ## GET /account/portfolio/history ### Description Retrieves the portfolio's historical data. ### Method GET ### Endpoint /account/portfolio/history ### Parameters #### Query Parameters - **date_start** (Date) - Optional - The start date for the portfolio history. - **date_end** (Date) - Optional - The end date for the portfolio history. - **period** ('1M' | '3M' | '6M' | '1A' | 'all' | 'intraday') - Optional - The time period for the history. - **timeframe** ('1Min' | '5Min' | '15Min' | '1H' | '1D') - Optional - The timeframe for the history data. - **extended_hours** (Boolean) - Optional - Whether to include extended hours data. ### Response #### Success Response (200) - **PortfolioHistory** (object) - The portfolio history data. ``` -------------------------------- ### Get Account Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /account and returns the current account information. ```APIDOC ## GET /account ### Description Retrieves the current account details. ### Method GET ### Endpoint /account ### Response #### Success Response (200) - **Account** (object) - The account details. ``` -------------------------------- ### Get Account Information Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/QUICK-REFERENCE.md Retrieve account balance, equity, and portfolio value. Also shows how to fetch portfolio history and account activities. ```javascript // Get account balance and info const account = await alpaca.getAccount(); console.log(account.buying_power, account.equity, account.portfolio_value); // Get portfolio history const history = await alpaca.getPortfolioHistory({ period: '1M', // 1M, 3M, 6M, 1A, all, intraday }); // Get activities (trades, dividends, etc.) const activities = await alpaca.getAccountActivities({ activityTypes: ['FILL', 'DIVIDEND'], limit: 100, }); // Update account settings await alpaca.updateAccountConfigurations({ dtbp_check: 'both', trade_confirm_email: 'all', }); ``` -------------------------------- ### Instantiate Alpaca Client with API Keys Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/alpaca-client.md Use this snippet to create an Alpaca client instance when you have your API key ID and secret key. Set `paper: true` for paper trading. ```javascript const Alpaca = require('@alpacahq/alpaca-trade-api'); // Using API keys const alpaca = new Alpaca({ keyId: 'YOUR_API_KEY', secretKey: 'YOUR_SECRET_KEY', paper: true, // use paper trading }); ``` -------------------------------- ### Configure Live Trading Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md For live trading, instantiate the Alpaca client without the `paper: true` option, as `false` is the default. Use your live trading API keys. ```javascript const alpaca = new Alpaca({ keyId: 'your_live_key', secretKey: 'your_live_secret', // paper: false (default) }); ``` -------------------------------- ### Get Position Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /positions/{symbol} and returns a specific position for a given symbol. ```APIDOC ## GET /positions/{symbol} ### Description Retrieves the details of a specific position for a given trading symbol. ### Method GET ### Endpoint /positions/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The trading symbol for the position. ### Response #### Success Response (200) - **Position** (object) - The details of the specified position. ``` -------------------------------- ### Get Order by ID Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /orders/{id} and returns a specific order by its ID. ```APIDOC ## GET /orders/{id} ### Description Retrieves a specific order using its unique identifier. ### Method GET ### Endpoint /orders/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **Order** (object) - The order details. ``` -------------------------------- ### Configure Alpaca Client with WebSocket Streams Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Instantiate the Alpaca client with specific configurations for data streams and enable debug logging. Connect to multiple WebSocket streams after initialization. ```javascript const alpaca = new Alpaca({ keyId: 'your_key', secretKey: 'your_secret', dataStreamUrl: 'https://stream.data.alpaca.markets', feed: 'iex', optionFeed: 'indicative', verbose: true, // Enable debug logging }); // WebSocket clients are ready to use alpaca.data_stream_v2.connect(); alpaca.crypto_stream_v1beta3.connect(); alpaca.news_stream.connect(); alpaca.option_stream.connect(); ``` -------------------------------- ### Get Asset Information Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /assets/{symbol} and returns detailed information about a specific asset. ```APIDOC ## GET /assets/{symbol} ### Description Retrieves detailed information for a specific trading symbol. ### Method GET ### Endpoint /assets/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The trading symbol for the asset. ### Response #### Success Response (200) - **Asset** (object) - The detailed information about the asset. ``` -------------------------------- ### Configure Alpaca API Client Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/QUICK-REFERENCE.md Initialize the Alpaca client using either direct configuration in the constructor or by setting environment variables. Access configuration settings like `baseUrl` and `feed` after initialization. ```javascript // Via constructor const alpaca = new Alpaca({ keyId: 'KEY', secretKey: 'SECRET', baseUrl: 'https://api.alpaca.markets', dataBaseUrl: 'https://data.alpaca.markets', paper: true, feed: 'iex', // or 'sip' with PRO optionFeed: 'indicative', // or 'opra' with PRO }); // Via environment variables process.env.APCA_API_KEY_ID = 'KEY'; process.env.APCA_API_SECRET_KEY = 'SECRET'; process.env.APCA_API_BASE_URL = 'https://paper-api.alpaca.markets'; // Access config alpaca.configuration.baseUrl; alpaca.configuration.feed; alpaca.configuration.keyId; ``` -------------------------------- ### Initialize Alpaca API with Paper Trading Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/README.md Instantiate the Alpaca API client for paper trading. Ensure your API keys are set as environment variables. This is useful for testing trading logic without using real funds. ```javascript const alpaca = new Alpaca({ keyId: process.env.APCA_API_KEY_ID, secretKey: process.env.APCA_API_SECRET_KEY, paper: true, // Test without real money }); // Test your trading logic here const order = await alpaca.createOrder({ symbol: 'AAPL', qty: 100, side: 'buy', }); ``` -------------------------------- ### Get Account Information Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves the current account details. This method calls the `GET /account` endpoint. ```typescript getAccount() => Promise ``` -------------------------------- ### Get Order by Client ID Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Calls GET /orders:by_client_order_id and returns an order by its client order ID. ```APIDOC ## GET /orders:by_client_order_id ### Description Retrieves an order using its client-assigned order ID. ### Method GET ### Endpoint /orders:by_client_order_id ### Parameters #### Query Parameters - **client_order_id** (string) - Required - The client-assigned order ID. ### Response #### Success Response (200) - **Order** (object) - The order details. ``` -------------------------------- ### Create Trailing Stop Order Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md This example shows how to create a trailing stop order with a specified trail percentage. The stop price adjusts dynamically to lock in profits as the market moves favorably. ```javascript const order = await alpaca.createOrder({ symbol: 'TSLA', qty: 1, side: 'sell', type: 'trailing_stop', trail_percent: '5', }); ``` -------------------------------- ### Get Market Calendar Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves the market calendar for a specified date range. This method calls `GET /calendar`. ```typescript getCalendar({ start: Date, end: Date }) => Promise ``` -------------------------------- ### Alpaca Client Constructor Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/alpaca-client.md Initializes a new Alpaca API client instance. Configuration can be provided via an object or inferred from environment variables. ```APIDOC ## Constructor ```typescript constructor(config?: { baseUrl?: string; dataBaseUrl?: string; dataStreamUrl?: string; keyId?: string; secretKey?: string; apiVersion?: string; oauth?: string; paper?: boolean; feed?: string; optionFeed?: string; verbose?: boolean; }): Alpaca ``` ### Description Creates a new Alpaca API client instance with the provided configuration. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | object | — | {} | Configuration object with API credentials and endpoints | | config.baseUrl | string | — | `https://api.alpaca.markets` or paper trading URL | REST API base URL, overrides APCA_API_BASE_URL env var | | config.dataBaseUrl | string | — | `https://data.alpaca.markets` | Data API base URL, overrides APCA_DATA_BASE_URL env var | | config.dataStreamUrl | string | — | `https://stream.data.alpaca.markets` | WebSocket data stream URL | | config.keyId | string | — | `APCA_API_KEY_ID` env var | API key ID for authentication | | config.secretKey | string | — | `APCA_API_SECRET_KEY` env var | Secret key for authentication | | config.apiVersion | string | — | `v2` | API version to use | | config.oauth | string | — | `APCA_API_OAUTH` env var | OAuth token for authentication (alternative to keyId/secretKey) | | config.paper | boolean | — | false | If true, uses paper trading API endpoint | | config.feed | string | — | `iex` | Market data feed (`iex` or `sip` for PRO subscription) | | config.optionFeed | string | — | `indicative` | Options data feed (`indicative` or `opra` for PRO subscription) | | config.verbose | boolean | — | false | Enable verbose logging for WebSocket connections | ### Configuration Precedence Configuration values are resolved in this order: 1. Constructor parameter value 2. Environment variable 3. Default value ### Environment Variables - `APCA_API_KEY_ID`: API key ID - `APCA_API_SECRET_KEY`: Secret key - `APCA_API_BASE_URL`: REST API base URL (overrides paper parameter) - `APCA_DATA_BASE_URL`: Data API base URL - `APCA_API_STREAM_URL`: WebSocket stream URL - `APCA_API_VERSION`: API version - `APCA_API_OAUTH`: OAuth token - `DATA_PROXY_WS`: Proxy for data WebSocket URL ### Example ```javascript const Alpaca = require('@alpacahq/alpaca-trade-api'); // Using API keys const alpaca = new Alpaca({ keyId: 'YOUR_API_KEY', secretKey: 'YOUR_SECRET_KEY', paper: true, // use paper trading }); // Using environment variables const alpaca = new Alpaca({ paper: true, }); // Using OAuth const alpaca = new Alpaca({ oauth: 'YOUR_OAUTH_TOKEN', baseUrl: 'https://api.alpaca.markets', }); ``` ``` -------------------------------- ### Error Response Example Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/endpoints.md This is an example of a JSON error response from the API. It includes an error code and a descriptive message. ```json { "code": 40001, "message": "Request failed" } ``` -------------------------------- ### Paper Trading Setup Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/README.md Configure the Alpaca client for paper trading by setting the 'paper' option to true. This is recommended for testing. ```javascript const alpaca = new Alpaca({ // ... credentials ... paper: true, }); ``` -------------------------------- ### Subscribe to Multiple Symbols and Unsubscribe Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/websockets.md This example shows how to subscribe to multiple trading symbols for trades and quotes upon connection, and how to add or remove subscriptions later. ```javascript // Subscribe at connection time ws.onConnect(() => { ws.subscribeForTrades(['AAPL', 'GOOGL', 'MSFT', 'TSLA']); ws.subscribeForQuotes(['SPY', 'QQQ']); }); // Add more subscriptions later ws.subscribeForBars(['AAPL', 'GOOGL']); // Unsubscribe as needed ws.unsubscribeFromTrades(['MSFT']); ``` -------------------------------- ### Get Asset by Symbol Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches detailed information for a specific asset using its symbol. This method calls `GET /assets/{symbol}`. ```typescript getAsset(symbol) => Promise ``` -------------------------------- ### Create a Market Order Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/README.md Submit a market order to buy a specified quantity of a stock. Ensure the `alpaca` client is initialized. ```javascript const order = await alpaca.createOrder({ symbol: 'AAPL', qty: 10, side: 'buy', type: 'market', time_in_force: 'day', }); console.log(`Order created: ${order.id}`); ``` -------------------------------- ### Get All Assets Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves a list of available assets, with options to filter by status and asset class. This method calls `GET /assets`. ```typescript getAssets({ status: 'active' | 'inactive', asset_class: string }) => Promise ``` -------------------------------- ### Get Position by Symbol Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves details for a specific open position identified by its symbol. This method calls `GET /positions/{symbol}`. ```typescript getPosition(symbol) => Promise ``` -------------------------------- ### Create Limit Order with Extended Hours Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md This example demonstrates creating a limit order with a specified limit price and enabling extended hours trading. This allows trading outside of regular market hours. ```javascript const order = await alpaca.createOrder({ symbol: 'GOOGL', qty: 5, side: 'buy', type: 'limit', limit_price: 140.50, extended_hours: true, }); ``` -------------------------------- ### Get Order by ID Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches a specific order using its unique identifier (UUID). This method calls `GET /orders/{id}`. ```typescript getOrder(uuid) => Promise ``` -------------------------------- ### Initialize Alpaca Client with OAuth Token Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Instantiate the Alpaca client using an OAuth token for authentication. This is an alternative to using API keys. ```javascript const alpaca2 = new Alpaca({ oauth: 'TOKEN', }); ``` -------------------------------- ### Configure Alpaca for Development with Paper Trading Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Set up the Alpaca client for development using paper trading. Load API keys and secrets from a `.env` file and enable verbose logging for debugging. ```javascript require('dotenv').config(); // Load .env file const alpaca = new Alpaca({ keyId: process.env.APCA_API_KEY_ID, secretKey: process.env.APCA_API_SECRET_KEY, paper: true, verbose: true, // Enable logging for debugging }); ``` -------------------------------- ### Get Orders Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves a list of orders based on status, date range, and sorting parameters. This method calls `GET /orders`. ```typescript getOrders({ status: 'open' | 'closed' | 'all', after: Date, until: Date, limit: number, direction: 'asc' | 'desc' }) => Promise ``` -------------------------------- ### Get Market Clock Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches the current market clock status, indicating if the market is open or closed. This method calls `GET /clock`. ```typescript getClock() => Promise ``` -------------------------------- ### Get Latest Option Trades Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-options.md Retrieves the most recent trade for multiple option symbols. Ideal for getting the latest price information for options. ```javascript const trades = await alpaca.getOptionLatestTrades(['AAPL250117C150']); trades.forEach((trade, symbol) => { console.log(`${symbol}: $${trade.Price}`); }); ``` -------------------------------- ### Get Account Configurations Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/account.md Retrieves the current account configuration settings. Use this to inspect your existing trading preferences. ```javascript const config = await alpaca.getAccountConfigurations(); console.log(`Fractional Trading: ${config.fractional_trading}`); console.log(`No Shorting: ${config.no_shorting}`); ``` -------------------------------- ### Configure Stock Data Feed (SIP) Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md To access the SIP stock data feed, set the `feed` option to 'sip'. This feed requires a PRO subscription. ```javascript // SIP Feed (requires PRO subscription) const alpaca = new Alpaca({ feed: 'sip', // ... }); ``` -------------------------------- ### Get Account Activities Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves account activities, supporting filtering by activity types, date ranges, and pagination. This method calls `GET /account/activities`. ```typescript getAccountActivities({ activityTypes: string | string[], // Any valid activity type until: Date, after: Date, direction: string, date: Date, pageSize: number, pageToken: string }) => Promise ``` -------------------------------- ### News WebSocket Client Initialization Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/news.md Access the news WebSocket client instance from the Alpaca SDK. ```APIDOC ## Access WebSocket Client ```javascript const newsWS = alpaca.news_stream; ``` ``` -------------------------------- ### Base URL Resolution Scenarios Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Demonstrates how the Alpaca client resolves the base URL based on constructor parameters, environment variables, and default values. The first matching configuration takes precedence. ```javascript // Scenario 1: Constructor parameter provided const alpaca = new Alpaca({ baseUrl: 'https://custom-api.example.com' }); // Uses: https://custom-api.example.com ``` ```javascript // Scenario 2: Environment variable set, no constructor parameter process.env.APCA_API_BASE_URL = 'https://api.alpaca.markets'; const alpaca = new Alpaca({}); // Uses: https://api.alpaca.markets ``` ```javascript // Scenario 3: No constructor parameter, no environment variable const alpaca = new Alpaca({ paper: true }); // Uses: https://paper-api.alpaca.markets (because paper=true) ``` ```javascript // Scenario 4: No configuration at all const alpaca = new Alpaca({}); // Uses: https://api.alpaca.markets (live default) ``` -------------------------------- ### Configure Options Data Feed (Indicative) Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Use the `optionFeed: 'indicative'` option for estimated option prices, which is free and the default. This feed provides non-official pricing. ```javascript // Indicative Feed (estimated prices, free) const alpaca = new Alpaca({ optionFeed: 'indicative', // or omit (default) // ... }); ``` -------------------------------- ### Get Crypto Bars Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-crypto.md Retrieves historical bar (OHLCV) data for cryptocurrencies. Specify a timeframe and date range to get historical price and volume data. ```javascript const bars = await alpaca.getCryptoBars(['BTC/USD'], { timeframe: '1H', start: '2024-01-01T00:00:00Z', end: '2024-01-02T00:00:00Z', limit: 50, }); bars.forEach((barList, symbol) => { barList.forEach(bar => { console.log(`${bar.Timestamp}: O:${bar.Open} H:${bar.High} L:${bar.Low} C:${bar.Close} V:${bar.Volume}`); }); }); ``` -------------------------------- ### Create Simple Market Order Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/orders.md Use this snippet to create a simple market order for a specified quantity of a stock. Ensure the `time_in_force` is set appropriately. ```javascript const order = await alpaca.createOrder({ symbol: 'AAPL', qty: 10, side: 'buy', type: 'market', time_in_force: 'day', }); ``` -------------------------------- ### Configure Stock Data Feed (IEX) Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Set the `feed` option to 'iex' to use the free IEX stock data feed. This is the default if no feed is specified. ```javascript // IEX Feed (free, default) const alpaca = new Alpaca({ feed: 'iex', // or omit (default) // ... }); ``` -------------------------------- ### Get News Articles Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/QUICK-REFERENCE.md Fetches news articles for specified symbols. Set `includeContent` to true to get the full article content. `totalLimit` controls the number of articles. ```javascript const news = await alpaca.getNews({ symbols: ['AAPL', 'GOOGL'], includeContent: true, totalLimit: 50, }); news.forEach(article => { console.log(article.Headline); console.log(` ${article.Source} - ${article.Author}`); }); ``` -------------------------------- ### Get Order by Client ID Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Retrieves an order using its client-assigned ID. Useful for tracking orders created with a `client_order_id`. This method calls `GET /orders:by_client_order_id`. ```typescript getOrderByClientOrderId(string) => Promise ``` -------------------------------- ### Import Alpaca Trade API Module Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Import the Alpaca module to begin using the library. ```js const Alpaca = require('@alpacahq/alpaca-trade-api') ``` -------------------------------- ### Get Latest Crypto Trades Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-crypto.md Retrieves the most recent trade for multiple cryptocurrency symbols. Use this to get the latest transaction price and volume for specified crypto pairs. ```javascript const latestTrades = await alpaca.getLatestCryptoTrades(['BTC/USD', 'ETH/USD']); latestTrades.forEach((trade, symbol) => { console.log(`${symbol}: $${trade.Price}`); }); ``` -------------------------------- ### OAuth Authentication Environment Variable Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Set this environment variable for OAuth authentication. Replace 'your_oauth_token' with your valid OAuth token. ```bash # OAuth Authentication export APCA_API_OAUTH="your_oauth_token" ``` -------------------------------- ### Access Runtime Configuration Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md After initializing the Alpaca client, its configuration settings are available through the `configuration` property. This allows dynamic access to parameters like base URLs and API keys. ```javascript const alpaca = new Alpaca({ keyId: 'KEY', secretKey: 'SECRET', paper: true, feed: 'iex', }); // Access configuration at runtime console.log(alpaca.configuration.baseUrl); console.log(alpaca.configuration.dataBaseUrl); console.log(alpaca.configuration.keyId); console.log(alpaca.configuration.feed); console.log(alpaca.configuration.optionFeed); ``` -------------------------------- ### Get Portfolio History Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/README.md Fetches historical portfolio data. Supports specifying date ranges, periods, timeframes, and extended hours trading. This method calls `GET /account/portfolio/history`. ```typescript getPortfolioHistory({ date_start: Date, date_end: Date, period: '1M' | '3M' | '6M' | '1A' | 'all' | 'intraday', timeframe: '1Min' | '5Min' | '15Min' | '1H' | '1D', extended_hours: Boolean }) => Promise ``` -------------------------------- ### Configure Alpaca for Production with Environment Variables Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/configuration.md Configure the Alpaca client for production by relying on environment variables for API credentials and endpoint URLs. The client can be instantiated with no arguments if all necessary environment variables are set. ```javascript const alpaca = new Alpaca(); // All config from environment ``` -------------------------------- ### Get Option Latest Quotes Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-options.md Retrieves the most recent quote for multiple option symbols. This is useful for getting a quick overview of current bid and ask prices for a list of options. ```APIDOC ## getOptionLatestQuotes(symbols, config) ### Description Retrieves the most recent quote for multiple option symbols. ### Method Signature ```typescript getOptionLatestQuotes(symbols: Array, config?: any): Promise> ``` ### Parameters - **symbols** (Array) - Required - An array of option symbols to retrieve quotes for. - **config** (any) - Optional - Configuration object. ### Return Value Returns a Promise that resolves to a Map where keys are option symbols and values are `AlpacaOptionQuote` objects. ### Example ```javascript const quotes = await alpaca.getOptionLatestQuotes(['AAPL250117C150']); quotes.forEach((quote, symbol) => { console.log(`${symbol}:`); console.log(` Bid: $${quote.BidPrice} x ${quote.BidSize}`); console.log(` Ask: $${quote.AskPrice} x ${quote.AskSize}`); }); ``` ``` -------------------------------- ### Get Latest Crypto Quotes Source: https://github.com/alpacahq/alpaca-trade-api-js/blob/master/_autodocs/api-reference/market-data-crypto.md Retrieves the most recent quote for multiple cryptocurrency symbols. Use this to get the current best bid and ask prices and sizes for crypto pairs. ```javascript const quotes = await alpaca.getLatestCryptoQuotes(['BTC/USD', 'ETH/USD']); quotes.forEach((quote, symbol) => { console.log(`${symbol}:`); console.log(` Bid: $${quote.BidPrice} @ ${quote.BidSize}`); console.log(` Ask: $${quote.AskPrice} @ ${quote.AskSize}`); }); ```