ptrader is an intraday crypto trading system built for economic fidelity and robust observability. It simulates and executes trades with full treatment of leverage, margin, slippage, fees, and partial fills, while providing transparent analytics for both backtesting and live trading (paper or real).
This system is designed for quants, researchers, and builders who demand reproducible workflows and production‑ready controls.
- Daily max loss and drawdown kill‑switches.
- Stop‑loss / take‑profit enforcement.
- Cooldown between entries.
- Circuit breakers for API/data/exec/feed errors.
- Dynamic slippage and Kelly‑based sizing with volatility throttling.
- Full leverage and margin accounting.
- Interest accrual on borrowed funds.
- Maintenance margin checks with liquidation buffer.
- Realized vs unrealized PnL separation.
- Feature engineering (returns, volatility, moving averages, signed volume).
- Adaptive labeling with volatility‑scaled horizons.
- Ensemble of LightGBM and RandomForest models with logistic meta‑learner.
- Cross‑validation gates and candidate promotion.
- Periodic retraining with accuracy thresholds.
- Structured JSONL logs for machine‑readable events (includes per‑iteration
entry_diagevents withprob,size_usd,gate_ok,cooldown_okand related diagnostics). - Human‑readable logs with detailed trade summaries.
- Prometheus gauges and counters (equity, PnL, fills, errors); registration is idempotent so the exporter/server can be started safely multiple times.
- External metrics push endpoint.
- State checkpointing for recovery.
Threaded market feed with locks for safe concurrent access.
Clone the repo and install dependencies:
git clone https://github.com/dare-afolabi/ptrader.git
cd ptrader
pip install -e .[dev]Set your Alpaca API keys in .env:
ALPACA_API_KEY="your_api_key_here"
ALPACA_API_SECRET="your_api_secret_here"Or export them directly:
export ALPACA_API_KEY="your_api_key_here"
export ALPACA_API_SECRET="your_api_secret_here"ptrader --backtest --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Minptrader --live --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30MinShort test run — useful for quick debugging and verifying entry_diag behavior:
ptrader --live --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Min --max-iters 50 --live-interval 1 --feed-timeout 10# Explicit confirmation required (flag or env var):
ptrader --live --real --confirm-real --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Min
# or set in your environment:
export PTRADER_CONFIRM_REAL=1
ptrader --live --real --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Min(!) WARNING: You are advised against using
--realas it executes trade with actual funds. The CLI will refuse to proceed without--confirm-real(orPTRADER_CONFIRM_REAL=1) and will emit aconfirm_real_requiredevent inlogs/run.jsonlwhen confirmation is missing. If you absolutely must use real trading, do so with extreme caution and after extensive testing.
ptrader --help
# NaN forensic check
ptrader --nan-check
# Custom retrain interval
ptrader --live --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Min --retrain-every 60Prometheus exporter runs by default on port 8000 (configurable via --prom-port).
Quick checklist:
-
Run a short test (
--max-iters) and inspectlogs/run.jsonlforentry_diagevents to see why entries were skipped. -
Confirm
entry_diagshowsprob,size_usd,prob_ok,size_ok,gate_ok,cooldown_okto isolate blocking conditions. -
If there are no
entry_diagevents, make sure thelogs/directory exists and is writable by the running user (the CLI writeslogs/run.jsonl). -
No trades are occurring: check
logs/run.jsonlforentry_diagevents and inspect theprob,prob_ok,size_usd,size_ok,gate_ok, andcooldown_okfields to see which condition is blocking entries. By default entry_threshold = 0.25, sizing uses a Kelly baseline (edge = max(0.0, prob - 0.5)) so a probability < 0.5 produces zero size, and Live currently requiressize_usd > 10USD to execute a trade. For quick experiments, lowerentry_threshold, allow sizing for lower prob, or lower the minimum trade USD. -
Alpaca credentials: the CLI validates API keys for accidental newlines or shell prompt characters (e.g.,
>). If you copy/pasted keys and the CLI prints aninvalid_keymessage, re-copy the keys without embedded newlines or extra characters. -
Real trading safety: enabling
--realnow requires explicit confirmation via the--confirm-realflag or the environment variablePTRADER_CONFIRM_REAL=1to avoid accidental execution with real funds. -
Old package in use: if you see behavior that doesn't match workspace code, reinstall editable package locally:
pip install -e .[dev]. -
Feed behavior:
MarketFeedhas a polling interval and backoff on errors to avoid tight loops and runaway logging — use--feed-timeoutto make live runs exit if the feed becomes stale.
- Run a short live session (no real trades):
ptrader --live --symbols "SOL/USD,BTC/USD,ETH/USD" --tf 30Min --max-iters 50 --live-interval 1 --feed-timeout 10 > out.txt 2>&1- Inspect per-iteration diagnostics (
entry_diagevents):
# Quick grep
grep '"entry_diag"' logs/run.jsonl | tail -n 50
# Structured: show timestamp, prob, size and gate/cooldown flags
jq -r 'select(.event=="entry_diag") | "\(.ts) prob=\(.prob) size=\(.size_usd) prob_ok=\(.prob_ok) size_ok=\(.size_ok) gate_ok=\(.gate_ok) cooldown_ok=\(.cooldown_ok)"' logs/run.jsonl | tail -n 50- Check for actual entry/exit events and counts:
jq 'select(.event=="entry" or .event=="exit")' logs/run.jsonl | tail -n 50
jq 'select(.event=="entry")' logs/run.jsonl | wc -l- Look for key validation or feed-timeout issues:
jq 'select(.event=="invalid_key" or .event=="feed_timeout")' logs/run.jsonl | tail -n 10Tip: use
--max-itersand--live-intervalto run fast experiments and revert any temporary config changes (thresholds/sizing/minimum trade USD) after testing.
(Historical Data)
Market Feed ──► Feature Engineering ──► Labeling ──► Ensemble Training
│
▼
Cross‑Validation / Pruning
│
▼
(In‑memory trained model)
│
├──────────► BacktestRunner ──► Paper Engine
│
▼
Live Market Feed ──► Feature Engineering ──► Live Engine ──► Paper Engine / Real Engine
│
▼
Monitoring (Prometheus, JSONL, Human logs)- Format code with Black:
black src/ tests/ scripts/- Lint with Flake8:
flake8 src/ tests/ scripts/Run the full test suite with pytest:
pytest -qUnit tests cover:
- Engines: Paper, Backtest, Live/Real via mocks.
- Risk: Kelly sizing and kill‑switch triggers.
- Features: schema validation and feature engineering.
- Labels: adaptive labels and regime gate.
- Models: RF, LGB, Ensemble predictions.
- CLI: wiring with dummy exchange and invalid key handling.
- Feeds: polling interval/backoff behavior and stale-feed detection.
- Metrics: Prometheus idempotence (safe re-registration).
- Live-run: max-iters, feed-timeout, and diagnostic
entry_diagemission.
- Add
pytest,flake8, andblack --checkto your CI pipeline. - Ensure environment variables (
ALPACA_API_KEY,ALPACA_API_SECRET) are set in CI for integration tests. - Prometheus metrics can be disabled in CI by skipping
start_http_server.
- Fork and clone the repo.
- Create a feature branch:
git checkout -b feature/my-change- Make changes with tests.
- Run linting and tests locally.
- Push and open a pull request.
- Multi‑exchange fallback (Binance, Coinbase).
- Automated retraining pipeline with drift monitoring.
- Portfolio‑level risk management (VaR, Expected Shortfall).
- CI/CD integration with containerized deployment.
- The
ptraderproject is provided for research, education, and experimentation only. It is not financial, investment, tax, or legal advice and is not intended to be used as a trading recommendation or service. - There is no guarantee of profitability; any examples, backtests, or live paper runs are for demonstration purposes. Past performance does not predict future returns.
- Using real-money mode (
--real) executes live orders and exposes you to financial risk — do not enable--realunless you fully understand the risks and have performed thorough testing and due diligence. - The maintainers, contributors, and authors expressly disclaim all liability for any losses, damages, or claims resulting from the use of this project. Users assume all responsibility and risk when running or modifying the software.
- If you intend to trade with real funds, ensure compliance with applicable laws and regulations and consider seeking professional advice.
MIT
Generated: December 18, 2025