Skip to content

About

Live VBO trading bot for Upbit — multi-account, +101% in 2024

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Crypto Bot

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.

Python 3.10+ Docker

Korean README: README_KR.md

Live Trading Track Record

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)

Key Features

  • 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

Strategy Summary (VBO v1.1)

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.

Runtime Behavior

bot.py startup:

  1. Load .env (load_env)
  2. Configure logging (LOG_FORMAT=text|json)
  3. Acquire single-instance lock at logs/.pid (format hostname:pid); stale files from a previous container/host are auto-replaced. Duplicate live instances exit immediately with a Telegram alert.
  4. Send a startup daily report (so operators see current state immediately)
  5. Start VBOBot().run()

Per-account loop (1 s default interval):

  1. Reconcile any unresolved pending buys (recover fills the exchange didn't ACK in time)
  2. Fetch / recalculate daily signals (fail-closed if stale across trading-day rollover)
  3. Opening sell — once per session, at 09:00 KST when signals first land
  4. 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_SEC for 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.

Quick Start

1) Local

pip install .
cp .env.example .env  # fill in keys
python bot.py

2) Docker

docker compose up -d --build
docker compose logs -f

Code-only update:

git pull
docker compose restart

3) Automatic deploy on push

.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.

Environment Variables (.env)

Full example: .env.example.

Accounts (required: at least 1)

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.

Strategy / Notifications / Logging

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: text

Twitter pipeline (optional)

TWITTER_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=sub

Code 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

State Files / Log Structure

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)

Trade CSV schema

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_data and position_after are JSON strings.
  • profit_pct / profit_krw are blank on BUY rows.
  • reference_price is the quote the order was sent against; slippage_pct / slippage_krw are 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.
  • notes distinguishes special cases: "pending-buy recovered", "manual liquidation" (from liquidate.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.

Operational Reliability

  • 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 open would 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 past STALE_CANDLE_GRACE_SEC the 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 past Account.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_order and/or pre/post-balance diff and materializes the position. After PENDING_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 spans asyncio.to_thread workers while keeping each account's batch separate, and splits only if it would exceed 4096 chars.

Testing / Quality

pip install -e ".[dev]"
pytest                       # 202 tests collected
ruff check . && ruff format --check .
mypy bot --ignore-missing-imports

CI 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.

Emergency Liquidation Script

python scripts/liquidate.py            # dry run (default)
python scripts/liquidate.py --execute  # actually sell

Live 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.

Live vs Backtest Reconciliation (monthly)

python scripts/reconcile_live.py                                  # on the bot host
python scripts/reconcile_live.py --logs ../crypto-bot-logs/logs --account sh --since 2026-05-14

Replays 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>&1

Live Track Record on Twitter (Optional)

Posts 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 sources

data/equity_history.csv — one row per UTC day:

date,equity
2024-01-01,17000000.00
2024-01-02,17050000.00

data/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: deposit flow_krw = +(amount − fee), withdraw flow_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.

Tweet schedule

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.

Setup

pip install -e ".[twitter]"

GitHub Actions secrets (Twitter app with Read+Write): TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET.

Local dry-run

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-run

Charts render to data/output/ without hitting the Twitter API.

Daily Log Backup to GitHub (Optional)

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>&1

Re-runs are no-ops when nothing changed, so over-cron is safe.

Project Structure

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

Disclaimer

  • 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.

About

Live VBO trading bot for Upbit — multi-account, +101% in 2024

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages