I’m looking for a copy trading tool for Alpaca accounts i.e. duplicating trades from one Alpaca account to another using the Alpaca API. There are lots of copy trading tools available but I don’t know of any that work with Alpaca. Is anyone aware of such a tool, or interested in building one using Python?
Here you have a python script to copy trades between a master and a slave account
import os
import asyncio
from alpaca_trade_api.rest import REST
from alpaca_trade_api.stream import StreamMaster account keys and endpoints
ALPACA_API_KEY_MASTER = os.environ.get(“ALPACA_API_KEY_MASTER”)
ALPACA_API_SECRET_MASTER = os.environ.get(“ALPACA_API_SECRET_MASTER”)
ALPACA_BASE_URL_MASTER = “https://paper-api.alpaca.markets”client_master = REST(
ALPACA_API_KEY_MASTER,
ALPACA_API_SECRET_MASTER,
base_url=ALPACA_BASE_URL_MASTER
)Slave account keys and endpoints
ALPACA_API_KEY_SLAVE = os.environ.get(“ALPACA_API_KEY_SLAVE”)
ALPACA_API_SECRET_SLAVE = os.environ.get(“ALPACA_API_SECRET_SLAVE”)
ALPACA_BASE_URL_SLAVE = “https://paper-api.alpaca.markets”client_slave = REST(
ALPACA_API_KEY_SLAVE,
ALPACA_API_SECRET_SLAVE,
base_url=ALPACA_BASE_URL_SLAVE
)Create the stream for the master account
stream = Stream(ALPACA_API_KEY_MASTER, ALPACA_API_SECRET_MASTER, base_url=ALPACA_BASE_URL_MASTER)
@stream.on(“trade_updates”)
async def handle_trade_updates(data):
event_type = data.event
order_info = data.ordersymbol = order_info["symbol"] side = order_info["side"] # 'buy' or 'sell' qty = order_info["qty"] order_type = order_info["type"] # e.g., 'market', 'limit', etc. tif = order_info["time_in_force"] # e.g., 'gtc', 'day', etc. if event_type == "new": # Replicate the new order in the slave account client_slave.submit_order( symbol=symbol, qty=qty, side=side, type=order_type, time_in_force=tif ) elif event_type == "canceled": # Find and cancel the corresponding open order in the slave account open_orders_slave = client_slave.list_orders(status="open") for o in open_orders_slave: if o.symbol == symbol and o.side == side: client_slave.cancel_order(o.id) elif event_type == "fill": # This block would handle any logic upon order fill if needed pass
if name == “main”:
stream.run()’
Thanks for the script - I’ll have fun checking it out.