Repository files navigation # Bitget AutoTrader - FastAPI Trading System
A production-ready automated trading system for Bitget perpetuals with technical analysis and risk management.
## Features
- **Technical Indicators**: EMA, RSI, MACD, ATR
- **Automated Signals**: BUY/SELL/WAIT based on multi-timeframe analysis
- **Risk Management**: Position sizing based on 1% risk rule
- **Stop-Loss & Take-Profit**: Automatic SL/TP placement using ATR
- **Portfolio Scanning**: Scan multiple symbols simultaneously
- **REST API**: FastAPI endpoints for integration
- **Async Support**: Non-blocking concurrent operations
- **Trade Logging**: Comprehensive trade history
## Installation
\`\`\`bash
pip install -r requirements.txt
\`\`\`
## Configuration
1. Create a `.env` file in the project root:
\`\`\`env
BITGET_API_KEY=your_api_key
BITGET_SECRET_KEY=your_secret_key
BITGET_PASSPHRASE=your_passphrase
\`\`\`
2. Edit `config.py` to customize:
- Trading symbols
- Risk parameters
- Indicator periods
- ATR multipliers
## Running the Application
\`\`\`bash
uvicorn main:app --host 0.0.0.0 --port 8000
\`\`\`
Access the API at: `http://localhost:8000`
Swagger docs: `http://localhost:8000/docs`
## API Endpoints
### GET /health
Health check
### GET /symbols
Get available USDT perpetual trading pairs
### GET /signal/{symbol}
Get trading signal for a specific symbol
\`\`\`bash
curl http://localhost:8000/signal/BTCUSDT_UMCBL
\`\`\`
### GET /scan_all
Scan all configured symbols for signals
\`\`\`bash
curl http://localhost:8000/scan_all
\`\`\`
### POST /trade
Execute a trade with custom parameters
\`\`\`bash
curl -X POST http://localhost:8000/trade \
-G \
--data-urlencode "symbol=BTCUSDT_UMCBL" \
--data-urlencode "side=BUY" \
--data-urlencode "entry=64200" \
--data-urlencode "stop_loss=63500" \
--data-urlencode "take_profit=65500" \
--data-urlencode "size=0.01"
\`\`\`
### GET /status
Get account status and open positions
\`\`\`bash
curl http://localhost:8000/status
\`\`\`
## Signal Logic
### BUY Signal
- EMA9 > EMA21 > EMA50 > EMA200 (uptrend)
- MACD > Signal Line (momentum)
- RSI < 65 (not overbought)
### SELL Signal
- EMA9 < EMA21 < EMA50 < EMA200 (downtrend)
- MACD < Signal Line (negative momentum)
- RSI > 35 (not oversold)
### WAIT
- Conditions not met
## Risk Management
- **Position Size**: `risk = balance × 1% / (entry - stop_loss)`
- **Stop-Loss**: `entry ± 1 × ATR`
- **Take-Profit**: `entry ± 2 × ATR`
## Extending with n8n
See `n8n_integration_plan.md` for orchestration and enrichment setup.
## Telegram Integration (Optional)
Add to `trade_manager.py`:
\`\`\`python
import aiohttp
async def send_telegram_alert(message: str):
token = os.getenv("TELEGRAM_BOT_TOKEN")
chat_id = os.getenv("TELEGRAM_CHAT_ID")
url = f"https://api.telegram.org/bot{token}/sendMessage "
async with aiohttp.ClientSession() as session:
await session.post(url, json={"chat_id": chat_id, "text": message})
\`\`\`
## Database Logging (Optional)
Integrate with PostgreSQL, MongoDB, or Firebase to persist trade data:
\`\`\`python
# Example with asyncpg
import asyncpg
async def log_trade_to_db(trade_record):
conn = await asyncpg.connect('postgresql://...')
await conn.execute(
'INSERT INTO trades (symbol, side, entry, status) VALUES ($1, $2, $3, $4)',
trade_record['symbol'], trade_record['side'],
trade_record['entry'], trade_record['status']
)
\`\`\`
## Performance Notes
- API rate limits: 100 requests per second per account
- Candle fetching: 200 candles per request (sufficient for 200-period indicators)
- Scan interval: 60 seconds between full portfolio scans
- Async operations reduce latency by 50-70%
## Troubleshooting
**API Connection Errors**
- Verify API credentials in `.env`
- Check network connectivity
- Ensure Bitget API keys have trading permissions
**Signal Generation Fails**
- Ensure at least 200 candles available (for indicators)
- Check symbol format: `BTCUSDT_UMCBL`
**Order Placement Fails**
- Verify account has sufficient balance
- Check order size meets minimum requirements
- Ensure stop-loss is realistic (within market range)
## Disclaimer
This system is for educational purposes. Always test with small amounts. Trading involves risk.
# TradingBot
About
No description, website, or topics provided.
Resources
Stars
Watchers
Forks
You can’t perform that action at this time.