alpaca-backtrader-api

repository·master·Indexed 20 days ago

https://github.com/alpacahq/alpaca-backtrader-api

A Python library that integrates the Alpaca trade API with the Backtrader framework. It enables developers to build and run trading algorithms using REST and streaming interfaces via the AlpacaStore class, supporting both paper and live trading modes.

Tokens
1K
Snippets
2
Records
5
Agent score
22%

What's inside alpaca-backtrader-api

  1. Switch between Paper and Live trading modes

    master

    The AlpacaStore class uses a paper parameter to determine the connection mode:

    • Set paper=True to enable Paper Trading mode.
    • Set paper=False (default) to enable Live Trading mode.

    When using live trading (paper=False), you must explicitly set the broker in your cerebro instance using store.getbroker().

  2. Run multiple strategies or data feeds using a proxy

    master

    Alpaca's websocket connection is limited to one connection per account. Because alpaca-backtrader-api opens a websocket connection for every data feed defined, running multiple data feeds or strategies directly may fail.

    To bypass this limit, use the alpaca-proxy-agent:

    1. Run the alpaca-proxy-agent as described in its repository.
    2. Set the DATA_PROXY_WS environment variable to the address of your proxy agent (e.g., DATA_PROXY_WS=ws://192.168.99.100:8765).
    3. Execute your algorithm; it will route connections through the proxy agent.
  3. Implement a basic trading strategy with AlpacaStore

    master

    To use Alpaca with the backtrader framework, you must initialize an AlpacaStore with your credentials. You can then use the store to retrieve a broker for live/paper trading or a data factory for fetching market data.

    Key steps:

    1. Initialize AlpacaStore with key_id, secret_key, and paper (boolean).
    2. If paper is False, use store.getbroker() to set the backtrader broker.
    3. Use store.getdata as a factory to create data feeds (e.g., data0 = DataFactory(dataname='AAPL', ...)).

    Note: Examples requiring real data may require a funded brokerage account or Polygon data access.

    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
    
    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)
    
    
    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)
    
    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()
  4. Authenticate with Alpaca API

    master

    Authentication is handled via the AlpacaStore constructor. You must provide your API key ID and secret key obtained from the Alpaca web console.

    Required parameters for AlpacaStore:

    • key_id: Your Alpaca API key ID.
    • secret_key: Your Alpaca API secret key.