Alpaca Trade API JS
Node.js library for Alpaca Trade API.
API Documentation
The REST API documentation can be found in https://docs.alpaca.markets. For detailed information about an endpoint, please consult the REST API docs. Documentation specific to this library can be found below.
Installation
npm install --save @alpacahq/alpaca-trade-api
Usage
Import the module first.
const Alpaca = require('@alpacahq/alpaca-trade-api')
Instantiate the API with config options (keyId, secretKey).
const alpaca = new Alpaca({
keyId: 'AKFZXJH121U18SHHDRFO',
secretKey: 'pnq4YHlpMF3LhfLyOvmdfLmlz6BnASrTPQIASeiU',
paper: true,
})
Call methods, which will return a promise.
alpaca.getAccount().then((account) => {
console.log('Current Account:', account)
})
The websocket api is a good way to watch and react to the market
const client = alpaca.websocket
client.onConnect(function() {
console.log("Connected")
client.subscribe(['trade_updates', 'account_updates', 'T.FB', 'Q.AAPL', 'A.FB', 'AM.AAPL'])
setTimeout(() => {
client.disconnect()
}, 30 * 1000)
})
client.onDisconnect(() => {
console.log("Disconnected")
})
client.onStateChange(newState => {
console.log(`State changed to ${newState}`)
})
client.onOrderUpdate(data => {
console.log(`Order updates: ${JSON.stringify(data)}`)
})
client.onAccountUpdate(data => {
console.log(`Account updates: ${JSON.stringify(data)}`)
})
client.onStockTrades(function(subject, data) {
console.log(`Stock trades: ${subject}, ${data}`)
})
client.onStockQuotes(function(subject, data) {
console.log(`Stock quotes: ${subject}, ${data}`)
})
client.onStockAggSec(function(subject, data) {
console.log(`Stock agg sec: ${subject}, ${data}`)
})
client.onStockAggMin(function(subject, data) {
console.log(`Stock agg min: ${subject}, ${data}`)
})
client.connect()
Methods
As a general rule, required method parameters are passed as plain function arguments, and the final parameter is an object containing any optional parameters to the method.
Account API
Calls GET /account
and returns the current account.
getAccount() => Promise<Account>
Orders API
Create Order
Calls POST /orders
and creates a new order.
createOrder({
symbol: string, // any valid ticker symbol
qty: number,
side: 'buy' | 'sell',
type: 'market' | 'limit' | 'stop' | 'stop_limit',
time_in_force: 'day' | 'gtc' | 'opg' | 'ioc',
limit_price: number,
stop_price: number,
client_order_id: string // optional
}) => Promise<Order>
Get Orders
Calls GET /orders
and returns a list of orders.
getOrders({
status: 'open' | 'closed' | 'all',
after: Date,
until: Date,
limit: number,
direction: 'asc' | 'desc'
}) => Promise<Order[]>
Get Order by ID
Calls GET /orders/{id}
and returns an order.
getOrder(uuid) => Promise<Order>
Get Order by Client ID
Calls GET /orders:by_client_order_id
and returns an order by client_order_id
.
You can set client_order_id
upon order creation to more easily keep track of your orders.
getOrderByClientOrderId(string) => Promise<Order>
Cancel Order
Calls DELETE /orders/{id}
and deletes an order.
cancelOrder(uuid) => Promise
Positions API
Get Position
Calls GET /positions/{symbol}
and returns a position.
getPosition(symbol) => Promise<Position>
Get All Positions
Calls GET /positions
and returns all positions.
getPositions() => Promise<Position[]>
Assets API
Get All Assets
Calls GET /assets
and returns assets matching your parameters.
getAssets({
status: 'active' | 'inactive',
asset_class: string,
}) => Promise<Asset[]>
Get information about an asset
Calls GET /assets/{symbol}
and returns an asset entity.
getAsset(symbol) => Promise<Asset>
Calendar API
Calls GET /calendar
and returns the market calendar.
getCalendar({ start: Date, end: Date }) => Promise<Calendar[]>
Data API
Get Bars
getBars(
'minute' | '1Min' | '5Min' | '15Min' | 'day' | '1D',
symbol | symbol[], // which ticker symbols to get bars for
{
limit: number,
start: Date,
end: Date,
after: Date,
until: Date
}
)
Websockets
let websocket = alpaca.websocket
: Create a websocket client instance.websocket.connect()
: Connect to the alpaca server using websocket.websocket.subscribe(channels)
: Subscribe to the alpaca server and possibly Polygon server Possible channels: 'trade_updates', 'account_updates', 'T.', 'Q.', 'A.', AM.' This will unsubscribe from any previously subscribed channels.trade_updates
andaccount_updates
are for the alpaca server, the rest are for the Polygon server. In order to make calls to the Polygon api, you must have opened your Alpaca brokerage account. Otherwise Polygon's api will be unavailable.websocket.onOrderUpdate(function(data))
: Register callback function for the channel 'trade_updates'.websocket.onAccountUpdate(function(data))
: Register callback function for the channel 'account_updates'.websocket.onStockTrades(function(data))
: Register callback function for the channel 'T.*'.websocket.onStockQuotes(function(data))
: Register callback function for the channel 'Q.*'.websocket.onStockAggSec(function(data))
: Register callback function for the channel 'A.*'.websocket.onStockAggMin(function(data))
: Register callback function for the channel 'AM.*'.