A Python-based cryptocurrency trading bot using ccxt library with asyncio for fast execution. MESA provides a simple and extensible framework for implementing trading strategies and backtesting them on historical data.
- β‘ Fast Async Execution: Built with asyncio for high-performance concurrent operations
- π Multi-Exchange Support: Uses ccxt library supporting 100+ cryptocurrency exchanges
- π Strategy Framework: Simple base class for implementing custom trading strategies
- π Backtesting Engine: Test strategies on historical data before live trading
- π― Example Strategy: Includes Simple Moving Average (SMA) crossover strategy
- π§ Configurable: Easy JSON-based configuration for exchange and trading parameters
MESA/
βββ src/
β βββ __init__.py # Package initialization
β βββ bot.py # Main trading bot
β βββ exchange.py # Exchange connector using ccxt
β βββ strategies/
β β βββ __init__.py # Strategy base class
β β βββ sma_strategy.py # SMA crossover strategy
β βββ backtesting/
β βββ __init__.py # Backtesting engine
βββ tests/ # Test files
βββ main.py # Main entry point for live trading
βββ example_backtest.py # Example backtest script
βββ config.example.json # Example configuration file
βββ requirements.txt # Python dependencies
βββ README.md # This file
- Python 3.8 or higher
- pip package manager
- Clone the repository:
git clone https://github.com/alphago2580/MESA.git
cd MESA- Install dependencies:
pip install -r requirements.txt- Create configuration file:
cp config.example.json config.json- Edit
config.jsonwith your exchange API credentials and trading parameters:
{
"exchange": {
"name": "binance",
"api_key": "YOUR_API_KEY",
"secret": "YOUR_SECRET",
"enableRateLimit": true
},
"trading": {
"symbol": "BTC/USDT",
"timeframe": "1m",
"amount": 0.001,
"strategy": "SimpleMovingAverage"
},
"backtesting": {
"initial_balance": 10000
}
}Test your strategy on historical data before live trading:
python example_backtest.pyThis will:
- Fetch historical OHLCV data from the exchange
- Run the strategy on the data
- Display performance metrics
- Save results to
backtest_results.json
python main.pyThe bot will:
- Connect to the configured exchange
- Monitor the market in real-time
- Execute trades based on strategy signals
- Log all activities to
trading_bot.log
Press Ctrl+C to gracefully stop the trading bot.
To create your own trading strategy:
-
Create a new file in
src/strategies/(e.g.,my_strategy.py) -
Inherit from the
Strategybase class:
from typing import List
from . import Strategy
class MyStrategy(Strategy):
def __init__(self):
super().__init__(name="MyStrategy")
async def analyze(self, ohlcv_data: List[List]) -> str:
"""
Analyze market data and return trading signal.
Args:
ohlcv_data: OHLCV candlestick data
Returns:
'buy', 'sell', or 'hold'
"""
# Your strategy logic here
# Convert data to DataFrame using self.convert_to_dataframe()
df = self.convert_to_dataframe(ohlcv_data)
# Implement your analysis
# Return 'buy', 'sell', or 'hold'
return 'hold'- Use your strategy in
main.py:
from src.strategies.my_strategy import MyStrategy
strategy = MyStrategy()
bot = TradingBot(exchange_config, trading_config, strategy)The included SimpleMovingAverage strategy demonstrates the strategy pattern:
- Calculates short-term and long-term moving averages
- Generates buy signal when short MA crosses above long MA (bullish crossover)
- Generates sell signal when short MA crosses below long MA (bearish crossover)
- Manages position state to avoid duplicate signals
The backtesting engine provides:
- Position Management: Simulates opening and closing positions
- Performance Metrics:
- Total return and return percentage
- Win rate
- Average win/loss
- Number of trades
- Trade History: Complete log of all simulated trades
- Flexible Configuration: Adjustable trade amounts and parameters
Async wrapper for ccxt exchange operations:
connect(): Establish exchange connectionfetch_ticker(symbol): Get current pricefetch_ohlcv(symbol, timeframe, limit): Get candlestick datacreate_market_order(symbol, side, amount): Execute market orderfetch_balance(): Get account balance
Abstract class for implementing strategies:
analyze(ohlcv_data): Main method to implement - returns 'buy', 'sell', or 'hold'convert_to_dataframe(ohlcv_data): Convert raw data to pandas DataFrameset_position(position, entry_price): Update position stateget_position(): Get current position
Main bot coordinating trading operations:
start(): Start the trading botstop(): Stop the trading botget_account_info(): Get balance and position info
Test strategies on historical data:
run(strategy, ohlcv_data, trade_amount): Execute backtest- Returns detailed performance metrics
name: Exchange name (binance, coinbase, kraken, etc.)api_key: Your API keysecret: Your API secretenableRateLimit: Enable rate limiting (recommended: true)
symbol: Trading pair (e.g., "BTC/USDT")timeframe: Candlestick timeframe ("1m", "5m", "1h", etc.)amount: Order size in base currencystrategy: Strategy name (for reference)
initial_balance: Starting capital for backtesting
- Start Small: Test with minimal amounts initially
- Use Testnet: Many exchanges offer testnet/sandbox for practice
- Monitor Logs: Always check logs for errors or unexpected behavior
- Backtest First: Thoroughly backtest strategies before live trading
- Set Limits: Implement stop-loss and take-profit mechanisms
- Secure Credentials: Never commit API keys to version control
- Understand Risks: Cryptocurrency trading carries significant risk
- ccxt >= 4.0.0
- aiohttp >= 3.8.0
- pandas >= 2.0.0
- numpy >= 1.24.0
- python-dotenv >= 1.0.0
MIT License - see LICENSE file for details
Contributions are welcome! Please feel free to submit a Pull Request.
This software is for educational purposes only. Use at your own risk. The authors are not responsible for any financial losses incurred through the use of this trading bot. Cryptocurrency trading involves substantial risk of loss.
For issues, questions, or suggestions, please open an issue on GitHub.
sin seongsik
Happy Trading! ππ