Alpaca Markets API Python Tutorial

This tutorial teaches how to call the Alpaca Markets API in Python using the official Alpaca-py client and the Python request function.

The Alpaca API provides extensive documentation for accessing its endpoint. In addition, a few articles on the internet demonstrate how to call Alpaca API in Python. 

However, I find that the official documentation lacks real-world examples. Moreover, most existing articles target the obsolete Alpaca trade API python library, which the new object-oriented Alpaca-py client has replaced.

In this article, I will explain, with the help of real-world examples, how to call the Alpaca API using the latest Alpaca-py Python client. You will see how to use the Alpaca-py to extract historical data via REST APIs and real-time streaming data via Websockets.

What Is Alpaca Markets?

Alpaca Markets is an intelligent trading platform that allows developers, investors, and traders to view stock values, process stock market information, and execute trading operations.

Alpaca’s was founded in 2015, and its headquarters is in San Mateo, California. 

What Is the Alpaca Markets API?

Alpaca Markets API offers REST API services to access Alpaca Markets data in code. Traders, investors, developers, and researchers can leverage Alpaca API to develop customized financial software, algorithmic trading applications, statistical stock forecasting models, etc. 

Alpaca Markets Pros and Cons

Following are some of the pros and cons of Alcapa Markets:

Pros

  • Alpaca doesn’t charge any commission on buying and selling stocks and ETFs.
  • Alpaca has a free API that allows you to develop customized financial applications.
  • Fantastic GUI and charting tools.
  • Paper trading allows you to simulate a natural trading environment.
  • Allows trading for US and Non-US residents.

Cons

  • Alpaca supports only US Stock markets.
  • Users report poor customer support.
  • Require a minimum of $30,000 for non-US Business trading accounts.

Alpaca Markets API Pricing Plans

Alpaca API has a free and unlimited subscription, which costs $99/per month. See Alpaca Markets subscription plans for more details.

Alpaca Markets Price Plans

How to Get Started with Alpaca Markets API in Python

You will use the free Alpaca Markets subscription for the codes in this tutorial. To do so, you must sign up with Alpaca Markets., as shown in the following screenshots.

Alpaca Markets Signup Page
Alpaca will send a verification email to your email address. Activate your Alpaca account from your email and log in to Alpaca Markets. Select the “Individual Account” option and complete the form that appears.
Alpaca Markets Account Selection

You will need an API key and API secret key to access Alpaca API. To do so, go to your dashboard, and click the “Generate New Key” on the right side of your dashboard. 

Alpaca Markets Generate API Key Screen

Save your API key and API secret in a secure place. For this tutorial, I saved these values in system environment variables.

Simple Example Fetching Data Using Alpaca Markets API in Python

You have a couple of options to make Alpaca REST API calls: 

  1. Depending upon the language of your choice, you can leverage one of the five Alpaca Markets API official clients. For Python, you can use the Alpaca-py Python client to call the Alpaca API endpoints. Alpaca-py library supports only python version 3.7 and above.
  1. The other option is to use the Python request function to access the Alpaca API. If speed and flexibility are your primary goals, I recommend using the request function. The Alpaca-py client library is a good entry point to Alpaca API. 

In this tutorial, you will use the Alpaca-py library. 

Alpaca Markets API Python Library Example

Four primary entities allow you to access any endpoint function in the Alpaca API using the Alpaca-py client.

  1. The client classes, e.g., TradingClient, StockHistoricalDataClient, BrokerClient, etc.
  2. The request classes e.g, GetAssetsRequest, StockLatestQuoteRequest, etc.
  3. The enums e.g. AssetClass, OrderSide, ActivityType, etc.
  4. The model classes, e.g., Account, Asset, Order, etc.

You need to initialize one of the client classes to call an API function. Depending upon the endpoint you want to access, you may need to pass one or more request classes as a parameter to the client class methods. The enums and models assign values to one or more request class attributes. 

The following script installs the Alpaca-py client library.

# install the library with the following command
# pip install alpaca-py # prepend a ! for Jupyter notebook

Let’s see a basic example of how you can access all stock assets using the get_all_assets() method from the TradingClient class.

The following script defines variables that store the API key and  API secret key from environment variables.

import os
import pandas as pd

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

The script below creates an object of the TradingClient class. You must pass your API key and secret to the TradingClient class constructor. 

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass

trading_client = TradingClient(api_key, api_secret, paper=True)

Next, you must define the search parameters for the assets you want to return using the GetAssetRequest class. The enum AssetClass.US_EQUITY specifies that we want to return US equity assets. To get a list of crypto assets, you can use the AssetClass.CRYPTO enum.


The final step is to pass the GetAssetRequest class object to the get_all_assets() method, as shown in the example below.

search_params = GetAssetsRequest(asset_class=AssetClass.US_EQUITY)
assets = trading_client.get_all_assets(search_params)
assets
Alpaca API Get All US Equity Assets Output

The above output contains a list of assets where each list item is an object of the alpaca.trading.models.Asset class.  

type(assets[0])
alpaca.trading.models.Asset

For a better view, you can convert the list of assets class objects to a list of dictionaries which you can subsequently convert to Pandas dataframes:

import pandas as pd
assets_dict = [dict(item) for item in assets]

df = pd.DataFrame.from_records(assets_dict)
df.head(10)
Alpaca API Get All US Equity Assets DataFrame

Alpaca Markets API Request Function Example

You can use the Python request() function to call the Alpaca API, just like any other REST API function. The request() function returns a JSON object, which can be further parsed to retrieve the required data. This approach is recommended if speed and flexibility are your main concerns.

The following example shows how to get a list of all assets using the Alpaca API asset endpoint.

import requests
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import pandas as pd

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

url = 'https://paper-api.alpaca.markets'
api_call = '/v2/assets'

headers = {'content-type': 'application/json', 
           'Apca-Api-Key-Id': api_key, 
           'Apca-Api-Secret-Key': api_secret}

response = requests.get(url + api_call, headers=headers)
response = json.loads(response.text)
assets = [dict(item) for item in response]
df = pd.DataFrame.from_records(assets)
df.head()
Alpaca API Request Method Assets DataFrame

What Are Alpaca Markets’ API Endpoints?

The Alpaca-Py client clusters the Alpaca API endpoints into three groups:

  1. Market Data API: allows retrieving live and historical data for equities and cryptocurrencies.
  2. Trading API: provides services to buy and sell stocks and cryptocurrencies, create watchlists, get asset information, etc. 
  3. Broker API: allows creating brokerage accounts on your users’ behalf.

Market Data API

The Market Data API has four main classes:

  1. StockHistoricalDataClient: contains methods returning historical stock data
  2. StockDataStream: provides endpoints to access live stock data
  3. CryptoHistoricalDataClient: consists of functionalities returning historical crypto data
  4. CryptoDataStream: returns live crypto data

You can use the appropriate python object from the above list depending on the API functions you want to access. 

Get Historical Stock Market Data with Alpaca

You do not need an API key and secret to access endpoints from the StockHistoricalData client classes. However, to achieve higher data access limits, I recommend that you use the API key and API secrets to access all Alpaca API endpoints. 

Get Historical Stock Bar Data

You can use the get_stock_bars() method from the StockHistoricalDataClient class to get historical OHLC stock values. The stock symbol list, start dates, and time duration are passed to the StockBarsRequest class, which subsequently parameterizes the  get_stock_bars() method. 

from alpaca.data.timeframe import TimeFrame
from alpaca.data.requests import StockBarsRequest
from alpaca.data.historical import StockHistoricalDataClient

import os
import pandas as pd


client = StockHistoricalDataClient(api_key, api_secret)
request_params = StockBarsRequest(
                        symbol_or_symbols=["AAPL", "TSLA"],
                        timeframe=TimeFrame.Day,
                        start="2022-10-04 00:00:00",
                        end="2022-10-06 00:00:00"
                 )
bars = client.get_stock_bars(request_params)
bars_df = bars.df
bars_df

Get Latest Stock Asking Price

The get_stock_latest_quote() method returns the latest asking price of a quote. You must pass the stock symbol to the StockLatestQuotesRequest class, which is passed to the get_stock_latest_quote() method.

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockLatestQuoteRequest
from alpaca.data.timeframe import TimeFrame

import os
import pandas as pd

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# keys required
client = StockHistoricalDataClient(api_key , api_secret)

request_params = StockLatestQuoteRequest(symbol_or_symbols=["TLT", "GLD"],
                                         timeframe=TimeFrame.Day
                                        )

quotes = client.get_stock_latest_quote(request_params)

pd.DataFrame(quotes)
Alpaca API Get Latest Stock Asking Price DataFrame
The Market API provides streaming data interfaces you can leverage to get real-time data. To do so, you have to create an asynchronous function that is periodically called. Next, you need to create an object of the StockDataStream class and the method that requests real-time data from the Alpaca API. 

The asynchronous function is passed to the StockDataStream class method that fetches the data in real time.

For example, the following script executes the bars_data_handler() function every minute, which prints the data returned by the  subscribe_bars() method on subsequent API calls.
import nest_asyncio
nest_asyncio.apply()

import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

from alpaca.data.live import StockDataStream

wss_client = StockDataStream(api_key, api_secret)

# async handler
async def bars_data_handler(data):
    # real-time data will be displayed here
    # as it arrives
    print(data)
    print("===")

wss_client.subscribe_bars(bars_data_handler, "GLD")

wss_client.run()

Get Alpaca Historical Crypto Market Data

The CryptoHistoricalDataClient class methods return historical cryptocurrency data. The process is very similar to retrieving historical stock data. You need to create an object of the CryptoHistoricalDataClient class and call the method that returns historical data. The method is parameterized by the request object, which specifies filters for retrieving historical data.

Get Historical Crypto Bar Data

The script below calls the get_crypto_bars() method to retrieve historical USD OHLC values for Bitcoin and Ethereum.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame

# no keys required for crypto data
client = CryptoHistoricalDataClient()

request_params = CryptoBarsRequest(
                        symbol_or_symbols=["BTC/USD", "ETH/USD"],
                        timeframe=TimeFrame.Day,
                        start="2022-10-04 00:00:00",
                        end="2022-10-06 00:00:00")

bars = client.get_crypto_bars(request_params)

bars.df

Get Latest Crypto Asset Asking Price

Similarly, you can get the latest asking prices for any cryptocurrency using the get_crypto_latest_quote() method of the CryptoHistoricalDataClient class.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoLatestQuoteRequest
from alpaca.data.timeframe import TimeFrame

import os
import pandas as pd

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# keys not required
client = CryptoHistoricalDataClient()

request_params = CryptoLatestQuoteRequest(symbol_or_symbols=["BTC/USD", "ETH/USD"],
                                         timeframe=TimeFrame.Day
                                        )

quotes = client.get_crypto_latest_quote(request_params)

pd.DataFrame(quotes)
Alpaca API Latest Crypto Asking Price DataFrame

Get Real-time Crypto Market Data with Alpaca

Finally, as you saw with real-time stock price data, you can retrieve real-time cryptocurrency data using CryptoDataStream class methods. The rest of the process is similar to fetching g real-time stock price data.

The following script uses the subscribe_bars() method of the CryptoDataStream class to retrieve real-time OHLC values for Ethereum.

import nest_asyncio
nest_asyncio.apply()

import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

from alpaca.data.live import CryptoDataStream

wsc_client = CryptoDataStream(api_key, api_secret)

# async handler
async def bar_data_handler(data):
    # real-time data will be displayed here after every minute
    print(data)
    print("====")

wsc_client.subscribe_bars(bar_data_handler,  "ETH/USD")

wsc_client.run()
Alpaca API Crypto Data Stream DataFrame

For further information on the other Market API functions, see the official Market Data Reference. 

Trading API

Trading API endpoints allow you to execute various trading operations, e.g., buying and selling stocks and cryptocurrencies, viewing order information, and account positions.

The TradingClient class from the Trading API provides the methods you need to perform trading operations on Alpaca using the Alpaca API. 

Get Alpaca Trading Account Details

Once you sign-up for an Alpaca paper trading or live trading account, you can retrieve your account information in Python using the get_account() method of the TradingClient class. Here is an example.

from alpaca.trading.client import TradingClient
import os
api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)
account = trading_client.get_account()
account
Alpaca API Trading Account Detail JSON Output

Get a List of All Alpaca Assets

The get_all_assets() method of the TradingClient class returns a list of all Alpaca Markets stock or crypto assets. For instance, you might be interested in finding tradable stocks or symbols. You can get this information from the tradable property of the information returned by the get_all_assets() method. 

Get Alpaca Stock Assets
To get Alpaca Markets stock assets, you need to pass AssetClass.US_EQUITY enum to the GetAssetsRequest class object.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass
import pandas as pd

trading_client = TradingClient(api_key, api_secret, paper=True)

search_params = GetAssetsRequest(asset_class=AssetClass.US_EQUITY)

assets = trading_client.get_all_assets(search_params)

assets_dict = [dict(item) for item in assets]


df = pd.DataFrame.from_records(assets_dict)
df.head()
Alpaca API Get Stock Assets DataFrame

Get Alpaca Crypto Assets

On the contrary, to retrieve crypto assets, you need to pass AssetClass.CRYPTO to the asset_class attribute of the GetAssetsRequest class, as shown in the script below:

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass

trading_client = TradingClient(api_key, api_secret, paper=True)

search_params = GetAssetsRequest(asset_class=AssetClass.CRYPTO)

assets = trading_client.get_all_assets(search_params)

assets_dict = [dict(item) for item in assets]


df = pd.DataFrame.from_records(assets_dict)
df.head()
Alpaca API Get Crypto Assets DataFrame

You can get information, e.g., whether an asset is shortable, active, tradable, etc., using the get_asset() method. The following script returns asset information for ETH/USD

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAssetsRequest
from alpaca.trading.enums import AssetClass

trading_client = TradingClient(api_key, api_secret, paper=True)
asset = trading_client.get_asset("ETH/USD")
asset
Alpaca API Python Client Get Ethereum Asset Information DataFrame

Buy or Sell an Asset with Alpaca Markets

The submit_order() method from the TradingClient class allows you to buy or sell an asset. You need to pass the OrderRequest object to the submit_order() method. The OrderRequest object is parameterized by enums OrderSide, TimeInForce, and OrderType. 

Create an Order to Buy an Asset

To create an order to buy an asset, you must pass the enum OrderSide.BUY to the side attribute of the OrderRequest class.
The following example demonstrates how to buy 2  ETH/USD assets.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import OrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce, OrderType

trading_client = TradingClient(api_key, api_secret, paper=True)

order_request = OrderRequest(
                   symbol="ETH/USD",
                   qty = 2,
                   side = OrderSide.BUY,
                   type = OrderType.MARKET,
                   time_in_force = TimeInForce.GTC
                   )

new_order  = trading_client.submit_order(
               order_data=order_request
              )
dict(new_order)
Alpaca API Python Client Submit Order Buy ETHUSD Dict

Create an Order for Selling an Asset

The process is the same for selling an asset except for the following:

  1. You must have a sufficient quantity of assets you want to sell. For instance, you bought two ETH/USD in the previous script. You can only sell less than or equal to 2 ETH/USD.
  2. You need to pass the enum OrderSide.SELL to the side attribute. 

Here is an example of selling an asset via Alpaca Trading API.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import OrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce, OrderType
import time

trading_client = TradingClient(api_key, api_secret, paper=True)

order_request = OrderRequest(
                   symbol="ETH/USD",
                   qty = 0.5,
                   side = OrderSide.SELL,
                   type = OrderType.MARKET,
                   time_in_force = TimeInForce.GTC
                   )

new_order  = trading_client.submit_order(
               order_data=order_request
              )
dict(new_order)
Alpaca API Python Client Submit Oorder Setll ETHUSD Dict

Get Alpaca Order Information

You can get information about all of your selling or buying orders using the get_orders() method from the TradingClient class. 

In the output, you will see order details such as the order creation time, order type, order status, etc.

from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)

all_orders = trading_client.get_orders()

orders_dict = [dict(item) for item in all_orders]

df = pd.DataFrame.from_records(orders_dict)
df
Alpaca API Python Client Get Orders DataFrame
from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)
order = trading_client.get_order_by_id("f7b0af79-5b7e-42d9-bb45-76f59eb31279")
order
Alpaca API Python Client Get Order By ID Dictionary

Get Alpaca Trading Asset Positions

An asset position refers to an asset’s quantity, current price, per-day price difference, market value, etc. The get_all_positions() method returns the positions of all your assets:

from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)
account_positions = trading_client.get_all_positions()
positions_dict = [dict(item) for item in account_positions]

df = pd.DataFrame.from_records(positions_dict)
df.head()
Alpaca API Python Client Get All Positions DataFrame

Cancel an Alpaca Order

If you change your mind anytime, you can cancel an already placed order using the cancel_order_by_id() method. You need to pass the order id to this method.

from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)

order = trading_client.cancel_order_by_id('e002bc38-1064-4c2e-bc3f-4a29bb3fb2ad')

You can cancel all of your orders using the cancel_orders() method. 

from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)

trading_client.cancel_orders()

Create an Alpaca Watchlist for Asset Tracking

A watchlist lists equities that a trader tracks for potential trading and investments. The main difference between an asset position is that you own the assets in asset positions, whereas you are only interested in watchlist assets but have not yet bought them. 


The Alpaca API allows you to create watchlists using the create_watchlist() method from the TradingClient class. The attributes of a watchlist, e.g., watch list name and symbol, are passed to the CreateWatchlistRequest() object.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import CreateWatchlistRequest
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)

watch_list_request = CreateWatchlistRequest(
                   name ="BTC WL3",
                   symbols=["BTC/USD"]
                   )

watch_list  = trading_client.create_watchlist(
               watchlist_data = watch_list_request
              )
dict(watch_list)
Alpaca API Python Client Create Watch List Dict

You can retrieve a list of all the watchlists you have created using the get_all_watchlists() method:

from alpaca.trading.client import TradingClient
import pandas as pd
import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)

get_all_watchlists = trading_client.get_watchlists()

watch_lists = [dict(item) for item in get_all_watchlists]

df = pd.DataFrame.from_records(watch_lists)
df.head()
Alpaca API Python Client Get Watch Lists DataFrame

Get Corporate Announcements with Alpaca

You can get information about splits, mergers, and other corporate events involving an asset using the get_corporate_announcements() method. 

You need to pass the list of event types,  start and end dates range, and the asset symbol to the GetCorporateAnnouncementsRequest class object, which is then passed to the get_coporate_announcements() method. 

For example, the following script searches for merger and dividend events for “ETH/USD” between 2022-09-04 and  2022-10-06.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetCorporateAnnouncementsRequest
from alpaca.trading.enums import CorporateActionType

import pandas as pd
from datetime import datetime

import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)


request_params =  GetCorporateAnnouncementsRequest(
                        ca_types = [CorporateActionType.MERGER, CorporateActionType.DIVIDEND],
                        since = datetime.strptime('2022-09-04', '%Y-%m-%d').date(),
                        until = datetime.strptime('2022-10-06', '%Y-%m-%d').date(),
                        symbol = "ETH/USD"
                        
                   )

corporate_announcements  = trading_client.get_corporate_annoucements(request_params)

How to Get Alpaca Markets Calendar

You can get a list of all trading days from Alpaca API using the get_calendar() method of the TradingClient class object. This method returns all trading days starting from 1970-01-02.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetCalendarRequest

import pandas as pd
from datetime import datetime

import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)


trading_calendar  = trading_client.get_calendar()

trading_cal = [dict(item) for item in trading_calendar]

df = pd.DataFrame.from_records(trading_cal)
df.head()
Alpaca API Python Client Get Calendar DataFrame

You can also get marketing days between two days using the get_calendar() method. However, to do so, you need to pass the start and end dates to the GetCalendarRequest class, which subsequently parameterizes the get_calendar().

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetCalendarRequest

import pandas as pd
from datetime import datetime

import os

api_key = os.environ['AP-Key']
api_secret = os.environ['AP-Secret']

# paper=True enables paper trading
trading_client = TradingClient(api_key, api_secret, paper=True)


request_params =  GetCalendarRequest(
                        start = datetime.strptime('2022-09-04', '%Y-%m-%d').date(),
                        end = datetime.strptime('2022-10-06', '%Y-%m-%d').date(),
                        
                   )

trading_calendar  = trading_client.get_calendar(request_params)

trading_cal = [dict(item) for item in trading_calendar]

df = pd.DataFrame.from_records(trading_cal)
df.head()
Alpaca API Python Client Get Calendar Window DataFrame

The Trading API offers several other endpoints you can leverage to perform various trading activities. For more details, see the Trading API documentation. 

Broker API

The Broker API allows you to perform various brokerage tasks, e.g., user account creation and handling, placing and managing orders on users’ behalf, etc. 


You must sign up for the Broker API to access broker API endpoints.

Alpaca Markets Broker Signup Page

You will receive a verification code that you need to enter to activate your account. Log in to your Broker API account, and select the “API/Devs” option from the left sidebar. Click the “Generate” button to generate your broker API key and secret. 

Alpaca Markets Broker API Generate Keys Page

The BrokerClient class lets you call various broker endpoints from the Alpaca API. 

Create Alpaca Broker Account

You will need a broker API key and secret to create an Alpaca broker account. The  create_account() method establishes a brokerage account. The method accepts an object of the CreateAccountRequest class. 

You need to pass the objects of the following classes to the CreateAccountRequest class:

  1. Contact: contains the contact details of the account holder
  2. Identity: stores the personal information of the account holder
  3. Disclosures: stores any information that needs to be disclosed
  4. Agreement: the type of the account agreement, e.g., customer agreement. 

Here is an example of creating a client account using fictional client information.

from alpaca.broker import BrokerClient
from alpaca.broker.requests import CreateAccountRequest
from alpaca.broker.models.accounts import Contact, Identity, Disclosures, Agreement, AccountDocument, TrustedContact
from alpaca.broker.enums import EmploymentStatus, TaxIdType

import os

api_key = os.environ['BAP-Key']
api_secret = os.environ['BAP-Secret']

contact = Contact(email_address = "abcd123@gmail.com",
                 phone_number = "0123456789",
                 street_address = ["abc"],
                 city = "London")
identity = Identity(given_name = "John",
                   family_name = "Doe",
                   date_of_birth = "1990-04-10",
                   country_of_citizenship = "FRA",
                   country_of_tax_residence = "FRA",
                   tax_id = "00000000",
                   tax_id_type = TaxIdType.FRA_SPI
                   )
disclosure = Disclosures(is_control_person = True,
                        is_affiliated_exchange_or_finra = False,
                        is_politically_exposed = False,
                        immediate_family_exposed = False,
                        #employment_status = EmploymentStatus.STUDENT
                        )
agreement = Agreement(agreement = "customer_agreement",
                     signed_at = "2022-09-02T15:04:05Z",
                     ip_address = "127.0.0.1"
                     )
request_params = CreateAccountRequest(contact = contact,
                                      identity = identity,
                                      disclosures = disclosure,
                                      agreements = [agreement]
                                     )
broker_client = BrokerClient(
                    api_key=api_key,
                    secret_key=api_secret,
                    sandbox=True,
                )
broker_client.create_account(account_data = request_params)
Alpaca API Python Broker Client Create Account Json

Get Alpaca Broker Account Details

You can get details of a brokerage account using the get_account_by_id() method.

You can get the broker account details using the get_account_by_id() method:

from alpaca.broker import BrokerClient
import os
api_key = os.environ['BAP-Key']
api_secret = os.environ['BAP-Secret']
broker_client = BrokerClient(
                    api_key=api_key,
                    secret_key=api_secret,
                    sandbox=True,
                )
broker_client.get_account_by_id("da4c3378-71c2-433e-bf09-2344eebd3c88"
Alpaca API Python Broker Client Create Account Json

List of All Alpaca Broker Accounts

Finally, you can retrieve a list of all your broker accounts using the list_accounts() method of the BrokerClient class:

from alpaca.broker import BrokerClient
import pandas as pd
import os

api_key = os.environ['BAP-Key']
api_secret = os.environ['BAP-Secret']

broker_client = BrokerClient(
                    api_key=api_key,
                    secret_key=api_secret,
                    sandbox=True,
                )
all_accounts = broker_client.list_accounts()

accounts_dict = [dict(item) for item in all_accounts]

df = pd.DataFrame.from_records(accounts_dict )
df.head()
Alpaca API Python Broker Client List Accounts DataFrame

Frequently Asked Questions

Is Alpaca Regulated?

Alpaca is a member of The Securities Investor Protection Corporation (SIPC) and is regulated by Financial Industry Regulatory Authority FINRA. If anything were to happen with Alpaca, the SIPC offers insurance protection of up to $500,000 per customer. 

Where Does Alpaca Get Its Data?

Alpaca claims to get real-time data with 99.5% accuracy from all the US stock exchanges. Alpaca Securities LLC  and Alpaca Crypto LLC render US stock and crypto services for Alpaca Markets. 

Can You Short on Alpaca?

You can short sell on Alpaca. However, it is essential to note that all exchanges listed on Alpaca may not allow short selling. 

Can You Backtest on Alpaca?

Backtesting refers to estimating the accuracy of a trading strategy by testing it on historical data. Alpaca trading API does not support backtesting. However, Alpaca provides integration with the Backtrader library, which allows backtesting on Alpaca data. 

What Clients Are Available for Alpaca API?

Alpaca API has several official and third-party API clients. See Alpaca API client libraries.

The Bottom Line

Alpaca Markets is a state-of-the-art trading platform providing highly accurate and real-time stock market and cryptocurrency information. Unlike traditional brokerage platforms, Alpaca Markets is an API-first company providing rich APIs for automating trading operations. Developers, investors, and researchers can leverage Alpaca Markets API to offer rapid trading algorithm development endpoints. 

This article explains how to perform various trading operations using the Alpaca API Python client. The information in this tutorial can help you develop algorithmic trading applications for you or your clients. The researchers can also benefit from this article in developing statistical and financial models.

Leave a Comment