# alpaca-backtrader-api: running Alpaca orders from a backtrader strategy

> alpaca-backtrader-api is a Python library that puts the Alpaca trade API behind backtrader's broker and data abstractions, so a backtrader strategy can read market data and place orders through Alpaca. Two details decide whether it is safe for you: the paper flag defaults to live trading, and the WebSocket connection limit of one per account caps how many feeds you can run.

**alpacahq/alpaca-backtrader-api** — Alpaca Trading API integrated with backtrader 

- Repository: https://github.com/alpacahq/alpaca-backtrader-api
- Website: https://pypi.org/project/alpaca-backtrader-api/
- Stars: 703 · Forks: 160
- Language: Python
- License: Apache-2.0
- Published: 2026-10-21 · Updated: 2026-10-21 · Language: en
- Canonical page: https://hysenlabs.com/projects/alpacahq-alpaca-backtrader-api

## AlpacaStore fills the broker and data slots backtrader expects

backtrader is built around two pluggable pieces: a broker that executes orders and a data feed that supplies the bars. This library supplies both for Alpaca. The README describes it as a Python library for the Alpaca trade API within the backtrader framework, allowing rapid trading algo development with support for both the REST and streaming interfaces, with details of each API behaviour left to Alpaca's online API document.

The entry point is AlpacaStore, created with a key_id, a secret_key and a paper flag. From that one object you get the broker through getbroker, or you can construct AlpacaBroker directly, and you get the data feed through getdata, or you can use AlpacaData. The distinction matters because the same class handles the historical and the live path: a data feed is created with dataname set to a ticker, historical set to True and a fromdate and timeframe, and the same AlpacaData class is what a live run uses when it subscribes to the streaming interface.

The audience is quant developers who have already chosen backtrader for its strategy and indicator library and now want Alpaca as the execution venue, rather than developers who want a trading framework from scratch. A backtrader SignalStrategy subclass, written with the usual indicators and crossover detection, becomes the whole of the strategy code, and the Alpaca specifics stay in the store construction.

The package is published on PyPI as alpaca-backtrader-api, the licence is Apache 2.0, and the repository is under the alpacahq organisation.

## The paper flag defaults to live trading

The single most important line in the documentation is a negative one. The README says the paper parameter is default to False, which allows live trading, and that setting it to True puts you in paper trading mode. A library whose default is real money is unusual, and it is worth reading twice before your first run.

The example makes the switch visible as a constant, and the README notes you can toggle between backtesting and paper trading by changing ALPACA_PAPER. The same constant also decides whether a broker is attached to the Cerebro engine at all. In the example, the broker is set only when the flag is false, and the comment notes that you can just use AlpacaBroker instead. When the flag is true, the strategy runs against the Cerebro default broker, which is the backtest path, while the data still comes from Alpaca's historical data.

That structure is the reason the example needs a funded brokerage account or another means of accessing Polygon data, as the README warns. Historical data is not free to everyone, and the examples do not run against a mock data source.

The practical habit this implies is simple: set paper explicitly rather than relying on a default, and treat a strategy file that does not mention the flag as untested, because a missing or misread value can route a live order.

## One WebSocket connection per account caps your data feeds

Here is the constraint that decides whether this library fits your strategy, and it is not a software limitation but an account limit at Alpaca. The README states that the WebSocket connection is limited to 1 connection per account, and that Alpaca backtrader opens a WebSocket connection for each data you define.

Multiply that out and you get the practical rule: one data feed per account unless you add something in front. The README describes running an algorithm with multiple datas, or running more than one algorithm, and points to a separate proxy agent project created for exactly this purpose. The steps it gives are to run the Alpaca Proxy Agent as described in that project's README, to define the environment variable DATA_PROXY_WS with the address of the proxy agent, for example DATA_PROXY_WS=ws://192.168.99.100:8765, and then to execute the algorithm, which then connects to the servers through the proxy agent and allows multiple datas and strategies to run.

So a multi-feed strategy is possible, but it depends on a component outside this repository, on a machine that can reach the proxy, and on an environment variable being set before the process starts. If your design needs several tickers at once, which is common for a pairs or cross-sectional strategy, that is the piece you must budget for. The sample directory in the repository reflects the same focus, with strategy_multiple_datas.py and strategy_multiple_indicators.py among the examples.

## Credentials go into the constructor, not an environment variable

Authentication is simple to the point of being a liability. The Alpaca API requires an API key ID and a secret key, which you obtain from the web console after signing in, and the README says you can set them in the AlpacaStore constructor using key_id and secret_key. The strategy example does exactly that, with the two values assigned to module level constants and then passed into the store.

There is no environment variable, no keyring and no credential file in the documentation, which means the usual practice of keeping secrets out of source control has to be handled by the caller, usually by reading them from the environment and assigning them to those constants before the strategy runs. The library does not care where the strings come from, so that decision stays with you.

Two related notes. The HTTP API document is at docs.alpaca.markets, which is Alpaca's own documentation for the REST interface that this library wraps, so behaviour questions about order types or account endpoints are answered there rather than in this repository. And the README splits support: technical issues particular to this module go to the GitHub repository, while any API issues go to Alpaca's customer support. That division is a clue about where the bugs live, since the library is a thin adapter over a REST and streaming API it does not define.

## A first strategy: SMA crossover against historical Alpaca data

The README's example is a complete, runnable shape and it is worth following as it stands. It starts with the imports and the credential and mode constants, where the two placeholders are replaced with what the web console gives you.

```python
import alpaca_backtrader_api
import backtrader as bt
from datetime import datetime
ALPACA_API_KEY = <key_id>
ALPACA_SECRET_KEY = <secret_key>
ALPACA_PAPER = True
```

The strategy itself is an ordinary backtrader SignalStrategy, computing two simple moving averages and going long on the crossover. No Alpaca API appears in it at all.

```python
class SmaCross(bt.SignalStrategy):
  def __init__(self):
    sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
    crossover = bt.ind.CrossOver(sma1, sma2)
    self.signal_add(bt.SIGNAL_LONG, crossover)
```

The engine and the store come next, and the branch on the paper flag decides whether a live broker is attached.

```python
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)
store = alpaca_backtrader_api.AlpacaStore(
    key_id=ALPACA_API_KEY,
    secret_key=ALPACA_SECRET_KEY,
    paper=ALPACA_PAPER
)
if not ALPACA_PAPER:
  broker = store.getbroker()  # or just alpaca_backtrader_api.AlpacaBroker()
  cerebro.setbroker(broker)
```

The data feed is requested from the same store, with a ticker, a start date and a daily timeframe, and the run prints the portfolio value before and after and plots the result.

```python
DataFactory = store.getdata  # or use alpaca_backtrader_api.AlpacaData
data0 = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(
    2015, 1, 1), timeframe=bt.TimeFrame.Days)
cerebro.adddata(data0)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.plot()
```

The plot call is the one step that pulls in a charting dependency outside this package.

## The package reads its version from the module and ships two requirement sets

The repository layout is small and tells you where the work sits. The top level holds the alpaca_backtrader_api package, a sample directory, a tests directory, a requirements directory, setup.py, setup.cfg, changes.txt and a CircleCI configuration, alongside a .pyup.yml for dependency updates and an .editorconfig-free, deliberately plain tree.

setup.py does two things worth noting. It reads the version out of alpaca_backtrader_api/__init__.py with a regular expression over the __version__ assignment and evaluates it with ast.literal_eval, rather than keeping the version in setup.py itself, so the package and the distribution never disagree. And it reads the dependency lists from the files in the requirements directory, splitting runtime requirements from test requirements, which the setup call passes as install_requires and tests_require.

The declared support is narrower than the README. The README says the module supports only python version 3.5 and above, due to the underlying library alpaca-trade-api, while the classifiers in setup.py list Python 3.7, 3.8 and 3.9 and the operating system as OS Independent. The samples directory is where the working end-to-end shapes live, with files for the readme sample, a plain sample, a sma crossover, multiple datas, multiple indicators and a resampling example, and the README points new users there.

## A current push, but the newest published release is from 2022

The two maintenance signals point in different directions and an adopter should hold both. The repository is not archived and the last push was on 2026-06-23. The release list, however, ends at v0.15.0 dated 2022-01-02, whose title records that it dropped support for python 3.6, before it came v0.14.1 in August 2021 as a small fix for the alpaca-proxy-agent and v0.14.0 in June 2021 as the Data V2 release. The changes.txt file at the top level holds the running change log.

So the code is still receiving commits, while the packaged releases a pip install would resolve to are years old. That is a real difference for anyone who installs from PyPI rather than from the repository, and it is the kind of gap where the version you report in a backtest is not the version your colleague is running.

The licence is Apache 2.0, with the LICENSE file at the top level. It permits use, modification and redistribution, including inside commercial and closed source products, provided the licence terms and any notices are preserved, and it comes with the usual warranty disclaimer. Pull requests for new features and bug fixes are welcomed per the README, and the repository carries a CircleCI badge for its build.

The one dependency to check before you start is the underlying alpaca-trade-api library, which the README names as the reason for the Python version floor. Alpaca has moved its own client libraries over time, and a wrapper pinned to an older client inherits that client's compatibility range, whatever the classifier list says.

## Conclusion

alpaca-backtrader-api fits a quant who already writes backtrader strategies and wants the same code path to move from historical data to paper trading through Alpaca, and it does not fit a team that needs multiple simultaneous data feeds without extra infrastructure, or that wants a current release train. Before adopting it, set the paper parameter to True explicitly, because the default is live trading, and confirm that the Alpaca account you use is the one whose WebSocket connection the strategy will hold.

## FAQ

### How do I install alpaca-backtrader-api?

Run pip3 install alpaca-backtrader-api from PyPI. The library requires Python 3.5 or above because of the underlying alpaca-trade-api library, while the setup.py classifiers list Python 3.7 to 3.9.

### How do I switch alpaca-backtrader-api between paper trading and live trading?

The paper parameter of AlpacaStore defaults to False, which allows live trading, and setting it to True puts you in paper trading mode. The example exposes this as the ALPACA_PAPER constant, and a broker is only attached to the Cerebro engine when the flag is false.

### Can I run multiple data feeds or strategies with alpaca-backtrader-api?

Not directly, because the WebSocket connection is limited to one connection per account and the library opens one per data. The README describes running the Alpaca Proxy Agent and setting DATA_PROXY_WS to its address, such as ws://192.168.99.100:8765, to allow multiple datas and strategies.

### Where do I get the API keys for alpaca-backtrader-api?

You need an API key ID and a secret key from the Alpaca web console after signing in, and you pass them to the AlpacaStore constructor as key_id and secret_key. API behaviour itself is documented at docs.alpaca.markets.

### What do the example strategies in alpaca-backtrader-api require?

The README warns that the examples only work if you have a funded brokerage account or another means of accessing Polygon data, since the historical data comes from Alpaca. The sample folder holds readme, plain, sma crossover, multiple datas, multiple indicators and resampling examples.

## Sources

- [alpacahq/alpaca-backtrader-api on GitHub](https://github.com/alpacahq/alpaca-backtrader-api)
- [License: Apache-2.0](https://github.com/alpacahq/alpaca-backtrader-api/blob/master/LICENSE)
- [Project website](https://pypi.org/project/alpaca-backtrader-api/)
- [README](https://github.com/alpacahq/alpaca-backtrader-api/blob/master/README.md)
- [Releases](https://github.com/alpacahq/alpaca-backtrader-api/releases)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/alpacahq-alpaca-backtrader-api
