8.8 KiB
Trading Agent System
A modular, extensible cryptocurrency trading system that can connect to multiple exchanges through a common interface.
Architecture
The trading agent system consists of the following components:
Exchange Interfaces
ExchangeInterface
: Abstract base class that defines the common interface for all exchange implementationsBinanceInterface
: Implementation for the Binance exchange (supports both mainnet and testnet)MEXCInterface
: Implementation for the MEXC exchange
Trading Agent
TradingAgent
: Main class that manages trading operations, including position sizing, risk management, and signal processing
Neural Network Orchestrator
NeuralNetworkOrchestrator
: Coordinates between neural network models and the trading agent to generate and process trading signals
Getting Started
Installation
The trading agent system is built into the main application. No additional installation is needed beyond the requirements for the main application.
Configuration
Configuration can be provided via:
- Command-line arguments
- Environment variables
- Configuration file
Example Configuration
{
"exchange": "binance",
"api_key": "your_api_key",
"api_secret": "your_api_secret",
"test_mode": true,
"trade_symbols": ["BTC/USDT", "ETH/USDT"],
"position_size": 0.1,
"max_trades_per_day": 5,
"trade_cooldown_minutes": 60
}
Running the Trading System
From Command Line
# Run with Binance in test mode
python trading_main.py --exchange binance --test-mode
# Run with MEXC in production mode
python trading_main.py --exchange mexc --api-key YOUR_API_KEY --api-secret YOUR_API_SECRET
# Run with custom position sizing and limits
python trading_main.py --exchange binance --test-mode --position-size 0.05 --max-trades-per-day 3 --trade-cooldown 120
Using Environment Variables
You can set these environment variables for configuration:
# Set exchange API credentials
export BINANCE_API_KEY=your_binance_api_key
export BINANCE_API_SECRET=your_binance_api_secret
# Enable neural network models
export ENABLE_NN_MODELS=1
export NN_INFERENCE_INTERVAL=60
export NN_MODEL_TYPE=cnn
export NN_TIMEFRAME=1h
# Run the trading system
python trading_main.py
Basic Usage Examples
Creating a Trading Agent
from NN.trading_agent import TradingAgent
# Initialize a trading agent for Binance testnet
agent = TradingAgent(
exchange_name="binance",
api_key="your_api_key",
api_secret="your_api_secret",
test_mode=True,
trade_symbols=["BTC/USDT", "ETH/USDT"],
position_size=0.1,
max_trades_per_day=5,
trade_cooldown_minutes=60
)
# Start the trading agent
agent.start()
# Process a signal
agent.process_signal(
symbol="BTC/USDT",
action="BUY",
confidence=0.85
)
# Get current positions
positions = agent.get_current_positions()
print(f"Current positions: {positions}")
# Stop the trading agent
agent.stop()
Using an Exchange Interface Directly
from NN.exchanges import BinanceInterface
# Initialize the Binance interface
exchange = BinanceInterface(
api_key="your_api_key",
api_secret="your_api_secret",
test_mode=True
)
# Connect to the exchange
exchange.connect()
# Get ticker info
ticker = exchange.get_ticker("BTC/USDT")
print(f"Current BTC price: {ticker['last']}")
# Get account balance
btc_balance = exchange.get_balance("BTC")
usdt_balance = exchange.get_balance("USDT")
print(f"BTC balance: {btc_balance}")
print(f"USDT balance: {usdt_balance}")
# Place a market order
order = exchange.place_order(
symbol="BTC/USDT",
side="buy",
order_type="market",
quantity=0.001
)
Testing the Exchange Interfaces
The system includes a test script that can be used to verify that exchange interfaces are working correctly:
# Test Binance interface in test mode (no real trades)
python -m NN.exchanges.trading_agent_test --exchange binance --test-mode
# Test MEXC interface in test mode
python -m NN.exchanges.trading_agent_test --exchange mexc --test-mode
# Test with actual trades (use with caution!)
python -m NN.exchanges.trading_agent_test --exchange binance --test-mode --execute-trades --test-trade-amount 0.001
Adding a New Exchange
To add support for a new exchange, you need to create a new class that inherits from ExchangeInterface
and implements all the required methods:
- Create a new file in the
NN/exchanges
directory (e.g.,kraken_interface.py
) - Implement the required methods (see
exchange_interface.py
for the specifications) - Add the new exchange to the imports in
__init__.py
- Update the
_create_exchange
method inTradingAgent
to support the new exchange
Example of a New Exchange Implementation
# NN/exchanges/kraken_interface.py
import logging
from typing import Dict, Any, List, Optional
from .exchange_interface import ExchangeInterface
logger = logging.getLogger(__name__)
class KrakenInterface(ExchangeInterface):
"""Kraken Exchange API Interface"""
def __init__(self, api_key: str = None, api_secret: str = None, test_mode: bool = True):
super().__init__(api_key, api_secret, test_mode)
self.base_url = "https://api.kraken.com"
# Initialize other Kraken-specific properties
def connect(self) -> bool:
# Implement connection to Kraken API
pass
def get_balance(self, asset: str) -> float:
# Implement getting balance for an asset
pass
def get_ticker(self, symbol: str) -> Dict[str, Any]:
# Implement getting ticker data
pass
def place_order(self, symbol: str, side: str, order_type: str,
quantity: float, price: float = None) -> Dict[str, Any]:
# Implement placing an order
pass
def cancel_order(self, symbol: str, order_id: str) -> bool:
# Implement cancelling an order
pass
def get_order_status(self, symbol: str, order_id: str) -> Dict[str, Any]:
# Implement getting order status
pass
def get_open_orders(self, symbol: str = None) -> List[Dict[str, Any]]:
# Implement getting open orders
pass
Then update the imports in __init__.py
:
from .exchange_interface import ExchangeInterface
from .binance_interface import BinanceInterface
from .mexc_interface import MEXCInterface
from .kraken_interface import KrakenInterface
__all__ = ['ExchangeInterface', 'BinanceInterface', 'MEXCInterface', 'KrakenInterface']
And update the _create_exchange
method in TradingAgent
:
def _create_exchange(self) -> ExchangeInterface:
"""Create an exchange interface based on the exchange name."""
if self.exchange_name == 'mexc':
return MEXCInterface(
api_key=self.api_key,
api_secret=self.api_secret,
test_mode=self.test_mode
)
elif self.exchange_name == 'binance':
return BinanceInterface(
api_key=self.api_key,
api_secret=self.api_secret,
test_mode=self.test_mode
)
elif self.exchange_name == 'kraken':
return KrakenInterface(
api_key=self.api_key,
api_secret=self.api_secret,
test_mode=self.test_mode
)
else:
raise ValueError(f"Unsupported exchange: {self.exchange_name}")
Security Considerations
- API Keys: Never hardcode API keys in your code. Use environment variables or secure storage.
- Permissions: Restrict API key permissions to only what is needed (e.g., trading, but not withdrawals).
- Testing: Always test with small amounts and use test mode/testnet when possible.
- Position Sizing: Implement conservative position sizing to manage risk.
- Monitoring: Set up monitoring and alerting for your trading system.
Troubleshooting
Common Issues
- Connection Problems: Make sure you have internet connectivity and correct API credentials.
- Order Placement Errors: Check for sufficient funds, correct symbol format, and valid order parameters.
- Rate Limiting: Avoid making too many API requests in a short period to prevent being rate-limited.
Logging
The trading agent system uses Python's logging module with different levels:
- DEBUG: Detailed information, typically useful for diagnosing problems.
- INFO: Confirmation that things are working as expected.
- WARNING: Indication that something unexpected happened, but the program can still function.
- ERROR: Due to a more serious problem, the program has failed to perform some function.
You can adjust the logging level in your trading script:
import logging
logging.basicConfig(
level=logging.DEBUG, # Change to INFO, WARNING, or ERROR as needed
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("trading.log"),
logging.StreamHandler()
]
)