FAQ · Getting systematic research right

How do I run a Python strategy live on Alpaca?

Run the strategy on each closed bar from Alpaca's market data, send its orders to Alpaca's trading API, and feed the fills back so the strategy sees its real position. Start on Alpaca's paper account, which takes the same API calls with no money, and compare its fills with your backtest's before switching the keys to live.

Run the strategy on each closed bar from Alpaca's market data, send its orders to Alpaca's trading API, and feed the fills back so the strategy sees its real position. Start on Alpaca's paper account, which takes the same API calls with no money, and compare its fills with your backtest's before switching the keys to live.

The three parts of a live loop

  • Bars in. A bar stream or a poll each minute delivers closed bars. The strategy should only ever see closed bars, as in the backtest.
  • Orders out. Each order the strategy returns becomes an Alpaca order request: market, limit or stop, with a time in force.
  • Fills back. Alpaca's trade-update stream reports each fill. The strategy's next decision must see the position those fills produced, not the one it assumed.

What changes between backtest and live

  • Fills. Live fills come from the market. Compare them with the backtest's for the same days on paper; the gap is your real slippage.
  • Stocks and crypto differ. US stocks trade in sessions, and Alpaca's crypto trades around the clock. Stock orders typically use day time in force, crypto gtc.
  • Failures. A dropped connection, a rejected order or a restart mid-position. The loop must read the account's real position on start.

How Reamer Research handles it

Reamer Research runs the same on_bar live through its relay: your loop feeds it closed bars, relay.send() passes its orders to a receiver that talks to the broker, and the receiver's fill reports update the positions the strategy reads. The kit's python/live/live_paper.py is a complete loop, and --alpaca BTC/USD runs it on Alpaca's free crypto bars against a local paper broker, with no account needed.

For Alpaca's own paper or live account, the receiver places orders with the alpaca-py SDK. This sketch handles market and limit orders and reports fills from Alpaca's trade-update stream:

from alpaca.trading.client import TradingClient
from alpaca.trading.enums import OrderSide, TimeInForce
from alpaca.trading.requests import LimitOrderRequest, MarketOrderRequest
from alpaca.trading.stream import TradingStream
from relay_receiver import Receiver, BUY, LIMIT, PARTIAL, FILLED, CANCELLED, REJECTED

class AlpacaBroker:
    def __init__(self, key, secret, paper=True):
        self.client = TradingClient(key, secret, paper=paper)
        self.stream = TradingStream(key, secret, paper=paper)
        self.orders = {}                                  # intent_id -> (order, report)
        self.stream.subscribe_trade_updates(self.on_update)

    def on_order(self, order, report):
        self.orders[order['intent_id']] = (order, report)
        args = dict(symbol=order['instrument'], qty=order['quantity'],
                    side=OrderSide.BUY if order['side'] == BUY else OrderSide.SELL,
                    time_in_force=TimeInForce.GTC if '/' in order['instrument'] else TimeInForce.DAY,
                    client_order_id=order['intent_id'])
        request = (LimitOrderRequest(limit_price=order['limit_price'], **args)
                   if order['order_type'] == LIMIT else MarketOrderRequest(**args))
        try:
            self.client.submit_order(request)
        except Exception as e:                            # rejected by Alpaca
            report(order['intent_id'], order['instrument'], order['side'],
                   REJECTED, 0.0, 0.0, reason=str(e)[:200])

    def on_cancel(self, cancel, report):
        placed = self.client.get_order_by_client_id(cancel['target_order_id'])
        self.client.cancel_order_by_id(placed.id)

    def on_replace(self, replace, report):
        pass                                              # this sketch re-sends instead

    async def on_update(self, update):
        status = {'fill': FILLED, 'partial_fill': PARTIAL,
                  'canceled': CANCELLED, 'rejected': REJECTED}.get(update.event)
        o = update.order
        if status is None or o.client_order_id not in self.orders:
            return
        order, report = self.orders[o.client_order_id]
        report(order['intent_id'], order['instrument'], order['side'], status,
               float(o.filled_qty or 0), float(o.filled_avg_price or 0))

broker = AlpacaBroker('PAPER_KEY', 'PAPER_SECRET', paper=True)
with Receiver('/tmp/reamer-live.sock', broker):
    broker.stream.run()                                   # until Ctrl-C

Each order's intent_id becomes Alpaca's client_order_id, so fills and cancels find their order without a lookup table. The strategy side is live_paper.py with its PaperBroker lines removed and the socket path above: it builds the window from Alpaca's bars, calls the same on_bar that ran in the backtest, and sends what it returns. The strategy can be a function, a class or a configured object, as in the backtest; backtest to live without a rewrite walks through the loop, and the live trading docs document every message.

Limits to know

  • The Alpaca receiver is your code. The kit includes the relay, the receiver framework, a paper broker and the crypto bar feed; the sketch above is the starting point for your own broker connection, including brackets, stops and replaces if your strategy uses them.
  • Live trading needs a licence and runs on Linux or macOS. Evaluation Mode backtests only.
  • Alpaca's free stock data is the IEX feed. Its consolidated SIP feed is a paid plan; crypto bars need no key.

A $20 month includes the full kit, so you can take your strategy to Alpaca's paper account and cancel if it does not fit.

Next questions

How do I take a strategy from backtest to live trading without a rewrite?Keep the decision logic, and port everything around it. Write the strategy so its signals depend only on state it updates one bar at a time, keep instrument names and costs out of it, then prove the live version matches by replaying the backtest's bars through it and comparing every signal. The strategy carries over, and the connection to your broker is a few calls to its API.Can I paper trade before going live?Yes, with either product on its own. Reamer Research's relay sends a strategy's orders through the open-source receiver to your broker's paper or demo account. With Reamer Server, a separate order-management core for firms, point your connector at the paper account instead. The licence allows paper and live trading for both. The Reamer Server kit's in-memory paper broker is a wiring check: it fills every order instantly at a made-up price to confirm your server is connected correctly.How do I backtest an intraday strategy that must be flat by the close?Send the exit one bar before the last bar of the session, so it fills inside the session, and stop new entries from the same time. An exit sent on the final bar's close can only fill at the next open, which leaves the position overnight. Do the time check in the exchange's own time zone, then confirm from the trade list that every trade opened and closed on the same day.How realistic do slippage and spread need to be in a backtest?Realistic enough that the result survives them. Set spread, slippage and commission per instrument from what your broker actually charges, let spread and slippage widen when the market moves fast, and then rerun at one and a half and two times those costs. A strategy whose edge disappears under slightly higher costs was never a reliable edge.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.