{"id":30913214,"url":"https://github.com/amirphl/simple-trader","last_synced_at":"2025-09-09T22:55:47.925Z","repository":{"id":303250896,"uuid":"1011847316","full_name":"amirphl/simple-trader","owner":"amirphl","description":"A Go-based trading system with modular strategies, risk management, and exchange integration.","archived":false,"fork":false,"pushed_at":"2025-08-28T17:33:31.000Z","size":610,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-28T23:58:53.308Z","etag":null,"topics":["algorithmic-trading","algorithmic-trading-engine","crypto-trading","cryptocurrency","trade-bot","tradebot","trading","trading-algorithms","trading-platform","trading-software","trading-strategies","trading-strategy","trading-systems","tradingbot"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/amirphl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-01T12:28:21.000Z","updated_at":"2025-08-28T17:33:35.000Z","dependencies_parsed_at":"2025-07-06T16:22:19.922Z","dependency_job_id":"4b458a99-a226-4ceb-9641-dc5c4e895905","html_url":"https://github.com/amirphl/simple-trader","commit_stats":null,"previous_names":["amirphl/simple-trader"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/amirphl/simple-trader","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amirphl%2Fsimple-trader","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amirphl%2Fsimple-trader/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amirphl%2Fsimple-trader/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amirphl%2Fsimple-trader/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/amirphl","download_url":"https://codeload.github.com/amirphl/simple-trader/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amirphl%2Fsimple-trader/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274377403,"owners_count":25273832,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-09T02:00:10.223Z","response_time":80,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithmic-trading","algorithmic-trading-engine","crypto-trading","cryptocurrency","trade-bot","tradebot","trading","trading-algorithms","trading-platform","trading-software","trading-strategies","trading-strategy","trading-systems","tradingbot"],"created_at":"2025-09-09T22:55:43.479Z","updated_at":"2025-09-09T22:55:47.916Z","avatar_url":"https://github.com/amirphl.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Simple Trader\n\nA robust, extensible crypto algorithmic trading bot written in Go, designed for both backtesting and live trading with comprehensive database persistence and advanced market data processing.\n\n## Features\n\n- **Exchange Integration**\n  - Modular exchange abstraction (currently supports Wallex)\n  - Mock exchange implementation for testing and simulation\n  - Easily extendable to support additional exchanges\n  - Real-time websocket integration for market data\n  - Optimized tick processing (stores last tick instead of overwhelming subscribers)\n\n- **Database Persistence**\n  - Full PostgreSQL/TimescaleDB integration with comprehensive schema\n  - Position management with unique ID-based tracking for historical records\n  - Automatic position saving on creation and updating on closure\n  - JSONB storage for complex data structures (risk parameters, order specs, trade logs)\n  - Transactional operations with rollback support\n\n- **Advanced Market Data Processing**\n  - Real-time orderbook fetching and processing from exchange APIs\n  - Optimized websocket implementation with last-tick storage pattern\n  - Market statistics and tick data retrieval\n  - Efficient market depth analysis for optimal order placement\n\n- **Advanced Candle Management**\n  - Real-time candle ingestion from exchange data\n  - Automatic candle aggregation (1m → 5m → 15m → 30m → 1h → 4h → 1d)\n  - Historical data backfill (up to 2 years)\n  - Efficient storage in PostgreSQL/TimescaleDB\n  - Optimized for high-frequency updates and queries\n  - Clear distinction between raw and constructed candles\n  - Comprehensive source tracking and validation\n\n- **Technical Analysis**\n  - Comprehensive technical indicators:\n    - Moving Averages (SMA, EMA)\n    - Oscillators (RSI, Stochastic)\n    - Trend indicators (MACD, Bollinger Bands, ATR)\n  - Candlestick pattern detection (Doji, Engulfing, Hammer, Morning/Evening Star)\n  - Price action analysis\n\n- **Strategy Engine**\n  - Modular strategy implementation\n  - Composite strategies (combining multiple indicators)\n  - Configurable risk management parameters\n  - Strategy-specific timeframe selection\n\n- **Enhanced Position Management**\n  - Database-backed position persistence with unique ID tracking\n  - Automatic position saving and updating lifecycle\n  - Sophisticated position tracking and management\n  - Trade statistics and performance metrics\n  - Automatic position sizing based on risk parameters\n  - Support for both long and short positions\n  - Trailing stop implementation with configurable parameters\n  - Historical position tracking for performance analysis\n\n- **Order Management**\n  - Market and limit orders with mock exchange support for testing\n  - Stop-loss and take-profit functionality\n  - Trailing stops\n  - Order tracking and management\n  - Optimal order placement using real-time orderbook data\n\n- **Risk Management**\n  - Per-trade risk calculation\n  - Stop-loss automation\n  - Maximum daily loss limits\n  - Position sizing based on risk percentage\n  - Strategy-specific risk parameters\n\n- **Backtesting**\n  - Historical performance analysis\n  - Realistic simulation with slippage and commission\n  - Equity curve generation\n  - Detailed trade logs\n  - Performance metrics (win rate, profit factor, Sharpe ratio, expectancy)\n\n- **Operational Features**\n  - Telegram notifications for trades and system events\n  - Event journaling and state persistence\n  - Graceful shutdown and recovery\n  - Comprehensive error handling and retry mechanisms\n  - Thread-safe operations with mutex protection\n\n## Architecture\n\n```\ncmd/\n  main.go                  # Main entry point with CLI options\ninternal/\n  candle/                  # Candle aggregation, storage, retrieval\n    candle.go              # Core candle types and interfaces\n    ingestion.go           # Real-time candle ingestion system\n    heiken_ashi.go         # Heikin Ashi candle construction\n  config/\n    config.go              # Configuration management\n  db/                      # Database layer with full persistence\n    db.go                  # Database interfaces and DTOs\n    postgres.go            # PostgreSQL/TimescaleDB implementation\n    conf/                  # Database configuration\n  exchange/                # Exchange abstraction layer\n    exchange.go            # Exchange interface\n    wallex.go              # Wallex exchange implementation\n    mock_wallex.go         # Mock exchange for testing/simulation\n    websocket.go           # Optimized websocket client for real-time data\n    adapter.go             # Exchange adapters\n  indicator/               # Technical analysis indicators\n    indicator.go           # Base indicator interface\n    sma.go, ema.go         # Moving average implementations\n    rsi.go                 # Relative Strength Index\n    macd.go                # Moving Average Convergence Divergence\n    bollinger.go           # Bollinger Bands\n    atr.go                 # Average True Range\n    stochastic.go          # Stochastic Oscillator\n  pattern/                 # Candlestick pattern detection\n    pattern.go             # Pattern detection interface\n    doji.go                # Doji pattern detection\n    engulfing.go           # Bullish/Bearish Engulfing patterns\n    hammer.go              # Hammer/Hanging Man patterns\n    morning_evening_star.go # Morning/Evening Star patterns\n  position/                # Enhanced position management\n    position.go            # Database-backed position management system\n  strategy/                # Trading strategies\n    strategy.go            # Strategy interface\n    sma.go                 # Simple Moving Average strategy\n    ema.go                 # Exponential Moving Average strategy\n    rsi.go                 # RSI strategy\n    rsi_obos.go            # RSI Overbought/Oversold strategy\n    macd.go                # MACD strategy\n    composite.go           # Composite strategy\n    stochastic_heikin_ashi.go # Stochastic with Heikin Ashi\n    engulfing_heikin_ashi.go  # Engulfing pattern with Heikin Ashi\n  order/\n    order.go               # Order types and management\n  market/\n    market.go              # Market data structures (orderbook, ticks)\n  notifier/\n    notifier.go            # Notification interface\n    telegram.go            # Telegram implementation\n  journal/                 # Event journaling\n  livetrading/            # Live trading coordination\n  backtest/               # Backtesting engine\n  state/\n    state.go               # State persistence\n  utils/\n    log.go                 # Logging utilities\n  tfutils/                # Timeframe utilities\nscripts/\n  schema.sql               # Complete database schema with positions table\n```\n\n## Database Schema\n\nThe system uses a comprehensive PostgreSQL/TimescaleDB schema:\n\n- **Positions Table**: ID-based position tracking with full persistence\n  - Unique BIGSERIAL primary key for historical tracking\n  - JSONB storage for complex structures (risk params, trade logs, equity curves)\n  - Support for multiple active/inactive positions per strategy/symbol\n  - Complete trade history and performance metrics\n\n- **Time-Series Tables**: Optimized for high-frequency market data\n  - Candles, Orderbooks, Ticks with TimescaleDB hypertables\n  - Efficient indexing for symbol/timestamp queries\n\n## Getting Started\n\n### Prerequisites\n\n- Go 1.24 or higher\n- PostgreSQL with TimescaleDB extension\n- Wallex API credentials (for live trading)\n- Telegram bot token (optional, for notifications)\n\n### Installation\n\n1. Clone the repository:\n   ```bash\n   git clone https://github.com/amirphl/simple-trader.git\n   cd simple-trader\n   ```\n\n2. Install dependencies:\n   ```bash\n   go mod download\n   ```\n\n3. Set up the database:\n   ```bash\n   psql -U your_user -d your_database -f scripts/schema.sql\n   ```\n\n4. Build the application:\n   ```bash\n   go build -o simple-trader ./cmd\n   ```\n\n### Configuration\n\nSimple Trader can be configured via command-line flags or a YAML configuration file:\n\n```yaml\nwallex_api_key: \"your-api-key\"\ndb_conn_str: \"postgres://user:password@localhost:5432/simple_trader?sslmode=disable\"\ndb_max_open: 10\ndb_max_idle: 5\nmode: \"live\"  # or \"backtest\"\nsymbols: [\"BTCIRT\", \"ETHIRT\"]\nstrategies: [\"rsi\", \"macd\"]\nrisk_percent: 1.0\nstop_loss_percent: 2.0\ntrailing_stop_percent: 0.5\ntake_profit_percent: 3.0\nmax_daily_loss: 100.0\nlimit_spread: 0.1\norder_type: \"market\"  # or \"limit\", \"stop-limit\", \"oco\"\nnotification_retries: 3\nnotification_delay: 5s\nrisk_map:\n  rsi: { risk_percent: 1.0, stop_loss_percent: 2.0, trailing_stop_percent: 0.5 }\n  macd: { risk_percent: 0.5, stop_loss_percent: 1.5, trailing_stop_percent: 0.2 }\nslippage_percent: 0.05\ncommission_percent: 0.1\ntelegram_token: \"your-telegram-bot-token\"\ntelegram_chat_id: \"your-chat-id\"\n```\n\n### Usage\n\n#### Live Trading\n\n```bash\n./simple-trader -mode live -symbols btc-usdt,eth-usdt -strategies rsi,macd -risk-percent 1.0 -stop-loss-percent 2.0\n```\n\nOr with a config file:\n\n```bash\n./simple-trader -config config.yaml\n```\n\n#### Testing with Mock Exchange\n\n```bash\n./simple-trader -mode live -use-mock-exchange -symbols btc-usdt -strategies rsi\n```\n\n#### Backtesting\n\n```bash\n./simple-trader -mode backtest -symbols btc-usdt -strategies rsi -from 2023-01-01 -to 2023-12-31\n```\n\n### Enhanced Position Management\n\nThe system features a sophisticated database-backed position management system:\n\n- **ID-Based Tracking**: Each position gets a unique BIGSERIAL ID for historical tracking\n- **Automatic Persistence**: Positions are automatically saved on creation and updated on closure\n- **Risk-Based Sizing**: Automatically calculates position size based on risk parameters\n- **Stop-Loss Management**: Implements fixed and trailing stops\n- **Take-Profit Targets**: Configurable take-profit levels\n- **Performance Tracking**: Calculates key metrics like win rate, profit factor, and Sharpe ratio\n- **Strategy-Specific Parameters**: Different risk parameters for each strategy\n- **Daily Loss Limits**: Automatically disables trading when daily loss threshold is reached\n- **Historical Analysis**: Complete trade history with performance metrics stored in database\n\n### Market Data Features\n\n- **Real-time Orderbook**: Fetches and processes live orderbook data from Wallex API\n- **Optimized Websockets**: Uses last-tick storage pattern to prevent subscriber overwhelm\n- **Market Statistics**: Comprehensive market data including bid/ask, volume, price changes\n- **Optimal Order Placement**: Uses real-time market depth for optimal entry/exit pricing\n\n### Mock Exchange for Testing\n\nThe system includes a comprehensive mock exchange implementation:\n\n- **Hybrid Approach**: Proxies read-only operations to real exchange while mocking order operations\n- **Limit Order Support**: Successfully simulates limit order execution\n- **Error Simulation**: Proper error handling for unsupported order types\n- **Testing Safety**: Allows strategy testing without real money at risk\n\n### Technical Indicators\n\nThe system implements a comprehensive set of technical indicators:\n\n- **Moving Averages**: Simple Moving Average (SMA), Exponential Moving Average (EMA)\n- **Oscillators**: Relative Strength Index (RSI), Stochastic Oscillator\n- **Trend Indicators**: Moving Average Convergence Divergence (MACD), Bollinger Bands, Average True Range (ATR)\n\n### Pattern Detection\n\nThe system includes detection for common candlestick patterns:\n\n- **Doji**: Identifies indecision in the market\n- **Engulfing**: Detects bullish and bearish engulfing patterns\n- **Hammer/Hanging Man**: Identifies potential reversals\n- **Morning/Evening Star**: Detects complex reversal patterns\n\n### Equity Curve \u0026 Trade Log Reporting\n\n- **Backtest mode:**\n  - Prints the equity curve (cumulative PnL after each trade) as a list.\n  - Prints a trade log with entry/exit price, timestamps, and PnL for each trade.\n- **Live mode:**\n  - Prints the live equity curve and trade log after each trade close.\n  - All data persisted to database for historical analysis.\n\nThis helps you visualize performance and audit every trade.\n\n## Candle Ingestion and Storage System\n\nThe system features a comprehensive candle ingestion and storage system:\n\n- **Raw 1m Candle Storage**: Efficient storage of raw 1-minute candles from exchanges\n- **Intelligent Aggregation**: Real-time aggregation to higher timeframes (5m, 15m, 30m, 1h, 4h, 1d)\n- **Constructed Candle Management**: Clear distinction between raw exchange data and constructed (aggregated) candles\n- **Source Tracking**: Support for multiple data sources with proper source attribution\n- **Gap Detection**: Identifies and fills missing candle data\n- **Efficient Storage**: Optimized for time-series data with TimescaleDB\n- **Performance Optimizations**: Batch processing, caching, and optimized queries\n\nFor detailed information, see [CANDLE_INGESTION_AND_STORAGE.md](CANDLE_INGESTION_AND_STORAGE.md).\n\n## Multi-Symbol Backtesting\n\nThe system now supports running backtests across multiple top-performing symbols from Binance automatically.\n\n### Configuration\n\nSet the following parameters in `conf.yml`:\n\n```yaml\nmode: \"backtest\"\nmulti_symbol_backtest: true\ntop_symbols_count: 100  # Test top 100 symbols by 24h volume\nstrategies: [\"engulfing_heikin_ashi\"]\n```\n\nOr use command line flags:\n\n```bash\ngo run cmd/main.go \\\n  --mode=backtest \\\n  --multi-symbol-backtest=true \\\n  --top-symbols-count=20 \\\n  --strategies=engulfing_heikin_ashi \\\n  --from=2023-01-01 \\\n  --to=2024-01-01\n```\n\n### Features\n\n- **Automatic Symbol Selection**: Fetches top N USDT pairs by 24h volume from Binance\n- **Parallel Processing**: Runs backtests for each symbol sequentially with progress tracking\n- **Comprehensive HTML Report**: Generates `multi_symbol_backtest_report.html` with:\n  - Overall performance metrics\n  - Individual charts for each symbol with Heikin Ashi candles\n  - Interactive controls for each chart\n  - Top/bottom performing symbols\n  - Aggregate statistics\n- **Robust API Calls**: Exponential backoff retry logic for reliable data fetching behind proxies\n\n### API Retry Configuration\n\nFor environments with proxy or network connectivity issues, configure retry behavior:\n\n```yaml\n# API retry configuration (useful for proxy environments)\napi_retry_max_attempts: 5     # Maximum retry attempts for API calls\napi_retry_base_delay: 1s      # Base delay between retries\napi_retry_max_delay: 30s      # Maximum delay between retries\n```\n\nOr via command line:\n\n```bash\ngo run cmd/main.go \\\n  --api-retry-max-attempts=3 \\\n  --api-retry-base-delay=2s \\\n  --api-retry-max-delay=60s\n```\n\n**Retry Features:**\n- **Exponential Backoff**: Delays increase exponentially with each retry\n- **Jitter**: Random variation prevents thundering herd problems\n- **Smart Retry**: Only retries on retryable errors (network issues, rate limits, server errors)\n- **Proxy Support**: Enhanced reliability for proxy environments\n- **Context Awareness**: Respects cancellation and timeouts\n\n### Output\n\nThe multi-symbol backtest generates:\n\n1. **Console Summary**: \n   - Total symbols tested\n   - Overall win rate and P\u0026L\n   - Top 10 and bottom 5 performing symbols\n   - Success/failure statistics\n\n2. **JSON Data File** (`multi_symbol_backtest_data.json`):\n   - Complete backtest results and chart data in JSON format\n   - Structured data for external processing or custom visualization\n\n3. **Interactive HTML Report** (`multi_symbol_backtest_report.html`):\n   - Standalone HTML file that loads data from the JSON file\n   - Interactive charts for each symbol with real-time data loading\n   - Overall performance dashboard with filterable results\n   - Responsive design that works offline\n\n**Usage**: Run the backtest to generate the JSON data, then open `multi_symbol_backtest_report.html` in your browser to view the interactive report. The HTML file will automatically fetch and display the latest backtest data.\n\n### Example Usage\n\nTest EngulfingHeikinAshi strategy on top 50 symbols:\n\n```bash\ngo run cmd/main.go \\\n  --config=conf.yml \\\n  --multi-symbol-backtest=true \\\n  --top-symbols-count=50\n```\n\nTest on specific smaller set for quick validation:\n\n```bash\ngo run cmd/main.go \\\n  --mode=backtest \\\n  --multi-symbol-backtest=true \\\n  --top-symbols-count=10 \\\n  --strategies=engulfing_heikin_ashi \\\n  --from=2023-06-01 \\\n  --to=2023-12-01\n```\n\n### Example Workflow\n\n1. **Run Multi-Symbol Backtest**:\n```bash\ngo run cmd/main.go \\\n  --mode=backtest \\\n  --multi-symbol-backtest=true \\\n  --top-symbols-count=20 \\\n  --strategies=engulfing_heikin_ashi \\\n  --from=2023-01-01 \\\n  --to=2023-06-01\n```\n\n2. **Generated Files**:\n   - `multi_symbol_backtest_data.json` - Raw backtest data\n   - `multi_symbol_backtest_report.html` - Interactive report viewer\n\n3. **View Results**:\n   - Open `multi_symbol_backtest_report.html` in your browser\n   - The page will automatically load data from the JSON file\n   - Use the \"Refresh Data\" button to reload after running new backtests\n\n## Roadmap\n\n- [x] Project scaffolding\n- [x] Exchange abstraction\n- [x] Mock exchange implementation for testing\n- [x] Real-time orderbook functionality\n- [x] Optimized websocket implementation\n- [x] Database persistence for positions\n- [x] ID-based position tracking\n- [x] Candle aggregation/storage\n- [x] Indicator/pattern engine\n- [x] Strategy engine\n- [x] Position management with database backing\n- [x] Order/trade/market management\n- [x] Event journaling/state persistence\n- [x] Notification integration\n- [ ] Web interface for monitoring\n- [ ] Machine learning integration\n- [ ] Portfolio management\n- [ ] Multi-exchange arbitrage\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Acknowledgments\n\n- [TimescaleDB](https://www.timescale.com/) for time-series database optimization\n- [Wallex Exchange](https://wallex.ir/) for API access ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famirphl%2Fsimple-trader","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famirphl%2Fsimple-trader","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famirphl%2Fsimple-trader/lists"}