Deploying the paper trader on a small cloud VM¶
This guide takes the paper trader from a fresh Linux VM to a service that trades unattended, tells you when something happens, and comes back by itself after a crash or a reboot. It uses the repository's Docker setup (see Running in Docker). Allow about half an hour.
It trades an Alpaca paper account only: the client cannot reach a live-money endpoint.
1. What you need¶
- An Alpaca account. In the dashboard, switch to the paper account and generate an API key pair.
- A VM with a recent Ubuntu LTS. The trader needs very little: the smallest instance most providers offer (1 vCPU, 1 GB of memory, 10 GB of disk) is plenty. Intel and Arm machines both work, since the image is built on the machine itself. Any region works for daily bars; for minute bars, a US region keeps requests to Alpaca quick.
- Optional: a webhook for alerts. In Slack, create an app with an incoming webhook. In
Discord, create a webhook under the channel's integrations and add
/slackto its URL. - Optional: an account with a monitoring service that alerts you when regular pings stop, such as healthchecks.io (see Monitoring).
2. Prepare the VM¶
Create the VM with your SSH key, then log in as the image's default user (ubuntu on
Ubuntu images). Nothing needs to reach the trader from outside: it only makes outbound
HTTPS requests. So allow SSH and nothing else, in your provider's firewall and on the
machine:
Docker. Install Docker Engine and the Compose plugin from Docker's apt repository, following Docker's instructions for Ubuntu. Then let your user run Docker, log out and back in, and check:
Membership of the docker group is as good as root, which is fine on a machine that only
runs the trader.
Clock. The trader decides that a bar is complete from the system clock, so the clock
must be synchronized. Ubuntu does this by default. timedatectl should say
System clock synchronized: yes. The time zone does not matter, because the trader works
in UTC and New York time. Cloud images usually run on UTC, which this guide assumes.
Security updates. Ubuntu installs them automatically but never reboots for them. To let it reboot when an update needs it, at a time when the market is closed (02:00 UTC is evening in New York), run:
sudo tee /etc/apt/apt.conf.d/52unattended-reboot > /dev/null <<'EOF'
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
EOF
A reboot stops the trader gracefully, and Docker starts it again at boot.
3. Get the code and add the secrets¶
git clone https://github.com/Space-Paragon1/Event-Driven-Trading-System.git
cd Event-Driven-Trading-System
cp .env.example .env
chmod 600 .env
nano .env
To run a fixed version, check out a release tag (git tag lists them) or a commit.
In .env, fill in APCA_API_KEY_ID and APCA_API_SECRET_KEY with the paper keys, and
TRADING_ALERT_WEBHOOK with the webhook URL, or leave it empty for no alerts. Docker
Compose hands these to the trader as environment variables. Git ignores .env, and it
never goes into the image.
4. Choose and check the strategy¶
The trader runs config/paper.yaml: SPY, a 10/50 moving-average
crossover on daily bars and a 5% stop-loss. It is a starting point, not a recommendation.
Change the symbols, strategy, sizing and risk limits to suit you, leaving the /data paths
as they are. config/default.yaml lists every setting.
portfolio.starting_cash (100,000 by default) is the strategy's virtual account inside
the paper account. Keep it within the paper account's buying power. A new session needs
the paper account to hold no positions and no open orders in the traded symbols. Changing
the symbols later also starts a new session. Positions in symbols you drop stay in the
account, with their stop-losses, until you close them.
Backtest the same file on your own computer before trading it. Yahoo Finance data needs
the data extra, and --no-db stops the backtest from writing to the /data path:
pip install -e ".[data]"
trading --config config/paper.yaml --from 2015-01-01 --to 2025-01-01 --no-db
Then, on the VM, build the image and do a dry run. It reads live bars with your keys and
simulates fills, but sends no orders. It is a quick test of the keys, the config and the
webhook, which should receive a "Session started" and a "Session ended" alert labelled
[dry run ...]:
docker compose build
docker compose run --rm trader paper --config /config/paper.yaml --dry-run --iterations 1
5. Start trading¶
docker compose up -d
docker compose logs -f trader # Ctrl-C stops following the logs, not the trader
docker compose ps # "healthy" once the first heartbeat is in
The trader warms up on recent bars and takes the strategy's current position straight away. With daily bars, it trades each bar a minute before the next open, at 09:29 New York time, and Alpaca fills the orders at the open. It checks for fills every minute while the market is open, sleeps from the close until just before the next open, and logs a heartbeat every five minutes throughout.
6. Day to day¶
Status.
docker compose exec trader trading health --config /config/paper.yaml
docker compose exec trader cat /data/heartbeat.json
docker compose exec trader trading runs
Logs. Each log line is a JSON object. The trader also prints its session report as
text when it stops, so filter the logs with jq -R 'fromjson?', which skips lines that
are not JSON (install it with sudo apt-get install -y jq):
docker compose logs --no-log-prefix trader | jq -cR 'fromjson? | select(.event == "fill")'
docker compose logs --no-log-prefix --since 24h trader | jq -cR 'fromjson? | select(.level != "INFO")'
Kill switch. Halt trading without stopping the service. The trader halts before its next step, cancels its open entry orders and leaves the stop-losses at Alpaca. During market hours that is within a minute. Overnight it is when the trader wakes before the open, and it halts before doing anything else:
A halted trader exits, Docker restarts it, and it refuses to start while the file exists,
so docker compose ps shows it restarting. To trade again, remove the file. Use a one-off
container for this, because the trader's own container keeps restarting:
The daily order limit (paper.max_orders_per_day) halts the trader in the same way, until
the next trading day.
Stopping and starting. docker compose stop stops the trader gracefully: it cancels its
open entry orders and leaves positions and their stop-losses at Alpaca.
docker compose start resumes the session. docker compose down also removes the
container, which is harmless, but never run docker compose down -v. It deletes the
data volume, and with it the run store that the trader resumes from.
7. Monitoring¶
There are three ways to keep an eye on the trader, and they cover different failures:
- Alerts (
TRADING_ALERT_WEBHOOK) report fills, errors, halts, and sessions starting and ending. They cannot report that the VM or the trader has died silently. - Docker's health check marks the container unhealthy when the trader has stopped,
halted or failed, or has not beaten for twice
heartbeat_secondsplus a loop (11 minutes by default). Docker only shows this indocker compose ps; it does not act on it. - A dead man's switch catches everything else. A cron job on the VM pings a monitoring service while the trader is healthy, and the service alerts you when the pings stop: because the VM is down, Docker is down, or the trader is stopped, halted or stuck.
To set up the switch, create a check at the service with a 5-minute period and about 15
minutes of grace. Then add the following line with crontab -e, using your check's ping
URL in place of https://hc-ping.com/YOUR-CHECK-ID:
*/5 * * * * cd $HOME/Event-Driven-Trading-System && docker compose exec -T trader trading health --config /config/paper.yaml > /dev/null && curl -fsS -m 10 --retry 3 -o /dev/null https://hc-ping.com/YOUR-CHECK-ID
Daily report. trading compare replays the session's bars through a backtest of the
same config and reports how paper trading differs: fill prices in basis points, fills on one
side only, commissions, and equity (see
Paper against backtest). To have it posted to the
webhook every weekday after the close, add this line with crontab -e:
30 21 * * 1-5 cd $HOME/Event-Driven-Trading-System && docker compose exec -T trader trading compare --config /config/paper.yaml --alert > /dev/null
With daily bars, a day is complete once the trader has traded its bar, a minute before the next open. So the report after Monday's close covers the previous Friday, and Monday's fills are listed as pending. The first fill compares cleanly when the trader is started before the open, after midnight New York time. Started later, it fills when it starts, while the backtest fills at the open of the bar being formed.
8. Backups¶
The run store (/data/trading.db) is what lets a restarted trader resume its session. If
it is lost, a new session refuses to start until the paper account holds no positions in
the traded symbols. Back it up nightly with SQLite's backup API, which copies the live
database safely, and keep 30 days of copies. Add these lines with crontab -e, and note
that % must be written \% in a crontab:
30 1 * * * cd $HOME/Event-Driven-Trading-System && mkdir -p backups && docker compose exec -T trader python -c "import sqlite3; sqlite3.connect('/data/trading.db').backup(sqlite3.connect('/data/backup.db'))" && docker compose cp trader:/data/backup.db backups/trading-$(date +\%F).db
45 1 * * * find $HOME/Event-Driven-Trading-System/backups -name 'trading-*.db' -mtime +30 -delete
Copies on the VM do not survive the loss of the VM. Your provider's scheduled disk
snapshots, or an occasional scp to another machine, cover that.
To restore a copy, stop the trader, copy the backup into the volume with a one-off container, and start it again:
docker compose stop
docker compose run --rm -v "$PWD/backups:/backups:ro" --entrypoint cp trader /backups/trading-2026-01-30.db /data/trading.db
docker compose start
9. Updating¶
Update outside market hours, after a backup:
git pull # or: git fetch --tags && git checkout <tag>
docker compose up -d --build
docker compose logs -f trader
Compose rebuilds the image and replaces the container. The old trader stops gracefully,
and the new one resumes its session. Read the changelog first. Settings
are validated, so a renamed setting stops the new version from starting, with an error in
the logs that names it. The run store is migrated to a new schema in place, and an older
version refuses to open a newer schema. To roll back, check out the previous version,
restore the backup taken before the update, and run docker compose up -d --build.
10. Troubleshooting¶
Most problems show up as a trader that Docker keeps restarting because it refuses to start.
The reason is in docker compose logs trader. Safety-limit refusals are logged as warnings,
but other errors are alerted on every attempt, so docker compose stop the trader while
you fix the cause.
| What you see | Why | What to do |
|---|---|---|
Restarting; Alpaca paper-trading keys not found |
.env is missing the keys |
Fill them in, then docker compose up -d |
Restarting; the paper account already holds ... |
A new session must start without positions in its symbols: the run store is missing, or the symbols changed | Close the positions in the Alpaca dashboard, or restore the run store |
Restarting; kill switch /data/KILL is engaged |
The kill switch | Remove /data/KILL (see Day to day) |
Restarting; ... orders were sent in ... today |
The daily order limit was reached | It starts again on the next trading day; find out why it sent so many |
Restarting; ... uses an incompatible schema |
The run store is newer than the code | Update the code, or restore an older backup |
Restarting; cannot resume session ... or ... that session ... did not place |
The paper account changed behind the trader's back: traded by hand, or reset | Cancel the stray orders, or flatten the symbols in the dashboard and start afresh (below) |
| Unhealthy | The trader stopped, halted or is stuck | docker compose exec trader trading health --config /config/paper.yaml, then the logs |
| Orders rejected for buying power | portfolio.starting_cash exceeds the account |
Lower it, or reset the paper account with more money |
To start afresh, for example after resetting the paper account, move the run store aside. The next start begins a new session: