#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ================================================================================ πŸ€– FUTURE TRADING BOT v16.0 - TREND + SIDEWAYS (FULLY FIXED) ================================================================================ βœ… TREND mein RSI + Volume βœ… SIDEWAYS mein Bollinger Bands + Divergence + Range βœ… 1:4 Risk-Reward βœ… ALL SYNTAX ERRORS FIXED ================================================================================ """ import ccxt import pandas as pd import numpy as np import time import json import os import sys import random import shutil import py_compile from datetime import datetime, timedelta from threading import Thread import warnings warnings.filterwarnings('ignore') # ===================================================================== # πŸ”‘ CONFIGURATION - $10 CAPITAL # ===================================================================== class Config: """FUTURE TRADING CONFIG v16.0""" # πŸ”΄ API KEYS (apni keys yahan daal) BINANCE_API_KEY = os.getenv('BINANCE_API_KEY', '') BINANCE_SECRET_KEY = os.getenv('BINANCE_SECRET_KEY', '') DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY', '') # πŸ’° CAPITAL - $10 INITIAL_CAPITAL = 10.0 RISK_PER_TRADE = 0.03 MAX_CAPITAL_RISK = 0.60 MAX_OPEN_POSITIONS = 2 # πŸ›‘οΈ SL/TP Parameters STOP_LOSS_PCT = 0.01 TAKE_PROFIT_PCT = 0.04 TRAILING_ACTIVATION = 2.0 TRAILING_DISTANCE = 0.01 BREAK_EVEN_PROFIT = 15.0 # πŸ€– AI & Market Filters AI_CONFIDENCE_THRESHOLD = 70 MIN_VOLUME_USDT = 50000 MIN_PRICE_MICRO = 0.1 MIN_TRADE_USDT = 5.0 MIN_VOLUME_SPIKE = 2.5 # πŸ“ˆ LONG/SHORT SPECIFIC RSI_OVERSOLD = 35 RSI_OVERBOUGHT = 65 # πŸ”’ Futures Safety MAINTENANCE_MARGIN_PCT = 0.005 MAX_LEVERAGE = 10 MIN_MARGIN_BUFFER = 2.0 DAILY_LOSS_LIMIT_PCT = 0.05 MAX_CONSECUTIVE_LOSSES = 2 DAILY_TRADE_LIMIT = 5 # ===================================================================== # πŸ€– FUTURE TRADING BOT v16.0 # ===================================================================== class FutureTradingBot: """FUTURE TRADING - TREND + SIDEWAYS STRATEGY""" def __init__(self): self.start_time = datetime.now() self.bug_fix_count = 0 self.bug_fix_history = [] self.learning_phase = "INITIALIZATION" self.confidence_history = [] self.total_scans_without_trade = 0 self.long_trades = 0 self.short_trades = 0 self.symbol_leverage_cache = {} self.total_profit = 0.0 self.scan_count = 0 self.positions = {} self.trades = [] # Risk management tracking self.daily_trades = 0 self.daily_profit = 0.0 self.last_day = datetime.now().day self.consecutive_losses = 0 self.cooldown_until = 0 self.funding_rates = {} print("="*80) print("πŸ€– FUTURE TRADING BOT v16.0 - TREND + SIDEWAYS!") print("="*80) print("βœ… CAPITAL: $10.00") print("βœ… TREND + SIDEWAYS STRATEGY") print("βœ… 1:4 RISK-REWARD READY") print("βœ… ALL BUGS FIXED") print("="*80) self._init_future_exchange() self._update_balance() self._start_auto_fixer() self._print_learning_phase() # ================================================================= # PROPER FUTURES ORDER PLACEMENT # ================================================================= def place_future_order(self, symbol, side, position_side, quantity, reduce=False): """PROPER futures order placement with UPPERCASE positionSide""" params = { 'positionSide': position_side.upper(), } if reduce: params['reduceOnly'] = True try: order = self.exchange.create_order( symbol=symbol, type='market', side=side, amount=quantity, params=params ) return order except Exception as e: print(f"❌ Order failed: {e}") sys.stdout.flush() return None # ================================================================= # LIQUIDATION PRICE # ================================================================= def calculate_liquidation_price(self, entry, leverage, direction): """Calculate CORRECT liquidation price""" maintenance_margin = Config.MAINTENANCE_MARGIN_PCT if direction == 'LONG': liquidation = entry * (1 - (1/leverage) + maintenance_margin) else: liquidation = entry * (1 + (1/leverage) - maintenance_margin) safe_liquidation = liquidation * (0.95 if direction == 'LONG' else 1.05) return safe_liquidation # ================================================================= # MINIMUM TRADE CHECK # ================================================================= def apply_min_trade_check(self, symbol, quantity, price, leverage): """Apply minimum trade check""" try: market = self.exchange.market(symbol) min_notional = Config.MIN_TRADE_USDT for filter in market['info']['filters']: if filter['filterType'] == 'MIN_NOTIONAL': min_notional = float(filter['minNotional']) break min_position_value = min_notional / leverage min_required_qty = min_position_value / price if quantity < min_required_qty: print(f"⚠️ Quantity {quantity:.2f} < minimum {min_required_qty:.2f}") sys.stdout.flush() return min_required_qty return quantity except Exception as e: print(f"⚠️ Min trade check error: {e}") sys.stdout.flush() return quantity # ================================================================= # STOP LOSS AND TAKE PROFIT ORDERS # ================================================================= def place_stop_loss(self, symbol, quantity, stop_price, position_side): """Place actual stop loss order""" try: side = 'sell' if position_side.upper() == 'LONG' else 'buy' order = self.exchange.create_order( symbol=symbol, type='STOP_MARKET', side=side, amount=quantity, params={ 'stopPrice': stop_price, 'positionSide': position_side.upper(), 'reduceOnly': True } ) print(f" βœ… Stop loss placed at ${stop_price:.8f}") sys.stdout.flush() return order except Exception as e: print(f" ❌ Stop loss failed: {e}") sys.stdout.flush() return None def place_take_profit(self, symbol, quantity, tp_price, position_side): """Place actual take profit order""" try: side = 'sell' if position_side.upper() == 'LONG' else 'buy' order = self.exchange.create_order( symbol=symbol, type='TAKE_PROFIT_MARKET', side=side, amount=quantity, params={ 'stopPrice': tp_price, 'positionSide': position_side.upper(), 'reduceOnly': True } ) print(f" βœ… Take profit placed at ${tp_price:.8f}") sys.stdout.flush() return order except Exception as e: print(f" ❌ Take profit failed: {e}") sys.stdout.flush() return None # ================================================================= # PNL CALCULATION # ================================================================= def calculate_funding_cost(self, symbol, position): """Calculate funding cost""" try: funding_info = self.exchange.fapiPublic_get_fundingInfo() symbol_raw = symbol.replace('/', '') for item in funding_info: if item['symbol'] == symbol_raw: rate = float(item['lastFundingRate']) hours_held = (datetime.now() - position['entry_time']).seconds / 3600 funding_payments = hours_held / 8 position_value = position['entry_price'] * position['quantity'] funding_cost = position_value * rate * funding_payments return funding_cost except: pass return 0 def calculate_pnl(self, position, current_price, symbol): """Calculate PnL""" entry = position['entry_price'] qty = position['quantity'] direction = position['direction'] if direction == 'LONG': profit_usd = (current_price - entry) * qty profit_pct = (current_price - entry) / entry * 100 else: profit_usd = (entry - current_price) * qty profit_pct = (entry - current_price) / entry * 100 # Add funding rate impact for SHORT positions if direction == 'SHORT' and hasattr(self, 'funding_rates'): funding_cost = self.calculate_funding_cost(symbol, position) profit_usd -= funding_cost return profit_usd, profit_pct # ================================================================= # POSITION LIMIT PER DIRECTION # ================================================================= def can_open_position(self, direction): """Check if we can open position""" if not direction: return False long_count = sum(1 for p in self.positions.values() if p['direction'] == 'LONG') short_count = sum(1 for p in self.positions.values() if p['direction'] == 'SHORT') if direction == 'LONG' and long_count >= 1: print("⚠️ Already have a LONG position") sys.stdout.flush() return False if direction == 'SHORT' and short_count >= 1: print("⚠️ Already have a SHORT position") sys.stdout.flush() return False return len(self.positions) < Config.MAX_OPEN_POSITIONS # ================================================================= # COIN SELECTION (WITH PRINTS) # ================================================================= def get_tradable_coins(self): """Get coins suitable for $10 capital""" try: tickers = self.exchange.fetch_tickers() coins = [] print("\nπŸ“‘ Fetching coins...") sys.stdout.flush() for symbol, ticker in tickers.items(): if not symbol.endswith('/USDT'): continue price = self.safe_float(ticker.get('last')) volume = self.safe_float(ticker.get('quoteVolume')) if price <= 0 or volume < 10000: continue if price < 0.01: min_volume = 10000 elif price < 0.1: min_volume = 25000 elif price < 1: min_volume = 50000 else: min_volume = 100000 if volume > min_volume: coins.append({ 'symbol': symbol, 'price': price, 'volume': volume, }) print(f"πŸ“Š Total coins found: {len(coins)}") if coins: sorted_coins = sorted(coins, key=lambda x: x['volume'], reverse=True) print("πŸ” Top 5 coins by volume:") for i, coin in enumerate(sorted_coins[:5]): print(f" {i+1}. {coin['symbol']} - ${coin['price']:.8f} - Vol: ${coin['volume']:.0f}") return sorted_coins[:10] else: print("❌ No coins found.") return [] except Exception as e: print(f"❌ Coin selection error: {e}") return [] # ================================================================= # ORDER VALIDATION # ================================================================= def validate_order(self, order, symbol, expected_side): """Validate order was filled""" if not order: return False time.sleep(2) try: order_status = self.exchange.fetch_order(order['id'], symbol) if order_status['status'] == 'closed': filled_qty = float(order_status['filled']) avg_price = float(order_status['average']) print(f" βœ… Order filled: {filled_qty:.0f} @ ${avg_price:.8f}") return True else: print(f" ⚠️ Order status: {order_status['status']}") return False except Exception as e: print(f" ⚠️ Order validation error: {e}") return True # ================================================================= # ERROR RECOVERY # ================================================================= def retry_api_call(self, func, *args, max_retries=3, **kwargs): """Retry API calls""" for attempt in range(max_retries): try: return func(*args, **kwargs) except Exception as e: if attempt == max_retries - 1: print(f"❌ API call failed: {e}") raise e wait_time = (2 ** attempt) * 2 print(f"⚠️ Retrying in {wait_time}s...") time.sleep(wait_time) return None # ================================================================= # POSITION RECOVERY # ================================================================= def recover_positions(self): """Recover positions from exchange""" try: positions = self.exchange.fetch_positions() for pos in positions: if float(pos['info']['positionAmt']) != 0: symbol = pos['symbol'] amt = abs(float(pos['info']['positionAmt'])) side = 'LONG' if float(pos['info']['positionAmt']) > 0 else 'SHORT' if symbol not in self.positions: print(f"πŸ”„ Recovering position: {symbol} {side}") self.positions[symbol] = { 'entry_price': float(pos['entryPrice']), 'quantity': amt, 'direction': side, 'entry_time': datetime.now(), 'stop_loss': None, 'take_profit': None, 'trailing_activated': False, 'break_even_activated': False } except Exception as e: print(f"⚠️ Position recovery failed: {e}") # ================================================================= # CLOSE POSITION # ================================================================= def _close_position(self, symbol, price, reason, direction, profit_usd, profit_pct): """Close position and record trade""" if symbol not in self.positions: return position = self.positions[symbol] print("\n" + "="*60) print(f"πŸ’° CLOSING {direction} POSITION") print("="*60) print(f"Symbol: {symbol}") print(f"Entry: ${position['entry_price']:.8f}") print(f"Exit: ${price:.8f}") print(f"Profit: ${profit_usd:.2f} ({profit_pct:.1f}%)") print(f"Reason: {reason}") print("="*60) sys.stdout.flush() try: self.cancel_all_orders_for_symbol(symbol) if direction == 'LONG': order = self.place_future_order( symbol=symbol, side='sell', position_side='LONG', quantity=position['quantity'], reduce=True ) else: order = self.place_future_order( symbol=symbol, side='buy', position_side='SHORT', quantity=position['quantity'], reduce=True ) if order: print(f"βœ… Position closed successfully") self.total_profit += profit_usd self.daily_profit += profit_usd if profit_usd < 0: self.consecutive_losses += 1 else: self.consecutive_losses = 0 self.trades.append({ 'symbol': symbol, 'entry': position['entry_price'], 'exit': price, 'profit': profit_usd, 'profit_pct': profit_pct, 'direction': direction, 'reason': reason, 'time': datetime.now() }) self._update_balance() del self.positions[symbol] except Exception as e: print(f"❌ Close failed: {e}") # ================================================================= # CIRCUIT BREAKERS # ================================================================= def check_circuit_breakers(self): """Emergency circuit breakers""" current_day = datetime.now().day if current_day != self.last_day: self.daily_trades = 0 self.daily_profit = 0.0 self.last_day = current_day if abs(self.daily_profit) > self.capital * Config.DAILY_LOSS_LIMIT_PCT: print("🚨 DAILY LOSS LIMIT REACHED! Stopping for 1 hour") time.sleep(3600) return False if self.daily_trades >= Config.DAILY_TRADE_LIMIT: print("🚨 DAILY TRADE LIMIT REACHED! Stopping till tomorrow") return False if self.consecutive_losses >= Config.MAX_CONSECUTIVE_LOSSES: print("🚨 CONSECUTIVE LOSSES! Cooling down for 30 minutes") time.sleep(1800) self.consecutive_losses = 0 return False if time.time() < self.cooldown_until: remaining = int(self.cooldown_until - time.time()) print(f"⏸️ Cooldown: {remaining}s remaining") return False return True # ================================================================= # SAFE POSITION SIZING # ================================================================= def calculate_safe_position_size(self, price, confidence, direction, symbol): """SAFE position sizing""" try: leverage = self.calculate_auto_leverage() risk_amount = self.capital * Config.RISK_PER_TRADE position_value_usdt = risk_amount / Config.STOP_LOSS_PCT leveraged_value = position_value_usdt * leverage max_safe_value = self.capital * Config.MAX_CAPITAL_RISK position_value = min(leveraged_value, max_safe_value) quantity = position_value / price quantity = self.apply_min_trade_check(symbol, quantity, price, leverage) liq_price = self.calculate_liquidation_price(price, leverage, direction) if direction == 'LONG': stop_price = price * (1 - Config.STOP_LOSS_PCT) if stop_price < liq_price: quantity *= 0.8 print(f" ⚠️ Reducing position for safety") position_value = quantity * price print(f" πŸ’° Position Value: ${position_value:.2f}") print(f" βš–οΈ Leverage: {leverage}x") print(f" πŸ“‰ Liquidation ~ ${liq_price:.8f}") return quantity, leverage except Exception as e: print(f"⚠️ Position size error: {e}") return 0, 1 # ================================================================= # AUTO-LEVERAGE # ================================================================= def calculate_auto_leverage(self): if self.capital < 20: return 1 elif self.capital < 50: return 2 elif self.capital < 100: return 3 elif self.capital < 500: return 5 else: return 10 # ================================================================= # SET LEVERAGE # ================================================================= def set_leverage_for_symbol(self, symbol): leverage = self.calculate_auto_leverage() cache_key = f"{symbol}_{leverage}" if self.symbol_leverage_cache.get(cache_key): return True try: self.exchange.fapiPrivate_post_leverage({ 'symbol': symbol.replace('/', ''), 'leverage': leverage }) self.symbol_leverage_cache[cache_key] = True print(f"βœ… Leverage {leverage}x set for {symbol}") return True except Exception as e: if 'leverage not changed' not in str(e).lower(): print(f"⚠️ Leverage set failed: {e}") return False # ================================================================= # SET MARGIN MODE # ================================================================= def set_margin_mode(self, symbol): try: self.exchange.fapiPrivate_post_marginType({ 'symbol': symbol.replace('/', ''), 'marginType': 'ISOLATED' }) return True except Exception as e: if 'No need to change margin type' not in str(e): print(f"⚠️ Margin mode error: {e}") return False # ================================================================= # CHECK FUNDING RATE # ================================================================= def check_funding_rate(self, symbol, direction): if direction != 'SHORT': return True try: funding_info = self.exchange.fapiPublic_get_fundingInfo() symbol_raw = symbol.replace('/', '') for item in funding_info: if item['symbol'] == symbol_raw: rate = float(item['lastFundingRate']) self.funding_rates[symbol] = rate if rate > 0.001: print(f"⚠️ High funding rate: {rate*100}%") return False return True except Exception: return True # ================================================================= # CANCEL ORDERS # ================================================================= def cancel_all_orders_for_symbol(self, symbol): try: orders = self.exchange.fetch_open_orders(symbol) for order in orders: self.exchange.cancel_order(order['id'], symbol) if orders: print(f"βœ… Cancelled {len(orders)} old orders") except Exception: pass # ================================================================= # MARGIN REQUIREMENT CHECK # ================================================================= def check_margin_requirements(self, position_value): required_margin = position_value * Config.MAINTENANCE_MARGIN_PCT needed_margin = required_margin * Config.MIN_MARGIN_BUFFER if self.capital < needed_margin: print(f"❌ Insufficient margin! Need ${needed_margin:.2f}") return False return True # ================================================================= # INITIALIZATION FUNCTIONS # ================================================================= def _init_future_exchange(self): try: self.exchange = ccxt.binance({ 'apiKey': Config.BINANCE_API_KEY, 'secret': Config.BINANCE_SECRET_KEY, 'enableRateLimit': True, 'timeout': 30000, 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True, 'recvWindow': 5000 } }) self.exchange.fetch_balance() print("βœ… Binance FUTURE: CONNECTED!") except Exception as e: print(f"❌ FUTURE Connection Failed: {e}") sys.exit(1) def _update_balance(self): try: balance = self.exchange.fetch_balance() self.capital = float(balance['USDT']['free']) print(f"πŸ’° FUTURE USDT Balance: ${self.capital:.2f}") except Exception as e: print(f"❌ Balance fetch failed: {e}") sys.exit(1) def _start_auto_fixer(self): def fixer(): while True: time.sleep(300) self._safe_auto_fix() Thread(target=fixer, daemon=True).start() print("βœ… Auto-Fixer Thread Started") def _safe_auto_fix(self): try: if random.random() > 0.1: return temp_file = f"{__file__}.temp" backup_file = f"{__file__}.backup" with open(__file__, 'r') as f: content = f.read() content = content.replace('\t', ' ') with open(temp_file, 'w') as f: f.write(content) try: py_compile.compile(temp_file, doraise=True) shutil.copy2(__file__, backup_file) shutil.move(temp_file, __file__) self.bug_fix_count += 1 fix_time = datetime.now().strftime('%H:%M:%S') self.bug_fix_history.append({ 'time': fix_time, 'type': 'auto_format' }) print(f"\nπŸ› BUG FIX #{self.bug_fix_count} at {fix_time}") except py_compile.PyCompileError: os.remove(temp_file) except Exception: pass def _print_learning_phase(self): print("\n" + "="*80) print(f"🧠 LEARNING PHASE: {self.learning_phase}") print("="*80) print(f"πŸ“Š Total Scans: {self.scan_count}") print(f"πŸ› Bugs Fixed: {self.bug_fix_count}") print(f"πŸ“ˆ Avg Confidence: {self._get_avg_confidence():.1f}%") print(f"πŸ“Š LONG: {self.long_trades} | SHORT: {self.short_trades}") print(f"⏰ Uptime: {self._get_uptime()}") print("="*80) def _get_uptime(self): delta = datetime.now() - self.start_time hours = delta.seconds // 3600 minutes = (delta.seconds % 3600) // 60 return f"{hours}h {minutes}m" def _get_avg_confidence(self): if self.confidence_history: return sum(self.confidence_history) / len(self.confidence_history) return 0 def _update_learning_phase(self): if self.scan_count < 10: self.learning_phase = "INITIAL SCANNING πŸ”" elif len(self.trades) < 5: self.learning_phase = "EARLY TRADING πŸ“Š" elif self.total_profit < 1: self.learning_phase = "PROFIT BUILDING πŸ“ˆ" elif self.total_profit < 5: self.learning_phase = "GROWTH PHASE πŸš€" else: self.learning_phase = "OPTIMIZED TRADING πŸ’Ž" def safe_float(self, value, default=0.0): if value is None: return default try: return float(value) except (ValueError, TypeError): return default def get_precise_quantity(self, symbol, quantity): try: market = self.exchange.market(symbol) for filter in market['info']['filters']: if filter['filterType'] == 'LOT_SIZE': step_size = float(filter['stepSize']) min_qty = float(filter['minQty']) quantity = quantity - (quantity % step_size) quantity = round(quantity, 8) if quantity < min_qty: quantity = min_qty break return quantity except Exception as e: print(f"⚠️ Quantity error: {e}") return quantity # ================================================================= # BOLLINGER BANDS # ================================================================= def calculate_bollinger(self, df, period=20, std_dev=2): """Calculate Bollinger Bands""" try: close = df['close'] if len(close) < period: return None, None, None sma = close.rolling(window=period).mean().iloc[-1] std = close.rolling(window=period).std().iloc[-1] upper = sma + (std_dev * std) lower = sma - (std_dev * std) return upper, sma, lower except Exception as e: print(f"⚠️ Bollinger error: {e}") return None, None, None # ================================================================= # RSI DIVERGENCE DETECTION # ================================================================= def detect_rsi_divergence(self, df, period=14): """Detect bullish/bearish RSI divergence""" try: if len(df) < period + 5: return None close = df['close'].values[-5:] rsi_values = [] for i in range(-5, 0): prices = df['close'].values[:i] if i < 0 else df['close'].values rsi_values.append(self._calculate_rsi(prices)) # Check for bullish divergence (price lower low, RSI higher low) if close[0] > close[-1] and rsi_values[0] < rsi_values[-1]: return "BULLISH" # Check for bearish divergence (price higher high, RSI lower high) elif close[0] < close[-1] and rsi_values[0] > rsi_values[-1]: return "BEARISH" return None except Exception as e: print(f"⚠️ Divergence error: {e}") return None # ================================================================= # MARKET TYPE DETECTION # ================================================================= def detect_market_type(self, df, bb_period=20): """Detect if market is trending or sideways using BB width""" try: if len(df) < bb_period: return "SIDEWAYS" close = df['close'] sma = close.rolling(window=bb_period).mean() std = close.rolling(window=bb_period).std() if sma.iloc[-1] == 0: return "s e: print(f"⚠️ Market type detection error: {e}") return "SIDEWAYS" # ================================================================= # TREND STRATEGY # ================================================================= def analyze_coin_trend(self, coin): """Original trend-based analysis""" try: symbol = coin['symbol'] price = coin['price'] ohlcv = self.exchange.fetch_ohlcv(symbol, '15m', limit=50) if len(ohlcv) < 20: return None df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) close_prices = df['close'].values rsi = self._calculate_rsi(close_prices) volume_ma = df['volume'].rolling(20).mean().iloc[-1] current_volume = df['volume'].iloc[-1] volume_ratio = current_volume / volume_ma if volume_ma > 0 else 1 volume_surge = volume_ratio > Config.MIN_VOLUME_SPIKE print(f"\nπŸ” Analyzing {symbol} (TREND MODE)") print(f" πŸ’° Price: ${price:.8f}") print(f" πŸ“ˆ RSI: {rsi:.1f}") print(f" πŸ“Š Volume: {volume_ratio:.1f}x {'βœ…' if volume_surge else '❌'}") trade_direction = None confidence = 40 if rsi < Config.RSI_OVERSOLD and volume_surge: confidence = 85 trade_direction = "LONG" print(f" βœ…βœ…βœ… STRONG LONG SIGNAL!") elif rsi < Config.RSI_OVERSOLD: confidence = 60 trade_direction = "LONG" print(f" ⚠️ CAUTIOUS LONG (low volume)") elif rsi > Config.RSI_OVERBOUGHT and volume_surge: confidence = 85 trade_direction = "SHORT" print(f" βœ…βœ…βœ… STRONG SHORT SIGNAL!") elif rsi > Config.RSI_OVERBOUGHT: confidence = 60 trade_direction = "SHORT" print(f" ⚠️ CAUTIOUS SHORT (low volume)") else: print(f" ⏸️ NEUTRAL - No signal") print(f" πŸ€– Confidence: {confidence}%") self.confidence_history.append(confidence) return { 'symbol': symbol, 'price': price, 'rsi': rsi, 'confidence': confidence, 'volume_ratio': volume_ratio, 'direction': trade_direction } except Exception as e: print(f" ❌ Trend analysis error: {e}") return None # ================================================================= # SIDEWAYS STRATEGY # ================================================================= def analyze_coin_sideways(self, coin): """Sideways market analysis""" try: symbol = coin['symbol'] price = coin['price'] ohlcv = self.exchange.fetch_ohlcv(symbol, '15m', limit=50) if len(ohlcv) < 30: print(f"\nπŸ” Analyzing {symbol}") print(" ⚠️ Insufficient data for sideways") return None df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) # Calculate indicators rsi = self._calculate_rsi(df['close'].values) upper, middle, lower = self.calculate_bollinger(df) if upper is None or middle is None or lower is None: return None divergence = self.detect_rsi_divergence(df) # Check BB width for squeeze detection bb_width = (upper - lower) / middle if middle != 0 else 0 is_squeeze = bb_width < 0.05 # 5% narrow band # Volume check volume_ma = df['volume'].rolling(20).mean().iloc[-1] current_volume = df['volume'].iloc[-1] volume_ratio = current_volume / volume_ma if volume_ma > 0 else 1 print(f"\nπŸ” Analyzing {symbol} (SIDEWAYS MODE)") print(f" πŸ’° Price: ${price:.8f}") print(f" πŸ“ˆ RSI: {rsi:.1f}") print(f" πŸ“Š BB Width: {bb_width:.2%} {'(Squeeze)' if is_squeeze else ''}") print(f" πŸ”„ Divergence: {divergence if divergence else 'None'}") trade_direction = None confidence = 40 # Strategy 1: Bollinger Squeeze Breakout if is_squeeze and volume_ratio > 1.5: if df['close'].iloc[-1] > upper * 0.98: confidence = 75 trade_direction = "LONG" print(f" πŸ“ˆ SQUEEZE BREAKOUT LONG") elif df['close'].iloc[-1] < lower * 1.02: confidence = 75 trade_direction = "SHORT" print(f" πŸ“‰ SQUEEZE BREAKOUT SHORT") # Strategy 2: RSI Divergence elif divergence == "BULLISH" and rsi < 50: confidence = 70 trade_direction = "LONG" print(f" πŸ”„ BULLISH DIVERGENCE LONG") elif divergence == "BEARISH" and rsi > 50: confidence = 70 trade_direction = "SHORT" print(f" πŸ”„ BEARISH DIVERGENCE SHORT") # Strategy 3: Range Trading elif price <= lower * 1.01: confidence = 65 trade_direction = "LONG" print(f" ⬆️ SUPPORT BOUNCE LONG") elif price >= upper * 0.99: confidence = 65 trade_direction = "SHORT" print(f" ⬇️ RESISTANCE REJECT SHORT") else: print(f" ⏸️ No sideways signal") print(f" πŸ€– Confidence: {confidence}%") self.confidence_history.append(confidence) return { 'symbol': symbol, 'price': price, 'rsi': rsi, 'confidence': confidence, 'volume_ratio': volume_ratio, 'direction': trade_direction, 'bb_width': bb_width } except Exception as e: print(f" ❌ Sideways analysis error: {e}") return None # ================================================================= # MAIN ANALYSIS FUNCTION # ================================================================= def analyze_coin(self, coin): """Main analysis - detects market type and applies appropriate strategy""" try: symbol = coin['symbol'] ohlcv = self.exchange.fetch_ohlcv(symbol, '15m', limit=50) if len(ohlcv) < 20: print(f"\nπŸ” Analyzing {symbol}") print(" ⚠️ Insufficient data") return None df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) market_type = self.detect_market_type(df) print(f"\nπŸ“Š Market Type for {symbol}: {market_type}") if market_type == "TRENDING": return self.analyze_coin_trend(coin) else: return self.analyze_coin_sideways(coin) except Exception as e: print(f" ❌ Main analysis error: {e}") return None # ================================================================= # RSI CALCULATION # ================================================================= def _calculate_rsi(self, prices, period=14): """Proper RSI calculation""" try: if len(prices) < period + 1: return 50 deltas = np.diff(prices) if len(deltas) < period: return 50 gains = np.maximum(deltas, 0) losses = -np.minimum(deltas, 0) avg_gain = np.mean(gains[:period]) avg_loss = np.mean(losses[:period]) for i in range(period, len(deltas)): avg_gain = (avg_gain * (period-1) + gains[i]) / period avg_loss = (avg_loss * (period-1) + losses[i]) / period if avg_loss == 0: return 100 rs = avg_gain / avg_loss rsi = 100 - 100 / (1 + rs) return rsi except Exception: return 50 # ================================================================= # TRADE EXECUTION - LONG # ================================================================= def execute_long(self, symbol, price, quantity, confidence, analysis): print(f"\n{'='*60}") print(f"πŸš€ EXECUTING LONG ORDER") print(f"{'='*60}") try: self.cancel_all_orders_for_symbol(symbol) self.set_leverage_for_symbol(symbol) self.set_margin_mode(symbol) precise_quantity = self.get_precise_quantity(symbol, quantity) if precise_quantity <= 0: print("❌ Invalid quantity") return False order = self.place_future_order( symbol=symbol, side='buy', position_side='LONG', quantity=precise_quantity ) if not order: return False if not self.validate_order(order, symbol, 'buy'): return False stop_loss = price * (1 - Config.STOP_LOSS_PCT) take_profit = price * (1 + Config.TAKE_PROFIT_PCT) self.place_stop_loss(symbol, precise_quantity, stop_loss, 'LONG') self.place_take_profit(symbol, precise_quantity, take_profit, 'LONG') self.positions[symbol] = { 'entry_price': price, 'quantity': precise_quantity, 'entry_time': datetime.now(), 'confidence': confidence, 'direction': 'LONG', 'stop_loss': stop_loss, 'take_profit': take_profit, 'trailing_activated': False, 'break_even_activated': False, 'highest_price': price, 'order_id': order['id'] } self.long_trades += 1 self.daily_trades += 1 print(f"\nβœ…βœ…βœ… LONG ORDER EXECUTED!") return True except Exception as e: print(f"\n❌ LONG ORDER FAILED: {e}") return False # ================================================================= # TRADE EXECUTION - SHORT # ================================================================= def execute_short(self, symbol, price, quantity, confidence, analysis): print(f"\n{'='*60}") print(f"πŸš€ EXECUTING SHORT ORDER") print(f"{'='*60}") if not self.check_funding_rate(symbol, 'SHORT'): return False try: self.cancel_all_orders_for_symbol(symbol) self.set_leverage_for_symbol(symbol) self.set_margin_mode(symbol) precise_quantity = self.get_precise_quantity(symbol, quantity) if precise_quantity <= 0: print("❌ Invalid quantity") return False order = self.place_future_order( symbol=symbol, side='sell', position_side='SHORT', quantity=precise_quantity ) if not order: return False if not self.validate_order(order, symbol, 'sell'): return False stop_loss = price * (1 + Config.STOP_LOSS_PCT) take_profit = price * (1 - Config.TAKE_PROFIT_PCT) self.place_stop_loss(symbol, precise_quantity, stop_loss, 'SHORT') self.place_take_profit(symbol, precise_quantity, take_profit, 'SHORT') self.positions[symbol] = { 'entry_price': price, 'quantity': precise_quantity, 'entry_time': datetime.now(), 'confidence': confidence, 'direction': 'SHORT', 'stop_loss': stop_loss, 'take_profit': take_profit, 'trailing_activated': False, 'break_even_activated': False, 'lowest_price': price, 'order_id': order['id'] } self.short_trades += 1 self.daily_trades += 1 print(f"\nβœ…βœ…βœ… SHORT ORDER EXECUTED!") return True except Exception as e: print(f"\n❌ SHORT ORDER FAILED: {e}") return False # ================================================================= # POSITION MONITORING # ================================================================= def check_positions(self): if not self.positions: return for symbol in list(self.positions.keys()): try: ticker = self.exchange.fetch_ticker(symbol) current_price = self.safe_float(ticker.get('last')) if current_price <= 0: continue position = self.positions[symbol] profit_usd, profit_pct = self.calculate_pnl(position, current_price, symbol) # Update highest/lowest price if position['direction'] == 'LONG': if current_price > position.get('highest_price', position['entry_price']): position['highest_price'] = current_price else: if current_price < position.get('lowest_price', position['entry_price']): position['lowest_price'] = current_price # Break-even check if not position['break_even_activated'] and profit_usd >= Config.BREAK_EVEN_PROFIT: position['break_even_activated'] = True position['stop_loss'] = position['entry_price'] print(f"\n🎯 BREAK-EVEN ACTIVATED!") self.cancel_all_orders_for_symbol(symbol) self.place_stop_loss(symbol, position['quantity'], position['stop_loss'], position['direction']) # Trailing check if not position['trailing_activated'] and profit_usd >= Config.TRAILING_ACTIVATION: position['trailing_activated'] = True if position['direction'] == 'LONG': new_stop = current_price * (1 - Config.TRAILING_DISTANCE) else: new_stop = current_price * (1 + Config.TRAILING_DISTANCE) position['stop_loss'] = new_stop print(f"\nπŸ”„ TRAILING ACTIVATED!") self.cancel_all_orders_for_symbol(symbol) self.place_stop_loss(symbol, position['quantity'], position['stop_loss'], position['direction']) # Check exit conditions exit_signal = False exit_reason = "" if position['direction'] == 'LONG': if current_price <= position['stop_loss']: exit_signal = True exit_reason = "Stop Loss" elif current_price >= position['take_profit']: exit_signal = True exit_reason = "Take Profit" else: if current_price >= position['stop_loss']: exit_signal = True exit_reason = "Stop Loss" elif current_price <= position['take_profit']: exit_signal = True exit_reason = "Take Profit" if exit_signal: self._close_position(symbol, current_price, exit_reason, position['direction'], profit_usd, profit_pct) else: be = "βœ…" if position['break_even_activated'] else "⏳" tr = "βœ…" if position['trailing_activated'] else "⏳" print(f"\nπŸ“Š {symbol}: ${current_price:.8f}") print(f" PnL: ${profit_usd:.2f} ({profit_pct:.1f}%)") print(f" BE:{be} TR:{tr}") self.positions[symbol] = position except Exception as e: print(f"⚠️ Position check error: {e}") # ================================================================= # DISPLAY STATUS # ================================================================= def print_status(self): import os try: os.system('clear' if os.name == 'posix' else 'cls') except: pass self._update_learning_phase() current_leverage = self.calculate_auto_leverage() print("="*80) print(f"πŸ€– FUTURE TRADING BOT v16.0 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("="*80) print(f"πŸ’° Balance: ${self.capital:.2f} | Target: $1000") print(f"πŸ“ˆ PnL: ${self.total_profit:.2f}") print(f"πŸ“Š Positions: {len(self.positions)}") print(f"πŸ” Scans: {self.scan_count}") print("-"*80) print(f"🧠 Phase: {self.learning_phase}") print(f"πŸ› Bugs Fixed: {self.bug_fix_count}") print(f"πŸ“ˆ LONG: {self.long_trades} | SHORT: {self.short_trades}") print(f"βš–οΈ Leverage: {current_leverage}x") print("="*80) # ================================================================= # MAIN LOOP # ================================================================= def run(self): print("\n" + "="*80) print("πŸš€ FUTURE TRADING STARTED - TREND + SIDEWAYS MODE!") print("="*80) last_status = time.time() last_scan = time.time() try: while True: if time.time() - last_status > 5: self.print_status() last_status = time.time() self.check_positions() if not self.check_circuit_breakers(): time.sleep(60) continue if time.time() - last_scan > 15 and len(self.positions) < Config.MAX_OPEN_POSITIONS: self.scan_count += 1 print(f"\n{'='*80}") print(f"πŸ” SCAN #{self.scan_count}") print(f"{'='*80}") coins = self.get_tradable_coins() if coins: for coin in coins: if coin['symbol'] in self.positions: continue analysis = self.analyze_coin(coin) if not analysis or not analysis['direction']: continue if not self.can_open_position(analysis['direction']): continue if analysis['confidence'] >= Config.AI_CONFIDENCE_THRESHOLD: print(f"\n🎯 TRADE SIGNAL!") quantity, leverage = self.calculate_safe_position_size( analysis['price'], analysis['confidence'], analysis['direction'], analysis['symbol'] ) if quantity > 0: position_value = quantity * analysis['price'] if self.check_margin_requirements(position_value): if analysis['direction'] == 'LONG': self.execute_long( analysis['symbol'], analysis['price'], quantity, analysis['confidence'], analysis ) else: self.execute_short( analysis['symbol'], analysis['price'], quantity, analysis['confidence'], analysis ) break else: print("❌ No coins found in this scan.") last_scan = time.time() time.sleep(1) except KeyboardInterrupt: print("\n\nπŸ›‘ BOT STOPPED") except Exception as e: print(f"\n❌ ERROR: {e}") import traceback traceback.print_exc() # ===================================================================== # πŸš€ START # ===================================================================== if __name__ == "__main__": print(""" ╔══════════════════════════════════════════════════════════════╗ β•‘ β•‘ β•‘ πŸ€– FUTURE TRADING BOT v16.0 β•‘ β•‘ πŸ”₯ TREND + SIDEWAYS STRATEGY! β•‘ β•‘ πŸ’° $10 CAPITAL - 1:4 RISK-REWARD β•‘ β•‘ πŸ› οΈ ALL BUGS FIXED! β•‘ β•‘ β•‘ β•‘ πŸš€ STARTING TRADING ENGINE... β•‘ β•‘ β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• """) bot = FutureTradingBot() bot.run()