A live-trading VBO (Volatility Breakout) bot for Upbit KRW markets. Multi-account execution, daily signal caching, position persistence, Telegram alerts, single-instance guard, Docker healthcheck, and an automated Twitter track-record pipeline.
Korean README: README_KR.md
Real-account performance based on Upbit money-weighted return.
| Year | Period | Cumulative Return | Cumulative P&L | Avg. Capital |
|---|---|---|---|---|
| 2024 | Jan 1 – Dec 31 | +101.26% | +17,217,701 KRW | 17,002,818 KRW |
| 2025 | Jan 1 – Dec 31 | +19.28% | +6,732,533 KRW | 34,915,469 KRW |
| 2026 | Jan 1 – Feb 28 | +8.58% | +1,250,766 KRW | 14,562,661 KRW |
| 2024 | 2025 | 2026 (Jan–Feb) |
![]() |
![]() |
![]() |
- Live trading on Upbit KRW pairs (
pyupbit) - Simultaneous multi-account execution (
ACCOUNT_1..N) - Daily VBO signal recalculation at 09:00 KST (
DailySignals, fail-closed) - Per-account state persistence: positions, pending buys, retry cooldowns
- Telegram trade/error notifications with key-based cooldown throttling
- Single-instance guard via PID file (hostname-scoped, ignores stale containers)
- Docker heartbeat healthcheck
- Rich, audit-grade trade CSV (order_id, strategy version, signal data, fees, post-trade state)
- Optional Twitter live-track-record automation (daily + monthly tear-sheets)
- Optional daily log mirroring to a private GitHub logs repo
Core logic lives in bot/market.py and bot/bot.py.
| Item | Rule |
|---|---|
| Entry target | today_open + (prev_high - prev_low) * NOISE_RATIO |
| Entry filter | Previous day BTC close > SMA(BTC_MA) (BTC bull market filter) |
| Buy trigger | Current price >= target_price |
| Late entry guard | Reject buy if price is more than +LATE_ENTRY_PCT above target (asymmetric: below-target buys still execute at target breach) |
| Exit signal | Previous day coin close <= EMA(MA_SHORT) → sell at 09:00 KST opening |
| Opening sell timing | Runs exactly once per trading day when daily signals first arrive; positions entered during the current session are never sold intra-day |
| Re-entry | Allowed within the same day if signal still buys and price breaks the target again after the morning sell |
| Capital allocation | equity / len(SYMBOLS); per order amount = min(alloc, cash * 0.99); cash refreshed between buys |
equity is computed from cash + Σ tracked_qty * current_price so manual
deposits the bot didn't fill are included as cash but coin balances outside
tracked positions are not double-counted.
bot.py startup:
- Load
.env(load_env) - Configure logging (
LOG_FORMAT=text|json) - Acquire single-instance lock at
logs/.pid(formathostname:pid); stale files from a previous container/host are auto-replaced. Duplicate live instances exit immediately with a Telegram alert. - Send a startup daily report (so operators see current state immediately)
- Start
VBOBot().run()
Per-account loop (1 s default interval):
- Reconcile any unresolved pending buys (recover fills the exchange didn't ACK in time)
- Fetch / recalculate daily signals (fail-closed if stale across trading-day rollover)
- Opening sell — once per session, at 09:00 KST when signals first land
- Collect buy candidates and execute sized market buys
Background tasks:
- Heartbeat every 30 s →
logs/.heartbeat(Docker healthcheck reads it) - Daily report scheduler sends one Telegram report per trading day, at or
after 09:00 KST (keyed on the trading date, so a delayed tick still reports),
and triggers the equity snapshot + Upbit flow sync used by the Twitter
pipeline. It waits up to
SIGNAL_WAIT_SECfor signals rather than reporting an empty signal set.
Shutdown: SIGINT / SIGTERM flips running=False, the loop drains, the PID
file is removed, and a "Bot Stopped" Telegram is sent.
pip install .
cp .env.example .env # fill in keys
python bot.pydocker compose up -d --build
docker compose logs -fCode-only update:
git pull
docker compose restart.github/workflows/deploy.yml SSHes into the bot
host after CI passes on main and runs git pull + systemctl restart bot,
then waits for a fresh logs/.heartbeat as proof the bot came back — rolling
back to the previous commit if it didn't. Server prerequisites and the four
repo secrets it needs are documented at the top of that file.
The compose file mounts ./logs, ./data, ./bot, and ./bot.py. Logs and
data survive container rebuilds; code mounts are read-only.
Full example: .env.example.
ACCOUNT_1_NAME=Main
ACCOUNT_1_ACCESS_KEY=...
ACCOUNT_1_SECRET_KEY=...Add additional accounts as ACCOUNT_2_*, ACCOUNT_3_*, ... The loader stops
after 3 consecutive empty slots; an account with partial credentials is
skipped with a warning.
SYMBOLS=BTC,ETH # comma-separated, no spaces
MA_SHORT=3 # EMA period for the exit signal
BTC_MA=30 # SMA period for the BTC bull-market entry filter
NOISE_RATIO=0.5 # 0 < ratio <= 1 (warns outside 0.1–0.9)
TELEGRAM_BOT_TOKEN=...
TELEGRAM_CHAT_ID=...
# LOG_FORMAT=json # default: textTWITTER_API_KEY=...
TWITTER_API_SECRET=...
TWITTER_ACCESS_TOKEN=...
TWITTER_ACCESS_SECRET=...
# Restrict the tweeted snapshot to a subset of accounts. Defaults to ALL.
# TWITTER_TRACK_ACCOUNTS=subCode constants (bot/config.py)
| Constant | Value |
|---|---|
MIN_ORDER_KRW |
5000 |
FEE |
0.0005 |
CHECK_INTERVAL_SEC |
1 |
ORDER_DELAY_SEC |
0.2 |
LATE_ENTRY_PCT |
1.0 |
API_RETRY_COUNT |
3 |
API_RETRY_DELAY |
1.0 |
| Order rate limit | 8 req/s (Upbit limit: 10) |
| Quotation rate limit | 25 req/s (Upbit limit: 30) |
Account-level safety constants (bot/account.py):
| Constant | Value | Purpose |
|---|---|---|
ZERO_BALANCE_RETRY_LIMIT |
3 | Drop tracked position after this many zero-balance reads in a row |
BUY_RETRY_COOLDOWN_SEC |
300 | Per-symbol pause after a failed/ambiguous buy |
PENDING_BUY_TIMEOUT_SEC |
1800 | Give up on a pending buy after 30 min if still unresolved |
DUST_THRESHOLD_KRW |
1000 | Residual below this is exchange rounding; position is dropped |
logs/
├── .heartbeat # epoch seconds, refreshed every 30s
├── .pid # "hostname:pid" single-instance lock
├── {account}/
│ ├── positions.json # bot-tracked positions only
│ ├── runtime_state.json # pending_buys, buy_block_until, zero_balance_counts
│ ├── trades_YYYY-MM-DD.csv # one file per UTC day
│ └── trades_YYYY-MM-DD.v1.csv # rotated when header schema changes
data/
├── equity_history.csv # daily total-equity snapshots
└── flows.csv # KRW deposits/withdraws (auto-synced from Upbit)
Rich, audit-grade schema (one row per fill). Each row is independently
verifiable against Upbit's order history via order_id:
timestamp, date, order_id, strategy_name, strategy_version,
symbol, side, order_type, price, qty, amount, fee, fee_currency,
signal_data, account_balance_krw, position_after,
profit_pct, profit_krw,
reference_price, slippage_pct, slippage_krw, is_live, notes
strategy_version= short git SHA captured at process start (resolves to"unknown"when running off-repo, e.g. inside a built image).signal_dataandposition_afterare JSON strings.profit_pct/profit_krware blank on BUY rows.reference_priceis the quote the order was sent against;slippage_pct/slippage_krware positive when the fill was adverse on either side (bought above the quote, or sold below it). All three are blank unless the fill price is the exchange's own execution average and the quote succeeded — a price inferred from a balance delta is good enough for the cost basis but is not a measurement, so it is never booked as one.notesdistinguishes special cases:"pending-buy recovered","manual liquidation"(fromliquidate.py), and free-form comments.- If the file exists with an outdated header on startup, it's rotated to
trades_<date>.vN.csv(old data preserved) and a fresh file is started.
- Single-instance guard: PID file scoped by hostname so a stale file from a dead container is auto-replaced, but two live containers on the same host refuse to both start.
- Separate rate limits for order vs. quotation endpoints.
- Exponential backoff on transient API failures.
- Fail-closed signals: across a 09:00 KST trading-day rollover, the bot
refuses to trade on stale signals and retries recalculation every 30 s.
Recalculation is serialized: threads that ask while one is in flight block
and receive its result, instead of seeing an empty set. That wait is capped
(
RECALC_WAIT_SEC) because pyupbit issues its HTTP requests without a timeout — a hung request must not wedge every account loop. - Candle freshness check: at 09:00:00 Upbit may not have opened the new
daily candle yet, and the previous row's
openwould become the whole day's breakout target — cached, so with no second chance. Signals are recomputed until the last candle is dated for the current trading day, and pastSTALE_CANDLE_GRACE_SECthe bot proceeds anyway rather than halt for good. - Slippage tracking: every fill is measured against the quote the order was
sent on, logged to the trade CSV, summarized in the daily report over
SLIPPAGE_WINDOW_DAYS, and alerted on pastAccount.SLIPPAGE_ALERT_PCT. - Pending buy recovery: if a buy is filled but the exchange returns no
fill detail in time, the order is persisted as pending. The next loop tick
reconciles via
get_orderand/or pre/post-balance diff and materializes the position. AfterPENDING_BUY_TIMEOUT_SEC(or a confirmed terminal no-fill), the pending is cleared and an alert is sent. - Double-sell prevention: when a sell is submitted but the fill reply is ambiguous, the position is removed from the tracker (a stuck residual is a smaller blast radius than re-submitting a sell).
- Dust guard: residuals below
DUST_THRESHOLD_KRW(post-fee exchange rounding) are dropped without an order. - Sell quantity = full wallet balance for the symbol — coins purchased manually outside the bot are liquidated together. If you don't want this, hold manual positions in a separate account.
- Graceful shutdown on
SIGINT/SIGTERM. - Telegram error throttle: same-keyed errors collapse within a 300 s cooldown so a flapping condition doesn't spam.
- Batched notifications:
batch_notifications()collapses everything sent inside a block into one Telegram — one message per trading pass (however many symbols filled) and one for startup (banner + opening report). It rides a ContextVar, so it spansasyncio.to_threadworkers while keeping each account's batch separate, and splits only if it would exceed 4096 chars.
pip install -e ".[dev]"
pytest # 202 tests collected
ruff check . && ruff format --check .
mypy bot --ignore-missing-importsCI runs lint, mypy, the test matrix (Python 3.10/3.11/3.12), a Docker build,
and a Bandit security scan on every push to main / develop and on PRs to
main. See .github/workflows/ci.yml.
python scripts/liquidate.py # dry run (default)
python scripts/liquidate.py --execute # actually sellLive runs append a row to the standard trade CSV with notes="manual liquidation" so the daily backup and Twitter pipeline see manual sells in
the same schema as automated ones. Skips dust positions worth < 5000 KRW.
python scripts/reconcile_live.py # on the bot host
python scripts/reconcile_live.py --logs ../crypto-bot-logs/logs --account sh --since 2026-05-14Replays the live rules on Upbit daily candles with the .env parameters and
matches every live round trip to the backtest trade with the same
(symbol, entry day): matched (the gap is execution), MISSED (live skipped a
signal), or EXTRA (live traded without one). It prints a monthly breakdown
in approximate portfolio %p and exits 1 when the rolling 3-month
live-minus-backtest gap exceeds --threshold (default ±3%p). If live tracks
the backtest, a bad stretch comes from the market regime, not from execution.
To get it monthly on Telegram, add one crontab line on the bot host (see the
header of scripts/reconcile_monthly.sh):
40 9 1 * * /opt/crypto-bot/scripts/reconcile_monthly.sh >> /opt/crypto-bot/logs/reconcile.log 2>&1Posts daily / monthly performance updates from a CSV-backed equity history. Daily-changing metrics live in the tweet body; slow-changing aggregates (CAGR, Sharpe, Calmar, Max DD, Inception, Total) live on the chart — so a new visitor grasps the whole track record from a single image.
data/equity_history.csv — one row per UTC day:
date,equity
2024-01-01,17000000.00
2024-01-02,17050000.00data/flows.csv — capital flows (deposits + / withdrawals −) so TWR can
isolate trading P&L from inflows/outflows:
date,flow_krw,note,upbit_uuid
2024-03-15,5000000.00,deposit (Main),94332e99-3a87-4a35-...
2024-06-20,-1001000.00,withdraw (Main),...Both CSVs are auto-written by the bot's daily report:
- Equity via
append_snapshot()— idempotent per UTC day. - Flows via
sync_flows()— pulls Upbit/v1/deposits+/v1/withdraws, dedupes by Upbit's UUID, ACCEPTED KRW entries only. Sign convention: depositflow_krw = +(amount − fee), withdrawflow_krw = −(amount + fee).
By default the snapshot sums equity across all configured accounts. Set
TWITTER_TRACK_ACCOUNTS=name1,name2 in .env to publish only a subset
(e.g. a sub-account as a public track record while keeping Main private).
Example seeds are checked in as data/equity_history.example.csv and
data/flows.example.csv.
| Trigger | Workflow | Contents |
|---|---|---|
| 00:00 UTC daily | twitter-daily.yml | Today / MTD / YTD / DD from peak + cumulative-return chart with stats panel |
| 00:05 UTC, day 1 | twitter-monthly.yml | Month / YTD + full tear-sheet (cumulative return, drawdown, last-12-months bars, stats) |
Quarterly / half-year / annual posts are intended to be hand-written with a retrospective comment.
All return metrics are time-weighted (TWR): capital flows are subtracted from equity changes before computing returns, so a 10M KRW deposit doesn't show as a +100% day. The plotted curve is cumulative return (%) — currency-free, so no chart/tweet ever exposes the actual account balance.
Two drawdown metrics are deliberately separated:
- DD from peak (daily tweet body) — current NAV vs. all-time-high NAV. Dynamic, often 0% when at ATH.
- Max DD (stats panel) — worst historical peak-to-trough on the NAV series. Static once realized; withdrawal-induced equity drops do NOT count.
pip install -e ".[twitter]"GitHub Actions secrets (Twitter app with Read+Write):
TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET.
python scripts/post_daily_tweet.py --equity-csv data/equity_history.csv --dry-run
python scripts/post_monthly_tweet.py --equity-csv data/equity_history.csv --dry-run
# Render a backtest series (headline aggregates instead of today's noise,
# chart labeled "Backtest", flows.csv auto-load disabled):
python scripts/post_daily_tweet.py --equity-csv bt.csv --backtest --dry-runCharts render to data/output/ without hitting the Twitter API.
scripts/backup_logs_to_github.sh mirrors
a whitelisted slice of runtime artifacts — per-account trades_<date>.csv,
equity_history.csv, flows.csv — into a separate private repo via SSH.
Daily cron commits make the track record append-only and externally
cross-verifiable by order_id against Upbit's order history.
The script's header documents the one-time setup (SSH deploy key, host alias, clone path). Default cron entry (server in KST):
# 09:30 KST = 00:30 UTC — just after the bot's daily snapshot
30 9 * * * /opt/crypto-bot/scripts/backup_logs_to_github.sh \
>> /opt/crypto-bot/logs/github_backup.log 2>&1Re-runs are no-ops when nothing changed, so over-cron is safe.
crypto-bot/
├── bot.py # entry point
├── bot/
│ ├── __init__.py
│ ├── account.py # Upbit account: buy/sell/reconcile/state
│ ├── bot.py # multi-account loop, scheduler, PID guard
│ ├── config.py # env loader, Config, rate limiters, JSON logger
│ ├── logger.py # rich Trade dataclass + CSV writer w/ rotation
│ ├── market.py # price fetch + DailySignals (VBO calc)
│ ├── slippage.py # fill-vs-quote measurement + CSV aggregation
│ ├── tracker.py # PositionTracker — bot-managed positions only
│ ├── utils.py # Telegram send, batching, error throttle
│ └── performance/ # Twitter track-record pipeline
│ ├── equity.py # CSV history + flows loader/writer (atomic)
│ ├── flow_sync.py # Upbit deposits/withdraws → flows.csv
│ ├── metrics.py # NAV/TWR: CAGR, Sharpe, Calmar, MDD, MTD/YTD
│ ├── charts.py # daily chart + monthly tear-sheet
│ ├── composer.py # tweet text formatting
│ └── twitter_client.py
├── scripts/
│ ├── liquidate.py # emergency liquidation (dry-run by default)
│ ├── reconcile_live.py # monthly live-vs-backtest trade reconciliation
│ ├── reconcile_monthly.sh # cron wrapper: reconcile + Telegram digest
│ ├── post_daily_tweet.py
│ ├── post_monthly_tweet.py
│ └── backup_logs_to_github.sh # daily mirror to private logs repo
├── tests/
│ ├── conftest.py
│ ├── unit/ # bot/* + performance/* unit tests
│ └── integration/ # end-to-end bot flow
├── data/
│ ├── equity_history.example.csv
│ └── flows.example.csv
├── .github/workflows/ # CI + twitter-daily + twitter-monthly
├── Dockerfile # multi-stage, python:3.12-slim
├── docker-compose.yml # logs + data volumes; bot/* mounted RO
└── pyproject.toml # ruff + mypy + pytest config
- Test with small amounts before live trading.
- The Upbit API key requires at minimum "View assets" and "Place orders" permissions. Withdrawal permission is NOT used or required.
- All investment decisions and resulting profits or losses are the user's sole responsibility.


