ALPHX Quantitative Engine is an institutional-grade algorithmic trading backend built in Python with FastAPI. It computes multi-timeframe technical indicators, detects algorithmic price action patterns (Support/Resistance, Fair Value Gaps), executes machine learning ensemble predictions (XGBoost, LightGBM, Deep LSTM), manages mathematical risk and dynamic ATR-based trade setups, and delivers high-frequency trade execution on CoinDCX (Futures, Margin, Spot) with native dual-currency (USDT $ & INR βΉ) precision.
- Architecture Overview
- Mathematical Formulas & Technical Indicators
- Quantitative Signal & ML Ensemble Engine
- Risk Management & Dynamic Position Sizing
- Dual-Currency (USD $ & INR βΉ) Engine
- Exchange Interoperability (CoinDCX & Paper Trading)
- Automated Telegram Broadcasting Sentinel
- Project Structure
- Installation & Setup Guide
- API Reference
- License
ββββββββββββββββββββββββββ
β Market Data Feeds β
β (CoinDCX / WebSockets) β
βββββββββββββ¬βββββββββββββ
β Candles & OrderBook
βΌ
ββββββββββββββββββββββββββ
β Indicator Engine β
β (EMAs, RSI, MACD, ATR) β
βββββββββββββ¬βββββββββββββ
β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β Price Action Engine β β Feature Transformer β
β (S&R, FVG, Pinbar/Doji) β β (30+ Normalized Feats) β
ββββββββββββββ¬βββββββββββββ ββββββββββββββ¬βββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β 6-Factor Quant Scorer β β ML Ensemble Predictor β
β Trend, Mom, Vol, OB, PA β β XGBoost, LightGBM, LSTM β
ββββββββββββββ¬βββββββββββββ ββββββββββββββ¬βββββββββββββ
β β
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β Consensus & Confidence
βΌ
ββββββββββββββββββββββββββ
β Risk Management & β
β Dynamic Position Sizer β
βββββββββββββ¬βββββββββββββ
β Dual-Currency Sized Orders
ββββββββββββββββββββββββ΄βββββββββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β CoinDCX Execution β β Telegram Signal Bot β
β (Futures, Margin, Spot) β β (Broadcasts to Channel) β
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
The engine computes technical features over candle streams with zero data leakage using vectorized calculations:
- Computed spans:
$N \in {9, 21, 50, 100, 200}$ . - Bullish Alignment:
$EMA_9 > EMA_{21} > EMA_{50} > EMA_{200}$ .
- Oversold bounce trigger:
$RSI < 32$ . Overbought exhaustion trigger:$RSI > 68$ .
- Squeeze Detection: Occurs when Bollinger Bands contract entirely inside Keltner Channels (
$KC = SMA_{20} \pm 1.5 \cdot ATR_{14}$ ), indicating explosive directional expansion is imminent.
-
Bullish FVG: Identified when
$Low_{t} > High_{t-2}$ , creating an unfilled liquidity imbalance gap. -
Bearish FVG: Identified when
$High_{t} < Low_{t-2}$ . -
Support & Resistance: Pivot detection via relative extrema (
$\text{order}=15$ ), clustered dynamically within a$0.5%$ price variance tolerance.
The rule engine aggregates 6 uncorrelated analytical dimensions into a unified score
-
Long Directive (BUY):
$S_{\text{composite}} \ge +0.18$ -
Short Directive (SELL):
$S_{\text{composite}} \le -0.18$ -
Neutral (HOLD):
$-0.18 < S_{\text{composite}} < +0.18$
The backend deploys an ensemble of 3 distinct architectures:
-
XGBoost Classifier (
$w_1 = 0.40$ ): Extreme gradient boosted decision trees capturing non-linear tabular interactions across technical oscillators. -
LightGBM Classifier (
$w_2 = 0.30$ ): Leaf-wise gradient boosting optimized for rapid inference across statistical price distributions. -
Deep LSTM Network (
$w_3 = 0.30$ ): Multi-layer Long Short-Term Memory recurrent neural network processing sequential 30-candle window embeddings.
- UNANIMOUS Agreement: All 3 models agree on the directional verdict.
- MAJORITY Agreement: 2 of 3 models agree.
- SPLIT: Conflicting signals trigger automatic hold/risk mitigation.
Position sizing limits capital exposure to a strict percentage (default
Stop loss and target levels adapt dynamically to real-time market volatility:
| Directive | Stop Loss (SL) | Target 1 (TP1) | Target 2 (TP2) | Target 3 (TP3) |
|---|---|---|---|---|
| BUY / LONG | ||||
| SELL / SHORT | ||||
| Risk:Reward | 1.0x (Baseline) | 1:1.33 | 1:2.0 | 1:3.0 |
To prevent "Invalid quantity" rejections on live exchanges, quantities are strictly step-quantized:
-
BTC: Min
$0.001$ , Step$0.001$ (3 decimal places) -
ETH: Min
$0.01$ , Step$0.01$ (2 decimal places) -
SOL / BNB: Min
$0.1$ , Step$0.1$ (1 decimal place) -
DOGE / XRP / ADA / TRX / MATIC: Min
$1.0$ , Step$1.0$ (0 decimal places) -
PEPE / SHIB / BONK: Min
$10000.0$ , Step$1000.0$ (0 decimal places)
To support Indian cryptocurrency traders seamlessly, the engine natively handles cross-currency conversions:
-
Live Exchange Rate Provider: Continuously synchronizes USD/INR rates (fallback
$99.95$ ). -
Unified Capital Aggregation:
$$Capital_{\text{USDT}} = Balance_{\text{USDT}} + \left(\frac{Balance_{\text{INR}}}{Rate_{\text{USD/INR}}}\right)$$ $$Capital_{\text{INR}} = \left(Balance_{\text{USDT}} \times Rate_{\text{USD/INR}}\right) + Balance_{\text{INR}}$$ - Zero-Balance Safety: Automatically provisions paper test capital ($1,000 USDT / βΉ1,00,000 INR) so unverified or test accounts never trigger execution crashes.
The adapter layer standardizes all interactions across spot, margin, and derivatives:
- CoinDCX Futures: Authenticated HMAC-SHA256 signature signing with millisecond epoch timestamps, targeting
/exchange/v1/derivatives/futures/orders/create. - CoinDCX Spot & Margin: Direct market creation (
BTCUSDT), automated leverage application, and position tracking. - Paper Trading Sandbox: High-fidelity local order matching with real-time balance deductions, PnL tracking, and liquidation price estimation.
The integrated Telegram service (@alphx_signal_bot) provides automated and manual signal delivery:
-
Auto-Broadcast Engine: Automatically pushes institutional trade signals when confidence exceeds the threshold (
$\ge 70%$ ). - Anti-Flood Deduplication: Enforces a 3-minute cooldown window per asset to prevent spamming channels during consolidation.
- Interactive Telegram Buttons: Includes deep-link inline action buttons for 1-click execution.
AI_singal_Backend/
βββ app/
β βββ api/
β β βββ routes/
β β β βββ analyze.py # Technical & ML analysis route
β β β βββ trade.py # Order execution & dual-currency risk sizing
β β β βββ markets.py # CoinDCX screener & market details
β β β βββ telegram.py # Telegram bot auto-detection & dispatch
β β β βββ webhook.py # TradingView & CoinDCX inbound webhook listener
β β β βββ ws.py # WebSocket streaming gateway
β β βββ schemas.py # Pydantic data schemas & request validators
β βββ core/
β β βββ indicator_engine.py # Vectorized technical indicator library
β β βββ signal_generator.py # 6-dimension quantitative scoring engine
β β βββ risk_manager.py # Position sizing & dynamic ATR levels
β β βββ price_action.py # Support/Resistance, FVG, & candlestick patterns
β β βββ currency.py # USD/INR real-time currency conversion
β β βββ telegram_service.py # Async Telegram Bot broadcast service
β βββ exchanges/
β β βββ base.py # Abstract exchange interface & data classes
β β βββ coindcx/
β β βββ adapter.py # Main CoinDCX unified exchange adapter
β β βββ auth.py # HMAC-SHA256 request signer
β β βββ constants.py # CoinDCX API endpoint mapping
β β βββ futures.py # Derivatives futures order executor
β β βββ spot.py # Spot market trading operations
β β βββ margin.py # Margin trading operations
β β βββ market_data.py # Ticker, candles, orderbook, & trade cache
β β βββ websocket.py # Live stream client
β βββ ml/
β β βββ ensemble.py # XGBoost + LightGBM + LSTM consensus
β β βββ feature_builder.py # 30+ numerical feature transformer
β β βββ models/ # Model wrappers
β β βββ pretrained/ # Model weights and pipeline configurations
β βββ config.py # Global settings via Pydantic BaseSettings
β βββ main.py # FastAPI application entrypoint & middleware
βββ .env.example # Environment variable template
βββ requirements.txt # Production Python dependencies
βββ README.md
- Python 3.12+
- Virtual environment tool (
venvoruv) - CoinDCX API Key & Secret (optional for Paper Trading mode)
- Telegram Bot Token from @BotFather (for Telegram broadcasting)
git clone https://github.com/your-username/AI_singal_Backend.git
cd AI_singal_Backendpython3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activatepip install --upgrade pip
pip install -r requirements.txtCopy the template and fill in your details:
cp .env.example .envEdit .env:
DEBUG=true
PORT=8000
# CoinDCX API Credentials (Leave as 'demo' for Paper Trading)
COINDCX_API_KEY=your_coindcx_api_key_here
COINDCX_API_SECRET=your_coindcx_api_secret_here
# Risk Parameters
DEFAULT_LEVERAGE=3.0
MAX_RISK_PER_TRADE=0.02
MIN_CONFIDENCE=0.70
# Telegram Bot Integration
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
TELEGRAM_CHAT_ID=your_channel_or_group_id_here
TELEGRAM_AUTO_SEND=false
TELEGRAM_MIN_CONFIDENCE=0.70
# Inbound Webhook Security
WEBHOOK_SECRET_KEY=your_secure_webhook_secret_key_hereuvicorn app.main:app --host 0.0.0.0 --port 8000 --reloadOnce started, interactive API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
GET /api/analyze?symbol=B-BTC_USDT&timeframe=15m- Computes technical indicators, price action setups, ML ensemble predictions, and ATR levels.
POST /api/trade/execute- Executes a trade with automated risk management or custom capital in USD or INR.
POST /api/trade/close- Closes an active position on CoinDCX or Paper Trading.
GET /api/exchange/balances?exchange=coindcx- Retrieves live balances across USDT, INR, and crypto assets.
GET /api/exchange/positions?exchange=coindcx- Returns active positions with mark price, liquidation price, and unrealized PnL.
GET /api/telegram/detect- Discovers recently joined Telegram channels and groups.
POST /api/telegram/send- Manually triggers a broadcast of the current signal.
POST /api/telegram/test- Sends an instant connectivity ping to the configured channel.
This project is licensed under the MIT License β see the LICENSE file for details.