A production-quality Python CLI application for placing orders on Binance Futures Testnet (USDT-M Futures). This project implements comprehensive validation, logging, and error handling for reliable trading operations.
- Features
- Architecture
- Project Structure
- Installation
- Setup Guide
- How to Run
- Command Examples
- Output Examples
- Logging
- Validation Rules
- Error Handling
- API Documentation
- Troubleshooting
- Assumptions
✅ MARKET Orders - Execute immediate orders at current market price ✅ LIMIT Orders - Place orders at specified price levels ✅ BUY/SELL Support - Full position opening and closing ✅ Binance Futures Testnet - Safe testing environment (no real funds) ✅ Comprehensive Logging - Rotating file logs with detailed information ✅ Input Validation - Complete parameter validation with clear error messages ✅ Error Handling - Graceful failure handling with user-friendly error messages ✅ Rich CLI Output - Colored console output with formatted tables ✅ Type Hints - Full Python type annotations for code clarity ✅ Production Quality - PEP8 formatting, docstrings, and modular design
- Separation of Concerns: Each module has a single responsibility
- Modular Structure: Easy to test, extend, and maintain
- Error Isolation: All errors caught and logged before user display
- Configuration Management: Centralized environment handling
- Validation Layer: All inputs validated before API calls
| Module | Responsibility |
|---|---|
config.py |
Load and validate environment variables |
logging_config.py |
Setup centralized logging with rotation |
validators.py |
Validate all CLI inputs |
client.py |
Binance API wrapper and HTTP communication |
orders.py |
Business logic for order execution |
cli.py |
CLI interface and user output |
trading_bot/
├── bot/
│ ├── __init__.py # Package initialization
│ ├── client.py # Binance Futures client wrapper
│ ├── orders.py # Order execution logic
│ ├── validators.py # Input validation
│ ├── config.py # Configuration management
│ └── logging_config.py # Centralized logging setup
├── logs/ # Log files (created at runtime)
│ └── trading_bot.log # Main application log
├── cli.py # CLI entry point
├── requirements.txt # Python dependencies
├── .env.example # Environment variables template
├── .env # Environment variables (DO NOT COMMIT)
├── .gitignore # Git ignore rules
└── README.md # This file
- Python 3.8 or higher
- pip (Python package manager)
- Internet connection (for package downloads and API calls)
- Binance Futures Testnet account (free)
Windows:
# Download from https://www.python.org/downloads/
# Run installer and ensure "Add Python to PATH" is checked
python --version # Verify installationmacOS:
brew install python3
python3 --version # Verify installationLinux (Ubuntu/Debian):
sudo apt-get update
sudo apt-get install python3 python3-pip
python3 --version # Verify installation# Navigate to your projects directory
cd /path/to/projects
# If from GitHub (replace with your repo)
git clone https://github.com/yourusername/binance-futures-bot.git
cd binance-futures-bot
# Or if local, just navigate to the project directory
cd trading_botWindows:
# Create virtual environment
python -m venv venv
# Activate virtual environment
venv\Scripts\activate
# You should see (venv) prefix in terminalmacOS/Linux:
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# You should see (venv) prefix in terminal# With virtual environment activated
pip install -r requirements.txt
# Verify installation
pip listExpected packages:
- python-binance (>=1.0.19)
- python-dotenv (>=1.0.0)
- rich (>=13.7.0)
- requests (>=2.31.0)
-
Go to Binance Testnet Website:
-
Create or Login to Account:
- Sign up for a new testnet account (free)
- Or login with existing Binance account
-
Generate API Keys:
- Click on account icon (top-right)
- Select "API Management" or "API Key"
- Create new key for "Futures Trading"
- Label: "Trading Bot" (optional)
- Restrictions: Enable "Futures Trading"
- Save API Key and Secret securely
-
Copy Your Credentials:
API Key: Your_API_Key_Here_123abc... Secret: Your_API_Secret_Here_xyz789...
-
Create .env file:
# Copy the example file # Windows: copy .env.example .env # macOS/Linux: cp .env.example .env
-
Edit .env file:
# Open in your text editor # Windows: notepad .env # macOS/Linux: nano .env # Add your credentials: BINANCE_API_KEY=your_actual_api_key_here BINANCE_API_SECRET=your_actual_api_secret_here
-
Save the file (do NOT commit to git)
# Test import without errors
python -c "from bot.config import Config; print('✓ Setup verified')"
# Should print: ✓ Setup verifiedpython cli.py --symbol SYMBOL --side SIDE --type TYPE --quantity QUANTITY [--price PRICE]Note: --price is mandatory for LIMIT orders, optional for MARKET orders.
python cli.py --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001What happens:
- Buys 0.001 BTC at current market price
- Order executes immediately at market rate
- Fastest execution, price may vary
python cli.py --symbol ETHUSDT --side SELL --type MARKET --quantity 1.0What happens:
- Sells 1 ETH at current market price
- Closes or reduces position
- Immediate execution
python cli.py --symbol BTCUSDT --side BUY --type LIMIT --quantity 0.001 --price 40000What happens:
- Places order to buy 0.001 BTC at exactly 40000 USDT
- Waits for price to reach limit
- May not execute if price never hits target
python cli.py --symbol BNBUSDT --side SELL --type LIMIT --quantity 10 --price 500What happens:
- Places order to sell 10 BNB at exactly 500 USDT each
- Sits in order book until filled
- Partial fills possible
# SOL trading
python cli.py --symbol SOLUSDT --side BUY --type MARKET --quantity 10
# XRP trading
python cli.py --symbol XRPUSDT --side SELL --type LIMIT --quantity 100 --price 2.5┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Order Summary ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Parameter │ Value │
├─────────────────────┼───────────────────────────────────────┤
│ Symbol │ BTCUSDT │
│ Side │ BUY │
│ Order Type │ MARKET │
│ Quantity │ 0.001 │
└─────────────────────┴───────────────────────────────────────┘
Placing order...
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ✓ Order Placed ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ │
│ ✓ SUCCESS │
│ │
│ Order ID: 123456789 │
│ Order has been placed on Binance Futures Testnet │
│ │
└─────────────────────────────────────────────────────────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Order Details ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Field │ Value │
├─────────────────────┼───────────────────────────────────────┤
│ Order ID │ 123456789 │
│ Status │ FILLED │
│ Symbol │ BTCUSDT │
│ Side │ BUY │
│ Type │ MARKET │
│ Quantity │ 0.001 │
│ Executed Quantity │ 0.001 │
│ Average Price │ 43250.50 │
└─────────────────────┴───────────────────────────────────────┘
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ✗ Order Failed ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ │
│ ✗ FAILURE │
│ │
│ Validation Error: Price is mandatory for LIMIT orders │
│ │
└─────────────────────────────────────────────────────────────┘
All logs are written to: logs/trading_bot.log
- Max File Size: 10 MB
- Backup Count: 5 files
- Naming:
trading_bot.log.1,trading_bot.log.2, etc.
When main log reaches 10MB, it's renamed and a new one starts.
YYYY-MM-DD HH:MM:SS - LEVEL - MODULE - MESSAGE
- DEBUG - Detailed diagnostic information
- INFO - General informational messages
- WARNING - Warning messages
- ERROR - Error messages with stack traces
2026-01-15 14:30:22 - INFO - client - Binance Futures Testnet client initialized successfully
2026-01-15 14:30:23 - DEBUG - validators - Symbol validation passed: BTCUSDT
2026-01-15 14:30:23 - INFO - orders - Executing market order: BUY 0.001 BTCUSDT
2026-01-15 14:30:24 - DEBUG - client - Order request parameters: {'symbol': 'BTCUSDT', 'side': 'BUY', 'type': 'MARKET', 'quantity': 0.001}
2026-01-15 14:30:25 - INFO - client - Market order placed successfully: Symbol=BTCUSDT, Side=BUY, Quantity=0.001, OrderID=123456789
# View last 50 lines (Windows PowerShell or Linux)
tail -50 logs/trading_bot.log
# View specific module logs (Windows - use | more or other tools)
grep "client" logs/trading_bot.log
# View error logs only
grep "ERROR" logs/trading_bot.log
# Count total log entries
wc -l logs/trading_bot.log- ✓ Cannot be empty
- ✓ Must be a string
- ✓ Minimum 2 characters
- ✓ Converted to uppercase
- ✓ Must be exactly:
BUYorSELL - ✓ Case-insensitive (BUY, buy, Buy all work)
- ✓ Cannot be empty
- ✓ Must be exactly:
MARKETorLIMIT - ✓ Case-insensitive
- ✓ Cannot be empty
- ✓ Must be a positive number
- ✓ Minimum: 0.001
- ✓ Cannot be zero or negative
- ✓ Must be numeric
- ✓ Required for LIMIT orders only
- ✓ Must be a positive number
- ✓ Minimum: 0.01
- ✓ Cannot be zero or negative
- ✓ Must be numeric
# Missing required argument
$ python cli.py --symbol BTCUSDT
error: the following arguments are required: --side, --type, --quantity
# Invalid side
$ python cli.py --symbol BTCUSDT --side INVALID --type MARKET --quantity 0.001
Validation Error: Side must be BUY or SELL, got: INVALID
# Missing price for LIMIT order
$ python cli.py --symbol BTCUSDT --side BUY --type LIMIT --quantity 0.001
Price is mandatory for LIMIT orders# Invalid symbol on Binance
Validation Error: Binance API error: Invalid symbol INVALIDUSDT
# Authentication failure
Binance API error: Invalid API key# Connection timeout
Unexpected error: Connection timeout - Check your internet connection
# Unable to reach server
Unexpected error: Failed to connect to testnet.binancefuture.comAll errors show:
- ✗ FAILURE indicator
- Clear error message
- Logged details for debugging
- Exit code 1 for script integration
Base URL: https://testnet.binancefuture.com
Order Types:
- MARKET - Immediate execution at market price
- LIMIT - Execution at specific price (GTC - Good Till Cancel)
Order Sides:
- BUY - Open long position or close short
- SELL - Open short position or close long
Response Fields:
{
"orderId": 123456789,
"symbol": "BTCUSDT",
"status": "FILLED",
"side": "BUY",
"type": "MARKET",
"origQty": "0.001",
"executedQty": "0.001",
"price": "43250.50",
"avgPrice": "43250.50"
}The application uses python-binance for API interaction.
Documentation: https://python-binance.readthedocs.io/
Key Methods Used:
UMFutures.new_order()- Place new orderUMFutures.query_order()- Query order status
Solution:
# Ensure virtual environment is activated
# Then reinstall dependencies
pip install -r requirements.txt
# Verify installation
python -c "import binance; print(binance.__version__)"Solution:
# Ensure you're in the correct directory
pwd # Check current directory
# Should be in trading_bot/ root directory
# Should see cli.py, bot/, requirements.txt
# Run from project root:
python cli.py --helpSolution:
# Check .env file exists
ls -la .env # macOS/Linux or dir .env (Windows)
# Verify contents (don't share this!)
cat .env # macOS/Linux or type .env (Windows)
# Should show:
# BINANCE_API_KEY=your_key
# BINANCE_API_SECRET=your_secret
# Ensure no quotes around values:
# INCORRECT: BINANCE_API_KEY="your_key"
# CORRECT: BINANCE_API_KEY=your_keySolution:
1. Check API key is correct (copy from Binance again)
2. Verify key is for Testnet, not Mainnet
3. Check API key has "Futures Trading" permission
4. Restart terminal to reload .env
5. Check logs for exact error: cat logs/trading_bot.logSolution:
# Symbol format is correct. This usually means:
1. API key doesn't have permission for this symbol
2. Symbol not trading on testnet
3. Typo in symbol
# Try with common testnet symbols:
python cli.py --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001
python cli.py --symbol ETHUSDT --side BUY --type MARKET --quantity 0.01
python cli.py --symbol BNBUSDT --side BUY --type MARKET --quantity 0.1Solution:
# Quantity too small. Increase quantity:
# INCORRECT: --quantity 0.0001
# CORRECT: --quantity 0.001
python cli.py --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001Solution:
# Check internet connection
ping google.com
# Check if testnet is accessible
curl https://testnet.binancefuture.com
# If still hanging, Ctrl+C to cancel and try again
# Check logs: tail logs/trading_bot.logSolution:
# Check logs directory exists
ls -d logs/ # macOS/Linux or dir logs (Windows)
# If not, create it:
mkdir logs # macOS/Linux or md logs (Windows)
# Run command again to generate logs
python cli.py --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001
# Check log file
cat logs/trading_bot.log-
Binance Futures Testnet is online
- Application requires live connection to testnet.binancefuture.com
- If testnet is down, orders will fail with connection errors
-
Python 3.8+ is installed
- Features used are compatible with Python 3.8+
- Tested on Python 3.9, 3.10, 3.11
-
Virtual environment best practice
- Project assumes use of virtual environment
- Ensures dependency isolation and reproducibility
-
Fresh API keys for security
- Each user should generate their own testnet API keys
- Keys are never shared or hardcoded
-
Testnet has sufficient balance
- Testnet accounts start with test USDT
- User responsible for maintaining testnet balance
-
Symbols are valid Binance Futures pairs
- Bot validates symbol format but depends on Binance's symbol list
- Popular pairs: BTCUSDT, ETHUSDT, BNBUSDT, ADAUSDT, etc.
-
Network connectivity is stable
- Bot makes live API calls
- Temporary network issues may cause timeouts
-
No concurrent order placement
- Application processes one order at a time
- Not designed for high-frequency trading
- No rate limiting implemented (assumed under Binance limits)
-
Order details are final
- No order modification or cancellation implemented
- Once placed, order follows Binance rules
-
Market orders execute immediately (testnet)
- Testnet provides instant fills on market orders
- Mainnet may have slippage/delays
-
LIMIT orders may not fill
- Limit orders placed at order book
- May remain pending if price never reached
-
User accepts testnet risks
- Testnet data may be reset
- Testnet orders don't involve real funds
- For learning/testing purposes only
# Update to latest compatible versions
pip install --upgrade -r requirements.txt
# Check for outdated packages
pip list --outdatedpytest tests/
pytest --cov=bot tests/# Format code (install black first)
pip install black
black bot/ cli.py
# Check linting (install flake8)
pip install flake8
flake8 bot/ cli.pypython cli.py --versionFor issues or improvements:
- Check logs in
logs/trading_bot.log - Review README troubleshooting section
- Verify API credentials are correct
- Ensure testnet is accessible
Last Updated: January 2026 Version: 1.0.0 Status: Production Ready
