alpaca-ts
v0.2.0
Published
A TypeScript SDK for the https://alpaca.markets REST API and WebSocket streams.
Maintainers
Keywords
Readme
alpaca-ts
A TypeScript SDK for the https://alpaca.markets REST API and WebSocket streams.
Features
- [x] REST API
- [x] WebSocket Streams
- [x] Built-in Rate Limiting (Token Bucket)
- [x] TypeScript
- [x] Deno
- [x] Node (ESM)
- [x] > 35% Test Coverage (and growing)
- [x] Tree-shakable
- [x] Both ESM and CJS Support
- [x] Zero Dependencies 🤯 (you read that right)
- [x] Community Driven 🚀
Feel free to contribute and PR to your 💖's content.
Install
From NPM:
npm install alpaca-tsFrom Skypack (or any CDN that supports ESM):
import { createClient } from "https://cdn.skypack.dev/alpaca-ts";Usage
Create a Client
First, you'll need to create an API key on the Alpaca website. You can do that here. Once you have an API key, you can use it to create a client.
import { createClient } from "alpaca-ts";
const client = createClient({
key: "YOUR_API_KEY_ID",
secret: "YOUR_API_SECRET_KEY",
// Or, provide an access token if you're using OAuth.
// accessToken: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
});By default, the client will make requests to the paper trading environment (https://paper-api.alpaca.markets). This is a safety measure to prevent accidental trades.
Configuration
Environment Variables
You can set the following environment variables to configure the client:
APCA_KEY_ID: Your API key.APCA_KEY_SECRET: Your API secret.APCA_ACCESS_TOKEN: Your access token (if using OAuth).APCA_DEBUG: Enables debug logging.
The client will automatically use these values if they are set. They will not override any credentials explicitly passed to createClient.
Rate Limiting
You can customize the rate limiting by passing a tokenBucket object to the createClient function. This object should contain the capacity and fillRate for the rate limiter.
tokenBucket: {
// Maximum number of tokens that can be stored
capacity: 200,
// Number of tokens refilled per second
fillRate: 60,
}Bursting is allowed, but the client will block requests if the token bucket is empty. The token bucket is shared across all requests. If you have multiple clients they will not share the same bucket.
Methods
Trading API
Account
getAccount- Get account informationgetAccountConfigurations- Get account configurationsupdateAccountConfigurations- Update account configurationsgetPortfolioHistory- Get portfolio history
Orders
createOrder- Create a new ordergetOrder- Get order by IDgetOrderByClientOrderId- Get order by client order IDgetOrders- List ordersreplaceOrder- Replace an existing ordercancelOrder- Cancel an ordercancelAllOrders- Cancel all open orders
Positions
getPosition- Get a positiongetPositions- List all positionsclosePosition- Close a positioncloseAllPositions- Close all positionsexerciseOption- Exercise an options contractdoNotExerciseOption- Elect to not exercise an options contract
Assets
Calendar
getCalendar- Get market calendargetClock- Get market clock
Activities
getActivity- Get activities by typegetActivities- List all activities
Options Contracts
getOptionsContract- Get an options contractgetOptionsContracts- List options contracts
Watchlists
getWatchlist- Get a watchlist by IDgetWatchlistByName- Get a watchlist by namegetWatchlists- List all watchlistscreateWatchlist- Create a watchlistupdateWatchlist- Update a watchlist by IDupdateWatchlistByName- Update a watchlist by namedeleteWatchlist- Delete a watchlist by IDdeleteWatchlistByName- Delete a watchlist by nameaddAssetToWatchlist- Add an asset to watchlist by IDaddAssetToWatchlistByName- Add an asset to watchlist by nameremoveAssetFromWatchlist- Remove an asset from watchlist
Corporate Actions (Announcements)
getCorporateAction- Get a corporate action announcementgetCorporateActions- List corporate action announcements
Crypto Funding
getCryptoWallet- Get a crypto walletgetCryptoWallets- List all crypto walletsgetFeeEstimate- Get fee estimate for withdrawalgetCryptoTransfer- Get a crypto transfergetCryptoTransfers- List crypto transferscreateCryptoTransfer- Create a crypto withdrawalgetCryptoWhitelistedAddress- Get a whitelisted addressgetCryptoWhitelistedAddresses- List whitelisted addressesrequestCryptoWhitelistedAddress- Request a whitelisted addressremoveCryptoWhitelistedAddress- Remove a whitelisted address
Market Data API
Stocks
getStocksBars- Get stock barsgetStocksBarsLatest- Get latest stock barsgetStocksQuotes- Get stock quotesgetStocksQuotesLatest- Get latest stock quotesgetStocksTrades- Get stock tradesgetStocksTradesLatest- Get latest stock tradesgetStocksSnapshots- Get stock snapshotsgetStocksAuctions- Get stock auctionsgetStocksConditions- Get condition codesgetStocksExchangeCodes- Get exchange codes
Crypto
getCryptoBars- Get crypto barsgetLatestCryptoBars- Get latest crypto barsgetCryptoQuotes- Get crypto quotesgetCryptoQuotesLatest- Get latest crypto quotesgetCryptoTrades- Get crypto tradesgetCryptoTradesLatest- Get latest crypto tradesgetCryptoSnapshots- Get crypto snapshotsgetLatestCryptoOrderbooks- Get latest crypto orderbooks
Options
getOptionsBars- Get options barsgetOptionsTrades- Get options tradesgetOptionsTradesLatest- Get latest options tradesgetOptionsSnapshots- Get options snapshotsgetOptionsExchanges- Get options exchanges
Forex
getForexRates- Get forex ratesgetLatestForexRates- Get latest forex rates
News
getNews- Get news articles
Screener
getStocksMostActives- Get most active stocksgetStocksMarketMovers- Get market movers
Logos
getLogo- Get company logo
Corporate Actions (Market Data)
getStocksCorporateActions- Get corporate actions data
getAccount
Retrieves the account information.
client.getAccount().then(console.log);createOrder
Creates a new order.
client
.createOrder({
symbol: "AAPL",
qty: 1,
side: "buy",
type: "market",
time_in_force: "day",
})
.then(console.log);getOrder
Retrieves a specific order by its ID.
client
.getOrder({ order_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" })
.then(console.log);getOrderByClientOrderId
Retrieves a specific order by its client order ID.
client
.getOrderByClientOrderId({ client_order_id: "my-custom-order-id" })
.then(console.log);getOrders
Retrieves a list of orders based on the specified parameters.
client
.getOrders({
status: "open",
limit: 10,
direction: "desc",
})
.then(console.log);replaceOrder
Replaces an existing order with updated parameters.
client
.replaceOrder({
qty: 2,
limit_price: 150.0,
order_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);cancelOrder
Cancels a specific order by its ID.
client
.cancelOrder({ order_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" })
.then(console.log);cancelAllOrders
Cancels all open orders.
client.cancelAllOrders().then(console.log);getPosition
Retrieves a specific position by symbol or asset ID.
client
.getPosition({
symbol_or_asset_id: "AAPL",
})
.then(console.log);getPositions
Retrieves all positions.
client.getPositions().then(console.log);closePosition
Closes a specific position by symbol or asset ID.
client
.closePosition({
symbol_or_asset_id: "AAPL",
})
.then(console.log);closeAllPositions
Closes all positions.
client.closeAllPositions().then(console.log);exerciseOption
Exercises an options contract.
client
.exerciseOption({
symbol_or_contract_id: "AAPL250117C00150000",
})
.then(console.log);doNotExerciseOption
Elects to not exercise an options contract.
client
.doNotExerciseOption({
symbol_or_contract_id: "AAPL250117C00150000",
})
.then(console.log);getCalendar
Retrieves the market calendar.
client
.getCalendar({
start: "2023-01-01",
end: "2023-12-31",
})
.then(console.log);getClock
Retrieves the current market clock.
client.getClock().then(console.log);getAsset
Retrieves a specific asset by symbol or asset ID.
client
.getAsset({
symbol_or_asset_id: "AAPL",
})
.then(console.log);getAssets
Retrieves a list of assets based on the specified parameters.
client
.getAssets({
status: "active",
asset_class: "us_equity",
})
.then(console.log);getWatchlist
Retrieves a specific watchlist by ID.
client
.getWatchlist({
watchlist_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);getWatchlists
Retrieves all watchlists.
client.getWatchlists().then(console.log);createWatchlist
Creates a new watchlist.
client
.createWatchlist({
name: "My Watchlist",
symbols: ["AAPL", "GOOGL", "AMZN"],
})
.then(console.log);updateWatchlist
Updates an existing watchlist.
client
.updateWatchlist({
name: "Updated Watchlist",
symbols: ["AAPL", "GOOGL", "MSFT"],
watchlist_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);deleteWatchlist
Deletes a specific watchlist by ID.
client
.deleteWatchlist({
watchlist_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);getWatchlistByName
Retrieves a specific watchlist by name.
client
.getWatchlistByName({
name: "My Watchlist",
})
.then(console.log);updateWatchlistByName
Updates an existing watchlist by name.
client
.updateWatchlistByName({
name: "My Watchlist",
symbols: ["AAPL", "GOOGL", "MSFT"],
})
.then(console.log);deleteWatchlistByName
Deletes a specific watchlist by name.
client
.deleteWatchlistByName({
name: "My Watchlist",
})
.then(console.log);addAssetToWatchlist
Adds an asset to a watchlist by watchlist ID.
client
.addAssetToWatchlist({
watchlist_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
symbol: "NVDA",
})
.then(console.log);addAssetToWatchlistByName
Adds an asset to a watchlist by watchlist name.
client
.addAssetToWatchlistByName({
name: "My Watchlist",
symbol: "NVDA",
})
.then(console.log);removeAssetFromWatchlist
Removes an asset from a watchlist.
client
.removeAssetFromWatchlist({
watchlist_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
symbol: "NVDA",
})
.then(console.log);getPortfolioHistory
Retrieves the portfolio history.
client
.getPortfolioHistory({
period: "1M",
timeframe: "1D",
})
.then(console.log);getAccountConfigurations
Retrieves the account configurations.
client.getAccountConfigurations().then(console.log);updateAccountConfigurations
Updates the account configurations.
client
.updateAccountConfigurations({
trade_confirm_email: "all",
suspend_trade: false,
})
.then(console.log);getActivity
Retrieves a specific activity type.
client
.getActivity({
activity_type: "FILL",
})
.then(console.log);getActivities
Retrieves all activities.
client.getActivities().then(console.log);getOptionsContract
Retrieves a specific options contract by symbol or contract ID.
client
.getOptionsContract({
symbol_or_contract_id: "AAPL230616C00150000",
})
.then(console.log);getOptionsContracts
Retrieves a list of options contracts based on the specified parameters.
client
.getOptionsContracts({
underlying_symbols: "AAPL",
expiration_date: "2023-06-16",
})
.then(console.log);getCorporateAction
Retrieves a specific corporate action by ID.
client
.getCorporateAction({
id: "xxxxxxxx",
})
.then(console.log);getCorporateActions
Retrieves a list of corporate actions based on the specified parameters.
client
.getCorporateActions({
ca_types: "MERGER",
since: "2023-01-01",
until: "2023-12-31",
})
.then(console.log);getCryptoWallet
Retrieves a specific crypto wallet by asset.
client
.getCryptoWallet({
asset: "BTCUSD",
})
.then(console.log);getCryptoWallets
Retrieves all crypto wallets.
client.getCryptoWallets().then(console.log);getFeeEstimate
Retrieves the fee estimate for a crypto withdrawal.
client
.getFeeEstimate({
asset: "BTCUSD",
from_address: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
to_address: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
amount: "0.1",
})
.then(console.log);getCryptoTransfer
Retrieves a specific crypto transfer by ID.
client
.getCryptoTransfer({
transfer_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);getCryptoTransfers
Retrieves a list of crypto transfers based on the specified parameters.
client
.getCryptoTransfers({
asset: "BTCUSD",
})
.then(console.log);createCryptoTransfer
Creates a new crypto withdrawal.
client
.createCryptoTransfer({
amount: "0.1",
address: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
asset: "BTCUSD",
})
.then(console.log);getCryptoWhitelistedAddress
Retrieves a specific whitelisted crypto address.
client
.getCryptoWhitelistedAddress({
address: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
asset: "BTCUSD",
})
.then(console.log);getCryptoWhitelistedAddresses
Retrieves all whitelisted crypto addresses.
client.getCryptoWhitelistedAddresses().then(console.log);requestCryptoWhitelistedAddress
Requests a new whitelisted crypto address.
client
.requestCryptoWhitelistedAddress({
address: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
asset: "BTCUSD",
})
.then(console.log);removeCryptoWhitelistedAddress
Removes a specific whitelisted crypto address.
client
.removeCryptoWhitelistedAddress({
whitelisted_address_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
})
.then(console.log);getStocksCorporateActions
Retrieves a list of corporate actions based on the specified parameters.
client
.getStocksCorporateActions({
symbols: "AAPL",
types: "cash_dividends",
})
.then(console.log);getLogo
Retrieves the logo for a specific symbol.
client
.getLogo({
symbol: "AAPL",
})
.then(console.log);getNews
Retrieves the latest news.
client
.getNews({
symbols: "AAPL,TSLA",
limit: 10,
})
.then(console.log);getStocksMostActives
Retrieves a list of the most active stocks.
client
.getStocksMostActives({
by: "volume",
top: 10,
})
.then(console.log);getStocksMarketMovers
Retrieves a list of the top market movers.
client
.getStocksMarketMovers({
by: "change",
top: 10,
})
.then(console.log);getStocksQuotes
Retrieves a list of stock quotes.
client
.getStocksQuotes({
symbols: "AAPL,TSLA",
limit: 10,
})
.then(console.log);getStocksQuotesLatest
Retrieves the latest stock quotes.
client
.getStocksQuotesLatest({
symbols: "AAPL,TSLA",
})
.then(console.log);getStocksBars
Retrieves a list of stock bars.
client
.getStocksBars({
symbols: "AAPL,TSLA",
timeframe: "1Day",
limit: 10,
})
.then(console.log);getStocksBarsLatest
Retrieves the latest stock bars.
client
.getStocksBarsLatest({
symbols: "AAPL,TSLA",
})
.then(console.log);getForexRates
Retrieves a list of forex rates.
client
.getForexRates({
currency_pairs: "EURUSD,GBPUSD",
timeframe: "1Min",
limit: 10,
})
.then(console.log);getLatestForexRates
Retrieves the latest forex rates.
client
.getLatestForexRates({
currency_pairs: "EURUSD,GBPUSD",
})
.then(console.log);getStocksSnapshots
Retrieves a list of stock snapshots.
client
.getStocksSnapshots({
symbols: "AAPL,TSLA",
})
.then(console.log);getStocksAuctions
Retrieves a list of stock auctions.
client
.getStocksAuctions({
symbols: "AAPL,TSLA",
limit: 10,
})
.then(console.log);getStocksConditions
Retrieves a list of stock conditions.
client
.getStocksConditions({
tickType: "trades",
tape: "xxx",
})
.then(console.log);getStocksExchangeCodes
Retrieves a list of stock exchange codes.
client.getStocksExchangeCodes().then(console.log);getStocksTrades
Retrieves a list of stock trades.
client
.getStocksTrades({
symbols: "AAPL,TSLA",
limit: 10,
})
.then(console.log);getStocksTradesLatest
Retrieves the latest stock trades.
client
.getStocksTradesLatest({
symbols: "AAPL,TSLA",
})
.then(console.log);getOptionsBars
Retrieves a list of options bars.
client
.getOptionsBars({
symbols: "AAPL220617C00270000,TSLA220617C01000000",
timeframe: "1Day",
limit: 10,
})
.then(console.log);getOptionsExchanges
Retrieves a list of options exchanges.
client.getOptionsExchanges().then(console.log);getOptionsSnapshots
Retrieves a list of options snapshots.
client
.getOptionsSnapshots({
symbols: "AAPL220617C00270000,TSLA220617C01000000",
})
.then(console.log);getOptionsTrades
Retrieves a list of options trades.
client
.getOptionsTrades({
symbols: "AAPL220617C00270000,TSLA220617C01000000",
limit: 10,
})
.then(console.log);getOptionsTradesLatest
Retrieves the latest options trades.
client
.getOptionsTradesLatest({
symbols: "AAPL220617C00270000,TSLA220617C01000000",
})
.then(console.log);getCryptoBars
Retrieves a list of crypto bars.
client
.getCryptoBars({
symbols: "BTCUSD,ETHUSD",
timeframe: "1Min",
limit: 10,
})
.then(console.log);getLatestCryptoBars
Retrieves the latest crypto bars.
client
.getLatestCryptoBars({
loc: "US",
symbols: "BTCUSD,ETHUSD",
})
.then(console.log);getCryptoQuotes
Retrieves a list of crypto quotes.
client
.getCryptoQuotes({
symbols: "BTCUSD,ETHUSD",
limit: 10,
})
.then(console.log);getCryptoQuotesLatest
Retrieves the latest crypto quotes.
client
.getCryptoQuotesLatest({
loc: "US",
symbols: "BTCUSD,ETHUSD",
})
.then(console.log);getCryptoSnapshots
Retrieves a list of crypto snapshots.
client
.getCryptoSnapshots({
loc: "US",
symbols: "BTCUSD,ETHUSD",
})
.then(console.log);getCryptoTrades
Retrieves a list of crypto trades.
client
.getCryptoTrades({
loc: "US",
symbols: "BTCUSD,ETHUSD",
limit: 10,
})
.then(console.log);getCryptoTradesLatest
Retrieves the latest crypto trades.
client
.getCryptoTradesLatest({
loc: "US",
symbols: "BTCUSD,ETHUSD",
})
.then(console.log);getLatestCryptoOrderbooks
Retrieves the latest crypto orderbooks.
client
.getLatestCryptoOrderbooks({
loc: "US",
symbols: "BTCUSD,ETHUSD",
})
.then(console.log);WebSocket
How It Works
todo
Channels
todo
Examples
todo
Need Help?
The primary maintainer of this project is @117. Feel free to reach out on Slack 👋 or by opening an issue on this repo. I'm happy to help with any questions or issues you may have.
