aalienau-cmyk
Apply all bug fixes from BUGFIX_AUFTRAG.md, implement dashboard enhancements (trade history, equity curve, stats, events), fix screener double calculation, update AI provider to Ollama with Nemotron-3-Super, and include all changes from previous session
ba0fd74 Download ai/validator.py from Agueli/trading-bot: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/Agueli/trading-bot/resolve/main/ai/validator.py
- Command line
-
hf download hf://Agueli/trading-bot/ai/validator.py
-
curl -L -o validator.py https://huggingface.co/Agueli/trading-bot/resolve/main/ai/validator.py
5.18 kB
| """ | |
| validator.py — Backend-Validation für KI-Entscheidungen. | |
| Wird NACH der KI, VOR dem Paper-Trade ausgeführt. | |
| Härtet Filter — auch wenn KI "BUY" sagt, kann der Validator blockieren. | |
| """ | |
| import logging | |
| import config | |
| logger = logging.getLogger(__name__) | |
| def validate_entry_decision(decision: dict, current_price: float) -> tuple[bool, str]: | |
| """ | |
| Validiert KI Entry-Entscheidung. | |
| Args: | |
| decision: KI-Output Dict | |
| current_price: Aktueller Preis | |
| Returns: | |
| Tuple von (is_valid, reason) | |
| """ | |
| # Entscheidung muss BUY sein | |
| if decision.get("decision") != "BUY": | |
| return False, f"NOT_BUY: {decision.get('decision')}" | |
| # Confidence Check | |
| confidence = decision.get("confidence", 0) | |
| if confidence < config.ENTRY_MIN_CONFIDENCE: | |
| return False, f"CONFIDENCE_TOO_LOW: {confidence} < {config.ENTRY_MIN_CONFIDENCE}" | |
| # Stop Loss muss unter Entry sein | |
| entry_price = decision.get("entry_price", current_price) | |
| stop_loss = decision.get("stop_loss", 0) | |
| if stop_loss <= 0: | |
| return False, "INVALID_STOP_LOSS: Kein Stop Loss gesetzt" | |
| if stop_loss >= entry_price: | |
| return False, f"STOP_ABOVE_ENTRY: SL={stop_loss} >= Entry={entry_price}" | |
| # Risk-Reward Check | |
| sl_distance = entry_price - stop_loss | |
| tp1 = decision.get("take_profit_1", 0) | |
| tp2 = decision.get("take_profit_2", 0) | |
| # TP1 muss > entry sein | |
| tp1_distance = tp1 - entry_price | |
| if tp1 <= 0 or tp1_distance <= 0: | |
| return False, "INVALID_TAKE_PROFIT_1" | |
| # TP2 muss > TP1 sein (falls vorhanden) | |
| if tp2 is not None and tp2 > 0 and tp2 <= tp1: | |
| return False, f"TP2_MUST_BE_ABOVE_TP1: TP2={tp2} <= TP1={tp1}" | |
| if sl_distance <= 0: | |
| return False, "INVALID_SL_DISTANCE" | |
| rr_ratio = tp1_distance / sl_distance | |
| if rr_ratio < config.ENTRY_MIN_RR: | |
| return False, f"RR_TOO_LOW: {rr_ratio:.2f} < {config.ENTRY_MIN_RR}" | |
| # Position Size Check | |
| position_size = decision.get("position_size_usd", 0) | |
| if position_size <= 0: | |
| return False, "INVALID_POSITION_SIZE" | |
| max_size = config.PORTFOLIO_VALUE_USD * 0.10 | |
| if position_size > max_size: | |
| return False, f"POSITION_TOO_LARGE: {position_size} > {max_size}" | |
| logger.info( | |
| f"Entry validiert: {decision.get('symbol', '?')} | " | |
| f"Confidence: {confidence} | R:R: {rr_ratio:.2f}" | |
| ) | |
| return True, "OK" | |
| def validate_exit_decision( | |
| decision: dict, current_price: float, current_trailing_stop: float | None, hold_count: int | |
| ) -> str: | |
| """ | |
| Validiert KI Exit-Entscheidung. | |
| Args: | |
| decision: KI-Output Dict | |
| current_price: Aktueller Preis | |
| current_trailing_stop: Aktueller Trailing Stop (oder None) | |
| hold_count: Anzahl HOLD-Entscheidungen in Folge | |
| Returns: | |
| "SELL" oder "HOLD" | |
| """ | |
| # Zwangsverkauf nach 3x HOLD | |
| if hold_count >= config.MAX_HOLD_COUNT: | |
| logger.info(f"Exit: Zwangsverkauf nach {hold_count}x HOLD") | |
| return "SELL" | |
| # Confidence zu niedrig → SELL | |
| confidence = decision.get("confidence", 0) | |
| if confidence < config.EXIT_MIN_CONFIDENCE: | |
| logger.info(f"Exit: Confidence {confidence} < {config.EXIT_MIN_CONFIDENCE} → SELL") | |
| return "SELL" | |
| # Trailing Stop Validierung | |
| new_stop = decision.get("new_trailing_stop_usd") | |
| if new_stop is not None: | |
| # Neuer Stop darf nicht über aktuellem Preis liegen | |
| if new_stop >= current_price: | |
| logger.warning( | |
| f"Exit: Neuer Trailing Stop {new_stop} >= Preis {current_price} → ignoriert" | |
| ) | |
| decision["new_trailing_stop_usd"] = None | |
| # Neuer Stop darf nicht schlechter als aktueller | |
| elif current_trailing_stop and new_stop < current_trailing_stop: | |
| logger.warning( | |
| f"Exit: Neuer Trailing Stop {new_stop} < aktueller {current_trailing_stop} → ignoriert" | |
| ) | |
| decision["new_trailing_stop_usd"] = None | |
| return str(decision.get("decision", "HOLD")) | |
| def calculate_position_size(entry_price: float, stop_loss: float) -> float: | |
| """ | |
| Berechnet Positionsgröße basierend auf Risikoprozentsatz. | |
| Formel: | |
| risk_amount = portfolio_value * (risk_per_trade_pct / 100) | |
| position_size = risk_amount / sl_distance | |
| capped = min(position_size * entry_price, portfolio_value * 0.10) | |
| Args: | |
| entry_price: Einstiegspreis | |
| stop_loss: Stop Loss Preis | |
| Returns: | |
| Positionsgröße in USD | |
| """ | |
| if entry_price <= 0 or stop_loss <= 0: | |
| return 0.0 | |
| sl_distance = entry_price - stop_loss | |
| if sl_distance <= 0: | |
| return 0.0 | |
| risk_amount = config.PORTFOLIO_VALUE_USD * (config.RISK_PER_TRADE_PCT / 100) | |
| position_size = risk_amount / sl_distance | |
| position_value = position_size * entry_price | |
| # Cap bei 10% des Portfolios | |
| max_value = config.PORTFOLIO_VALUE_USD * 0.10 | |
| final_value = min(position_value, max_value) | |
| logger.info( | |
| f"Positionsgröße: ${final_value:.2f} " | |
| f"(Risk: ${risk_amount:.2f}, SL Distance: ${sl_distance:.4f})" | |
| ) | |
| return round(final_value, 2) | |