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 =
Instantiate the API with config options, obtained from the dashboard at app.alpaca.markets.
const alpaca = keyId: 'AKFZXJH121U18SHHDRFO' secretKey: 'pnq4YHlpMF3LhfLyOvmdfLmlz6BnASrTPQIASeiU' paper: true usePolygon: false
Note: keyId
and secretKey
may also be specified by setting the APCA_API_KEY_ID
and APCA_API_SECRET_KEY
environment variables, respectively. Also, rather than specifying paper
, you may set APCA_API_BASE_URL
as an environment variable to direct your API calls to the paper trading API.
Call methods, which will return a promise.
alpaca
The websocket api is a good way to watch and react to the market we have 2 types of websockets:
- data websocket: get updates data equities
- account/trade websocket: get updates on your account
please refer to this example code to see how to use the websockets.
Data WS
you could use one of the 2 websockets we provide:
- The Alpaca WS
- The Polygon WS
The default WS is Alpaca. and you could use it even if you don't have a
funded account. The polygon WS can only be used with a funded account.
In order to use the Polygon WS you need to pass this parameter to the
Alpaca constructor usePolygon: true
Subscribing to the different WS
The other difference is the way we subscribe to different channels.
Alpaca
client
Polygon
client
Example Code
const client = alpacadata_wsclientclientclientclientclientclientclientclient
Account WS
used like this
const updates_client = thisalpacatrade_wsupdates_clientupdates_clientupdates_clientupdates_clientupdates_clientupdates_client
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
Get Account
Calls GET /account
and returns the current account.
getAccount Promise<Account>
Account Configurations API
Get Account Configurations
Calls GET /account/configurations
and returns the current account configurations.
getAccountConfigurations Promise<AccountConfigurations>
Update Account Configurations
Calls PATCH /account/configurations
to update the account configurations, and returns
the updated configurations.
updateAccountConfigurationsAccountConfigurations Promise<AccountConfigurations>
Get Account Activities
Calls GET /account/activities
and returns account actvities.
getActivities Promise<AccountActivity>
Portfolio History API
Get Portfolio History
Calls GET /account/portfolio/history
and returns portfolio history.
getPortfolioHistory Promise<PortfolioHistory>
Orders API
Create Order
Calls POST /orders
and creates a new order.
createOrder Promise<Order>
Get Orders
Calls GET /orders
and returns a list of orders.
getOrders Promise<Order>
Get Order by ID
Calls GET /orders/{id}
and returns an order.
getOrderuuid 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.
getOrderByClientOrderIdstring Promise<Order>
Update Order by ID
Calls PATCH /orders/{id}
and updates an existing open order. The updated order will have
a new ID.
replaceOrderuuid Promise<Order>
Cancel Order
Calls DELETE /orders/{id}
and deletes an order.
cancelOrderuuid Promise
Cancel all Orders
Calls DELETE /orders
and deletes all open orders.
cancelAllOrders Promise
Positions API
Get Position
Calls GET /positions/{symbol}
and returns a position.
getPositionsymbol Promise<Position>
Get All Positions
Calls GET /positions
and returns all positions.
getPositions Promise<Position>
Close a Position
Calls DELETE /positions/{symbol}
and liquidates your position in the given symbol.
closePositionsymbol Promise
Close all Positions
Calls DELETE /positions
and liquidates all open positions.
closeAllPositions Promise
Assets API
Get All Assets
Calls GET /assets
and returns assets matching your parameters.
getAssets Promise<Asset>
Get information about an asset
Calls GET /assets/{symbol}
and returns an asset entity.
getAssetsymbol Promise<Asset>
Calendar API
Calls GET /calendar
and returns the market calendar.
getCalendar Promise<Calendar>
Data API
Get Bars
getBars 'minute' | '1Min' | '5Min' | '15Min' | 'day' | '1D', symbol | symbol, // which ticker symbols to get bars for Promise<BarsObject>
example
thisalpaca
Get Aggregates
getAggregates symbol: string, timespan: 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year', from: Date, to: Date, Promise<AggregatesObject>
example
thisalpaca
Last trade
lastTrade symbol: string) Promise<LastTradeObject>
example
thisalpaca
Last quote
lastQuote symbol: string) Promise<LastQuoteObject>
example
thisalpaca
Websockets
When to use which websocket?
- first of all - if you don't have a funded account you cannot use the
polygon websocket.
The data in the Alpaca websocket is free (currently in beta) and this is your only option. - if you do have a funded account read the docs to understand exactly what
are the differences between the data streams
Now since there's is a redundancy in the data we assume that if you use one
you will not use the other.
The way you select which websocket to use is by setting the usePolygon
argument when creating the Alpaca instance (see example above).
Working with websocket
-
The websocket is created when you creating the Alpaca instance
-
let websocket = alpaca.data_ws
: Get the websocket client instance. -
websocket.connect()
: Connect to the Alpaca server using websocket. -
client.onConnect(function() {}
: all the following code should be inside this function because we should not do anything until we're connected to the websocket. -
websocket.subscribe(channels)
: Subscribe to the Alpaca data server and/or the Polygon server.
Please note that Polygon and Alpaca servers use different channels.
You need to specify the channel you want to subscribe to as specified here:
Channels for the Polygon service:['T.*', 'Q.*', 'A.*', 'AM.*']
.
Channels for the Alpaca data service:['alpacadatav1/T .*', 'alpacadatav1/Q.*', 'alpacadatav1'/AM.*]
When calling
subscribe()
first it will unsubscribe from any previously subscribed channels (so if you want to add channels you need to specifiy all channels you want to subscribe to).
Channels'trade_updates'
,'account_updates'
and all'alpacadatav1 /*.*'
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.
Callbacks
how to get the data you subscribed to. we do this by calling these methods with our callback for each and every channel:
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.<SYMBOL>'
or'alpacadatav1/T.<SYMBOL>'
.websocket.onStockQuotes(function(data))
: Register callback function for the channel'Q.<SYMBOL>'
or'alpacadatav1/Q.<SYMBOL>'
.websocket.onStockAggSec(function(data))
: Register callback function for the channel'A.<SYMBOL>'
. (Polygon only)websocket.onStockAggMin(function(data))
: Register callback function for the channel'AM.<SYMBOL>'
or'alpacadatav1/AM.<SYMBOL>'
.