Node.js library for Alpaca Trade API.
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.
npm install --save @alpacahq/alpaca-trade-api
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()
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.
Calls GET /account
and returns the current account.
getAccount() => Promise<Account>
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>
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[]>
Calls GET /orders/{id}
and returns an order.
getOrder(uuid) => Promise<Order>
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>
Calls DELETE /orders/{id}
and deletes an order.
cancelOrder(uuid) => Promise
Calls GET /positions/{symbol}
and returns a position.
getPosition(symbol) => Promise<Position>
Calls GET /positions
and returns all positions.
getPositions() => Promise<Position[]>
Calls GET /assets
and returns assets matching your parameters.
getAssets({
status: 'active' | 'inactive',
asset_class: string,
}) => Promise<Asset[]>
Calls GET /assets/{symbol}
and returns an asset entity.
getAsset(symbol) => Promise<Asset>
Calls GET /calendar
and returns the market calendar.
getCalendar({ start: Date, end: Date }) => Promise<Calendar[]>
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
}
)
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. For more information, please contact the relevant pages.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.*'.