:seo_title: Alpaca Trading Bot in Python: AI Agent and Algorithmic Trading with LumiBot .. Generated by scripts/generate_ccxt_exchange_pages.py from docsrc/_data/. Edit the data, not this page. Alpaca Trading Bot in Python ============================ .. meta:: :description: Build a Alpaca trading bot in Python with LumiBot and CCXT. Create Alpaca API keys, connect them, and run a regular or AI agent strategy. :keywords: Alpaca trading bot, Alpaca API, Alpaca Python, agentic trading Alpaca, AI trading bot Alpaca, algorithmic trading Alpaca, ccxt alpaca This guide shows how to build a Alpaca trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to Alpaca through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a Alpaca account and API key, connect it, and run two examples: a simple algorithmic trading bot and an agentic trading bot where an AI agent makes the calls. Alpaca at a glance ------------------ .. list-table:: :widths: 35 65 * - CCXT exchange id - ``alpaca`` * - Markets - Spot * - Testnet (sandbox) - Yes * - Credentials - API key, API secret * - Live data streams - prices, order book, trades, candles, your orders * - CCXT request spacing - about 333 ms between requests * - Official site - https://alpaca.markets * - API docs - https://alpaca.markets/docs/ * - Fees - https://docs.alpaca.markets/docs/crypto-fees What is Alpaca? --------------- Alpaca is a trading platform with an API for stocks and crypto. Its crypto API lets you trade coins such as BTC around the clock against USD, USDT and USDC. Sign up for Alpaca ------------------ #. Sign up for an Alpaca Trading API account with your email address. #. To trade real money, open a live account and finish Alpaca's account application. Anyone can start with a paper-only account. #. Your account comes with a paper trading account. Alpaca starts it with a $100,000 simulated balance. `Open a Alpaca account `_ Create a Alpaca API key ----------------------- #. Log in to the Alpaca dashboard. #. Pick the account you want the bot to use: paper or live. Each one has its own keys. #. On the Home page, generate your API Key and Secret Key. #. Copy the Secret Key right away. Alpaca shows it only once. #. If you make a new paper account later, generate new keys for it. **Which permissions to turn on:** Alpaca's docs describe one key ID and one secret key per account, with no separate permission boxes. Anyone with the key can trade the account, so keep it private. If Alpaca ever shows a withdrawal or transfer option for a key, leave it off. .. warning:: Never turn on withdrawals for a Alpaca trading bot key. Bind the key to your server's IP address when Alpaca lets you, keep the secret out of your code and out of Git, and delete the key if it ever leaks. Connect Alpaca to LumiBot ------------------------- The simplest way: put these lines in a ``.env`` file next to your strategy. LumiBot loads the file, sees ``TRADING_BROKER=ccxt:alpaca`` and connects to Alpaca for you, so your strategy needs no broker code. .. code-block:: bash TRADING_BROKER=ccxt:alpaca ALPACA_API_KEY=your_apiKey ALPACA_API_SECRET=your_secret ALPACA_SANDBOX=true # testnet; remove this line for your live account ``alpaca`` is also the name of one of LumiBot's own brokers, so the ``ccxt:`` prefix tells LumiBot to use the Alpaca exchange through CCXT. LumiBot reads exactly the fields CCXT needs for Alpaca (``apiKey``, ``secret``). If one is missing, LumiBot stops at start-up and names the variable you still need. You can also build the broker in code. This is handy when one script talks to more than one exchange, or when you need extra CCXT options. The keys in the config are CCXT's own credential names for Alpaca: .. code-block:: python import os ALPACA_CONFIG = { "exchange_id": "alpaca", "apiKey": os.environ.get("ALPACA_API_KEY"), "secret": os.environ.get("ALPACA_API_SECRET"), "sandbox": True, # testnet first; set False for your live account } from lumibot.brokers import Ccxt broker = Ccxt(ALPACA_CONFIG) # then: MyStrategy(broker=broker, ...) Either way, LumiBot turns on CCXT's built-in rate limiting for you. Practice on the Alpaca testnet ------------------------------ Alpaca's sandbox is its paper trading account at https://paper-api.alpaca.markets. It fills orders against real-time quotes but sends nothing to a live market, and it uses separate paper keys. Set ``ALPACA_SANDBOX=true`` (or ``"sandbox": True`` in a code config) to use it. CCXT sends sandbox requests to: https://broker-api.sandbox.alpaca.markets, https://paper-api.alpaca.markets. Testnet and live accounts use different keys. Algorithmic trading example: a simple Alpaca bot ------------------------------------------------ This bot buys about 50 USD of BTC on Alpaca once and then holds it. It is a starting point to check that your keys, balances and orders work. If the exchange's minimum order is larger, raise the amount. .. code-block:: python from lumibot.entities import Asset from lumibot.strategies import Strategy class AlpacaBuyOnce(Strategy): """Buy a small amount of BTC once, then hold it.""" def initialize(self): self.sleeptime = "1H" self.set_market("24/7") # crypto trades all day, every day def on_trading_iteration(self): coin = Asset("BTC", asset_type=Asset.AssetType.CRYPTO) if self.get_position(coin) is not None: return # already holding BTC price = self.get_last_price(coin, quote=self.quote_asset) if price: quantity = round(50 / price, 6) # about 50 USD worth order = self.create_order(coin, quantity, "buy", quote=self.quote_asset) self.submit_order(order) if __name__ == "__main__": # LumiBot reads TRADING_BROKER and the keys from your .env file. strategy = AlpacaBuyOnce(quote_asset=Asset("USD", asset_type=Asset.AssetType.CRYPTO)) strategy.run_live() Agentic trading example: an AI agent that trades on Alpaca ---------------------------------------------------------- Agentic trading means an AI agent reads the market and decides what to do. In this example one LumiBot agent looks at prices and your Alpaca account, then places the orders itself. There is no Python logic in between: you set the rules in plain English in the prompt, such as what it may trade and how big each order can be. This follows the same pattern as LumiBot's AI trading team examples. .. code-block:: python from lumibot.entities import Asset from lumibot.strategies import Strategy class AlpacaAITrader(Strategy): """One AI agent researches the market and places the trades itself.""" def initialize(self): self.sleeptime = "4H" self.set_market("24/7") self.agents.create( name="trader", model="openai/gpt-6-luna", reasoning_effort="high", allow_trading=True, system_prompt=( "You manage a small crypto account on Alpaca. " "You may trade BTC and ETH against USD (asset_type 'crypto', quote_symbol 'USD'), or hold cash. " "Before every order, call account_portfolio, account_positions and " "market_last_price for that exact symbol in the same run. " "Keep each order under 10% of the account value. " "Explain each decision in one short paragraph." ), ) def on_trading_iteration(self): self.agents["trader"].run( task_prompt="Review recent BTC/USD and ETH/USD prices and your current holdings, then decide whether to buy, sell or hold.", context={"exchange": "Alpaca", "quote": "USD", "date": self.get_datetime().isoformat()}, ) if __name__ == "__main__": # LumiBot reads TRADING_BROKER and the keys from your .env file. strategy = AlpacaAITrader(quote_asset=Asset("USD", asset_type=Asset.AssetType.CRYPTO)) strategy.run_live() The agent needs a model key such as ``OPENAI_API_KEY`` in your environment. See the :doc:`AI agents quickstart ` for models, tools and memory. What you can trade on Alpaca through CCXT ----------------------------------------- .. list-table:: :header-rows: 1 :widths: 40 60 * - Market - Listed by CCXT * - Spot - Yes * - Margin - No * - Perpetual swaps - No * - Dated futures - No * - Options - No CCXT lists these order features for Alpaca: market orders, limit orders, stop orders, editing open orders, canceling orders. Alpaca tips ----------- * ``alpaca`` is also the name of LumiBot's own Alpaca broker, which keeps priority. To reach Alpaca's crypto API through CCXT, set ``TRADING_BROKER=ccxt:alpaca``. * Paper keys and live keys are different. Alpaca says live keys do not work with the paper API, and paper keys do not work with the live API. * Alpaca crypto pairs use a slash, for example ``BTC/USD``. Alpaca supports market, limit and stop limit orders for crypto, with ``gtc`` and ``ioc`` time in force. Frequently asked questions -------------------------- **Can I build a Alpaca trading bot in Python?** Yes. Install LumiBot (``pip install lumibot``), set your Alpaca keys and use the ``alpaca`` CCXT exchange id as shown above. **Does Alpaca have a testnet?** Yes. Set ``ALPACA_SANDBOX=true`` and use keys from the Alpaca testnet. **Which API permissions does a Alpaca bot need?** Alpaca's docs describe one key ID and one secret key per account, with no separate permission boxes. Anyone with the key can trade the account, so keep it private. If Alpaca ever shows a withdrawal or transfer option for a key, leave it off. **Can an AI agent trade on Alpaca by itself?** Yes. The agentic example above gives one agent permission to trade. You control what it may trade and how much through its prompt. **Can I trade Alpaca perpetual futures with LumiBot?** CCXT does not list perpetual swaps for Alpaca, so use spot markets. **Is LumiBot free?** Yes. LumiBot is open source on GitHub at https://github.com/Lumiwealth/lumibot. You pay only your exchange's trading fees and, for AI agents, your model provider. Run it in the cloud with BotSpot -------------------------------- Do not want to keep a computer running for your Alpaca bot? BotSpot is the hosted home for LumiBot strategies and AI trading agents: build with AI, backtest, connect a broker, and watch every trade with logs and alerts. `Try BotSpot `_ Related guides -------------- * :doc:`CCXT crypto trading with LumiBot ` * :doc:`AI agents quickstart ` * :doc:`Bequant trading bot ` * :doc:`Binance US trading bot ` * :doc:`Bit2C trading bot ` * :doc:`bitbank trading bot ` Sources ------- * `Alpaca Learn: How to get Alpaca Trading API key and start connection `_ (read 2026-10-23) * `Alpaca Docs: Paper Trading `_ (read 2026-10-23) * `Alpaca Docs: Authentication `_ (read 2026-10-23) * `Alpaca Docs: Crypto Spot Trading `_ (read 2026-10-23) * Exchange id, URLs, markets, credentials and stream support: CCXT 4.5.64 metadata, generated 2026-10-23