A clean, production-ready Python application for placing orders on Binance Futures Testnet (USDT-M). Built with proper logging, error handling, and a structured codebase.
- Market and Limit Orders: Place both market and limit orders on Binance Futures Testnet
- Comprehensive Validation: Input validation for all order parameters
- Structured Code: Separated concerns with client, order, and CLI layers
- Detailed Logging: All API requests, responses, and errors are logged to files
- Error Handling: Robust exception handling for network failures, API errors, and invalid inputs
- CLI Interface: User-friendly command-line interface using Click
- Environment Configuration: Secure API credential management via
.envfile
trading_bot/
βββ bot/
β βββ __init__.py # Package initialization
β βββ __main__.py # Module entry point
β βββ cli.py # CLI commands
β βββ client.py # Binance API client wrapper
β βββ orders.py # Order management logic
β βββ validators.py # Input validation
β βββ logging_config.py # Logging configuration
βββ logs/ # Log files (auto-generated)
βββ .env.example # Environment variables template
βββ requirements.txt # Python dependencies
βββ README.md # This file
- Python 3.7+
- pip (Python package manager)
- Binance Futures Testnet account with API credentials
- Visit Binance Futures Testnet
- Create a new account or use your existing Binance account
- Complete the registration and verification process
- Log in to Binance Futures Testnet
- Go to Account β API Management
- Create a new API key:
- Set Label: "Trading Bot" (or any name)
- Enable: Futures Trading
- Restrict to IP: (optional, leave blank for testing)
- Copy your API Key and Secret Key
# Clone or download the repository
cd trading_bot
# Create a virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtCreate a .env file in the project root:
cp .env.example .envEdit .env and add your credentials:
BINANCE_API_KEY=your_api_key_here
BINANCE_API_SECRET=your_api_secret_here
Important: Never commit .env to version control. It's already in .gitignore.
The bot provides a CLI interface with multiple commands:
# Interactive mode (prompts for input)
python -m bot order
# Non-interactive mode (direct arguments)
python -m bot order --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001
# LIMIT order with price
python -m bot order --symbol ETHUSDT --side SELL --type LIMIT --quantity 1 --price 2000Parameters:
--symbol: Trading pair (e.g., BTCUSDT, ETHUSDT)--side: BUY or SELL--type: MARKET or LIMIT--quantity: Order quantity--price: Price (required for LIMIT orders only)
# Interactive mode
python -m bot status
# Non-interactive mode
python -m bot status --symbol BTCUSDT --order-id 123456789python -m bot account# 1. Place a market order to buy 0.001 BTC
python -m bot order --symbol BTCUSDT --side BUY --type MARKET --quantity 0.001
# Output will show:
# ============================================================
# ORDER REQUEST SUMMARY
# ============================================================
# Symbol: BTCUSDT
# Side: BUY
# Type: MARKET
# Quantity: 0.001
# ============================================================
#
# ============================================================
# ORDER RESPONSE
# ============================================================
# orderId : 123456789
# symbol : BTCUSDT
# side : BUY
# type : MARKET
# status : FILLED
# quantity : 0.001
# executedQty : 0.001
# avgPrice : 45000.50
# ============================================================
#
# β Order placed successfully! Order ID: 123456789
# 2. Place a limit order
python -m bot order --symbol ETHUSDT --side SELL --type LIMIT --quantity 1 --price 2500
# 3. Check order status
python -m bot status --symbol BTCUSDT --order-id 123456789
# 4. View account info
python -m bot accountAll API requests, responses, and errors are logged to files in the logs/ directory:
logs/
βββ trading_bot_20240115_143022.log
βββ trading_bot_20240115_150045.log
βββ ...
Each log file contains:
- Timestamp
- Log level (INFO, WARNING, ERROR)
- Function name and line number
- Detailed message
Market Order:
2024-01-15 14:30:22 - trading_bot - INFO - place_order:45 - Placing MARKET order: BTCUSDT BUY 0.001
2024-01-15 14:30:22 - trading_bot - INFO - _request:78 - API Request: POST /fapi/v1/order with params: {...}
2024-01-15 14:30:23 - trading_bot - INFO - _request:82 - API Response Status: 200
2024-01-15 14:30:23 - trading_bot - INFO - _request:87 - API Response Data: {"orderId": 123456789, ...}
2024-01-15 14:30:23 - trading_bot - INFO - place_order:52 - Order placed successfully: 123456789
Limit Order:
2024-01-15 15:00:45 - trading_bot - INFO - place_order:45 - Placing LIMIT order: ETHUSDT SELL 1
2024-01-15 15:00:45 - trading_bot - INFO - _request:78 - API Request: POST /fapi/v1/order with params: {...}
2024-01-15 15:00:46 - trading_bot - INFO - _request:82 - API Response Status: 200
2024-01-15 15:00:46 - trading_bot - INFO - _request:87 - API Response Data: {"orderId": 987654321, ...}
2024-01-15 15:00:46 - trading_bot - INFO - place_order:52 - Order placed successfully: 987654321
The codebase follows clean architecture principles:
- Client Layer (
client.py): Low-level API communication with Binance - Business Logic (
orders.py): Order management and formatting - Validation (
validators.py): Input validation and error handling - CLI Layer (
cli.py): User interface and command handling - Logging (
logging_config.py): Centralized logging configuration
- ValidationError: Invalid user input (symbol, side, type, quantity, price)
- BinanceClientError: API errors, network failures, invalid credentials
- Exception Handling: All exceptions are caught, logged, and reported to the user
All user inputs are validated before API calls:
- Symbol: Must be alphanumeric (e.g., BTCUSDT)
- Side: Must be BUY or SELL
- Type: Must be MARKET or LIMIT
- Quantity: Must be positive number
- Price: Must be positive number (required for LIMIT orders)
-
Testnet Only: This bot is configured for Binance Futures Testnet only. To use mainnet, change the base URL in
client.py. -
USDT-M Futures: The bot uses USDT-M (perpetual) futures contracts.
-
GTC Time in Force: LIMIT orders use "Good Till Cancel" (GTC) time in force by default.
-
No Position Management: The bot only places orders; it doesn't manage positions or set stop losses.
-
Decimal Precision: Quantities and prices use Python's
Decimaltype for precision. -
Synchronous API: The bot uses synchronous REST API calls (not WebSocket).
- Ensure
.envfile exists in the project root - Check that
BINANCE_API_KEYandBINANCE_API_SECRETare set correctly - Verify no typos in environment variable names
- Check symbol format (e.g., BTCUSDT, not BTC-USDT)
- Ensure the symbol is available on Binance Futures Testnet
- Visit testnet.binancefuture.com to verify available symbols
- Verify API key and secret are correct
- Check that API key has "Futures Trading" permission enabled
- Regenerate API credentials if needed
- Ensure API key is not restricted to specific IPs (or add your IP)
- Check that your testnet account has trading enabled
- Add funds to your testnet account via the faucet
- Visit testnet.binancefuture.com and look for the deposit/faucet option
To test the bot without placing real orders:
- Use very small quantities (e.g., 0.001 BTC)
- Start with MARKET orders to verify connectivity
- Check logs in
logs/directory for detailed API interactions - Use the
accountcommand to verify your balance
- Base URL:
https://testnet.binancefuture.com - Documentation: Binance Futures API
- Testnet Account: Binance Futures Testnet
- Never commit
.env: API credentials should never be in version control - Rotate credentials: Periodically regenerate API keys
- IP Whitelist: Consider restricting API key to your IP address
- Testnet Only: This bot is for testing only; use with caution on mainnet
- API Rate Limits: Binance Futures has rate limits. The bot respects these with 10-second timeouts.
- Network Latency: Market orders may execute at different prices due to network delays.
- Log Rotation: Logs are automatically rotated at 10MB to prevent disk space issues.
- Add support for more order types (Stop-Limit, OCO, TWAP, Grid)
- Implement WebSocket for real-time price updates
- Add position management (close positions, set stop losses)
- Create a web UI for order management
- Add backtesting capabilities
- Implement risk management (position sizing, max loss)
This project is provided as-is for educational and testing purposes.
For issues or questions:
- Check the logs in
logs/directory - Verify API credentials and permissions
- Review the Binance Futures API documentation
- Check the troubleshooting section above
Created as a Python Developer Intern Assignment for Primetrade.ai
Last Updated: January 2024 Version: 1.0.0