Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🤖 Binance Futures Trading Bot

A production-ready Python trading bot for Binance Futures Testnet with an interactive CLI featuring enhanced UX — color-coded output, live validation, spinners, and a polished menu system.


✨ Features

  • Market & Limit Orders — Place orders with guided, step-by-step prompts
  • Interactive CLI — Rich panels, tables, spinners, and color-coded output
  • Inline Validation — Real-time feedback on every input (symbol, quantity, price)
  • Order History — View session orders and fetch history from Binance
  • Account Balance — Check your testnet account balance
  • Comprehensive Logging — Rotating file logs + colored console output
  • Error Handling — Graceful handling of network, API, and input errors with retry logic
  • Secure Credentials — API keys stored in .env, masked in logs (only last 4 chars shown)

📁 Project Structure

trading_bot/
├── bot/
│   ├── __init__.py              # Package init, version, exports
│   ├── client.py                # Binance API client (httpx + HMAC signing)
│   ├── orders.py                # Order placement & management logic
│   ├── validators.py            # Input validation (symbol, qty, price)
│   ├── logging_config.py        # Dual logging setup (file + console)
│   └── models.py                # Data models (OrderRequest, OrderResponse, enums)
├── cli.py                       # Interactive CLI entry point
├── README.md                    # This file
├── requirements.txt             # Python dependencies
├── .env.example                 # Environment variable template
└── logs/
    └── trading_bot.log          # Auto-generated log file

🚀 Setup Instructions

1. Clone / Download the Project

cd "Trading Bot"

2. Create a Virtual Environment

python -m venv venv

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure API Credentials

  1. Register on Binance Futures Testnet
  2. Generate API credentials (API Key & Secret)
  3. Create your .env file:
copy .env.example .env
  1. Edit .env and add your credentials:
BINANCE_API_KEY=your_actual_api_key_here
BINANCE_API_SECRET=your_actual_api_secret_here
BINANCE_TESTNET=true

⚠️ Never commit your .env file to version control!


▶️ Running the Bot

python cli.py

You'll see the interactive menu:

╔════════════════════════════════════════════╗
║   BINANCE FUTURES TRADING BOT             ║
║   Testnet Mode 🔬                         ║
╚════════════════════════════════════════════╝

? Select an action:
  📈  Place Market Order
  📊  Place Limit Order
  📋  View Order History
  💰  Check Account Balance
  ⚙️   Settings
  🚪  Exit

📖 Example Usage

Place a Market Order

  1. Select "Place Market Order" from the menu
  2. Enter symbol: BTCUSDT → ✅ Symbol found
  3. Select side: BUY (Long) or SELL (Short)
  4. Enter quantity: 0.001 → ✅ Quantity validated
  5. Confirm the order → Press y
  6. View the result with Order ID, status, and execution details

Place a Limit Order

Same flow as above, plus:

  • You'll see the current market price as a reference
  • Enter your desired limit price
  • The bot validates against Binance tick size rules

View Order History

  • See all orders placed in the current session
  • Optionally fetch historical orders from Binance for any symbol

Check Balance

  • View all non-zero asset balances
  • Shows available balance and unrealized PnL

📋 Log Files

All bot activity is logged to logs/trading_bot.log:

[2024-01-15 10:30:45] INFO - Starting Binance Futures Trading Bot
[2024-01-15 10:30:46] INFO - Initializing Binance client (TESTNET) | API Key: ****abcd
[2024-01-15 10:30:47] INFO - Loaded 287 trading symbols
[2024-01-15 10:30:48] INFO - User Input: symbol=BTCUSDT, side=BUY, type=MARKET, qty=0.001
[2024-01-15 10:30:48] DEBUG - Validating inputs...
[2024-01-15 10:30:48] DEBUG - Inputs validated successfully
[2024-01-15 10:30:49] INFO - Placing order: Symbol: BTCUSDT | Side: BUY | Type: MARKET | Quantity: 0.001
[2024-01-15 10:30:50] INFO - Order placed successfully! ID: 1234567890 | Status: FILLED

Security: Full API keys are never logged — only the last 4 characters are shown.


🔧 Technical Details

Dependencies

Package Purpose
httpx HTTP client for Binance API calls
python-dotenv Load credentials from .env file
rich Terminal UI (panels, tables, spinners, colors)
questionary Interactive prompts with validation

API Authentication

All signed requests use HMAC-SHA256:

  1. Add timestamp parameter (current Unix time in ms)
  2. Create query string from all parameters
  3. Sign with your API secret using SHA-256
  4. Append signature to the request

Error Handling

Error Type Handling
Network timeout Retry with exponential backoff (1s, 2s, 4s)
HTTP 5xx Retry up to 3 times
HTTP 429 (rate limit) Wait for Retry-After header duration
API errors (4xx) Display error code + message with helpful hints
Invalid input Caught before API call with inline feedback

Binance API Endpoints Used

Endpoint Method Purpose
/fapi/v1/exchangeInfo GET Symbol info & trading rules
/fapi/v1/ticker/price GET Current market price
/fapi/v1/order POST Place order
/fapi/v1/allOrders GET Order history
/fapi/v1/openOrders GET Open orders
/fapi/v2/balance GET Account balance

⚠️ Assumptions & Limitations

  1. Testnet Only — This bot is configured for Binance Futures Testnet by default
  2. No Live Trading — The settings menu shows testnet mode but does not enable live switching for safety
  3. API Keys — Must be stored in a .env file; never hardcoded
  4. Quantity Validation — Based on Binance's LOT_SIZE filter from exchangeInfo
  5. Session History — Order history within the session is stored in-memory only
  6. Single-threaded — The bot runs synchronously; no background order monitoring

🧪 Testing Checklist

  • Bot starts and connects to testnet
  • Exchange info loads successfully
  • Market BUY order for BTCUSDT executes
  • Limit SELL order for ETHUSDT executes
  • Invalid symbol shows error with suggestions
  • Invalid quantity shows error with hints
  • Order history displays correctly
  • Account balance shows non-zero assets
  • Log file contains proper entries
  • API keys are masked in logs

📜 License

This project is for educational and testing purposes only. Use at your own risk. Never trade with real funds using code that hasn't been thoroughly tested and audited.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages