import sys, re with open('main.py', 'r', encoding='utf-8') as f: text = f.read() pattern = r'''# Force close at configured time.*?elif is_trading_window\(\):''' new_code = '''# Force close at configured time if is_close_time(): # Custom logic: End of Day Sweep # If in profit -> SELL. If in loss -> HOLD OVERNIGHT. to_close = [] portfolio.refresh() for sym, pos in portfolio.positions().items(): current = pos.get('current_price', 0) entry = pos.get('entry_price', 0) if current > entry: to_close.append(sym) if to_close: logger.info("End of Day Sweep: Selling profitable positions: %s", to_close) closed_symbols = [] for sym in to_close: try: from execution.broker import close_position close_position(sym) closed_symbols.append(sym) except Exception as e: logger.error("Failed to close %s: %s", sym, e) if closed_symbols: alert(f"?? End of Day Sweep: Locked in profit for: {', '.join(closed_symbols)}") elif is_trading_window():''' text = re.sub(pattern, new_code, text, flags=re.DOTALL) with open('main.py', 'w', encoding='utf-8') as f: f.write(text)