Skip to content

FLASH-4/TradingBot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Trading Bot - Binance Futures Testnet

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.

Features

  • 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 .env file

Project Structure

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

Prerequisites

  • Python 3.7+
  • pip (Python package manager)
  • Binance Futures Testnet account with API credentials

Setup Instructions

1. Register on Binance Futures Testnet

  1. Visit Binance Futures Testnet
  2. Create a new account or use your existing Binance account
  3. Complete the registration and verification process

2. Generate API Credentials

  1. Log in to Binance Futures Testnet
  2. Go to Account β†’ API Management
  3. Create a new API key:
    • Set Label: "Trading Bot" (or any name)
    • Enable: Futures Trading
    • Restrict to IP: (optional, leave blank for testing)
  4. Copy your API Key and Secret Key

3. Install Dependencies

# 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.txt

4. Configure API Credentials

Create a .env file in the project root:

cp .env.example .env

Edit .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.

Usage

Running the Bot

The bot provides a CLI interface with multiple commands:

1. Place an Order

# 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 2000

Parameters:

  • --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)

2. Check Order Status

# Interactive mode
python -m bot status

# Non-interactive mode
python -m bot status --symbol BTCUSDT --order-id 123456789

3. View Account Information

python -m bot account

Example Workflow

# 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 account

Logging

All 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

Log Examples

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

Code Quality

Architecture

The codebase follows clean architecture principles:

  1. Client Layer (client.py): Low-level API communication with Binance
  2. Business Logic (orders.py): Order management and formatting
  3. Validation (validators.py): Input validation and error handling
  4. CLI Layer (cli.py): User interface and command handling
  5. Logging (logging_config.py): Centralized logging configuration

Error Handling

  • 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

Input Validation

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)

Assumptions

  1. Testnet Only: This bot is configured for Binance Futures Testnet only. To use mainnet, change the base URL in client.py.

  2. USDT-M Futures: The bot uses USDT-M (perpetual) futures contracts.

  3. GTC Time in Force: LIMIT orders use "Good Till Cancel" (GTC) time in force by default.

  4. No Position Management: The bot only places orders; it doesn't manage positions or set stop losses.

  5. Decimal Precision: Quantities and prices use Python's Decimal type for precision.

  6. Synchronous API: The bot uses synchronous REST API calls (not WebSocket).

Troubleshooting

"API credentials not found"

  • Ensure .env file exists in the project root
  • Check that BINANCE_API_KEY and BINANCE_API_SECRET are set correctly
  • Verify no typos in environment variable names

"API Error 400: Invalid symbol"

  • 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

"API Error 401: Unauthorized"

  • Verify API key and secret are correct
  • Check that API key has "Futures Trading" permission enabled
  • Regenerate API credentials if needed

"API Error 403: Forbidden"

  • Ensure API key is not restricted to specific IPs (or add your IP)
  • Check that your testnet account has trading enabled

"Insufficient balance"

  • Add funds to your testnet account via the faucet
  • Visit testnet.binancefuture.com and look for the deposit/faucet option

Testing

To test the bot without placing real orders:

  1. Use very small quantities (e.g., 0.001 BTC)
  2. Start with MARKET orders to verify connectivity
  3. Check logs in logs/ directory for detailed API interactions
  4. Use the account command to verify your balance

API Reference

Binance Futures Testnet API

Security Notes

  1. Never commit .env: API credentials should never be in version control
  2. Rotate credentials: Periodically regenerate API keys
  3. IP Whitelist: Consider restricting API key to your IP address
  4. Testnet Only: This bot is for testing only; use with caution on mainnet

Performance Considerations

  • 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.

Future Enhancements

  • 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)

License

This project is provided as-is for educational and testing purposes.

Support

For issues or questions:

  1. Check the logs in logs/ directory
  2. Verify API credentials and permissions
  3. Review the Binance Futures API documentation
  4. Check the troubleshooting section above

Author

Created as a Python Developer Intern Assignment for Primetrade.ai


Last Updated: January 2024 Version: 1.0.0

About

πŸš€ Binance Futures Trading Bot (Testnet) - A clean, modular Python application for placing Market and Limit orders on Binance Futures Testnet (USDT-M). Features robust input validation, detailed logging, and a professional CLI. Built for the Primetrade.ai Python Developer Intern Assignment.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages