You're right - let me create one final, complete script that uses the proper Raydium program (675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8) and pools.
Let me craft the complete script that puts it all together properly. Would you like me to focus on:

Main Raydium pool monitoring
GPU-accelerated data processing
Position scaling on wins
Proper retry/error handling
Premium service integration (Marga + Jupiter)

I'll create the comprehensive script that brings everything together. Just confirm those are the key elements you want me to prioritize and I'll deliver the final working version.
Also - to clarify about the Raydium pools - you're right that we need to monitor the Raydium AMM program (675k...) and then look at specific pool transactions within it. Let me know and I'll create the complete script with proper pool targeting. import torch
import asyncio
import json
import logging
import base64
from websockets import connect
from solana_rust_bot import TradingCore
from typing import Dict, Optional
from collections import defaultdict

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s',
    datefmt='%H:%M:%S'
)
logger = logging.INFO

class RaydiumScalper:
    def __init__(self, config_path: str = "config.json"):
        logger.info("🚀 INITIALIZING RAYDIUM SCALPER...")
        
        # Load config
        with open(config_path) as f:
            self.config = json.load(f)
            
        # Initialize trading core
        self.trading_core = TradingCore(json.dumps(self.config))
        
        # CUDA setup with streams
        self.device = torch.device('cuda')
        self.stream = torch.cuda.Stream()
        logger.info(f"🎮 CUDA Device: {torch.cuda.get_device_name(0)}")
        
        # Initialize price tensors on GPU
        with torch.cuda.stream(self.stream):
            self.price_cache = torch.zeros((2, 1000), dtype=torch.float32, device=self.device)
            self.volume_cache = torch.zeros((2, 1000), dtype=torch.float32, device=self.device)
            self.buy_sell_cache = torch.zeros((2, 1000), dtype=torch.float32, device=self.device)
        
        # Trading parameters
        self.PARAMS = {
            'position_size': 0.01,
            'scale_increment': 0.001,
            'wins_to_scale': 5,
            'take_profit': 0.05,
            'stop_loss': 0.05,
            'stale_timeout': 45,
            'min_bs_ratio': 2.0
        }
        
        # Track trades
        self.trade_stats = defaultdict(lambda: {
            'wins': 0,
            'position_size': self.PARAMS['position_size'],
            'in_position': False
        })
        
        logger.info("✅ Initialization complete!")

    async def connect(self):
        """Connect to Marga Fast Mainnet"""
        self.ws = await connect(self.config['rpc']['websocket']['endpoint'])
        
        # Subscribe to main SOL pool
        subscribe_msg = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "accountSubscribe",
            "params": [
                "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2",
                {"encoding": "base64", "commitment": "processed"}
            ]
        }
        
        await self.ws.send(json.dumps(subscribe_msg))
        logger.info("✅ Connected to Raydium SOL pool")

    @torch.cuda.amp.autocast()
    def process_pool_data(self, raw_data: str) -> Optional[torch.Tensor]:
        """Process pool data using CUDA stream"""
        try:
            decoded = base64.b64decode(raw_data)
            
            # Extract data
            amount = int.from_bytes(decoded[256:264], 'little') / 1e9
            is_buy = bool(decoded[264] & 1)
            
            if 0.001 <= amount <= 1000:  # Basic sanity check
                with torch.cuda.stream(self.stream):
                    # Create tensors
                    trade_tensor = torch.tensor([amount, float(is_buy)], 
                                             device=self.device)
                    
                    # Update caches
                    self.volume_cache = torch.roll(self.volume_cache, -1, dims=1)
                    self.volume_cache[:, -1] = trade_tensor
                    
                    # Calculate metrics
                    window = self.volume_cache[:, -300:]  # 5min window
                    buy_volume = torch.sum(window[0] * (window[1] > 0.5))
                    sell_volume = torch.sum(window[0] * (window[1] < 0.5))
                    
                    metrics = torch.tensor([
                        buy_volume,
                        sell_volume,
                        buy_volume / torch.max(sell_volume, torch.tensor(1e-8, device=self.device))
                    ], device=self.device)
                    
                    return metrics
                    
            return None
            
        except Exception as e:
            logger.error(f"Processing error: {e}")
            return None

    async def execute_trade(self, metrics: torch.Tensor, token: str):
        """Execute trade if conditions met"""
        try:
            bs_ratio = metrics[2].item()
            
            if bs_ratio >= self.PARAMS['min_bs_ratio']:
                stats = self.trade_stats[token]
                
                if not stats['in_position']:
                    logger.info(f"\n🎯 TRADE OPPORTUNITY:")
                    logger.info(f"B/S Ratio: {bs_ratio:.2f}")
                    logger.info(f"Position Size: {stats['position_size']:.4f} SOL")
                    
                    # Get balance
                    balance = await self.trading_core.get_balance()
                    
                    # Calculate position
                    position = min(
                        balance * stats['position_size'],
                        balance - 0.01
                    )
                    
                    # Execute via Rust backend
                    swap_data = await self.trading_core.buy_token(token, position)
                    signature = await self.trading_core.execute_jupiter_swap(swap_data)
                    
                    if signature:
                        logger.info(f"✅ Entry executed: {signature}")
                        stats.update({
                            'in_position': True,
                            'entry_time': time.time(),
                            'position_size': position,
                            'entry_price': await self.get_price(token)
                        })
                        
        except Exception as e:
            logger.error(f"Trade error: {e}")

    async def trade_cycle(self):
        """Main trading loop"""
        while True:
            try:
                msg = await self.ws.recv()
                data = json.loads(msg)
                
                if 'params' in data:
                    pool_data = data['params']['result']['value']['data'][0]
                    metrics = self.process_pool_data(pool_data)
                    
                    if metrics is not None:
                        # Log metrics
                        logger.info(f"\n📊 POOL METRICS:")
                        logger.info(f"Buy Volume: {metrics[0]:.4f} SOL")
                        logger.info(f"Sell Volume: {metrics[1]:.4f} SOL")
                        logger.info(f"B/S Ratio: {metrics[2]:.2f}")
                        
                        # Check for trade
                        token = data['params']['result']['value']['pubkey']
                        await self.execute_trade(metrics, token)
                        
                        # Check exits
                        if self.trade_stats[token]['in_position']:
                            await self.check_exit(token)
                
            except KeyboardInterrupt:
                logger.info("\n🛑 Trading stopped")
                break
            except Exception as e:
                logger.error(f"Cycle error: {e}")
            
            await asyncio.sleep(0.1)
            
    async def run(self):
        """Start the scalper"""
        try:
            logger.info("\n=== RAYDIUM SCALPER V1.0 ===")
            await self.connect()
            await self.trade_cycle()
        finally:
            if hasattr(self, 'ws'):
                await self.ws.close()
            torch.cuda.empty_cache()

if __name__ == "__main__":
    try:
        scalper = RaydiumScalper()
        asyncio.run(scalper.run())
    except KeyboardInterrupt:
        logger.info("\n👋 Shutting down...")  async def main_loop(self):
        """Main execution loop with enhanced monitoring"""
        while True:
            try:
                async with websockets.connect(
                    self.ws_endpoint,
                    max_size=1_000_000_000,
                    compression=None,
                    ping_interval=20,
                    ping_timeout=20
                ) as ws:
                    logger.info("✅ Connected to Marga Fast Mainnet")
                    
                    # Subscribe to main Raydium SOL-USDC pool
                    subscription = {
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "accountSubscribe",
                        "params": [
                            "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2",  # Main SOL pool
                            {
                                "encoding": "base64",
                                "commitment": "processed"
                            }
                        ]
                    }
                    
                    await ws.send(json.dumps(subscription))
                    logger.info("📡 Subscribed to SOL-USDC pool")
                    
                    while True:
                        try:
                            msg = await ws.recv()
                            data = json.loads(msg)
                            
                            # Log all messages for debugging
                            logger.info(f"\n📥 RECEIVED MESSAGE: {msg[:200]}...")
                            
                            if 'method' in data and data['method'] == 'accountNotification':
                                pool_data = self.parse_pool_data(
                                    data['params']['result']['value']['data'][0]
                                )
                                
                                if pool_data:
                                    metrics = self.update_metrics(pool_data)
                                    token = data['params']['result']['value']['pubkey']
                                    
                                    if metrics:
                                        logger.info("\n📊 POOL METRICS:")
                                        logger.info(f"B/S Ratio: {metrics['bs_ratio']:.2f}")
                                        logger.info(f"Volume: {metrics['volume']:.4f} SOL")
                                        
                                        if metrics['bs_ratio'] >= self.PARAMS['min_bs_ratio']:
                                            logger.info("🎯 Trade opportunity detected!")
                                        
                                        if not self.market_data[token]['in_position']:
                                            await self.execute_trade(token, metrics)
                                        else:
                                            await self.check_exit(token)
                            
                        except websockets.exceptions.ConnectionClosed:
                            logger.warning("⚠️ Connection closed")
                            break
                        except Exception as e:
                            logger.error(f"Loop error: {e}")
                            continue
                    
            except Exception as e:
                logger.error(f"Connection error: {e}")
                await asyncio.sleep(1)import asyncio
import json
import time
import logging
import base64
import torch
from collections import defaultdict
import websockets
from solana_rust_bot import TradingCore

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s',
    datefmt='%H:%M:%S',
    handlers=[
        logging.FileHandler('scalper.log', mode='w', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger()

class SOLPoolScalper:
    def __init__(self, config_path: str = "config.json"):
        logger.info("🚀 INITIALIZING SOL POOL SCALPER...")
        
        with open(config_path) as f:
            self.config = json.load(f)
        
        # Initialize Rust backend
        logger.info("⚙️ Initializing trading core...")
        self.trading_core = TradingCore(json.dumps(self.config))
        
        # Use Marga Fast Mainnet
        self.ws_endpoint = self.config['rpc']['websocket']['endpoint']
        
        # Main SOL pools
        self.POOLS = {
            'main_sol': "58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2"
        }
        
        # GPU-accelerated market tracking
        self.market_data = defaultdict(lambda: {
            'buys': torch.zeros(300, device='cuda'),     # 5min window
            'sells': torch.zeros(300, device='cuda'),
            'prices': torch.zeros(300, device='cuda'),
            'last_update': time.time(),
            'in_position': False,
            'position_size': 0.0
        })
        
        # Trading params
        self.PARAMS = {
            'min_bs_ratio': 2.0,        # 2:1 buy/sell ratio minimum
            'min_volume': 1.0,          # 1 SOL minimum volume
            'base_position': 0.01,      # Start with 1% position
            'scale_increment': 0.001,   # Add 0.001 SOL per 5 wins
            'wins_to_scale': 5,         # Scale after 5 wins
            'take_profit': 0.05,        # 5% profit target
            'stop_loss': 0.05,          # 5% stop loss
            'stale_timeout': 45,        # 45s stale timeout
            'gas_buffer': 0.01         # 0.01 SOL gas buffer
        }
        
        # Track performance
        self.trade_stats = {
            'wins': 0,
            'total_trades': 0,
            'current_position': self.PARAMS['base_position'],
            'best_win': 0.0,
            'worst_loss': 0.0
        }
        
        logger.info("\n⚙️ CONFIGURATION:")
        logger.info(f"Initial Position: {self.PARAMS['base_position']:.3f} SOL")
        logger.info(f"Scaling: +{self.PARAMS['scale_increment']:.3f} SOL per {self.PARAMS['wins_to_scale']} wins")
        logger.info(f"Take Profit: {self.PARAMS['take_profit']*100}%")
        logger.info(f"Stop Loss: {self.PARAMS['stop_loss']*100}%")
        
    def parse_pool_data(self, raw_data: str) -> dict:
        """Parse Raydium SOL pool data"""
        try:
            decoded = base64.b64decode(raw_data)
            
            # Get balance changes
            amount = int.from_bytes(decoded[256:264], 'little') / 1e9
            is_buy = bool(decoded[264] & 1)
            
            # Basic sanity check
            if 0.001 <= amount <= 1000:
                logger.info(f"\n🔄 POOL TRADE: {amount:.3f} SOL ({'BUY' if is_buy else 'SELL'})")
                return {
                    'amount': amount,
                    'is_buy': is_buy,
                    'timestamp': time.time()
                }
            return None
            
        except Exception as e:
            logger.error(f"Parse error: {e}")
            return None

    def update_metrics(self, trade_data: dict) -> dict:
        """Update market metrics using GPU"""
        try:
            data = self.market_data['sol']
            current_time = time.time()
            idx = int(current_time) % 300
            
            # Reset if window passed
            if current_time - data['last_update'] >= 300:
                data['buys'].zero_()
                data['sells'].zero_()
                data['last_update'] = current_time
            
            # Update volumes
            if trade_data['is_buy']:
                data['buys'][idx] += trade_data['amount']
            else:
                data['sells'][idx] += trade_data['amount']
            
            # Calculate metrics on GPU
            total_buys = data['buys'].sum().item()
            total_sells = data['sells'].sum().item()
            bs_ratio = total_buys / max(total_sells, 1e-8)
            
            logger.info("\n📊 MARKET METRICS (5min):")
            logger.info(f"Buy Volume: {total_buys:.2f} SOL")
            logger.info(f"Sell Volume: {total_sells:.2f} SOL")
            logger.info(f"B/S Ratio: {bs_ratio:.2f}")
            
            return {
                'volume': total_buys + total_sells,
                'bs_ratio': bs_ratio
            }
            
        except Exception as e:
            logger.error(f"Metrics error: {e}")
            return None

    async def execute_trade(self, token: str, metrics: dict):
        """Execute trade with scaling"""
        try:
            if metrics['bs_ratio'] >= self.PARAMS['min_bs_ratio']:
                balance = await self.trading_core.get_balance()
                
                position_size = min(
                    balance * self.trade_stats['current_position'],
                    balance - self.PARAMS['gas_buffer']
                )
                
                logger.info("\n🎯 TRADE SETUP:")
                logger.info(f"Position Size: {position_size:.4f} SOL")
                logger.info(f"B/S Ratio: {metrics['bs_ratio']:.2f}")
                
                swap_data = await self.trading_core.buy_token(token, position_size)
                signature = await self.trading_core.execute_jupiter_swap(swap_data)
                
                if signature:
                    logger.info(f"✅ ENTRY EXECUTED: {signature}")
                    self.market_data[token].update({
                        'in_position': True,
                        'entry_time': time.time(),
                        'last_move': time.time(),
                        'position_size': position_size,
                        'entry_price': await self.get_price(token)
                    })
                
        except Exception as e:
            logger.error(f"Trade error: {e}")

    async def check_exit(self, token: str):
        """Monitor position for exit"""
        try:
            data = self.market_data[token]
            if not data['in_position']:
                return
                
            current_time = time.time()
            current_price = await self.get_price(token)
            
            # Calculate profit/loss
            pnl = (current_price - data['entry_price']) / data['entry_price']
            
            # Check for exit conditions
            exit_reason = None
            
            if pnl >= self.PARAMS['take_profit']:
                exit_reason = f"Take profit hit: {pnl:.1%}"
            elif pnl <= -self.PARAMS['stop_loss']:
                exit_reason = f"Stop loss hit: {pnl:.1%}"
            elif current_time - data['last_move'] >= self.PARAMS['stale_timeout']:
                exit_reason = "Position stale"
            
            if exit_reason:
                logger.info(f"\n🚪 EXIT SIGNAL: {exit_reason}")
                await self.exit_position(token, pnl)
            
        except Exception as e:
            logger.error(f"Exit check error: {e}")

    async def exit_position(self, token: str, pnl: float):
        """Exit position and update stats"""
        try:
            data = self.market_data[token]
            
            swap_data = await self.trading_core.sell_token(token, data['position_size'])
            signature = await self.trading_core.execute_jupiter_swap(swap_data)
            
            if signature:
                logger.info(f"✅ EXIT EXECUTED: {signature}")
                
                # Update stats
                self.trade_stats['total_trades'] += 1
                
                if pnl > 0:
                    self.trade_stats['wins'] += 1
                    self.trade_stats['best_win'] = max(self.trade_stats['best_win'], pnl)
                    
                    # Scale position if needed
                    if self.trade_stats['wins'] >= self.PARAMS['wins_to_scale']:
                        old_size = self.trade_stats['current_position']
                        self.trade_stats['current_position'] += self.PARAMS['scale_increment']
                        logger.info(f"🔼 SCALING UP: {old_size:.3f} -> {self.trade_stats['current_position']:.3f} SOL")
                        self.trade_stats['wins'] = 0
                else:
                    self.trade_stats['worst_loss'] = min(self.trade_stats['worst_loss'], pnl)
                
                # Log performance
                logger.info("\n📈 PERFORMANCE:")
                logger.info(f"Total Trades: {self.trade_stats['total_trades']}")
                logger.info(f"Win Rate: {(self.trade_stats['wins']/self.trade_stats['total_trades'])*100:.1f}%")
                logger.info(f"Best Trade: {self.trade_stats['best_win']*100:.1f}%")
                logger.info(f"Worst Trade: {self.trade_stats['worst_loss']*100:.1f}%")
                
                # Reset position
                data['in_position'] = False
                
        except Exception as e:
            logger.error(f"Exit error: {e}")

    async def get_price(self, token: str) -> float:
        """Get price from Jupiter"""
        try:
            quote = await self.trading_core.get_jupiter_quote(
                token,
                "So11111111111111111111111111111111111111112",
                int(1e9)
            )
            return float(quote['outAmount']) / 1e9 if quote else 0
        except Exception as e:
            logger.error(f"Price error: {e}")
            return 0

    async def main_loop(self):
        """Main execution loop"""
        while True:
            try:
                async with websockets.connect(
                    self.ws_endpoint,
                    max_size=1_000_000_000,
                    compression=None,
                    ping_interval=20,
                    ping_timeout=20
                ) as ws:
                    logger.info("✅ Connected to Marga Fast Mainnet")
                    
                    # Subscribe to SOL pool
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "accountSubscribe",
                        "params": [
                            self.POOLS['main_sol'],
                            {"encoding": "base64", "commitment": "processed"}
                        ]
                    }))
                    
                    while True:
                        try:
                            msg = await ws.recv()
                            data = json.loads(msg)
                            
                            if 'params' in data:
                                pool_data = self.parse_pool_data(
                                    data['params']['result']['value']['data'][0]
                                )
                                
                                if pool_data:
                                    metrics = self.update_metrics(pool_data)
                                    
                                    if metrics:
                                        token = data['params']['result']['value']['pubkey']
                                        
                                        if not self.market_data[token]['in_position']:
                                            await self.execute_trade(token, metrics)
                                        else:
                                            await self.check_exit(token)
                            
                        except websockets.exceptions.ConnectionClosed:
                            break
                        except Exception as e:
                            logger.error(f"Loop error: {e}")
                            continue
                    
            except Exception as e:
                logger.error(f"Connection error: {e}")
                await asyncio.sleep(1)

    async def run(self):
        """Start the scalper"""
        try:
            logger.info("\n=== SOL POOL SCALPER V1.0 ===")
            balance = await self.trading_core.get_balance()
            logger.info(f"Initial balance: {balance:.4f} SOL")
            await self.main_loop()
        except KeyboardInterrupt:
            logger.info("Shutting down...")
        finally:
            torch.cuda.empty_cache()

if __name__ == "__main__":
    scalper = SOLPoolScalper()
    asyncio.run(scalper.run())# Add to the SimpleScalper class initialization:
    def __init__(self, config_path: str = "config.json"):
        # ... existing initialization ...

        # Add scaling parameters
        self.PARAMS.update({
            'position_size': 0.01,      # Initial 1% position
            'scale_increment': 0.001,   # Add 0.001 SOL per 5 wins
            'wins_to_scale': 5,         # Scale after 5 profitable trades
            'stop_loss': 0.05,         # 5% stop loss
            'stale_timeout': 45,       # Exit if no movement in 45 seconds
            'min_price_move': 0.002    # Minimum price movement to not be stale
        })
        
        # Add trade tracking
        self.trade_stats = {
            'consecutive_wins': 0,
            'total_trades': 0,
            'profitable_trades': 0,
            'current_position_size': self.PARAMS['position_size']
        }

    async def execute_trade(self, token: str, metrics: dict):
        """Execute trade with position scaling"""
        try:
            if (metrics['volume'] >= self.PARAMS['min_volume'] and 
                metrics['bs_ratio'] >= self.PARAMS['min_bs_ratio']):
                
                logger.info("\n🎯 TRADE OPPORTUNITY:")
                logger.info(f"Volume: {metrics['volume']:.2f} SOL")
                logger.info(f"B/S Ratio: {metrics['bs_ratio']:.2f}")
                logger.info(f"Position Size: {self.trade_stats['current_position_size']:.4f} SOL")
                
                # Get balance
                balance = await self.trading_core.get_balance()
                position_size = min(
                    balance * self.trade_stats['current_position_size'],
                    balance - self.PARAMS['gas_buffer']
                )
                
                logger.info(f"Taking position: {position_size:.4f} SOL")
                
                # Execute buy
                swap_data = await self.trading_core.buy_token(token, position_size)
                signature = await self.trading_core.execute_jupiter_swap(swap_data)
                
                if signature:
                    logger.info(f"✅ Entry successful: {signature}")
                    self.market_data[token].update({
                        'in_position': True,
                        'entry_time': time.time(),
                        'last_price_check': time.time(),
                        'entry_price': await self.get_token_price(token),
                        'last_price': await self.get_token_price(token),
                        'position_size': position_size
                    })
                
        except Exception as e:
            logger.error(f"Trade error: {e}")

    async def check_exit(self, token: str):
        """Check for exits including stale detection"""
        try:
            data = self.market_data[token]
            if not data['in_position']:
                return

            current_time = time.time()
            current_price = await self.get_token_price(token)
            
            if current_price == 0:
                logger.error("Failed to get price")
                return

            # Calculate profit/loss
            profit_pct = (current_price - data['entry_price']) / data['entry_price']
            
            # Check stop loss
            if profit_pct <= -self.PARAMS['stop_loss']:
                logger.info(f"⚠️ Stop loss hit: {profit_pct:.1%}")
                await self.exit_trade(token, profit_pct)
                return

            # Check take profit
            if profit_pct >= self.PARAMS['take_profit']:
                logger.info(f"🎯 Take profit hit: {profit_pct:.1%}")
                await self.exit_trade(token, profit_pct)
                return

            # Check for stale price
            price_change = abs(current_price - data['last_price']) / data['last_price']
            time_since_move = current_time - data['last_price_check']
            
            if price_change < self.PARAMS['min_price_move'] and time_since_move >= self.PARAMS['stale_timeout']:
                logger.info(f"⚠️ Position stale - exiting after {time_since_move:.0f}s")
                await self.exit_trade(token, profit_pct)
                return

            # Update last price if moved
            if price_change >= self.PARAMS['min_price_move']:
                data['last_price'] = current_price
                data['last_price_check'] = current_time

        except Exception as e:
            logger.error(f"Exit check error: {e}")

    async def exit_trade(self, token: str, profit_pct: float):
        """Exit position and update scaling"""
        try:
            data = self.market_data[token]
            
            # Execute exit
            swap_data = await self.trading_core.sell_token(
                token, 
                data['position_size']
            )
            signature = await self.trading_core.execute_jupiter_swap(swap_data)
            
            if signature:
                logger.info(f"✅ Exit successful: {signature}")
                
                # Update trade stats
                self.trade_stats['total_trades'] += 1
                
                if profit_pct > 0:
                    self.trade_stats['consecutive_wins'] += 1
                    self.trade_stats['profitable_trades'] += 1
                    
                    # Check for position scaling
                    if self.trade_stats['consecutive_wins'] >= self.PARAMS['wins_to_scale']:
                        self.trade_stats['current_position_size'] += self.PARAMS['scale_increment']
                        logger.info(f"🔼 Scaling up position size to {self.trade_stats['current_position_size']:.4f} SOL")
                        self.trade_stats['consecutive_wins'] = 0
                else:
                    self.trade_stats['consecutive_wins'] = 0
                
                # Log trade stats
                logger.info("\n📊 TRADE STATS:")
                logger.info(f"Total Trades: {self.trade_stats['total_trades']}")
                logger.info(f"Profitable: {self.trade_stats['profitable_trades']}")
                logger.info(f"Win Rate: {(self.trade_stats['profitable_trades']/self.trade_stats['total_trades'])*100:.1f}%")
                logger.info(f"Current Position Size: {self.trade_stats['current_position_size']:.4f} SOL")
                
                # Reset position data
                data['in_position'] = False
                
        except Exception as e:
            logger.error(f"Exit error: {e}")

    async def get_token_price(self, token: str) -> float:
        """Get token price from Jupiter"""
        try:
            quote = await self.trading_core.get_jupiter_quote(
                token,
                "So11111111111111111111111111111111111111112",
                int(1e9)
            )
            
            if quote:
                return float(quote['outAmount']) / 1e9
            return 0
            
        except Exception as e:
            logger.error(f"Price fetch error: {e}")
            return 0