Skip to main content

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

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 .

Dependencies

binance, requests, numpy, pandas, numba, yfinance, python-dotenv, google-genai, anthropic, openai

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

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.

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 → cancels stale orders → places new orders.

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 optimization with multi-model sentiment analysis. Runs in a continuous loop: fetches sentiment from all three AI models, computes optimized buy/sell prices, blends them with sentiment-adjusted targets, places/cancels orders on Binance, and saves JSON reports for orders, performance, sentiment, and suggestions.
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.
create_package.ipynb Utility notebook for building and publishing the btcagent package to PyPI using setuptools and twine.
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.

License

See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

btcagent-0.2.0.tar.gz (35.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

btcagent-0.2.0-py3-none-any.whl (33.4 kB view details)

Uploaded Python 3

File details

Details for the file btcagent-0.2.0.tar.gz.

File metadata

  • Download URL: btcagent-0.2.0.tar.gz
  • Upload date:
  • Size: 35.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for btcagent-0.2.0.tar.gz
Algorithm Hash digest
SHA256 d2dd293e6f53e7929430baa3b46b5dee24358585f4724e1da98f839f9f6305cc
MD5 d724ad26fa6317644b8c502baf6cd9d4
BLAKE2b-256 c52ad7e73423d0c0c8b4381867c826637fd022532fb5b47652760c47992257a3

See more details on using hashes here.

File details

Details for the file btcagent-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: btcagent-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 33.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for btcagent-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 26cda99a7067cbb5556c70d4e9691d78c1af15334094bc7ac5ff28029c7cfa10
MD5 e329436fb118a23db52a0b1fd7787c87
BLAKE2b-256 9d9a0d0dcaf6237d767fd043aae709aed020dfe34223e90d7a37ee5351adb5b8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page