Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """Webhook receiver for trading signals (e.g., TradingView alerts).""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import logging |
| 6 | from dataclasses import dataclass |
| 7 | from datetime import datetime |
| 8 | from enum import Enum |
| 9 | from typing import Any |
| 10 | |
| 11 | logger = logging.getLogger(__name__) |
| 12 | |
| 13 | |
| 14 | class SignalType(Enum): |
| 15 | """Types of trading signals.""" |
| 16 | |
| 17 | BUY = "buy" |
| 18 | SELL = "sell" |
| 19 | CLOSE = "close" |
| 20 | |
| 21 | |
| 22 | @dataclass |
| 23 | class TradingSignal: |
| 24 | """Represents a trading signal received from external source.""" |
| 25 | |
| 26 | symbol: str |
| 27 | signal_type: SignalType |
| 28 | price: float | None = None |
| 29 | timestamp: datetime | None = None |
| 30 | strength: float | None = None # Signal strength 0-1 |
| 31 | stop_loss: float | None = None |
| 32 | take_profit: float | None = None |
| 33 | comment: str | None = None |
| 34 | raw_data: dict[str, Any] | None = None |
| 35 | |
| 36 | |
| 37 | class SignalReceiver: |
| 38 | """Base class for signal receivers.""" |
| 39 | |
| 40 | def parse_signal(self, raw_data: dict[str, Any]) -> TradingSignal | None: |
| 41 | """Parse raw data into a TradingSignal. |
| 42 | |
| 43 | Args: |
| 44 | raw_data: Raw data received from external source. |
| 45 | |
| 46 | Returns: |
| 47 | TradingSignal or None if parsing failed. |
| 48 | """ |
| 49 | raise NotImplementedError |
| 50 | |
| 51 | |
| 52 | def _opt_float(raw_data: dict[str, Any], key: str) -> float | None: |
| 53 | """Return float(raw_data[key]) or None when the key is missing/null.""" |
| 54 | value = raw_data.get(key) |
| 55 | if value is None: |
| 56 | return None |
| 57 | try: |
| 58 | return float(value) |
| 59 | except (TypeError, ValueError): |
| 60 | logger.warning("Could not parse numeric field %s: %r", key, value) |
| 61 | return None |
| 62 | |
| 63 | |
| 64 | def _opt_str(raw_data: dict[str, Any], key: str) -> str | None: |
| 65 | """Return str(raw_data[key]) or None when the key is missing/null.""" |
| 66 | value = raw_data.get(key) |
| 67 | if value is None: |
| 68 | return None |
| 69 | return str(value) |
| 70 | |
| 71 | |
| 72 | class TradingViewSignalReceiver(SignalReceiver): |
| 73 | """Receiver for TradingView webhook alerts.""" |
| 74 | |
| 75 | def __init__(self, secret: str | None = None) -> None: |
| 76 | """Initialize TradingView signal receiver. |
| 77 | |
| 78 | Args: |
| 79 | secret: Optional secret for validating requests. |
| 80 | """ |
| 81 | self.secret = secret |
| 82 | |
| 83 | def parse_signal(self, raw_data: dict[str, Any]) -> TradingSignal | None: |
| 84 | """Parse TradingView webhook alert into TradingSignal. |
| 85 | |
| 86 | Expected TradingView alert format: |
| 87 | { |
| 88 | "symbol": "AAPL", |
| 89 | "action": "buy", |
| 90 | "price": 150.00, |
| 91 | "time": "2023-01-01T10:30:00Z", |
| 92 | "strength": 0.8, |
| 93 | "stop_loss": 145.00, |
| 94 | "take_profit": 160.00, |
| 95 | "comment": "My strategy signal" |
| 96 | } |
| 97 | |
| 98 | Args: |
| 99 | raw_data: Raw webhook data from TradingView. |
| 100 | |
| 101 | Returns: |
| 102 | TradingSignal or None if parsing failed. |
| 103 | """ |
| 104 | try: |
| 105 | # Validate required fields |
| 106 | if "symbol" not in raw_data or "action" not in raw_data: |
| 107 | logger.warning("Missing required fields in TradingView signal") |
| 108 | return None |
| 109 | |
| 110 | symbol = str(raw_data["symbol"]).upper() |
| 111 | action = str(raw_data["action"]).lower() |
| 112 | |
| 113 | # Map action to signal type |
| 114 | if action in ["buy", "long"]: |
| 115 | signal_type = SignalType.BUY |
| 116 | elif action in ["sell", "short"]: |
| 117 | signal_type = SignalType.SELL |
| 118 | elif action in ["close", "exit"]: |
| 119 | signal_type = SignalType.CLOSE |
| 120 | else: |
| 121 | logger.warning("Unknown action in TradingView signal: %s", action) |
| 122 | return None |
| 123 | |
| 124 | # Parse timestamp |
| 125 | timestamp: datetime | None = None |
| 126 | raw_time = raw_data.get("time") |
| 127 | if raw_time is not None: |
| 128 | try: |
| 129 | timestamp = datetime.fromisoformat(str(raw_time).replace("Z", "+00:00")) |
| 130 | except ValueError: |
| 131 | logger.warning("Could not parse timestamp: %s", raw_time) |
| 132 | timestamp = datetime.now() |
| 133 | else: |
| 134 | timestamp = datetime.now() |
| 135 | |
| 136 | return TradingSignal( |
| 137 | symbol=symbol, |
| 138 | signal_type=signal_type, |
| 139 | price=_opt_float(raw_data, "price"), |
| 140 | timestamp=timestamp, |
| 141 | strength=_opt_float(raw_data, "strength"), |
| 142 | stop_loss=_opt_float(raw_data, "stop_loss"), |
| 143 | take_profit=_opt_float(raw_data, "take_profit"), |
| 144 | comment=_opt_str(raw_data, "comment"), |
| 145 | raw_data=raw_data, |
| 146 | ) |
| 147 | |
| 148 | except Exception as exc: |
| 149 | logger.error("Error parsing TradingView signal: %s", exc) |
| 150 | return None |
| 151 | |
| 152 | |
| 153 | # Simple HTTP server for receiving webhooks (optional) |
| 154 | def create_webhook_app(receiver: SignalReceiver, host: str = "0.0.0.0", port: int = 5000) -> Any: |
| 155 | """Create a simple Flask app for receiving webhook signals. |
| 156 | |
| 157 | Args: |
| 158 | receiver: SignalReceiver instance to use for parsing. |
| 159 | host: Host to bind to (used by callers running the app). |
| 160 | port: Port to bind to (used by callers running the app). |
| 161 | |
| 162 | Returns: |
| 163 | Flask app instance, or None when Flask is not installed. |
| 164 | """ |
| 165 | try: |
| 166 | from flask import Flask, jsonify, request |
| 167 | |
| 168 | app = Flask(__name__) |
| 169 | |
| 170 | @app.route("/webhook", methods=["POST"]) # type: ignore[untyped-decorator] |
| 171 | def webhook() -> Any: |
| 172 | if not request.is_json: |
| 173 | return jsonify({"error": "Expected JSON"}), 400 |
| 174 | |
| 175 | data = request.get_json() |
| 176 | signal = receiver.parse_signal(data) |
| 177 | |
| 178 | if signal is None: |
| 179 | return jsonify({"error": "Failed to parse signal"}), 400 |
| 180 | |
| 181 | logger.info("Received signal: %s", signal) |
| 182 | return jsonify({"status": "received", "signal": signal.__dict__}), 200 |
| 183 | |
| 184 | @app.route("/health", methods=["GET"]) # type: ignore[untyped-decorator] |
| 185 | def health() -> Any: |
| 186 | return jsonify({"status": "healthy"}), 200 |
| 187 | |
| 188 | return app |
| 189 | |
| 190 | except ImportError: |
| 191 | logger.warning("Flask not installed. Webhook server not available.") |
| 192 | return None |