From ced986d3dd4ebe602bf85803f521114d1876b4c1 Mon Sep 17 00:00:00 2001 From: Marc Blatter Date: Fri, 24 Jul 2026 16:24:32 +0200 Subject: [PATCH] v0.5: Bollinger Bands entry signals (60%+ Win-Rate target) - Replace RSI+Support --- src/main_ml.py | 137 +++++++++++++++++++------------------------------ 1 file changed, 53 insertions(+), 84 deletions(-) diff --git a/src/main_ml.py b/src/main_ml.py index 4a8d6e0..df3f7b5 100644 --- a/src/main_ml.py +++ b/src/main_ml.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Trading Bot v0.4.2 - Win-Rate Optimization (RSI + Support Detection)""" +"""Trading Bot v0.5 - Bollinger Bands Entry Signals (60%+ Win-Rate target)""" import os, json, time, logging, sqlite3 from datetime import datetime from dotenv import load_dotenv @@ -23,15 +23,13 @@ MAX_POSITION_PCT = 0.07 TAKE_PROFIT_PCT = 0.015 STOP_LOSS_PCT = -0.008 CYCLE_SEC = 60 -RSI_PERIOD = 14 -RSI_OVERSOLD = 30 -RSI_OVERBOUGHT = 70 +BB_PERIOD = 20 +BB_STD_DEV = 2.0 -class TradingBotV042: +class TradingBotV05: def __init__(self): self.client = Client(API_KEY, API_SECRET) self.price_history = {sym: [] for sym in SYMBOLS} - self.rsi_values = {sym: [] for sym in SYMBOLS} self.active_trades = {} self.portfolio_value = 0 self.max_trade_usdt = 0 @@ -59,26 +57,51 @@ class TradingBotV042: except Exception as e: logger.warning(f"Recovery failed: {e}") - logger.info("[v0.4.2 INIT] RSI + Support-based Entry Signals (55%+ Win-Rate target)") + logger.info("[v0.5 INIT] Bollinger Bands Entry Signals (60%+ WR target)") - def calculate_rsi(self, prices): - """Calculate RSI from price list""" - if len(prices) < RSI_PERIOD + 1: - return None + def calculate_bollinger_bands(self, prices): + """Calculate 20-EMA +/- 2*StdDev""" + if len(prices) < BB_PERIOD: + return None, None, None - deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))] - gains = [d if d > 0 else 0 for d in deltas[-RSI_PERIOD:]] - losses = [abs(d) if d < 0 else 0 for d in deltas[-RSI_PERIOD:]] + # EMA-20 + ema = prices[-1] + alpha = 2.0 / (BB_PERIOD + 1) + for price in prices[-BB_PERIOD:]: + ema = (price * alpha) + (ema * (1 - alpha)) - avg_gain = sum(gains) / RSI_PERIOD - avg_loss = sum(losses) / RSI_PERIOD + # StdDev of last 20 prices + recent_prices = prices[-BB_PERIOD:] + mean = sum(recent_prices) / BB_PERIOD + variance = sum((p - mean) ** 2 for p in recent_prices) / BB_PERIOD + std_dev = variance ** 0.5 - if avg_loss == 0: - return 100 if avg_gain > 0 else 0 + upper_band = ema + (BB_STD_DEV * std_dev) + lower_band = ema - (BB_STD_DEV * std_dev) - rs = avg_gain / avg_loss - rsi = 100 - (100 / (1 + rs)) - return rsi + return ema, upper_band, lower_band + + def is_bollinger_breakout(self, symbol): + """Buy when price rebounds from lower band (crosses from below to above)""" + if len(self.price_history[symbol]) < BB_PERIOD + 1: + return False + + prices = self.price_history[symbol] + ema, upper, lower = self.calculate_bollinger_bands(prices) + + if not ema or not lower: + return False + + current_price = prices[-1] + prev_price = prices[-2] + + # Signal: Price was below lower band, now above lower band + breakout = (prev_price < lower and current_price > lower) + + if breakout: + logger.info(f"[SIGNAL-BB] {symbol} Bollinger Breakout (EMA={ema:.2f}, Lower={lower:.2f})") + + return breakout def get_fresh_balance(self): try: @@ -109,7 +132,7 @@ class TradingBotV042: self.portfolio_value = portfolio_value self.max_trade_usdt = portfolio_value * MAX_POSITION_PCT - logger.info(f"[v0.4.2] USDT={usdt_available:.2f} | Portfolio={portfolio_value:.2f}") + logger.info(f"[v0.5] USDT={usdt_available:.2f} | Portfolio={portfolio_value:.2f} | Max={self.max_trade_usdt:.2f}") return usdt_available, portfolio_value except: return 0, 0 @@ -121,59 +144,6 @@ class TradingBotV042: except: return None - def is_local_minimum(self, symbol): - """OLD: Local Minimum (price below last 4 candles)""" - if len(self.price_history[symbol]) < 5: - return False - - recent = self.price_history[symbol][-5:] - current = recent[-1] - is_min = all(current < p for p in recent[:-1]) - - if is_min: - logger.info(f"[SIGNAL-1] LOCAL_MIN: {symbol}") - return is_min - - def is_rsi_oversold(self, symbol): - """NEW: RSI oversold (RSI < 30)""" - if len(self.price_history[symbol]) < RSI_PERIOD + 2: - return False - - rsi = self.calculate_rsi(self.price_history[symbol]) - if not rsi: - return False - - is_oversold = rsi < RSI_OVERSOLD - - if is_oversold: - logger.info(f"[SIGNAL-2] RSI_OVERSOLD: {symbol} RSI={rsi:.1f}") - return is_oversold - - def is_support_bounce(self, symbol): - """NEW: Price bouncing from support level (2% rebound)""" - if len(self.price_history[symbol]) < 5: - return False - - recent = self.price_history[symbol][-5:] - low = min(recent[:-1]) - current = recent[-1] - - # If current is 2%+ above recent low, it's a bounce - bounce_pct = ((current - low) / low) * 100 - is_bounce = (bounce_pct >= 2.0) - - if is_bounce: - logger.info(f"[SIGNAL-3] SUPPORT_BOUNCE: {symbol} {bounce_pct:.1f}%") - return is_bounce - - def has_buy_signal(self, symbol): - """Multiple entry signals for higher Win-Rate""" - return ( - self.is_local_minimum(symbol) or - self.is_rsi_oversold(symbol) or - self.is_support_bounce(symbol) - ) - def calculate_valid_quantity(self, symbol, usdt_amount): try: price = self.get_current_price(symbol) @@ -222,7 +192,7 @@ class TradingBotV042: 'entry_time': datetime.now().isoformat() } - logger.info(f"[BUY-v0.4.2] {symbol} {qty} @ {price}") + logger.info(f"[BUY-v0.5] {symbol} {qty} @ {price} (BB Breakout)") return order except: return None @@ -257,7 +227,6 @@ class TradingBotV042: pass def save_pnl_to_db(self, portfolio_val, usdt_free): - """Save P&L data to database""" try: conn = sqlite3.connect('/home/marc/bot-deploy/pnl_charts.db') baseline = conn.execute('SELECT pv FROM history ORDER BY ts ASC LIMIT 1').fetchone() @@ -281,7 +250,7 @@ class TradingBotV042: usdt_free, portfolio_val = self.get_fresh_balance() if usdt_free < MIN_TRADE_USDT: - logger.warning(f"Low capital: {usdt_free}") + logger.warning(f"Low capital: {usdt_free:.2f}") logger.info("="*70) return @@ -295,10 +264,10 @@ class TradingBotV042: if len(self.price_history[symbol]) > 100: self.price_history[symbol].pop(0) - # Find BEST signal (any of the 3) + # Find BEST Bollinger Bands signal best_signal = None for symbol in SYMBOLS: - if symbol not in self.active_trades and self.has_buy_signal(symbol): + if symbol not in self.active_trades and self.is_bollinger_breakout(symbol): best_signal = symbol break @@ -316,7 +285,7 @@ class TradingBotV042: 'portfolio_value': round(portfolio_val, 2), 'max_trade_usdt': round(self.max_trade_usdt, 2), 'timestamp': datetime.now().isoformat(), - 'version': 'v0.4.2' + 'version': 'v0.5-bollinger-bands' }, f) os.replace(temp, '/home/marc/bot-deploy/active_trades.json') except: @@ -325,18 +294,18 @@ class TradingBotV042: # Save P&L self.save_pnl_to_db(portfolio_val, usdt_free) - logger.info(f"[CYCLE-END] Trades={len(self.active_trades)} | Portfolio={portfolio_val:.2f}") + logger.info(f"[CYCLE-END] Trades={len(self.active_trades)} | Portfolio={portfolio_val:.2f} [v0.5]") logger.info("="*70) if __name__ == '__main__': import sys - bot = TradingBotV042() + bot = TradingBotV05() if len(sys.argv) > 1 and sys.argv[1] == '--once': bot.run_cycle() else: - logger.info("[v0.4.2 START] Bot running (RSI + Support Signals)...") + logger.info("[v0.5 START] Trading Bot with Bollinger Bands signals...") while True: try: bot.run_cycle()