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.
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:
pip install pandas==1.1.5 numpy==1.19.4 scipy==1.5.4Also note that we do not limit the version of the websockets library, but we advise using
websockets>=9.0
Installing using pip
$ pip3 install alpaca-trade-apiTo use this package you first need to obtain an API key. Go here to signup
These services are provided by Alpaca:
The free services are limited, please check the docs to see the differences between paid/free services.
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.
| Environment | default | Description |
|---|---|---|
| APCA_API_KEY_ID=<key_id> | Your API Key | |
| APCA_API_SECRET_KEY=<secret_key> | Your API Secret Key | |
| APCA_API_BASE_URL=url | https://api.alpaca.markets (for live) | Specify the URL for API calls, Default is live, you must specify https://paper-api.alpaca.markets to switch to paper endpoint! |
| APCA_API_DATA_URL=url | https://data.alpaca.markets | Endpoint for data API |
| APCA_RETRY_MAX=3 | 3 | 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 |
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.
option 1: wait for the data
fromalpaca_trade_api.restimportREST, TimeFrameapi=REST()
api.get_bars("AAPL", TimeFrame.Hour, "2021-06-08", "2021-06-08", adjustment='raw').dfopenhighlowclosevolumetimestamp2021-06-0808:00:00+00:00126.100126.3000125.9600126.3000421072021-06-0809:00:00+00:00126.270126.4000126.2200126.3800210952021-06-0810:00:00+00:00126.380126.6000125.8400126.4900547432021-06-0811:00:00+00:00126.440126.8700126.4000126.85002064602021-06-0812:00:00+00:00126.821126.9500126.7000126.93003851642021-06-0813:00:00+00:00126.920128.4600126.4485127.0250184073982021-06-0814:00:00+00:00127.020127.6400126.7800127.1350134469612021-06-0815:00:00+00:00127.140127.4700126.2101126.6100104440992021-06-0816:00:00+00:00126.610126.8400126.5300126.825052895562021-06-0817:00:00+00:00126.820126.9300126.4300126.707248134592021-06-0818:00:00+00:00126.709127.3183126.6700127.285053384552021-06-0819:00:00+00:00127.290127.4200126.6800126.740098170832021-06-0820:00:00+00:00126.740126.8500126.5400126.660055255202021-06-0821:00:00+00:00126.690126.8500126.6500126.66001563332021-06-0822:00:00+00:00126.690126.7400126.6600126.7300492522021-06-0823:00:00+00:00126.725126.7600126.6400126.640041430option 2: iterate over bars
defprocess_bar(bar):
# process barprint(bar)
bar_iter=api.get_bars_iter("AAPL", TimeFrame.Hour, "2021-06-08", "2021-06-08", adjustment='raw')
forbarinbar_iter:
process_bar(bar)Alternatively, you can decide on your custom timeframes by using the TimeFrame constructor:
fromalpaca_trade_api.restimportREST, TimeFrame, TimeFrameUnitapi=REST()
api.get_bars("AAPL", TimeFrame(45, TimeFrameUnit.Minute), "2021-06-08", "2021-06-08", adjustment='raw').dfopenhighlowclosevolumetrade_countvwaptimestamp2021-06-0807:30:00+00:00126.1000126.1600125.9600126.060020951304126.0494472021-06-0808:15:00+00:00126.0500126.3000126.0500126.300021181349126.2319042021-06-0809:00:00+00:00126.2700126.3200126.2200126.280015955308126.2841202021-06-0809:45:00+00:00126.2900126.4000125.9000125.900030179582126.1968772021-06-0810:30:00+00:00125.9000126.7500125.8400126.75001053801376126.5308632021-06-0811:15:00+00:00126.7300126.8500126.5600126.83001297211760126.7380412021-06-0812:00:00+00:00126.4101126.9500126.3999126.83004181073615126.7718892021-06-0812:45:00+00:00126.8500126.9400126.6000126.62004286145526126.8028252021-06-0813:30:00+00:00126.6200128.4600126.4485127.415023065023171263127.4257972021-06-0814:15:00+00:00127.4177127.6400126.9300127.1350853506865753127.3423372021-06-0815:00:00+00:00127.1400127.4700126.2101126.7101844769664616126.7893162021-06-0815:45:00+00:00126.7200126.8200126.5300126.6788508414738366126.7121102021-06-0816:30:00+00:00126.6799126.8400126.5950126.5950320587026614126.7188372021-06-0817:15:00+00:00126.5950126.9300126.4300126.7010390828331922126.6657272021-06-0818:00:00+00:00126.7072127.0900126.6700127.0600392305629114126.9398872021-06-0818:45:00+00:00127.0500127.4200127.0000127.0050505168238235127.2141572021-06-0819:30:00+00:00127.0150127.0782126.6800126.78001166559847146126.8131822021-06-0820:15:00+00:00126.7700126.7900126.5400126.6600837251973126.6792592021-06-0821:00:00+00:00126.6900126.8500126.6700126.7200145153769126.7464572021-06-0821:45:00+00:00126.7000126.7400126.6500126.710038455406126.6995442021-06-0822:30:00+00:00126.7100126.7600126.6700126.710030822222126.7138922021-06-0823:15:00+00:00126.7200126.7600126.6400126.640032585340126.704131option 1: wait for the data
fromalpaca_trade_api.restimportRESTapi=REST()
api.get_quotes("AAPL", "2021-06-08", "2021-06-08", limit=10).dfask_exchangeask_priceask_sizebid_exchangebid_pricebid_sizeconditionstimestamp2021-06-0808:00:00.070928640+00:00P143.0010.000 [Y]
2021-06-0808:00:00.070929408+00:00P143.001P102.511 [R]
2021-06-0808:00:00.070976768+00:00P143.001P116.501 [R]
2021-06-0808:00:00.070978816+00:00P143.001P118.181 [R]
2021-06-0808:00:00.071020288+00:00P143.001P120.001 [R]
2021-06-0808:00:00.071020544+00:00P134.181P120.001 [R]
2021-06-0808:00:00.071021312+00:00P134.181P123.361 [R]
2021-06-0808:00:00.071209984+00:00P131.111P123.361 [R]
2021-06-0808:00:00.071248640+00:00P130.131P123.361 [R]
2021-06-0808:00:00.071286016+00:00P129.801P123.361 [R]option 2: iterate over quotes
defprocess_quote(quote):
# process quoteprint(quote)
quote_iter=api.get_quotes_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
forquoteinquote_iter:
process_quote(quote)option 1: wait for the data
fromalpaca_trade_api.restimportRESTapi=REST()
api.get_trades("AAPL", "2021-06-08", "2021-06-08", limit=10).dfexchangepricesizeconditionsidtapetimestamp2021-06-0808:00:00.069956608+00:00P126.10179 [@, T] 1C2021-06-0808:00:00.207859+00:00K125.971 [@, T, I] 1C2021-06-0808:00:00.207859+00:00K125.9712 [@, T, I] 2C2021-06-0808:00:00.207859+00:00K125.974 [@, T, I] 3C2021-06-0808:00:00.207859+00:00K125.974 [@, T, I] 4C2021-06-0808:00:00.207859+00:00K125.978 [@, T, I] 5C2021-06-0808:00:00.207859+00:00K125.971 [@, T, I] 6C2021-06-0808:00:00.207859+00:00K126.0030 [@, T, I] 7C2021-06-0808:00:00.207859+00:00K126.0010 [@, T, I] 8C2021-06-0808:00:00.207859+00:00K125.9770 [@, T, I] 9Coption 2: iterate over trades
defprocess_trade(trade):
# process tradeprint(trade)
trades_iter=api.get_trades_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
fortradeintrades_iter:
process_trade(trade)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.
There are 2 streams available as described here.
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.
fromalpaca_trade_api.commonimportURLfromalpaca_trade_api.streamimportStreamasyncdeftrade_callback(t):
print('trade', t)
asyncdefquote_callback(q):
print('quote', q)
# Initiate Class Instancestream=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 eventstream.subscribe_trades(trade_callback, 'AAPL')
stream.subscribe_quotes(quote_callback, 'IBM')
stream.run()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 Instancestream=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 subscriptionwebsocket_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:
{
"ping_interval": 10,
"ping_timeout": 180,
"max_queue": 1024,
}The HTTP API document is located at https://docs.alpaca.markets/
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.
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.
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.
importalpaca_trade_apiastradeapiapi=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.
- the API error code:
.codeproperty - the API error message:
str(error) - the original request object:
.requestproperty - the original response object:
.responseproperty - the HTTP status code:
.status_codeproperty
| Rest Method | End Point | Result |
|---|---|---|
| get_account() | GET /account and | Account entity. |
| get_order_by_client_order_id(client_order_id) | GET /orders with client_order_id | Order entity. |
| list_orders(status=None, limit=None, after=None, until=None, direction=None, params=None,nested=None, symbols=None, side=None) | GET /orders | list of Order entities. after and until need to be string format, which you can obtain by pd.Timestamp().isoformat() |
| submit_order(symbol, qty=None, side="buy", type="market", time_in_force="day", limit_price=None, stop_price=None, client_order_id=None, order_class=None, take_profit=None, stop_loss=None, trail_price=None, trail_percent=None, notional=None) | POST /orders | Order entity. |
| get_order(order_id) | GET /orders/{order_id} | Order entity. |
| cancel_order(order_id) | DELETE /orders/{order_id} | |
| cancel_all_orders() | DELETE /orders | |
| list_positions() | GET /positions | list of Position entities |
| get_position(symbol) | GET /positions/{symbol} | Position entity. |
| list_assets(status=None, asset_class=None) | GET /assets | list of Asset entities |
| get_asset(symbol) | GET /assets/{symbol} | Asset entity |
| get_clock() | GET /clock | Clock entity |
| get_calendar(start=None, end=None) | GET /calendar | Calendar entity |
| get_portfolio_history(date_start=None, date_end=None, period=None, timeframe=None, extended_hours=None) | GET /account/portfolio/history | PortfolioHistory entity. PortfolioHistory.df can be used to get the results as a dataframe |
Please see the examples/ folder for some example scripts that make use of this API
Below is an example of submitting a bracket order.
api.submit_order(
symbol='SPY',
side='buy',
type='market',
qty='100',
time_in_force='day',
order_class='bracket',
take_profit=dict(
limit_price='305.0',
),
stop_loss=dict(
stop_price='295.5',
limit_price='295.5',
)
)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',
qty=1.5, # fractional sharesside='buy',
type='market',
time_in_force='day',
)api.submit_order(
symbol='SPY',
notional=450, # notional value of 1.5 shares of SPY at $300side='buy',
type='market',
time_in_force='day',
)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:
importlogginglogging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)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)
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_WSset 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
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
_rawproperty 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_dataargument toRest()object or theStream()object.
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.