A sophisticated cryptocurrency trading bot implementing a Martingale-style averaging strategy with EMA filters, volatility protection, and automated risk management.
- Martingale Strategy: Systematic position averaging with EMA-based trend filtering
- Volatility Protection: Automatically pauses trading during high volatility (ATR, Bollinger Bands, Historical Volatility)
- Telegram Notifications: Real-time alerts for positions, profits, warnings, and errors
- Risk Management: Margin monitoring, position size limits, and liquidation protection
- Multi-Symbol Support: Trade multiple pairs simultaneously with different strategies
- Retry & Rate Limiting: Built-in error handling and API rate limiting
- Cloud Ready: Docker support and Render.com deployment configuration
git clone https://github.com/pehur00/dcabot.git
cd dcabot
pip install -r requirements.txtCreate a .env file:
API_KEY=your_phemex_api_key
API_SECRET=your_phemex_api_secret
SYMBOL=BTCUSDT:Long:True
EMA_INTERVAL=1
TESTNET=True
# Optional: Telegram notifications
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id
# Optional: Fee optimization (default: True)
USE_POSTONLY=True# Option 1: Using virtual environment (recommended)
dcabot-env/bin/python main.py
# Option 2: If virtual env is activated
python main.pyWhat happens when you run:
- Bot loads environment variables from
.env - Connects to Phemex API (TESTNET=True uses testnet, TESTNET=False uses mainnet)
- Executes strategy once for each symbol in SYMBOL env var
- Places orders if strategy conditions are met
- Exits (simulates one cron job cycle)
Testing PostOnly orders:
# Set in .env file (recommended):
USE_POSTONLY=True # Uses maker fees (0.075%)
USE_POSTONLY=False # Uses taker fees (0.15%)
# Or export temporarily:
export USE_POSTONLY=false
dcabot-env/bin/python main.pySafety tips for local testing:
- Start with
TESTNET=Truefor risk-free testing - Use small position sizes initially
- Check current positions before running
- Monitor logs for "Order timeInForce: PostOnly" (entry orders) or "GoodTillCancel" (exit orders)
- Setup Guide - Local and remote installation
- Strategy Explanation - How the Martingale strategy works
- Deployment Guide - Deploy to Render.com or VPS
- Telegram Setup - Configure notifications
dcabot/
├── clients/ # Exchange API clients (Phemex)
├── strategies/ # Trading strategy implementations
├── workflows/ # Execution workflows
├── notifications/ # Telegram notification system
├── indicators/ # Technical indicators (volatility, EMA)
├── utils/ # Retry logic and rate limiting
└── docs/ # Documentation
The bot implements a Martingale averaging strategy:
- Entry: Opens positions when price is trending (EMA filter)
- Averaging: Adds to losing positions with increasing size
- Profit Taking: Systematically closes profitable positions
- Volatility Protection: Pauses during high volatility
- Risk Management: Maintains safe margin levels
See STRATEGY.md for detailed explanation.
The bot includes a comprehensive backtesting framework to validate strategy performance on historical data. The backtest simulates the exact bot behavior, checking every 5 minutes using 1-minute candles.
# Run backtest with default settings (1 day, $70 balance)
dcabot-env/bin/python backtest/backtest.py --symbol HBARUSDT --days 1 --interval 1 --source binance --balance 70 --side Long
# Run longer backtest (90 days)
dcabot-env/bin/python backtest/backtest.py --symbol HBARUSDT --days 90 --interval 1 --source binance --balance 70 --side Long
# Test different initial balance
dcabot-env/bin/python backtest/backtest.py --symbol BTCUSDT --days 30 --balance 100 --side Long
# Optimize profit-taking threshold
dcabot-env/bin/python backtest/backtest.py --symbol HBARUSDT --days 30 --profit-pnl 0.15 --side Long
# Test with margin protection (40% max margin cap to prevent early liquidations)
dcabot-env/bin/python backtest/backtest.py --symbol HBARUSDT --days 30 --max-margin-pct 0.40 --side Long
# Test with different leverage (default is 10x)
dcabot-env/bin/python backtest/backtest.py --symbol BTCUSDT --days 30 --leverage 5 --side Long
dcabot-env/bin/python backtest/backtest.py --symbol BTCUSDT --days 30 --leverage 20 --side Long--symbol: Trading pair (e.g., HBARUSDT, BTCUSDT, u1000PEPEUSDT)--days: Number of days to backtest (e.g., 1, 7, 30, 90)--interval: Candle interval in minutes (always use1for 1-minute candles)--source: Data source (binancerecommended)--balance: Initial balance in USDT (default: 100)--side: Position side (LongorShort)--profit-pnl: Profit-taking threshold as decimal (default: 0.1 = 10%)--max-margin-pct: Optional maximum margin usage cap (e.g., 0.40 = 40% max). When absent, no cap is applied--leverage: Leverage multiplier (default: 10). Test different leverages like 5, 10, 15, 20
Performance Metrics:
- Initial Balance: $200.00
- Final Balance: $221.81
- Total Return: +10.90%
- Win Rate: 96.30% (26 wins, 1 loss)
- Max Drawdown: 23.38%
- Total Operations: 585 (18 opens, 540 adds, 9 reduces, 18 closes)
- Average Win: $0.95
- Total Fees: $2.67
The backtest generates a comprehensive 5-panel chart:
-
Price Chart: Shows price action with 1-minute EMA200 and all trade markers
- Green triangles = OPEN positions
- Blue triangles = ADD to positions
- Orange squares = REDUCE positions (profit-taking)
- Red circles = CLOSE positions
-
Account Balance & Total Value: Clean view of your account performance
- Blue line = Realized balance (only changes on close/reduce)
- Purple line = Total value (balance + unrealized PnL)
-
Position Size Chart: Shows margin invested over time
- Orange filled area = How much margin is actively in positions
- Helps visualize when bot is heavily invested vs idle
-
Drawdown Analysis: Shows risk metrics and account drawdowns
-
Performance Summary: Detailed statistics and trade breakdown
SOLUSDT 31-Day Backtest - $200 Balance @ 5x Leverage
This chart demonstrates the bot's position management strategy during real market conditions:
-
Top Panel (Price & Positions): Shows multiple position cycles with precise entry/exit timing. Green markers indicate position opens below the 1h EMA100 (dip-buying strategy), blue markers show systematic averaging during drawdowns, and orange/red markers show profit-taking as price recovers.
-
Middle Panel (Balance Performance): The purple line (Total Value including unrealized PnL) shows smooth upward trajectory despite market volatility. Notice how unrealized losses are temporary as the bot averages down and recovers.
-
Position Margin Panel: Orange area shows how the bot dynamically manages capital allocation. Peaks represent full position buildups during drawdowns, valleys show idle periods between trades. The strategy respects the 50% margin cap (dynamic tapering prevents overexposure).
-
Drawdown Chart: Visualizes risk management effectiveness. Maximum drawdown of ~10% shows the bot's ability to weather adverse conditions without approaching liquidation.
-
Performance Summary: Final result of +11.19% return over 31 days demonstrates consistent profitability through multiple market cycles.
Key Observations:
- Bot opens positions only during favorable conditions (below 1h EMA100)
- Systematic position building during drawdowns with controlled margin usage
- Profit-taking occurs at multiple levels (33% close @ 7.5%, 50% close @ 10%)
- Multiple successful cycles with 92.3% win rate (12 wins, 1 loss)
- Dynamic tapering keeps margin usage under control as positions grow
All backtest results are saved to backtest/results/ with timestamps:
HBARUSDT_Long_bal70_profit0.10_20251027_154543_chart.png # Visual charts
HBARUSDT_Long_bal70_profit0.10_20251027_154541_balance.csv # Balance history
HBARUSDT_Long_bal70_profit0.10_20251027_154541_trades.csv # Trade log
- Backtest checks every 5 minutes (matching real bot behavior)
- Uses 1-minute candles for accurate price data
- Includes all volatility protections and risk management
- Simulates exact margin calculations and leverage (configurable via
--leverage) - Fees are included in calculations (0.075% per trade)
Test Multiple Leverages (test_leverages.sh):
# Test one symbol with 5x, 10x, 15x, 20x leverage
./test_leverages.sh HBARUSDT 30 200 Long
# Results saved as: HBARUSDT_lev5x_30d_*, HBARUSDT_lev10x_30d_*, etc.Test Top Volume Coins (test_top_coins.py):
# Test top 10 volume coins automatically
dcabot-env/bin/python test_top_coins.py --leverage 10 --days 7 --balance 200
# Test specific coins
dcabot-env/bin/python test_top_coins.py --coins BTCUSDT ETHUSDT SOLUSDT --days 30
# Test top 5 coins with custom settings
dcabot-env/bin/python test_top_coins.py --num-coins 5 --leverage 5 --days 60 --balance 500Features:
- Automatically fetches top volume coins from Binance (excludes stablecoins/fiat)
- Runs backtests sequentially for all coins
- Generates summary CSV comparing performance across all coins
- Saves individual charts, balance CSVs, and trade logs for each coin
Key parameters in strategies/MartingaleTradingStrategy.py:
CONFIG = {
'leverage': 10, # Trading leverage (10x)
'begin_size_of_balance': 0.006, # Initial position: 0.6% of balance
'buy_until_limit': 0.05, # Max position: 5% of balance (in margin)
'profit_threshold': 0.003, # Min profit: 0.3% of balance to consider closing
'profit_pnl': 0.1, # Target: 10% profit on margin invested
'max_margin_pct': None, # Optional: Max margin cap (e.g., 0.40 = 40%). None = no limit
}Important Notes:
buy_until_limitrefers to margin invested, not notional value. With 10x leverage, 5% margin = 50% notional position.max_margin_pctprovides margin protection with dynamic tapering:- When
None: No protection (not recommended for live trading) - When set (e.g.,
0.50): Implements smart tapering system - Dynamic Tapering: Order sizes reduce exponentially as margin usage increases
- At 0% margin: 100% order size (full adds)
- At 25% margin: 56% order size
- At 40% margin: 4% order size
- At 50% margin: 0% order size (no adds)
- Benefits: More trades with smaller sizes, better price averaging, maintains volatility buffer
- Example: With $200 balance and 50% cap, bot gradually reduces order sizes approaching $100 margin
- Result: Never hits the hard cap, prevents liquidations while staying active
- When
- Python 3.8+
- Phemex account with API access
- (Optional) Telegram bot for notifications
- Push code to GitHub
- Create Cron Job on Render.com
- Set environment variables
- Deploy
See DEPLOYMENT.md for details.
docker build -t martingale-bot .
docker run -d \
-e API_KEY=your_key \
-e API_SECRET=your_secret \
-e SYMBOL=BTCUSDT:Long:True \
martingale-bot- Telegram: Real-time notifications for all bot actions
- Logs: Structured JSON logging for easy parsing
- Phemex Dashboard: Monitor positions and PnL
- ✅ Testnet support for safe testing
- ✅ Rate limiting to prevent API bans
- ✅ Retry logic for failed requests
- ✅ Margin level monitoring
- ✅ Volatility detection and pausing
- ✅ Position size limits
- ✅ Emergency liquidation protection
- ✅ Dynamic position tapering (reduces order sizes as margin increases)
- ✅ Optional margin usage cap (50% default with exponential tapering)
- Can experience extended drawdowns
- Requires sufficient capital for averaging
- Uses leverage (amplifies both gains and losses)
- May lose your entire trading account in extreme conditions
Only use funds you can afford to lose completely.
MIT License - see LICENSE file for details.
- Documentation: See
docs/directory - Issues: Report bugs via GitHub Issues
- Strategy Questions: See STRATEGY.md
See CHANGELOG.md for version history.
This software is provided for educational purposes. Cryptocurrency trading carries significant risk. Past performance does not guarantee future results. The authors are not responsible for any financial losses incurred using this bot.
Trade responsibly. Start small. Test thoroughly.
