Binance Spot ML trading bot with strict risk management.
Project description
BN-ML - Binance Spot ML Trading Bot
Bot de trading Binance Spot orienté production avec:
- entraînement ML par symbole
- hyperparameter optimization walk-forward (objectif Sharpe/Sortino/Accuracy)
- scanner multi-paires
- risk/money management strict
- dashboard web "Trader Terminal" auto-lançable avec le bot
1) Prérequis
- Python 3.10+
- Compte Binance Spot (API key + secret)
- macOS (M1) ou Linux (Ubuntu recommandé pour CUDA)
Installation:
# Option 1 (PyPI, install par nom)
python3 -m venv .venv
source .venv/bin/activate
pip install bn-ml-trading-bot
# Option 2 (auto-install depuis GitHub)
python3 -m venv .venv
source .venv/bin/activate
pip install "git+https://github.com/san2stic/BN-ML.git"
# Option 3 (dev local depuis le repo cloné)
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .
cp .env.example .env
Publication PyPI automatique: voir docs/pypi_trusted_publisher.md.
2) Configuration
Fichier principal: configs/bot.yaml
Variables d'environnement (dans .env ou shell):
BINANCE_API_KEY=...
BINANCE_API_SECRET=...
BINANCE_TESTNET=false
Modes:
environment: paperpour simulationenvironment: livepour réel- en live,
exchange.testnetdoit êtrefalse risk.capital_total: autopour utiliser automatiquement le capital réel Binance (authentifié) en mode livedata.paper_market_data_mode: livepour paper trading sur données de marché Binance réelles (fallback synthétique si indisponible)
Universe dynamique:
universe.dynamic_base_quote_pairs: truepour scanner toutes les paires*/base_quote(ex:*/USDC)universe.max_pairs_scannedpour limiter la charge/rate limituniverse.train_dynamic_pairs: truepour entraîner par symbole sur cet universuniverse.train_max_pairspour limiter le nombre de modèles entraînésuniverse.train_missing_only: truepour n'entraîner que les modèles manquants/anciensuniverse.model_max_age_hours: 24seuil d'ancienneté modèle avant retrain
Mode liste utilisateur (trader uniquement des paires choisies):
universe.user_selected_only: trueactive le mode restreintuniverse.user_selected_pairs: [BTC/USDC, ETH/USDC, ...]liste prioritaire des paires autorisées- fallback compatibilité: si
user_selected_pairsest vide, le bot utiliseuniverse.pairs - en mode restreint, l'univers dynamique est ignoré pour le scan et l'entraînement
Auto-retrain en fond (thread séparé):
model.auto_retrain_enabled: trueactive le worker d'entraînement asynchronemodel.retrain_check_interval_sec: 30fréquence de vérification (x) des conditions de retrainmodel.retrain_interval_hours: 6intervalle minimal entre retrains completsmodel.auto_train_missing_models: trueentraîne automatiquement les bundles manquantsmodel.auto_train_missing_batch_size: 5limite les auto-trains manquants par batchmodel.auto_train_missing_disable_hpo: trueaccélère l'auto-train manquant (désactive HPO sur ce flux)
Monitoring et alerting runtime:
monitoring.realtime_prices.enabled: trueactive le flux websocket Binance pour suivi prix temps réel (positions + paires scannées)monitoring.alerting.webhook_urlpour webhook externemonitoring.alerting.telegram_bot_token+monitoring.alerting.telegram_chat_idpour Telegrammonitoring.alerting.email.*pour SMTP emailmodel.drift.*active le monitoring runtime de drift régime (KS + ratio de volatilité)risk.circuit_breakers.drift_block_enabled: truebloque les nouvelles entrées si drift détecté
Backups automatiques:
storage.backup.enabled: truestorage.backup.interval_minutes: 60storage.backup.keep_last: 48storage.backup.base_dir: artifacts/backups
Analyse multi-timeframe (MTF):
model.multi_timeframe.enabled: trueactive la fusion multi-timeframemodel.multi_timeframe.base_timeframe: 15mtimeframe principalmodel.multi_timeframe.timeframes: [1h, 4h, 1d]timeframes supérieurs fusionnésmodel.multi_timeframe.feature_columnsfeatures HTF à projeter sur le timeframe de basemodel.multi_timeframe.min_candles_per_timeframe/max_candles_per_timeframe/extra_candles_bufferpour contrôler la profondeur de chaque HTF- les signaux de confluence sont ajoutés automatiquement (
mtf_trend_consensus,mtf_macd_consensus,mtf_confluence_score, etc.) model.lstm.enabled: trueactive un modèle séquentiel entraîné et inféré dans l’ensemble (backendsequence_mlp, compatible joblib)
3) Commandes principales
Si tu as installé le package via pip install bn-ml-trading-bot (ou pip install git+...), utilise les commandes bnml-*.
Si tu exécutes depuis le repo cloné, les commandes python3 -m scripts.* restent disponibles.
Entraîner les modèles par symbole:
bnml-trainer
Entraînement incrémental (manquants/anciens uniquement):
bnml-trainer --train-missing-only
Forcer entraînement complet:
bnml-trainer --train-all
Entraîner seulement certains symboles:
bnml-trainer --symbol BTC/USDC --symbol ETH/USDC
Lancer un cycle unique bot (paper):
bnml-bot --once --paper
Campagne DoD paper 30 jours (checks quotidiens + rapport final):
bnml-dod-30d --days 30 --disable-retrain
Lancer en live continu:
bnml-bot --live
Le dashboard est auto-lancé en mode continu si monitoring.dashboard.auto_launch_with_bot: true.
Lancer sans dashboard:
bnml-bot --live --no-dashboard
Lancer dashboard seul:
streamlit run monitoring/dashboard.py
Backtest baseline:
bnml-backtest --paper
Kill switch (fermeture d'urgence):
bnml-kill-switch
Check quotidien DoD:
bnml-dod-check --fail-on-violation
Rapport synthese DoD:
python3 -m scripts.generate_dod_report --days 30
4) Dashboard "Trader Terminal"
Le dashboard inclut:
- mode full-screen desk
- auto-refresh (5s par défaut)
- filtre timeframe (
15m,1h,4h,1d,1w,all) - panneaux détachables (workspace par onglets)
- watchlist sticky, heatmap opportunités, equity/drawdown, blotter, cycle feed
- monitor live des prix via websocket quand activé
Paramètres dans configs/bot.yaml:
monitoring.dashboard.auto_launch_with_botmonitoring.dashboard.addressmonitoring.dashboard.portmonitoring.dashboard.auto_refresh_secmonitoring.dashboard.full_screen_defaultmonitoring.dashboard.timeframe_defaultmonitoring.dashboard.live_market_enabledmonitoring.dashboard.scan_stale_sec
5) Modèles ML par crypto
Chaque symbole a son bundle dédié:
models/<SYMBOL_KEY>/rf.joblibmodels/<SYMBOL_KEY>/xgb.joblibmodels/<SYMBOL_KEY>/metadata.json
Le trainer applique:
- sélection de features
- fusion de features multi-timeframe alignées temporellement (sans look-ahead)
- validation temporelle
- HPO walk-forward orienté rentabilité nette (Sharpe/Sortino/Accuracy + rendement net + pénalité drawdown/turnover)
- accélération XGBoost selon le hardware
- retrain en arrière-plan (thread dédié), sans bloquer la boucle de scan
- ensemble pondéré par performance hors-échantillon avec seuils de décision BUY/SELL
- labels dynamiques adaptés à la volatilité et aux coûts d'exécution
Réglages HPO:
model.hpo.enabledmodel.hpo.max_samplesmodel.hpo.max_splitsmodel.hpo.rf_trialsmodel.hpo.xgb_trialsmodel.hpo.objective_weight_*model.execution.cost_multipliermodel.labeling.*model.ensemble.*model.train_ohlcv_limitscanner.ohlcv_limit
6) Hardware (Mac M1 + Ubuntu RTX 2070 Super)
Probe matériel:
python3 -m scripts.hardware_probe
Mac M1:
- mettre
model.acceleration.mode: cpu
Ubuntu + RTX:
- mettre
model.acceleration.mode: auto(oucuda) - installer build XGBoost compatible CUDA
Le fallback CPU est géré via model.acceleration.allow_cuda_fallback.
7) Sécurité live
Le bot bloque le démarrage live si:
- clés API absentes
exchange.testnetencore àtrue- pas de market data valide
- impossible de lire le solde authentifié
Recommandations:
- API key trading avec whitelist IP
- commencer par paper trading prolongé
- garder
scripts.kill_switchprêt - brancher au moins un canal
monitoring.alerting(webhook/Telegram/email) avant live continu
8) Fichiers importants
configs/bot.yaml: configuration runtimescripts/run_bot.py: boucle de tradingscripts/run_trainer.py: entraînement per-symbolmonitoring/dashboard.py: interface webartifacts/state/bn_ml.db: état persistant (positions/trades/cycles)artifacts/logs/dashboard.log: logs Streamlitartifacts/metrics/latest_scan.csv: snapshot complet des paires scannéesartifacts/metrics/latest_opportunities.csv: opportunités retenues par les filtresartifacts/reports/dod/: checks quotidiens + rapport DoDdocs/runbook_incident.md: procedures incidentdocs/deployment_docker.md: deploiement Docker
9) Checklist avant push Git
python3 -m pytest -q
python3 -m scripts.run_bot --once --paper --disable-retrain --no-dashboard
python3 -m scripts.hardware_probe
Optionnel:
python3 -m scripts.run_trainer --paper --symbol BTC/USDC
Si tu pushes un setup live, ne commite jamais .env ou des secrets.
Contribution et sécurité
- Guide contribution:
CONTRIBUTING.md - Politique sécurité:
SECURITY.md - Template PR:
.github/PULL_REQUEST_TEMPLATE.md - Templates issues:
.github/ISSUE_TEMPLATE/
10) Sync modèles GitHub (publisher/client)
Objectif:
- serveur publisher: entraîne chaque jour à
00:00, puis push les modèles vers un repo GitHub dédié - client(s): pull chaque jour à
06:00, puis resynchronisent leur dossier localmodels/
Configuration (configs/bot.yaml):
model_sync:
enabled: false
repo_dir: ""
remote: origin
branch: main
repo_models_subdir: models
publisher:
schedule: "00:00"
train_before_push: true
client:
schedule: "06:00"
Commande publisher (one-shot):
python3 -m scripts.model_sync publish \
--config configs/bot.yaml \
--repo-dir /ABS/PATH/model-registry-repo
Commande client (one-shot):
python3 -m scripts.model_sync pull \
--config configs/bot.yaml \
--repo-dir /ABS/PATH/model-registry-repo \
--models-dir models
Mode daemon (scheduler intégré):
# serveur: train + push à 00:00 local
python3 -m scripts.model_sync daemon --role publisher --repo-dir /ABS/PATH/model-registry-repo
# client: pull + sync local à 06:00 local
python3 -m scripts.model_sync daemon --role client --repo-dir /ABS/PATH/model-registry-repo
Exemple cron (recommandé en production):
# Publisher à 00:00 tous les jours
0 0 * * * cd /ABS/PATH/BN-ML && /usr/bin/python3 -m scripts.model_sync publish --config configs/bot.yaml --repo-dir /ABS/PATH/model-registry-repo >> artifacts/logs/model_sync_publisher.log 2>&1
# Client à 06:00 tous les jours
0 6 * * * cd /ABS/PATH/BN-ML && /usr/bin/python3 -m scripts.model_sync pull --config configs/bot.yaml --repo-dir /ABS/PATH/model-registry-repo --models-dir models >> artifacts/logs/model_sync_client.log 2>&1
Pré-requis Git:
- repo Git local cloné avec remote
originpointant vers GitHub - auth configurée (SSH key ou token)
- worktree propre avant sync (sinon blocage par défaut)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file bn_ml_trading_bot-0.1.0.tar.gz.
File metadata
- Download URL: bn_ml_trading_bot-0.1.0.tar.gz
- Upload date:
- Size: 104.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
631eafffda923188dd32effaccf1107a683989dd7391a4bf22a2c2b36a8f223d
|
|
| MD5 |
373315f9f4a29412113db8151811a420
|
|
| BLAKE2b-256 |
a47271ca743d354ed3de125d84db9dd682197ad442f0e1ceb7beb567e25e00da
|
Provenance
The following attestation bundles were made for bn_ml_trading_bot-0.1.0.tar.gz:
Publisher:
publish-pypi.yml on san2stic/BN-ML
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
bn_ml_trading_bot-0.1.0.tar.gz -
Subject digest:
631eafffda923188dd32effaccf1107a683989dd7391a4bf22a2c2b36a8f223d - Sigstore transparency entry: 932922827
- Sigstore integration time:
-
Permalink:
san2stic/BN-ML@aad3e9d7bd1d34b2bb8875a8f23b3379049aa7a2 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/san2stic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@aad3e9d7bd1d34b2bb8875a8f23b3379049aa7a2 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file bn_ml_trading_bot-0.1.0-py3-none-any.whl.
File metadata
- Download URL: bn_ml_trading_bot-0.1.0-py3-none-any.whl
- Upload date:
- Size: 99.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7ff15aa97c33895dede6efc983f38c3d9dbe33a1692a7ab1e71f63f34e6c3cf8
|
|
| MD5 |
1c76790f9f86574aac80bfe04dfcf63b
|
|
| BLAKE2b-256 |
18d644d3635bd7141c5851b4cde9917782c4eba2db0430861b0120b6f5e78723
|
Provenance
The following attestation bundles were made for bn_ml_trading_bot-0.1.0-py3-none-any.whl:
Publisher:
publish-pypi.yml on san2stic/BN-ML
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
bn_ml_trading_bot-0.1.0-py3-none-any.whl -
Subject digest:
7ff15aa97c33895dede6efc983f38c3d9dbe33a1692a7ab1e71f63f34e6c3cf8 - Sigstore transparency entry: 932922885
- Sigstore integration time:
-
Permalink:
san2stic/BN-ML@aad3e9d7bd1d34b2bb8875a8f23b3379049aa7a2 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/san2stic
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish-pypi.yml@aad3e9d7bd1d34b2bb8875a8f23b3379049aa7a2 -
Trigger Event:
workflow_dispatch
-
Statement type: