A new python SDK, Alpaca-py, is available. This SDK will be the primary python SDK starting in 2023. We recommend moving over your code to use the new SDK. Keep in mind, we will be maintaining this repo as usual until the end of 2022.
alpaca-trade-api-python
alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.
It allows rapid trading algo development easily, with support for
both REST and streaming data interfaces. For details of each API behavior,
please see the online API document.
Note that this package supports only python version 3.7 and above.
Install
We support python>=3.7. If you want to work with python 3.6, please note that these package dropped support for python <3.7 for the following versions:
pandas >= 1.2.0
numpy >= 1.20.0
scipy >= 1.6.0
The solution - manually install these packages before installing alpaca-trade-api. e.g:
The free services are limited, please check the docs to see the differences between paid/free services.
Alpaca Environment Variables
The Alpaca SDK will check the environment for a number of variables that can be used rather than hard-coding these into your scripts.
Alternatively you could pass the credentials directly to the SDK instances.
The number of subsequent API calls to retry on timeouts
APCA_RETRY_WAIT=3
3
seconds to wait between each retry attempt
APCA_RETRY_CODES=429,504
429,504
comma-separated HTTP status code for which retry is attempted
DATA_PROXY_WS
When using the alpaca-proxy-agent you need to set this environment variable as described
Working with Data
Historic Data
You could get one of these historic data types:
Bars
Quotes
Trades
You now have 2 pythonic ways to retrieve historical data.
One using the traditional rest module and the other is to use the experimental asyncio module added lately.
Let's have a look at both:
The first thing to understand is the new data polling mechanism. You could query up to 10000 items, and the API is using a pagination mechanism to provide you with the data.
You now have 2 options:
Working with data as it is received with a generator. (meaning it's faster but you need to process each item alone)
Wait for the entire data to be received, and then work with it as a list or dataframe.
We provide you with both options to choose from.
def process_bar(bar):
# process bar
print(bar)
bar_iter = api.get_bars_iter("AAPL", TimeFrame.Hour, "2021-06-08", "2021-06-08", adjustment='raw')
for bar in bar_iter:
process_bar(bar)
Alternatively, you can decide on your custom timeframes by using the TimeFrame constructor:
from alpaca_trade_api.rest import REST
api = REST()
api.get_quotes("AAPL", "2021-06-08", "2021-06-08", limit=10).df
ask_exchange ask_price ask_size bid_exchange bid_price bid_size conditions
timestamp
2021-06-08 08:00:00.070928640+00:00 P 143.00 1 0.00 0 [Y]
2021-06-08 08:00:00.070929408+00:00 P 143.00 1 P 102.51 1 [R]
2021-06-08 08:00:00.070976768+00:00 P 143.00 1 P 116.50 1 [R]
2021-06-08 08:00:00.070978816+00:00 P 143.00 1 P 118.18 1 [R]
2021-06-08 08:00:00.071020288+00:00 P 143.00 1 P 120.00 1 [R]
2021-06-08 08:00:00.071020544+00:00 P 134.18 1 P 120.00 1 [R]
2021-06-08 08:00:00.071021312+00:00 P 134.18 1 P 123.36 1 [R]
2021-06-08 08:00:00.071209984+00:00 P 131.11 1 P 123.36 1 [R]
2021-06-08 08:00:00.071248640+00:00 P 130.13 1 P 123.36 1 [R]
2021-06-08 08:00:00.071286016+00:00 P 129.80 1 P 123.36 1 [R]
option 2: iterate over quotes
def process_quote(quote):
# process quote
print(quote)
quote_iter = api.get_quotes_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
for quote in quote_iter:
process_quote(quote)
Trades
option 1: wait for the data
from alpaca_trade_api.rest import REST
api = REST()
api.get_trades("AAPL", "2021-06-08", "2021-06-08", limit=10).df
exchange price size conditions id tape
timestamp
2021-06-08 08:00:00.069956608+00:00 P 126.10 179 [@, T] 1 C
2021-06-08 08:00:00.207859+00:00 K 125.97 1 [@, T, I] 1 C
2021-06-08 08:00:00.207859+00:00 K 125.97 12 [@, T, I] 2 C
2021-06-08 08:00:00.207859+00:00 K 125.97 4 [@, T, I] 3 C
2021-06-08 08:00:00.207859+00:00 K 125.97 4 [@, T, I] 4 C
2021-06-08 08:00:00.207859+00:00 K 125.97 8 [@, T, I] 5 C
2021-06-08 08:00:00.207859+00:00 K 125.97 1 [@, T, I] 6 C
2021-06-08 08:00:00.207859+00:00 K 126.00 30 [@, T, I] 7 C
2021-06-08 08:00:00.207859+00:00 K 126.00 10 [@, T, I] 8 C
2021-06-08 08:00:00.207859+00:00 K 125.97 70 [@, T, I] 9 C
option 2: iterate over trades
def process_trade(trade):
# process trade
print(trade)
trades_iter = api.get_trades_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
for trade in trades_iter:
process_trade(trade)
Asyncio Rest module
The rest_async.py module now provides an asyncion approach to retrieving the historic data.
This module is, and thus may have expansions in the near future to support more endpoints.
It provides a much faster way to retrieve the historic data for multiple symbols.
Under the hood we use the aiohttp library.
We provide a code sample to get you started with this new approach and it is located here.
Follow along with the example code to learn more, and utilize it for your own needs.
The free plan is using the iex stream, while the paid subscription is using the sip stream.
You can subscribe to bars, trades, quotes, and trade updates for your account as well.
Under the example folder you can find different code samples
to achieve different goals.
Here in this basic example, We use the Stream class under alpaca_trade_api.stream for API V2 to subscribe to trade
updates for AAPL and quote updates for IBM.
from alpaca_trade_api.common import URL
from alpaca_trade_api.stream import Stream
async def trade_callback(t):
print('trade', t)
async def quote_callback(q):
print('quote', q)
# Initiate Class Instance
stream = Stream(<ALPACA_API_KEY>,
<ALPACA_SECRET_KEY>,
base_url=URL('https://paper-api.alpaca.markets'),
data_feed='iex') # <- replace to 'sip' if you have PRO subscription
# subscribing to event
stream.subscribe_trades(trade_callback, 'AAPL')
stream.subscribe_quotes(quote_callback, 'IBM')
stream.run()
Websockets Config For Live Data
Under the hood our SDK uses the Websockets library to handle
our websocket connections. Since different environments can have wildly differing requirements for resources we allow you
to pass your own config options to the websockets lib via the websocket_params kwarg found on the Stream class.
ie:
# Initiate Class Instance
stream = Stream(<ALPACA_API_KEY>,
<ALPACA_SECRET_KEY>,
base_url=URL('https://paper-api.alpaca.markets'),
data_feed='iex', # <- replace to 'sip' if you have PRO subscription
websocket_params = {'ping_interval': 5}, #here we set ping_interval to 5 seconds
)
If you're curious this link to their docs
shows the values that websockets uses by default as well as any parameters they allow changing. Additionally, if you
don't specify any we set the following defaults on top of the ones the websockets library uses:
API Version now defaults to 'v2', however, if you still have a 'v1' account, you may need to specify api_version='v1' to properly use the API until you migrate.
Authentication
The Alpaca API requires API key ID and secret key, which you can obtain from the
web console after you sign in. You can pass key_id and secret_key to the initializers of
REST or Stream as arguments, or set up environment variables as
outlined below.
REST
The REST class is the entry point for the API request. The instance of this
class provides all REST API calls such as account, orders, positions,
and bars.
Each returned object is wrapped by a subclass of the Entity class (or a list of it).
This helper class provides property access (the "dot notation") to the
json object, backed by the original object stored in the _raw field.
It also converts certain types to the appropriate python object.
import alpaca_trade_api as tradeapi
api = tradeapi.REST()
account = api.get_account()
account.status
=> 'ACTIVE'
The Entity class also converts the timestamp string field to a pandas.Timestamp
object. Its _raw property returns the original raw primitive data unmarshaled
from the response JSON text.
Please note that the API is throttled, currently 200 requests per minute, per account. If your client exceeds this number, a 429 Too many requests status will be returned and this library will retry according to the retry environment variables as configured.
If the retries are exceeded, or other API error is returned, alpaca_trade_api.rest.APIError is raised.
You can access the following information through this object.
For simple orders with type='market' and time_in_force='day', you can pass a fractional amount (qty) or a notional amount (but not both). For instance, if the current market price for SPY is $300, the following calls are equivalent:
api.submit_order(
symbol='SPY',
notional=450, # notional value of 1.5 shares of SPY at $300
side='buy',
type='market',
time_in_force='day',
)
Logging
You should define a logger in your app in order to make sure you get all the messages from the different components.
It will help you debug, and make sure you don't miss issues when they occur.
The simplest way to define a logger, if you have no experience with the python logger - will be something like this:
Under the examples folder you could find several examples to do the following:
Different subscriptions(channels) usage with the alpaca streams
pause / resume connection
change subscriptions/channels of existing connection
ws disconnections handler (make sure we reconnect when the internal mechanism fails)
Running Multiple Strategies
The base version of this library only allows running a single algorithm due to Alpaca's limit of one websocket connection per account. For those looking to run multiple strategies, there is alpaca-proxy-agent project.
The steps to execute this are:
Run the Alpaca Proxy Agent as described in the project's README
Define a new environment variable: DATA_PROXY_WS set to the address of the proxy agent. (e.g: DATA_PROXY_WS=ws://127.0.0.1:8765)
If you are using the Alpaca data stream, make sure to initiate the Stream object with the container's url: data_url='http://127.0.0.1:8765'
Execute your algorithm. It will connect to the Alpaca servers through the proxy agent, allowing you to execute multiple strategies
Raw Data vs Entity Data
By default the data returned from the api or streamed via Stream is wrapped with an Entity object for ease of use. Some users may prefer working with vanilla python objects (lists, dicts, ...). You have 2 options to get the raw data:
Each Entity object as a _raw property that extract the raw data from the object.
If you only want to work with raw data, and avoid casting to Entity (which may take more time, casting back and forth) you could pass raw_data argument to Rest() object or the Stream() object.
Support and Contribution
For technical issues particular to this module, please report the
issue on this GitHub repository. Any API issues can be reported through
Alpaca's customer support.
New features, as well as bug fixes, by sending a pull request is always
welcomed.
Alternatives
Use instead of alpaca-trade-api: tools that do the same job, closest first.