Package: alpaca-py
Table of ContentsAboutDocumentationInstallationUpdateWhat's New?Broker APIOOP DesignData ValidationMany ClientsAPI KeysTrading and Market Data API KeysBroker API KeysUsageBroker API ExampleTrading API ExampleMarket Data API ExampleContributingLicenseAboutAlpaca-py provides an interface for interacting with the API products Alpaca offers. These API products are provided as various REST, WebSocket and SSE endpoints that allow you to do everything from streaming market data to creating your own investment apps.Learn more about the API products Alpaca offers athttps://alpaca.markets.DocumentationAlpaca-py has a supplementary documentation site which contains references for all clients, methods and models found in this codebase. The documentation
also contains examples to get started with alpaca-py.You can find the documentation site here:https://docs.alpaca.markets/docs/getting-started-1InstallationAlpaca-py is supported on Python 3.7+.  You can install Alpaca-py using pip.Run the following command in your terminal.pipinstallalpaca-pyUpdateIf you already have Alpaca-py installed, and would like to use the latest version available...Run the following command in your terminal:pipinstallalpaca-py--upgradeWhat’s New?If you’ve used the previous python SDK alpaca-trade-api, there are a few key differences to be aware of.Broker APIAlpaca-py lets you use Broker API to start building your investment apps! Learn more at theBrokerpage.OOP DesignAlpaca-py uses a more OOP approach to submitting requests compared to the previous SDK. To submit a request, you will most likely need to create a request object containing the desired request data. Generally, there is a unique request model for each method.Some examples of request models corresponding to methods:GetOrdersRequestforTradingClient.get_orders()CryptoLatestOrderbookRequestforCryptoHistoricalDataClient.get_crypto_latest_orderbook()Request Models Usage ExampleTo get historical bar data for crypto, you will need to provide aCryptoBarsRequestobject.fromalpaca.data.historicalimportCryptoHistoricalDataClientfromalpaca.data.requestsimportCryptoBarsRequestfromalpaca.data.timeframeimportTimeFramefromdatetimeimportdatetime# no keys required for crypto dataclient=CryptoHistoricalDataClient()request_params=CryptoBarsRequest(symbol_or_symbols=["BTC/USD","ETH/USD"],timeframe=TimeFrame.Day,start=datetime(2022,7,1))bars=client.get_crypto_bars(request_params)Data ValidationAlpaca-py usespydanticto validate data models at run-time. This means if you are receiving request data via JSON from a client. You can handle parsing and validation through Alpaca’s request models. All request models can be instantiated by passing in data in dictionary format.Here is a rough example of what is possible.@app.route('/post_json',methods=['POST'])defdo_trade():# ...order_data_json=request.get_json()# validate dataMarketOrderRequest(**order_data_json)# ...Many ClientsAlpaca-py has a lot of client classes. There is a client for each API and even asset class specific clients (StockHistoricalDataClient,CryptoDataStream,OptionHistoricalDataClient). This requires you to pick and choose clients based on your needs.Broker API:BrokerClientTrading API:TradingClientMarket Data API:StockHistoricalDataClient,CryptoHistoricalDataClient,OptionHistoricalDataClient,CryptoDataStream,StockDataStream,OptionDataStreamAPI KeysTrading and Market Data APIIn order to use Alpaca’s services you’ll need to sign up for an Alpaca account and retrieve your API keys. Signing up is completely free and takes only a few minutes. Sandbox environments are available to test out the API. To use the sandbox environment, you will need to provide sandbox/paper keys. API keys are passed into Alpaca-py through eitherTradingClient,StockHistoricalDataClient,CryptoHistoricalDataClient,OptionHistoricalDataClient.StockDataStream,CryptoDataStream, orOptionDataStream.Broker APITo use the Broker API, you will need to sign up for a broker account and retrieve your Broker API keys. The API keys can be found on the dashboard once you’ve logged in. Alpaca also provides a sandbox environment to test out Broker API. To use the sandbox mode, provide your sandbox keys. Once you have your keys, you can pass them intoBrokerClientto get started.UsageAlpaca’s APIs allow you to do everything from building algorithmic trading strategies to building a full brokerage experience for your own end users. Here are some things you can do with Alpaca-py.To view full descriptions and examples view thedocumentation page.Market Data API: Access live and historical market data for 5000+ stocks, 20+ crypto, and options(beta).Trading API: Trade stock and crypto with lightning fast execution speeds.Broker API & Connect: Build investment apps - from robo-advisors to brokerages.Broker API ExampleListing All AccountsTheBrokerClient.list_accountsmethod allows you to list all the brokerage accounts under your management. The method takes an optional parametersearch_parameterswhich requires aListAccountsRequestobject. This parameter allows you to filter the list of accounts returned.fromalpaca.broker.clientimportBrokerClientfromalpaca.broker.requestsimportListAccountsRequestfromalpaca.broker.enumsimportAccountEntitiesbroker_client=BrokerClient('api-key','secret-key')# search for accounts created after January 30th 2022.# Response should contain Contact and Identity fields for each account.filter=ListAccountsRequest(created_after=datetime.datetime.strptime("2022-01-30","%Y-%m-%d"),entities=[AccountEntities.CONTACT,AccountEntities.IDENTITY])accounts=broker_client.list_accounts(search_parameters=filter)Trading API ExampleSubmitting an OrderTo create an order on Alpaca-py you must use anOrderRequestobject. There are differentOrderRequestobjects based on the type of order you want to make. For market orders, there isMarketOrderRequest, limit orders haveLimitOrderRequest, stop ordersStopOrderRequest, and trailing stop orders haveTrailingStopOrderRequest. Each order type have their own required parameters for a successful order.fromalpaca.trading.clientimportTradingClientfromalpaca.trading.requestsimportMarketOrderRequestfromalpaca.trading.enumsimportOrderSide,TimeInForcetrading_client=TradingClient('api-key','secret-key')# preparing order datamarket_order_data=MarketOrderRequest(symbol="BTC/USD",qty=0.0001,side=OrderSide.BUY,time_in_force=TimeInForce.DAY)# Market ordermarket_order=trading_client.submit_order(order_data=market_order_data)Market Data API ExampleQuerying Historical Bar DataYou can request bar data via the HistoricalDataClients. In this example, we query daily bar data for “BTC/USD” and “ETH/USD” since July 1st 2022. You can convert the response to a multi-index pandas dataframe using the.dfproperty.fromalpaca.data.historicalimportCryptoHistoricalDataClientfromalpaca.data.requestsimportCryptoBarsRequestfromalpaca.data.timeframeimportTimeFramefromdatetimeimportdatetime# no keys required for crypto dataclient=CryptoHistoricalDataClient()request_params=CryptoBarsRequest(symbol_or_symbols=["BTC/USD","ETH/USD"],timeframe=TimeFrame.Day,start=datetime.strptime("2022-07-01",'%Y-%m-%d'))bars=client.get_crypto_bars(request_params)# convert to dataframebars.dfOptions Trading (Beta)We're excited to support options trading! Use this section to read up on Alpaca's Beta trading capabilities.
For more details, please refer toour documentation page for options tradingOptions trading is in BETA. Only BETA users are able to access options endpoints. We will continue to update our documentation as we collect your valuable feedback.There is an example jupyter notebook to explain methods of alpaca-py for options trading.jupyter notebook: options trading basic example with alpaca-py