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
daytime in force, cryptogtc. - 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.