This article was last updated on March 25 , 2026.

Connecting to Alpaca’s Trading API allows you to access market data and trade stocks programmatically using Python, JavaScript, C#, and Go. This guide walks you through creating your Trading API account, generating your API key, and getting started with `alpaca-py` (the Python SDK) in Google Colab as your integrated development environment (IDE).

NOTE: We now offer 24/5 trading. Read “How to Use 24/5 Trading with Alpaca’s Trading API and Dashboard” for more details.

Broker API

Execute your trading algos commission-free

Sign Up for Free

Step 1: Open a Paper Account

First, sign up for an Alpaca Trading API account by completing the required information.

Note: If your country is not listed under Country of Tax Residence, you will only be eligible for paper trading. For questions about country availability, please contact support at [email protected].

If you’re looking to start live trading, you will need to open an account. You can read our guides on opening a live trading account below:

Step 2: How to Get Your Alpaca’s Trading API Keys

Once you’ve created your Trading API account, navigate to the “Home” section to generate your API Key and Secret Key.

Note: Make sure to securely store your “Secret Key” when it’s first generated. You will only be able to view it once. If you regenerate your API Key and Secret Key, you will need to update your credentials and reconnect your IDE using the same setup process described below.

Step 3: Choose your IDE and Language

Alpaca’s Trading API can be used with various languages and IDEs. In this tutorial, we’ll be using Python and Google Colab. If you’re coding in Python, other common IDEs you could use include Visual Studio Code, Pycharm, and Cursor. You can also use a graphical user interface (GUI) like Postman or command-line tool with cURL.

Step 4: Set Up Google Colab

Open Google Colab and click the “New Notebook” button. This will initialize a Python environment for us to run the code in.

Step 5: Authenticate and Connect to Alpaca’s Trading API

Step 5-A: Install and Import Python Packages.

We’ll use the uv Python package manager to install all the necessary packages. You can also find example code notebooks on Alpaca’s GitHub page.

!uv pip install alpaca-py

Next, import the necessary libraries.

import os
import sys
import requests
from dotenv import load_dotenv
# Import Alpaca's package to initialize API client
from alpaca.trading.client import TradingClient

Step 5-B: Connect to Alpaca’s Trading API

This section sets up the environment configuration keys for each working environment (flexibly adjusting for Google Colab or local IDEs) and initializes Alpaca clients.

You can configure keys without typing them directly by using Google's 'Secrets' feature.

The environment configuration below automatically detects whether it's running in Google Colab or a local IDE and loads API keys accordingly.

if "google.colab" in sys.modules:
    # In Google Colab environment, we will fetch API keys from Secrets.
    # Please set ALPACA_API_KEY, ALPACA_SECRET_KEY in Google Colab's Secrets from the left sidebar
    from google.colab import userdata
    ALPACA_API_KEY = userdata.get("ALPACA_API_KEY")
    ALPACA_SECRET_KEY = userdata.get("ALPACA_SECRET_KEY")
else:
    # Please safely store your API keys and never commit them to the repository (use .gitignore)
    # Load environment variables from environment file (e.g., .env)
    load_dotenv()
    # API credentials for Alpaca's Trading API
    ALPACA_API_KEY = os.environ.get("ALPACA_API_KEY")
    ALPACA_SECRET_KEY = os.environ.get("ALPACA_SECRET_KEY")

Step 5-C: Initialize Alpaca's Trading Client

You can choose whether to trade in a live or paper account by setting the `paper` parameter to `True` or `False`. Set `paper=True` to place simulated trades in your paper account, or `paper=False` to send real orders to your live account.

# If you want to use a live account instead of paper account, set `paper=False`
trade_client = TradingClient(api_key=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY, paper=True)

Step 6: Verify Connection and Fetch Account Information

You can verify your setup by running one endpoint such as account details. See the API documentation for “Account Information” for details on account information fields.

# check trading account
# You can check definition of each field in the following documents
acct = trade_client.get_account()
acct

If the request succeeds, your account information will be returned, including your account number and status. This confirms a successful connection. 

{   'account_blocked': False,
    'account_number': 'XXXXXXXX',
    'accrued_fees': '0',
    'buying_power': '100000.0',
    'cash': '200000',
    'created_at': datetime.datetime(2024, 1, 3, 10, 00, 00, 40242, tzinfo=TzInfo(0)),
    'crypto_status': <AccountStatus.ACTIVE: 'ACTIVE'>,
    'currency': 'USD',
    'daytrade_count': 1,
    ...,
    'status': <AccountStatus.ACTIVE: 'ACTIVE'>,
    'trade_suspended_by_user': False,
    'trading_blocked': False,
    'transfers_blocked': False
}

If you receive error messages like HTTP 401 Error, it likely means your request was not authorized for the account you are trying to access. 

To resolve this:

  1. Make sure you are using the correct API key/secret pair for the environment you are calling (paper vs live)
  2. Make sure your credentials are sent using the exact required header names.

See the Alpaca’s Trading API Error Cheat Sheet: 30 Common Errors Explained and Troubleshot for details.

Conclusion

With your Paper Trading API account connected, you can test strategies for US stocks, ETFs, crypto, and options using simulated funds before trading with real capital. Paper trading does not reflect all market conditions or risks associated with live trading.  For more, you can read our data-backed blog on paper trading vs live trading and when users make the change.

When your workflow looks solid, the next step is to open and fund a live trading account so you can place live orders with the same API setup. Visit our guide on how to open a live Alpaca Trading API account as a US resident or non US resident. Once your live account is open, check out how to fund your live Alpaca Trading API Account as well.

If you want to keep building, explore the resources below for account setup, paper trading, and advanced Trading API workflows.


The content of this article is for general information only and is believed to be accurate as of posting date but may be subject to change. Alpaca does not provide investment, tax, or legal advice.

The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.

Orders placed outside regular trading hours (9:30 a.m. – 4:00 p.m. ET) may experience price fluctuations, partial executions, or delays due to lower liquidity and higher volatility. Orders not designated for extended hours execution will be queued for the next trading session. Additionally, fractional trading may be limited during extended hours. For more details, please review Alpaca Extended Hours & Overnight Trading Risk Disclosure.

All investments involve risk and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Keep in mind that while diversification may help spread risk, it does not assure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.

Securities brokerage services are provided by Alpaca Securities LLC (dba "Alpaca Clearing"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.

Cryptocurrency is highly speculative in nature, involves a high degree of risks, such as volatile market price swings, market manipulation, flash crashes, and cybersecurity risks. Cryptocurrency regulations are continuously evolving, and it is your responsibility to understand and abide by them. Cryptocurrency trading can lead to large, immediate and permanent loss of financial value. You should have appropriate knowledge and experience before engaging in cryptocurrency trading. For additional information, please click here.

Cryptocurrency services are made available by Alpaca Crypto LLC ("Alpaca Crypto"), a FinCEN registered money services business (NMLS # 2160858), and a wholly-owned subsidiary of AlpacaDB, Inc. Alpaca Crypto is not a member of SIPC or FINRA. Cryptocurrencies are not stocks and your cryptocurrency investments are not protected by either FDIC or SIPC. Please see the Disclosure Library for more information.

This is not an offer, solicitation of an offer, or advice to buy or sell securities or cryptocurrencies or open a brokerage account or cryptocurrency account in any jurisdiction where Alpaca Securities or Alpaca Crypto, respectively, are not registered or licensed, as applicable.