Package: alpaca-trade-api
Deprecation NoticeA 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-pythonalpaca-trade-api-pythonis a python library for theAlpaca 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 onlineAPI document.Note that this package supports only python version 3.7 and above.InstallWe 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.0The solution - manually install these packages before installing alpaca-trade-api. e.g:pipinstallpandas==1.1.5numpy==1.19.4scipy==1.5.4Also note that we do not limit the version of the websockets library, but we advise usingwebsockets>=9.0Installing using pip$pip3installalpaca-trade-apiAPI KeysTo use this package you first need to obtain an API key. Go here tosignupServicesThese services are provided by Alpaca:Data:HistoricalLive Data StreamAccount/Portfolio ManagementThe free services are limited, please check the docs to see the differences between paid/free services.Alpaca Environment VariablesThe 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.EnvironmentdefaultDescriptionAPCA_API_KEY_ID=<key_id>Your API KeyAPCA_API_SECRET_KEY=<secret_key>Your API Secret KeyAPCA_API_BASE_URL=urlhttps://api.alpaca.markets(for live)Specify the URL for API calls,Default is live, you must specifyhttps://paper-api.alpaca.marketsto switch to paper endpoint!APCA_API_DATA_URL=urlhttps://data.alpaca.marketsEndpoint for data APIAPCA_RETRY_MAX=33The number of subsequent API calls to retry on timeoutsAPCA_RETRY_WAIT=33seconds to wait between each retry attemptAPCA_RETRY_CODES=429,504429,504comma-separated HTTP status code for which retry is attemptedDATA_PROXY_WSWhen using the alpaca-proxy-agent you need to set this environment variable as describedWorking with DataHistoric DataYou could get one of these historic data types:BarsQuotesTradesYou 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.Barsoption 1: wait for the datafromalpaca_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 barsdefprocess_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.704131Quotesoption 1: wait for the datafromalpaca_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 quotesdefprocess_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)Tradesoption 1: wait for the datafromalpaca_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 tradesdefprocess_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)Asyncio Rest moduleTherest_async.pymodule 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 theaiohttplibrary.We provide a code sample to get you started with this new approach and it is locatedhere.Follow along with the example code to learn more, and utilize it for your own needs.Live Stream Market DataThere are 2 streams available as describedhere.The free plan is using theiexstream, while the paid subscription is using thesipstream.You can subscribe to bars, trades, quotes, and trade updates for your account as well.
Under the example folder you can find differentcode samplesto achieve different goals.Here in this basic example, We use the Stream class underalpaca_trade_api.streamfor 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()Websockets Config For Live DataUnder the hood our SDK uses theWebsockets libraryto 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 thewebsocket_paramskwarg 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 curiousthis link to their docsshows 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,}Account & Portfolio ManagementThe HTTP API document is located athttps://docs.alpaca.markets/API VersionAPI 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.AuthenticationThe Alpaca API requires API key ID and secret key, which you can obtain from the
web console after you sign in.  You can passkey_idandsecret_keyto the initializers ofRESTorStreamas arguments, or set up environment variables as
outlined below.RESTTheRESTclass 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 theEntityclass (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_rawfield.
It also converts certain types to the appropriate python object.importalpaca_trade_apiastradeapiapi=tradeapi.REST()account=api.get_account()account.status=>'ACTIVE'TheEntityclass also converts the timestamp string field to a pandas.Timestamp
object.  Its_rawproperty 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.APIErroris raised.
You can access the following information through this object.the API error code:.codepropertythe API error message:str(error)the original request object:.requestpropertythe original response object:.responsepropertythe HTTP status code:.status_codepropertyAPI REST MethodsRest MethodEnd PointResultget_account()GET /accountandAccountentity.get_order_by_client_order_id(client_order_id)GET /orderswith client_order_idOrderentity.list_orders(status=None, limit=None, after=None, until=None, direction=None, params=None,nested=None, symbols=None, side=None)GET /orderslist ofOrderentities.afteranduntilneed to be string format, which you can obtain bypd.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 /ordersOrderentity.get_order(order_id)GET /orders/{order_id}Orderentity.cancel_order(order_id)DELETE /orders/{order_id}cancel_all_orders()DELETE /orderslist_positions()GET /positionslist ofPositionentitiesget_position(symbol)GET /positions/{symbol}Positionentity.list_assets(status=None, asset_class=None)GET /assetslist ofAssetentitiesget_asset(symbol)GET /assets/{symbol}Assetentityget_clock()GET /clockClockentityget_calendar(start=None, end=None)GET /calendarCalendarentityget_portfolio_history(date_start=None, date_end=None, period=None, timeframe=None, extended_hours=None)GET /account/portfolio/historyPortfolioHistory entity. PortfolioHistory.df can be used to get the results as a dataframeRest ExamplesPlease see theexamples/folder for some example scripts that make use of this APIUsingsubmit_order()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 withtype='market'andtime_in_force='day', you can pass a fractional amount (qty) or anotionalamount (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',)LoggingYou 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)Websocket best practicesUnder the examples folder you could find several examples to do the following:Different subscriptions(channels) usage with the alpaca streamspause / resume connectionchange subscriptions/channels of existing connectionws disconnections handler (make sure we reconnect when the internal mechanism fails)Running Multiple StrategiesThe 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 isalpaca-proxy-agent project.The steps to execute this are:Run the Alpaca Proxy Agent as described in the project's READMEDefine 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 strategiesRaw Data vs Entity DataBy 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 passraw_dataargument toRest()object or theStream()object.Support and ContributionFor 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.