Automated Bitcoin trading on Binance with AI-powered sentiment analysis
Project description
btcagent
A Python package for automated Bitcoin trading on Binance with AI-powered sentiment analysis. It combines a Monte Carlo-optimized trading agent with multi-model sentiment analysis (Gemini, Claude, ChatGPT) to generate buy/sell recommendations.
Installation
Requires Python 3.9+.
pip install btcagent
Or install from source:
git clone https://github.com/gogo40/btcagent.git
cd btcagent
pip install -r requirements.txt
pip install -e .
To install with documentation dependencies:
pip install -e ".[docs]"
To install with optional extras (Telegram reporter, Streamlit dashboard):
pip install -e ".[telegram,dashboard]"
Dependencies
binance, requests, numpy, pandas, numba, yfinance, python-dotenv, google-genai, anthropic, openai
Optional: python-telegram-bot (Telegram reporter), streamlit + plotly (dashboard)
Configuration
Set the following environment variables (or use a .env file):
# Binance
BINANCE_API_KEY=your-binance-api-key
BINANCE_API_SECRET=your-binance-api-secret
# Sentiment Analysis (at least one required)
GOOGLE_API_KEY=your-google-api-key
ANTHROPIC_API_KEY=your-anthropic-api-key
OPENAI_API_KEY=your-openai-api-key
# Telegram Reporter (optional)
TELEGRAM_BOT_TOKEN=your-telegram-bot-token
TELEGRAM_CHAT_ID=your-telegram-chat-id
API Reference
Trading Agent (btcagent)
btcagent.bitcoin_agent(prices, wc, wv, epsc, epsv, USDTo, BTCo)
Simulates a trading agent on historical price data using a moving-average crossover strategy. JIT-compiled with Numba.
| Parameter | Description |
|---|---|
prices |
NumPy array of historical prices |
wc |
Buy window size (lookback period for buy signal) |
wv |
Sell window size (lookback period for sell signal) |
epsc |
Buy threshold (fraction below mean to trigger buy) |
epsv |
Sell threshold (fraction above mean to trigger sell) |
USDTo |
Initial USDT balance |
BTCo |
Initial BTC balance |
Returns [wallet_value, BTC, USDT].
btcagent.optimize_agent(prices, USDTo, BTCo, ...)
Runs a Monte Carlo optimization to find the best trading parameters.
| Parameter | Default | Description |
|---|---|---|
prices |
— | NumPy array of historical prices |
USDTo |
— | Initial USDT balance |
BTCo |
— | Initial BTC balance |
range_wc |
[1, 500] |
Buy window size range |
range_wv |
[1, 500] |
Sell window size range |
range_epsc |
[0.0, 0.1] |
Buy threshold range |
range_epsv |
[0.0, 0.3] |
Sell threshold range |
n_scenarios |
100 |
Number of random scenarios to evaluate |
Returns an array with best/worst/mean wallet values and corresponding parameters.
btcagent.get_recommendation(prices, USDTo, BTCo, ...)
High-level function that optimizes the agent and returns buy/sell price recommendations.
| Parameter | Default | Description |
|---|---|---|
prices |
— | NumPy array of historical prices |
threshold |
1 |
Minimum return % to consider a good recommendation |
n_scenarios |
5_000_000 |
Number of Monte Carlo scenarios |
Returns a dict:
{
"score": int, # Quality score (0-9)
"buy_price": float, # Recommended buy price
"sell_price": float, # Recommended sell price
"max_wallet": float, # Best simulated wallet value
"mean_wallet": float, # Average simulated wallet value
"min_wallet": float, # Worst simulated wallet value
}
btcagent.get_target_prices(prices, wc, wv, epsc, epsv)
Computes buy and sell target prices from the current price window and parameters.
Returns (buy_price, sell_price).
btcagent.create_orders(buy_price, sell_price, symbol, api_key, api_secret, ...)
Creates buy and sell limit orders on Binance based on the recommended prices and current account balance.
| Parameter | Default | Description |
|---|---|---|
buy_price |
— | Target buy price |
sell_price |
— | Target sell price |
symbol |
— | Trading pair (e.g. "BTCUSDT") |
max_size_buy |
0.95 |
Fraction of token balance to sell |
max_size_sell |
0.95 |
Fraction of USDT balance to buy with |
Price Data
btcagent.get_prices_using_binance(api_key, api_secret, symbol="BTCUSDT", N=1000)
Fetches the last N one-minute candle close prices from Binance.
btcagent.get_prices_using_yfinance(start_date, end_date, ticker="BTC-USD")
Fetches minute-level historical prices from Yahoo Finance.
btcagent.get_current_price_using_binance(api_key, api_secret, symbol="BTCUSDT")
Returns the current spot price for a symbol on Binance.
btcagent.get_account_balance_using_binance(api_key, api_secret, token="BTC", full=False)
Returns (usdt_balance, token_balance). When full=True, includes balances locked in open orders.
Frequency Analysis
btcagent.get_freq(v, window_size, sell_window_size, nbins=100)
Builds a 2-D frequency map of sequential price movement patterns. Scans overlapping triplets of prices within the given windows and accumulates discretised relative changes. JIT-compiled with Numba.
| Parameter | Description |
|---|---|
v |
1-D NumPy array of historical prices |
window_size |
Number of recent prices to consider as starting points |
sell_window_size |
Maximum forward look-ahead from each starting point |
nbins |
Bins per side for discretisation (default 100) |
btcagent.compute_expected_return(map_freq, target, ref_freq1, ref_freq2, nbins=100)
Computes expected return and loss probabilities from a frequency map produced by get_freq.
Returns (probability_of_target, expected_loss, expected_return).
Binance Robot (btcagent.binance_robot)
Low-level order management functions for the Binance exchange.
binance_robot.create_buy_order(quantity, buy_price, symbol, api_key, api_secret)
Places a limit buy order. Quantities are truncated to 5 decimal places and prices to 2 decimal places.
binance_robot.create_sell_order(quantity, sell_price, symbol, api_key, api_secret)
Places a limit sell order. Same truncation rules as create_buy_order.
binance_robot.cancel_order(order, symbol, api_key, api_secret)
Cancels an existing open order by its orderId.
binance_robot.get_binance_depth(symbol="BTCUSDT", limit=100)
Fetches the order book depth (bids/asks) for a symbol from the public API.
binance_robot.compute_target_buy_sell_prices(buy_margin=0.02, sell_margin=0.02, symbol="BTCUSDT", limit=5000)
Computes target buy and sell prices from the order book depth. Fetches the book, calculates quantity-weighted average bid/ask prices, and applies margins.
| Parameter | Default | Description |
|---|---|---|
buy_margin |
0.02 |
Discount fraction applied to the weighted-average ask price |
sell_margin |
0.02 |
Mark-up fraction applied to the weighted-average bid price |
symbol |
"BTCUSDT" |
Trading pair symbol |
limit |
5000 |
Number of order-book levels to fetch (max 5000) |
Returns:
{
"buy_price": float, # Target buy price
"sell_price": float, # Target sell price
"weighted_avg_bid": float, # Quantity-weighted average bid
"weighted_avg_ask": float, # Quantity-weighted average ask
"best_bid": float, # Highest bid price
"best_ask": float, # Lowest ask price
"spread": float, # Best ask - best bid
"total_bid_volume": float, # Total bid quantity (BTC)
"total_ask_volume": float, # Total ask quantity (BTC)
}
Trader (btcagent.trader)
High-level trading orchestration module that combines price optimisation, sentiment analysis, and order management into a single iteration loop.
trader.get_wallet_performance(api_key, api_secret, wallet_value0, symbol="BTCUSDT")
Fetches the current account balance (including amounts in open orders) and computes total wallet value and percentage performance relative to wallet_value0.
Returns:
{"usdt": float, "btc": float, "current_price": float, "wallet_value": float, "performance": float}
trader.compute_target_prices(api_key, api_secret, symbol="BTCUSDT", ...)
Fetches recent prices and runs Monte Carlo optimisation to produce buy/sell target prices.
| Parameter | Default | Description |
|---|---|---|
threshold |
1 |
Quality scoring threshold |
range_wc |
[1, 400] |
Buy window range |
range_wv |
[1, 400] |
Sell window range |
range_epsc |
[0.004, 0.04] |
Buy threshold range |
range_epsv |
[0.004, 0.04] |
Sell threshold range |
n_scenarios |
5_000_000 |
Monte Carlo scenarios |
n_prices |
1000 |
Number of 1-minute candles to fetch |
Returns {"buy_price", "sell_price", "score", "current_price"}.
trader.adjust_prices_with_sentiment(buy_price, sell_price, sentiment_data)
Blends optimisation-derived prices with sentiment boundaries using direction-dependent weights (positive sentiment favours the maximum price for selling, negative favours the minimum for buying).
Returns (adjusted_buy_price, adjusted_sell_price).
trader.fetch_sentiment(token="BTC")
Calls the multi-model sentiment analysis and normalises the result keys.
Returns {"sentiment", "minimum_price", "maximum_price", "reasoning"} or None on failure.
trader.cancel_stale_orders(orders, buy_price, sell_price, symbol, api_key, api_secret, tolerance=0.012, force=False)
Cancels buy orders below buy_price * (1 - tolerance) and sell orders above sell_price * (1 + tolerance). When force=True, cancels all orders unconditionally.
trader.place_orders(buy_price, sell_price, symbol, api_key, api_secret, max_size_buy=0.15, max_size_sell=0.15)
Places new buy and sell limit orders using the specified fraction of available balances.
trader.save_reports(orders_report, performance_report, sentiment_report, suggestion_report)
Writes four JSON report files to the current directory: orders_report.json, performance_report.json, sentiment_report.json, and suggestion_report.json.
trader.run_trading_iteration(api_key, api_secret, wallet_value0, symbol="BTCUSDT", ...)
Executes a complete trading cycle: fetches sentiment → computes wallet performance → optimises target prices → adjusts with sentiment → blends with order-book targets (75/25 weight) → cancels stale orders → places new orders.
| Parameter | Default | Description |
|---|---|---|
threshold |
1 |
Optimisation quality threshold |
max_size_buy |
0.15 |
Fraction of token balance to sell |
max_size_sell |
0.15 |
Fraction of USDT balance to buy with |
n_scenarios |
5_000_000 |
Monte Carlo scenarios |
n_prices |
1000 |
Number of 1-minute candles to fetch |
buy_margin |
0.02 |
Discount fraction for order-book buy target |
sell_margin |
0.02 |
Mark-up fraction for order-book sell target |
limit_order_book |
5000 |
Order-book levels to fetch |
Returns:
{
"performance": [timestamp, wallet_value, performance_pct],
"cancelled": [list of cancellation responses],
"new_orders": [list of order responses],
"sentiment": [timestamp, sentiment, min_price, max_price, reasoning] or None,
"suggestion": [timestamp, buy_price, sell_price, score, min_price, max_price, sentiment, reasoning],
}
Sentiment Analysis (btcagent.sentiment_analysis)
All three models (Gemini, Claude, ChatGPT) use internet search to find the latest news before generating their analysis.
get_sentiment_analysis(token, config=None, prompt_template=None)
Runs sentiment analysis using a single Gemini model with Google Search.
Returns:
{
"status": True,
"minimum price": float,
"minimum price probability": float,
"maximum price": float,
"maximum price probability": float,
"reasoning": str,
"sentiment": float, # -1 to 1
"model": str,
}
get_sentiment(token, config=None, prompt_template=None)
Runs sentiment analysis across all three models (Gemini, Claude, ChatGPT) and returns a weighted average of their predictions. Uses Gemini to summarize the combined reasoning.
Returns:
{
"status": True,
"minimum price": float, # Weighted average
"maximum price": float, # Weighted average
"sentiment": float, # Weighted average (-1 to 1)
"reasoning": str, # Gemini-summarized combined reasoning
"models_used": ["gemini", "claude", "chatgpt"],
"individual_results": {...},
}
Default Configuration
DEFAULT_CONFIG = {
"gemini": {"model": "gemini-3.1-flash-lite-preview"},
"claude": {"model": "claude-sonnet-4-6"},
"chatgpt": {"model": "gpt-5.4-mini"},
"weights": {"gemini": 0.4, "claude": 0.35, "chatgpt": 0.25},
}
Logging
All modules use Python's logging module with loggers named after their module path (e.g. btcagent.trader, btcagent.binance_robot). To enable log output, configure logging at the entry point:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
Log levels used:
- DEBUG: Individual order details, open order listings
- INFO: Prices, wallet value, recommendations, order placement/cancellation counts
- WARNING: Prices outside sentiment range, low-quality recommendations
- ERROR: API failures, model errors
Usage Examples
Quick Start — Multi-Model Sentiment
from btcagent.sentiment_analysis import get_sentiment
result = get_sentiment("BTC")
if result["status"]:
print(f"Price range: {result['minimum price']:.2f} – {result['maximum price']:.2f}")
print(f"Sentiment: {result['sentiment']:.2f}")
print(f"Reasoning: {result['reasoning']}")
Quick Start — Trading Recommendation
import btcagent
prices = btcagent.get_prices_using_binance(api_key, api_secret, "BTCUSDT", 1000)
rec = btcagent.get_recommendation(prices, USDTo=100, BTCo=0, n_scenarios=5_000_000)
print(f"Buy at {rec['buy_price']:.2f}, Sell at {rec['sell_price']:.2f}")
Quick Start — Single Trading Iteration
from btcagent.trader import get_wallet_performance, run_trading_iteration, save_reports
perf = get_wallet_performance(api_key, api_secret, wallet_value0=1)
wallet_value0 = perf["wallet_value"]
result = run_trading_iteration(api_key, api_secret, wallet_value0)
save_reports([result], [result["performance"]], [], [result["suggestion"]])
Example Notebooks & Scripts
| File | Description |
|---|---|
binance_buy_sell_bot.ipynb |
Full automated trading bot that combines Monte Carlo price optimisation with multi-model sentiment analysis and order-book depth analysis. Runs in a continuous loop: fetches sentiment from all three AI models, computes optimised buy/sell prices, blends them with sentiment-adjusted and order-book-derived targets, places/cancels orders on Binance, and saves JSON reports. |
bot_binance.ipynb |
Demonstrates the trading agent using live Binance data. Fetches real-time 1-minute prices, builds price frequency distributions, optimizes trading parameters via Monte Carlo, and computes expected returns. |
bot_yfinance.ipynb |
Same trading agent workflow as bot_binance.ipynb but uses Yahoo Finance (yfinance) as the data source instead of live Binance API. |
2017_bot.ipynb |
Backtesting notebook. Runs the trading agent optimization on historical 1-minute BTC/USDT data from 2017 (BTCUSDT_1m_2017.csv) to evaluate strategy performance on past data. |
sentiment_analysis_demo.ipynb |
Interactive demo of the sentiment analysis module. Shows single-model (Gemini) and multi-model weighted sentiment, custom configurations, weight adjustments, and individual model result inspection. |
telegram_bot.ipynb |
Telegram reporter bot that reads the JSON reports produced by binance_buy_sell_bot.ipynb and sends human-friendly performance updates every 20 minutes — wallet value, P&L, target prices, sentiment, and recent orders. |
dashboard/ |
Streamlit dashboard for real-time monitoring. Shows wallet value, P&L, target prices, sentiment, recommendation score, spread, recent orders, and AI reasoning. Run with streamlit run dashboard/app.py. |
create_package.ipynb |
Interactive notebook for building and publishing the btcagent package to PyPI using the PEP 517 build backend and twine. |
create_package.py |
CLI script equivalent of create_package.ipynb. Cleans artifacts, builds sdist + wheel, verifies with twine check, and optionally uploads. Run with python create_package.py (build only) or python create_package.py --upload. |
run_btc_binance_robot.py |
Standalone Python script version of binance_buy_sell_bot.ipynb. Production-ready continuous trading loop with sentiment analysis, order management, and JSON report generation. Run with python run_btc_binance_robot.py. |
Documentation
Full API documentation is generated from docstrings using Sphinx:
pip install -e ".[docs]"
cd docs
make html
The generated HTML is available at docs/_build/html/index.html.
Project Structure
btcagent/
├── btcagent/ # Core package
│ ├── __init__.py # Trading agent, optimisation, price fetching, orders
│ ├── binance_robot.py # Low-level Binance order management
│ ├── sentiment_analysis.py # Multi-model AI sentiment analysis
│ └── trader.py # High-level trading orchestration
├── docs/ # Sphinx documentation source
│ ├── conf.py
│ ├── index.rst
│ └── api/ # Auto-generated API reference
├── setup.py # Package configuration
├── requirements.txt # Runtime dependencies
├── create_package.py # Build & publish script
├── create_package.ipynb # Build & publish notebook
├── dashboard/ # Streamlit monitoring dashboard
│ ├── app.py
│ └── requirements.txt
├── run_btc_binance_robot.py # Production trading loop
├── telegram_bot.ipynb # Telegram performance reporter
└── *.ipynb # Example / demo notebooks
License
See LICENSE.
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 btcagent-0.5.0.tar.gz.
File metadata
- Download URL: btcagent-0.5.0.tar.gz
- Upload date:
- Size: 39.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0e6511e68299cf358f0dcc9dd04616d20e82fa150085e5ef38e6d39577bac688
|
|
| MD5 |
0262167d6bd65824d1fb717e3017a6c1
|
|
| BLAKE2b-256 |
5f4a332d416faae1cdbbede15310eda965e548b8cdd0443ba520e8733336d805
|
File details
Details for the file btcagent-0.5.0-py3-none-any.whl.
File metadata
- Download URL: btcagent-0.5.0-py3-none-any.whl
- Upload date:
- Size: 35.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d0d90b5d781655e6d2d260a88c262982aef93ff526c54aaef872a0179c8520c9
|
|
| MD5 |
7f9c3e46cab6ddb0a78000ff1eb43fcc
|
|
| BLAKE2b-256 |
4ef3c39bc7e1bf196064b6e177939135d1b294829b4e69bfc162ce6a85cb9986
|