Version: 2.0 Last Updated: January 29, 2026 Status: β Production-Ready Architecture
NIJA is an enterprise-grade autonomous cryptocurrency trading platform that combines:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT APPLICATIONS β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Web Dashboardβ β Mobile Apps β β API Clients β β
β β (React.js) β β (React Nativeβ β (REST) β β
β ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ β
βββββββββββΌβββββββββββββββββββΌβββββββββββββββββββΌβββββββββββββββββββ
β β β
ββββββββββββββββββββ΄βββββββββββββββββββ
β
HTTPS/WSS (TLS 1.3)
β
βββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββ
β API GATEWAY LAYER β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Kong/Nginx API Gateway β β
β β β’ SSL Termination β β
β β β’ JWT Authentication β β
β β β’ Rate Limiting (tier-based) β β
β β β’ Request Routing β β
β β β’ CORS Policy Enforcement β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββ΄ββββββββββββββββββββ
β β
βββββββββββΌββββββββββββ βββββββββββΌββββββββββββ
β PUBLIC APIs β β ADMIN APIs β
β (FastAPI) β β (FastAPI) β
β β β β
β β’ Dashboard API β β β’ User Management β
β β’ Trading API β β β’ System Control β
β β’ Analytics API β β β’ Monitoring β
β β’ User Settings β β β’ Audit Logs β
βββββββββββ¬ββββββββββββ βββββββββββ¬ββββββββββββ
β β
ββββββββββββββββββββ¬ββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββ
β BUSINESS LOGIC LAYER β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β User Control β βSubscription β β Permission β β
β β Service β β Engine β β Validator β β
β ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬ββββββββ β
βββββββββββΌβββββββββββββββββββΌβββββββββββββββββββΌβββββββββββββββββββ
β β β
ββββββββββββββββββββ΄βββββββββββββββββββ
β
βββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββ
β EXECUTION LAYER β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Execution Router & Trade Isolation β β
β β β’ Per-user execution contexts β β
β β β’ Broker adapter factory β β
β β β’ Order routing & validation β β
β β β’ Position tracking β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββ΄ββββββββββββββββββββ
β β
βββββββββββΌββββββββββββ βββββββββββΌββββββββββββ
β CORE BRAIN β β BROKER ADAPTERS β
β (PRIVATE) β β (MULTI-EXCHANGE) β
β β β β
β β’ APEX Strategy ββββsignalsβββΆ β β’ Coinbase β
β β’ Meta-AI Engine β β β’ Kraken β
β β’ MMIN System β β β’ Binance β
β β’ GMIG System β β β’ OKX β
β β’ Risk Manager β β β’ Alpaca β
β β’ Indicators β β β’ Paper Trading β
βββββββββββββββββββββββ βββββββββββ¬ββββββββββββ
β
βββββββββββΌββββββββββββ
β EXCHANGES β
β (External APIs) β
βββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DATA LAYER β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β PostgreSQL β β Redis β β TimescaleDB β β
β β β β β β β β
β β β’ Users β β β’ Sessions β β β’ Trade Data β β
β β β’ Trades β β β’ Cache β β β’ Metrics β β
β β β’ Positions β β β’ Job Queue β β β’ Analytics β β
β β β’ Subscript. β β β’ PubSub β β β’ Time Seriesβ β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INFRASTRUCTURE LAYER β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β HashiCorp β β Prometheus + β β Logging β β
β β Vault β β Grafana β β (ELK Stack) β β
β β β β β β β β
β β β’ API Keys β β β’ Metrics β β β’ Audit Logs β β
β β β’ Secrets β β β’ Dashboards β β β’ Error Logs β β
β β β’ Rotation β β β’ Alerts β β β’ Trade Logs β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Purpose: Contains proprietary trading algorithms and decision-making logic.
Location: /core/ and /bot/
Components:
Access Control:
# NEVER exposed to users
# Only accessible via execution layer
from core import verify_core_access
verify_core_access(__name__) # Raises PermissionError if unauthorized
Key Files:
bot/nija_apex_strategy_v72_upgrade.py - Main strategybot/meta_ai/ - AI evolution enginebot/mmin/ - Multi-market intelligencebot/gmig/ - Global macro intelligencebot/execution_intelligence.py - Execution optimizationbot/risk_manager.py - Risk managementPurpose: Handles broker connections and order execution with user-specific permissions.
Location: /execution/ and /bot/broker_*.py
Components:
Routes trades to appropriate broker adapters with user isolation.
from execution import ExecutionRouter
router = ExecutionRouter()
result = router.route_order(
user_id="user_123",
broker="coinbase",
symbol="BTC-USD",
side="buy",
size_usd=100.0
)
Unified interface to multiple exchanges:
from execution.broker_adapter import SecureBrokerAdapter
adapter = SecureBrokerAdapter(
user_id="user_123",
broker_name="coinbase"
)
# Place order (automatically validated)
result = adapter.place_order(
pair="BTC-USD",
side="buy",
size_usd=50.0
)
Enforces user-specific trading limits.
from execution import UserPermissions, get_permission_validator
# Define user permissions
perms = UserPermissions(
user_id="user_123",
allowed_pairs=["BTC-USD", "ETH-USD"],
max_position_size_usd=100.0,
max_daily_loss_usd=50.0,
max_positions=3,
trade_only=True
)
# Validate trade
validator = get_permission_validator()
valid, error = validator.validate_trade(
user_id="user_123",
pair="BTC-USD",
position_size_usd=50.0
)
Key Files:
execution/broker_adapter.py - Secure broker wrapperexecution/__init__.py - Permission systembot/broker_manager.py - Broker managementbot/broker_integration.py - Exchange integrationsbot/unified_execution_engine.py - Unified executionPurpose: Public-facing interface for monitoring and configuration.
Location: /ui/, /frontend/, /mobile/
Components:
Single-page application for desktop browsers.
Features:
Tech Stack:
Native iOS and Android applications.
Features:
Tech Stack:
from ui import DashboardAPI
dashboard = DashboardAPI()
# Get user statistics
stats = dashboard.get_user_stats("user_123")
# Returns: {
# 'total_trades': 150,
# 'win_rate': 0.68,
# 'total_pnl': 2340.50,
# 'active_positions': 3,
# 'total_volume': 45000.00
# }
# Get active positions
positions = dashboard.get_positions("user_123")
# Get trade history
history = dashboard.get_trade_history(
user_id="user_123",
limit=50,
offset=0
)
Key Files:
ui/__init__.py - Dashboard APIfrontend/ - Web dashboard (React)mobile/ - Mobile apps (React Native)bot/user_dashboard_api.py - User data APIPurpose: Secure user authentication and API credential management.
Location: /auth/
Components:
Manages user accounts and authentication.
from auth import get_user_manager
user_mgr = get_user_manager()
# Create user
user_mgr.create_user(
user_id="user_123",
email="user@example.com",
password_hash=hash_password("secure_password"),
subscription_tier="pro"
)
# Authenticate user
authenticated, user = user_mgr.authenticate(
email="user@example.com",
password="secure_password"
)
# Generate JWT token
token = user_mgr.generate_jwt_token(user_id="user_123")
Securely stores user exchange API keys.
from auth import get_api_key_manager
api_manager = get_api_key_manager()
# Store encrypted API keys
api_manager.store_user_api_key(
user_id="user_123",
broker="coinbase",
api_key="user_api_key",
api_secret="user_api_secret",
additional_params={'org_id': 'org_123'}
)
# Retrieve decrypted credentials (internal only)
creds = api_manager.get_user_api_key("user_123", "coinbase")
Security Features:
Key Files:
auth/__init__.py - Auth systemauth/user_database.py - User data storagePurpose: Manage user-specific trading preferences.
Location: /config/
Components:
from config import get_config_manager
config_mgr = get_config_manager()
# Get user configuration
user_config = config_mgr.get_user_config("user_123")
# Update configuration
config_mgr.update_user_config("user_123", {
'max_position_size': 150.0,
'max_concurrent_positions': 5,
'risk_level': 'medium',
'allowed_pairs': ['BTC-USD', 'ETH-USD'],
'notifications_enabled': True
})
Default Configuration:
max_position_size: $100max_concurrent_positions: 3max_daily_loss_pct: 10%risk_level: βmediumβallowed_pairs: All (null = all allowed)Key Files:
config/__init__.py - Config management.env.example - Configuration templatePurpose: Enforce mandatory safety limits.
Location: /controls/
Components:
from controls import get_hard_controls
controls = get_hard_controls()
# Validate position size (enforces 2-10% rule)
valid, error = controls.validate_position_size(
user_id="user_123",
position_size_usd=50.0,
account_balance=1000.0
)
# Trigger kill switch
controls.trigger_user_kill_switch(
user_id="user_123",
reason="Excessive losses detected"
)
# Global kill switch (stops ALL trading)
controls.trigger_global_kill_switch(
reason="Market emergency"
)
Hard Limits:
Kill Switches:
Key Files:
controls/__init__.py - Safety controls/
βββ api_gateway.py # Main API gateway (FastAPI)
βββ api_server.py # Legacy API server
βββ fastapi_backend.py # FastAPI backend
βββ user_control.py # User control backend
βββ monetization_engine.py # Subscription & billing
β
βββ core/ # Layer 1: Private strategy logic
β βββ (strategy files - private)
β
βββ execution/ # Layer 2: Execution engine
β βββ __init__.py # Execution router
β βββ broker_adapter.py # Secure broker wrapper
β
βββ ui/ # Layer 3: User interface
β βββ __init__.py # Dashboard API
β βββ (UI components)
β
βββ auth/ # Authentication & API key management
β βββ __init__.py # User manager
β βββ user_database.py # User data storage
β
βββ config/ # User configuration
β βββ __init__.py # Config manager
β
βββ controls/ # Hard safety controls
β βββ __init__.py # Kill switches & limits
β
βββ database/ # Database layer
β βββ __init__.py
β βββ db_connection.py # PostgreSQL connection
β βββ models.py # SQLAlchemy models
β
βββ bot/ # Core trading engine
β βββ nija_apex_strategy_v72_upgrade.py # Main strategy
β βββ broker_manager.py # Broker management
β βββ broker_integration.py # Exchange integrations
β βββ execution_intelligence.py # Execution optimization
β βββ risk_manager.py # Risk management
β βββ meta_ai/ # Meta-AI engine
β βββ mmin/ # Multi-market intelligence
β βββ gmig/ # Global macro intelligence
β βββ (other modules)
β
βββ frontend/ # Web dashboard (React)
β βββ static/
β βββ templates/
β
βββ mobile/ # Mobile apps (React Native)
β βββ ios/
β βββ android/
β βββ (app source)
β
βββ scripts/ # Utility scripts
β βββ (various scripts)
β
βββ k8s/ # Kubernetes manifests
β βββ base/
β βββ components/
β
βββ docker-compose.yml # Local development stack
βββ Dockerfile.api # API container
βββ Dockerfile.dashboard # Dashboard container
βββ Dockerfile.gateway # Gateway container
β
βββ requirements.txt # Python dependencies
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β NIJA Platform Services β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. API Gateway Service (Port 8000)
- Entry point for all API requests
- JWT authentication
- Rate limiting
- Request routing
2. Trading Engine Service (Port 8001)
- Core APEX strategy execution
- Market scanning (732+ pairs)
- Signal generation
- Trade execution
3. Dashboard API Service (Port 8002)
- User statistics
- Position tracking
- Performance analytics
- Settings management
4. Subscription Service (Port 8003)
- Stripe integration
- Tier management
- Usage tracking
- Billing
5. WebSocket Service (Port 8004)
- Real-time position updates
- Trade notifications
- Market data streaming
- Chat support
6. Webhook Service (Port 5000)
- TradingView webhooks
- Payment webhooks (Stripe)
- Exchange webhooks
7. Admin API Service (Port 8005)
- User management
- System monitoring
- Kill switches
- Audit logs
See DATABASE_SCHEMA.md for detailed schema.
Core Tables:
users - User accountssubscriptions - Subscription dataapi_keys - Encrypted exchange credentialstrades - Trade historypositions - Active positionstransactions - Payment historyaudit_logs - System audit trailSee API_ROUTES.md for complete API specification.
POST /api/v1/auth/register - Register new user
POST /api/v1/auth/login - User login (returns JWT)
POST /api/v1/auth/logout - User logout
POST /api/v1/auth/refresh - Refresh JWT token
POST /api/v1/auth/reset-password - Password reset request
PUT /api/v1/auth/change-password - Change password
POST /api/v1/trading/start - Start trading bot
POST /api/v1/trading/stop - Stop trading bot
GET /api/v1/trading/status - Get bot status
POST /api/v1/trading/emergency-stop - Emergency kill switch
GET /api/v1/account/balance - Get account balance
GET /api/v1/account/positions - Get active positions
GET /api/v1/account/history - Get trade history
GET /api/v1/account/performance - Get performance metrics
GET /api/v1/account/stats - Get trading statistics
GET /api/v1/config/settings - Get user settings
PUT /api/v1/config/settings - Update settings
GET /api/v1/config/brokers - Get configured brokers
POST /api/v1/config/brokers - Add broker API keys
DELETE /api/v1/config/brokers/:id - Remove broker
GET /api/v1/subscription/plans - Get available plans
GET /api/v1/subscription/current - Get current subscription
POST /api/v1/subscription/upgrade - Upgrade subscription
POST /api/v1/subscription/cancel - Cancel subscription
GET /api/v1/subscription/usage - Get usage statistics
GET /api/v1/admin/users - List all users
GET /api/v1/admin/users/:id - Get user details
PUT /api/v1/admin/users/:id - Update user
DELETE /api/v1/admin/users/:id - Delete user
POST /api/v1/admin/kill-switch - Trigger global kill switch
GET /api/v1/admin/metrics - System metrics
GET /api/v1/admin/audit-logs - Audit logs
WS /ws/positions - Real-time position updates
WS /ws/trades - Real-time trade notifications
WS /ws/market-data - Live market data
WS /ws/notifications - General notifications
See DASHBOARD_DESIGN.md for detailed UI/UX specification.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HEADER β
β [NIJA Logo] Dashboard Trading Analytics Settings [π€] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β OVERVIEW CARDS β
β β β
β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ
β β β Balance β β P&L β β Win Rate β β Active ββ
β β β $10,450 β β +$1,234 β β 68% β β Trades ββ
β β β β² 2.5% β β β² 15% β β β² 3% β β 3 ββ
β β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β EQUITY CURVE CHART β
β β [Interactive line chart showing account growth] β
β β $12k β€ βββ β
β β β ββββββββββ― β
β β $10k β€ ββββββββββ― β
β β β βββββββββββ― β
β β $8k β€ ββββββββββ― β
β β ββββ΄βββββ΄βββββ΄βββββ΄βββββ΄βββββ΄βββββ΄βββββ΄βββββ β
β β Jan Feb Mar Apr May Jun Jul Aug Sep β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β ACTIVE POSITIONS β
β β βββββββ¬ββββββββββ¬βββββββ¬βββββββ¬βββββββ¬βββββββββ¬βββββββ
β β β ID β Symbol β Side β Size β P&L β Entry β ... ββ
β β βββββββΌββββββββββΌβββββββΌβββββββΌβββββββΌβββββββββΌββββββ€β
β β β 001 β BTC-USD β LONG β $500 β +$45 β 43210 β ... ββ
β β β 002 β ETH-USD β LONG β $300 β +$28 β 2345 β ... ββ
β β β 003 β SOL-USD β LONG β $200 β -$12 β 98.5 β ... ββ
β β βββββββ΄ββββββββββ΄βββββββ΄βββββββ΄βββββββ΄βββββββββ΄βββββββ
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β RECENT TRADES β
β β [Scrollable list of recent closed trades] β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
See SUBSCRIPTION_SYSTEM.md for detailed specification.
FREE_TIER = {
'name': 'Free',
'price_monthly': 0,
'price_yearly': 0,
'features': [
'Paper trading only',
'Basic strategy (APEX V7.2)',
'1 exchange connection',
'Community support',
'Basic analytics'
],
'limits': {
'max_position_size_usd': 0, # Paper only
'max_positions': 3,
'max_daily_trades': 10,
'api_calls_per_minute': 10
}
}
BASIC_TIER = {
'name': 'Basic',
'price_monthly': 49,
'price_yearly': 470, # ~20% discount
'features': [
'Live trading',
'APEX V7.2 strategy',
'2 exchange connections',
'Email support',
'Standard analytics',
'Mobile app access'
],
'limits': {
'max_position_size_usd': 500,
'max_positions': 5,
'max_daily_trades': 30,
'api_calls_per_minute': 30
}
}
PRO_TIER = {
'name': 'Pro',
'price_monthly': 149,
'price_yearly': 1430, # ~20% discount
'features': [
'All Basic features',
'Meta-AI optimization',
'MMIN multi-market intelligence',
'5 exchange connections',
'Priority support',
'Advanced analytics',
'Custom risk profiles',
'TradingView integration'
],
'limits': {
'max_position_size_usd': 2000,
'max_positions': 10,
'max_daily_trades': 100,
'api_calls_per_minute': 100
}
}
ENTERPRISE_TIER = {
'name': 'Enterprise',
'price_monthly': 499,
'price_yearly': 4790, # ~20% discount
'features': [
'All Pro features',
'GMIG macro intelligence',
'Unlimited exchanges',
'Dedicated support',
'Custom strategy tuning',
'API access',
'White-label option',
'Multi-account management'
],
'limits': {
'max_position_size_usd': 10000,
'max_positions': 50,
'max_daily_trades': 500,
'api_calls_per_minute': 500
}
}
User Registration
β
14-Day Free Trial (Pro features)
β
Trial Expiration
β
ββββββββ΄βββββββ
β β
Choose Tier β
β Downgrade to Free
Enter Payment (Stripe)
β
Active Subscription
β
Usage Tracking
β
Monthly/Yearly Renewal
from monetization_engine import SubscriptionEngine
import stripe
stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
sub_engine = SubscriptionEngine()
# Create subscription
subscription = sub_engine.create_subscription(
user_id="user_123",
tier="pro",
interval="monthly",
payment_method_id="pm_123"
)
# Handle webhook events
@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
event = stripe.Webhook.construct_event(
payload=await request.body(),
sig_header=request.headers.get('stripe-signature'),
secret=os.getenv('STRIPE_WEBHOOK_SECRET')
)
if event['type'] == 'invoice.payment_succeeded':
# Activate subscription
sub_engine.activate_subscription(event['data']['object'])
elif event['type'] == 'invoice.payment_failed':
# Suspend account
sub_engine.suspend_subscription(event['data']['object'])
return {'status': 'success'}
See SCALING_BLUEPRINT.md for detailed scaling strategy.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Load Balancer (Nginx/HAProxy) β
β SSL Termination β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β β β
βββββββββΌββββ ββββββΌββββββ ββββΌββββββββ
β API Pod β β API Pod β β API Pod β
β Instance β β Instance β β Instance β
β 1 β β 2 β β 3 β
βββββββββ¬ββββ ββββββ¬ββββββ ββββ¬ββββββββ
β β β
ββββββββββββββΌβββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β β β
βββββββββΌββββ ββββββΌββββββ ββββΌββββββββ
β Trading β β Trading β β Trading β
β Engine β β Engine β β Engine β
β Worker 1 β β Worker 2 β β Worker 3 β
βββββββββββββ ββββββββββββ ββββββββββββ
Compute Resources:
Auto-scaling Triggers:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Cache Layers β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Level 1: Browser Cache
- Static assets (JS, CSS, images)
- Cache duration: 7 days
Level 2: CDN Cache (Cloudflare)
- API responses (GET only)
- User settings
- Cache duration: 5 minutes
Level 3: Redis Cache
- User sessions (JWT tokens)
- Active positions
- Market data
- Cache duration: 30 seconds - 5 minutes
Level 4: Database Query Cache
- PostgreSQL query cache
- Recent trade history
- User statistics
# Round-robin for API requests
api_instances = [
'api-1.nija.com',
'api-2.nija.com',
'api-3.nija.com'
]
# Least-connections for WebSocket
websocket_instances = [
'ws-1.nija.com',
'ws-2.nija.com'
]
# User-based sharding for trading engines
def get_trading_engine(user_id: str) -> str:
shard = hash(user_id) % NUM_TRADING_ENGINES
return f'trading-engine-{shard}'
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Global Distribution β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Primary Region: US-East (Virginia)
- API Gateway
- Trading Engines
- Database (Master)
Secondary Region: US-West (Oregon)
- API Gateway (failover)
- Database (Read Replica)
Tertiary Region: EU-West (Ireland)
- API Gateway (EU users)
- Database (Read Replica)
Edge Locations (Cloudflare CDN):
- 200+ locations worldwide
- Static asset delivery
- DDoS protection
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Performance SLAs β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
API Response Time:
- p50: < 100ms
- p95: < 300ms
- p99: < 500ms
WebSocket Latency:
- Trade notifications: < 50ms
- Position updates: < 100ms
Database Queries:
- Simple reads: < 10ms
- Complex aggregations: < 100ms
Trade Execution:
- Signal to order: < 500ms
- Order confirmation: < 2s (depends on exchange)
Uptime:
- Target: 99.9% (8.7 hours downtime/year)
- Monitoring: 24/7 automated alerts
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Security Layers β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Layer 1: Network Security
- DDoS protection (Cloudflare)
- WAF (Web Application Firewall)
- IP whitelisting for admin endpoints
- Rate limiting (tier-based)
Layer 2: Authentication & Authorization
- JWT tokens (HS256 signing)
- Refresh token rotation
- Role-based access control (RBAC)
- Multi-factor authentication (optional)
Layer 3: Application Security
- Input validation (Pydantic)
- SQL injection prevention (SQLAlchemy ORM)
- XSS protection (React escaping)
- CSRF tokens for state-changing operations
Layer 4: Data Security
- Encryption at rest (AES-256)
- Encryption in transit (TLS 1.3)
- API key encryption (Fernet)
- Secure credential storage (HashiCorp Vault)
Layer 5: Audit & Monitoring
- Comprehensive audit logging
- Anomaly detection
- Security alerts (Slack, PagerDuty)
- Regular security audits
# API Key Encryption (Fernet)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt API key
encrypted_key = cipher.encrypt(api_key.encode())
# Decrypt API key
decrypted_key = cipher.decrypt(encrypted_key).decode()
# Database Encryption (at rest)
# PostgreSQL: pgcrypto extension
# Redis: redis-encryption module
# TLS/SSL (in transit)
# All HTTPS traffic uses TLS 1.3
# Certificate management: Let's Encrypt
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
# Tier-based rate limits
@app.get("/api/v1/account/balance")
@limiter.limit("30/minute") # Basic tier
async def get_balance(request: Request):
# Check user tier
tier = get_user_tier(request)
if tier == "pro":
# 100/minute for Pro
pass
elif tier == "enterprise":
# 500/minute for Enterprise
pass
return {"balance": 10000.0}
# Local development with Docker Compose
docker-compose up -d
# Services:
# - PostgreSQL (localhost:5432)
# - Redis (localhost:6379)
# - API Gateway (localhost:8000)
# - Dashboard (localhost:3000)
# Hot reload enabled for development
# Kubernetes cluster on Railway/Render
kubectl apply -f k8s/staging/
# Features:
# - Mirrors production architecture
# - Uses separate database
# - Automated testing
# - Preview deployments for PRs
# Kubernetes cluster on AWS EKS / GCP GKE
kubectl apply -f k8s/production/
# Features:
# - Multi-region deployment
# - Auto-scaling
# - Load balancing
# - Monitoring & alerting
# - Automated backups
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CI/CD Workflow β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Code Push (GitHub)
β
Automated Tests (GitHub Actions)
- Unit tests
- Integration tests
- Security scans (CodeQL)
β
Build Docker Images
β
Push to Container Registry
β
Deploy to Staging
β
Automated E2E Tests
β
Manual Approval
β
Blue-Green Deployment to Production
β
Health Checks
β
Rollback if Failed
# Example deployment manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: nija-api-gateway
spec:
replicas: 3
selector:
matchLabels:
app: nija-api-gateway
template:
metadata:
labels:
app: nija-api-gateway
spec:
containers:
- name: api
image: nija/api-gateway:v2.0
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: nija-secrets
key: database-url
resources:
requests:
memory: "2Gi"
cpu: "1"
limits:
memory: "4Gi"
cpu: "2"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 5
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Monitoring Stack β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Prometheus
- Metrics collection (15s intervals)
- Time-series database
- Alerting rules
Grafana
- Dashboard visualization
- Multi-source aggregation
- Custom alerts
ELK Stack (Elasticsearch, Logstash, Kibana)
- Centralized logging
- Log aggregation
- Search & analytics
Jaeger / OpenTelemetry
- Distributed tracing
- Request flow visualization
- Performance profiling
# Application Metrics
app_requests_total = Counter('app_requests_total', 'Total requests')
app_request_duration = Histogram('app_request_duration_seconds', 'Request duration')
app_errors_total = Counter('app_errors_total', 'Total errors')
# Trading Metrics
trades_executed_total = Counter('trades_executed_total', 'Total trades')
trade_pnl = Gauge('trade_pnl_usd', 'Current P&L')
positions_active = Gauge('positions_active', 'Active positions')
# System Metrics
cpu_usage = Gauge('cpu_usage_percent', 'CPU usage')
memory_usage = Gauge('memory_usage_bytes', 'Memory usage')
db_connections = Gauge('db_connections', 'Database connections')
# Prometheus alerting rules
groups:
- name: nija_alerts
rules:
# High error rate
- alert: HighErrorRate
expr: rate(app_errors_total[5m]) > 0.05
for: 5m
labels:
severity: warning
annotations:
summary: "High error rate detected"
# API latency
- alert: HighLatency
expr: histogram_quantile(0.95, app_request_duration_seconds) > 0.5
for: 5m
labels:
severity: warning
# Database connections
- alert: DatabaseConnectionsHigh
expr: db_connections > 80
for: 5m
labels:
severity: critical
# Trading stopped
- alert: TradingStopped
expr: rate(trades_executed_total[15m]) == 0
for: 15m
labels:
severity: warning
import logging
import structlog
# Structured logging
logger = structlog.get_logger()
logger.info(
"trade_executed",
user_id="user_123",
symbol="BTC-USD",
side="buy",
size_usd=100.0,
price=43210.50,
trade_id="trade_456"
)
# Log levels:
# - DEBUG: Detailed debugging information
# - INFO: General informational messages
# - WARNING: Warning messages (potential issues)
# - ERROR: Error messages (failures)
# - CRITICAL: Critical issues (system failures)
β Secure Multi-User Platform
β Scalable Infrastructure
β Advanced Trading System
β SaaS Monetization
β Comprehensive Monitoring
Phase 1: Foundation (Weeks 1-2)
Phase 2: Core Services (Weeks 3-4)
Phase 3: Frontend (Weeks 5-6)
Phase 4: Testing & Security (Weeks 7-8)
Phase 5: Launch (Week 9)
Platform Architecture Documents (This PR):
Existing Documentation:
Planned Documentation:
Version: 2.0 Last Updated: January 29, 2026 Status: β Production-Ready Architecture Maintained By: NIJA Engineering Team