Uptime
99.8%
Active Followers
3
Trades Today
42
Success Rate
98.5%
Architectural Principles
Modularity & Separation
Distinct logical components with clear boundaries and responsibilities.
Idempotency
Restart-safe design prevents trade duplication through meticulous state tracking.
Persistence First
Atomic commits to SQLite before any subsequent action ensures data integrity.
Security by Design
API keys encrypted at rest with verification of limited permissions.
Core Implementation
### File: main.py #!/usr/bin/env python3 """Main entry point for SpotSync Alpha - Master-Follower Replication Engine""" import logging import signal import sys import time from datetime import datetime from typing import Dict, Optional from database.models import init_db, SessionLocal from core.trade_watcher import TradeWatcher from core.trade_executor import TradeExecutor from config.settings import MASTER_API_CONFIG class TradingEngine: """Orchestrates the complete trade replication lifecycle""" def __init__(self, poll_interval: int = 30): self.running = False self.poll_interval = poll_interval self.logger = logging.getLogger(__name__) # Initialize components init_db() self.trade_watcher = TradeWatcher(MASTER_API_CONFIG) self.trade_executor = TradeExecutor() def start(self): """Start the main engine loop""" self.running = True self.logger.info("🚀 SpotSync Alpha Engine starting...") self.setup_signal_handlers() # Main execution loop while self.running: try: # Poll for new trades from master new_trades = self.trade_watcher.poll_for_new_trades() if new_trades: self.logger.info(f"📊 Detected {len(new_trades)} new master trades to replicate") # Execute each trade on all active followers for trade in new_trades: self.trade_executor.execute_trade_on_followers(trade) # Sleep until next poll time.sleep(self.poll_interval) except KeyboardInterrupt: self.logger.info("⚠️ Shutdown signal received") break except Exception as e: self.logger.error(f"❌ Unexpected error in main loop: {e}", exc_info=True) time.sleep(self.poll_interval) # Don't crash on single error def setup_signal_handlers(self): """Handle graceful shutdown on SIGINT/SIGTERM""" signal.signal(signal.SIGINT, self.shutdown_handler) signal.signal(signal.SIGTERM, self.shutdown_handler) # More code follows...
Behavioral Contracts
Trade Trigger Contract
A trade is copied if and only if it appears as a new, successfully executed trade in the master's get_my_trades endpoint. No other event (balance changes, transfers, deposits) shall ever trigger a trade.
replicate_trade(trade)
else:
ignore() # Idempotency guarantee
Allocation Contract
Follower trades are sized proportionally based on a pre-configured rule (e.g., percentage of available capital). The system must perform a balance check before every single trade execution.
(follower_balance / master_balance)
* allocation_percentage
* master_quantity
)
assert follower_balance >= follower_quantity
Error Handling Contract
The failure of one follower must not impact others. Repeated critical errors automatically move followers to a PAUSED state. The system logs all execution failures with specific reasons and proceeds gracefully.
>= follower.max_consecutive_errors:
follower.status = 'PAUSED'
commit_to_database()
State Management Contract
Follower accounts exist in well-defined states (ACTIVE, PAUSED, DISABLED). Only ACTIVE followers are included in the trade execution loop.
f for f in followers
if f.status == 'ACTIVE'
]
for follower in active_followers:
execute_trade(follower)
Follower Management Dashboard
Active Followers
3 followers| Name | Status | Allocation | Last Trade | Consecutive Errors | Actions |
|---|---|---|---|---|---|
|
Alpha Trader
|
ACTIVE |
75%
|
2024-03-15 14:30:22 |
0
|
|
|
Beta Follower
|
PAUSED |
50%
|
2024-03-14 09:15:07 |
5
|
|
|
Gamma Investor
|
DISABLED |
25%
|
2024-03-10 16:45:33 |
12
|
|
Add New Follower
Secure API key import with encryption at rest
System Health Check
Verify master connection and follower statuses
Built for Financial Grade Reliability
Every component is engineered to withstand failures, ensure data integrity, and maintain perfect idempotency.
API Security Verification
Validates API keys don't have withdrawal permissions. Automatic detection and rejection of over-privileged credentials.
Restart-Safe Operation
Persistent tracking of last processed trade ID ensures duplicate trades are never executed, no matter how many restarts.
Error Isolation & Recovery
Follower failures are isolated. The system automatically pauses problematic followers while continuing normal operation.
Real-time Performance Analytics
Comprehensive dashboards track latency, success rates, execution delays, and allocation efficiency across all followers.
Full Audit Trail
Every trade, error, and state change is logged with timestamps, providing a complete, verifiable history for compliance.
Dynamic Allocation Strategies
Supports multiple allocation models: fixed percentages, dynamic ratio adjustment, and equity-based scaling for sophisticated strategies.