File size: 13,999 Bytes
b1f38ad
8ced8b5
 
 
b1f38ad
 
 
 
 
 
 
 
 
 
8ced8b5
b1f38ad
8ced8b5
b1f38ad
 
 
 
8ced8b5
 
 
 
b1f38ad
8ced8b5
 
b1f38ad
 
8ced8b5
b1f38ad
 
 
 
8ced8b5
 
 
b1f38ad
 
8ced8b5
 
b1f38ad
 
 
 
 
 
 
8ced8b5
b1f38ad
 
8ced8b5
c68bdc6
eee8483
 
 
8ced8b5
b1f38ad
8ced8b5
 
b1f38ad
8ced8b5
b1f38ad
 
8ced8b5
b1f38ad
 
 
8ced8b5
 
 
b1f38ad
 
 
8ced8b5
b1f38ad
eee8483
 
 
5456a82
eee8483
 
 
 
 
 
5456a82
eee8483
5456a82
 
eee8483
5456a82
eee8483
 
5456a82
 
eee8483
 
 
 
 
 
b1f38ad
8ced8b5
b1f38ad
8ced8b5
 
b1f38ad
867cda8
8ced8b5
b1f38ad
 
 
867cda8
b1f38ad
 
8ced8b5
b1f38ad
 
8ced8b5
b1f38ad
 
 
 
 
8ced8b5
b1f38ad
 
 
8ced8b5
 
 
 
 
 
 
2b05b19
b1f38ad
8ced8b5
 
 
2b05b19
8ced8b5
 
 
2b05b19
8ced8b5
b1f38ad
 
 
8ced8b5
b1f38ad
2b05b19
 
 
 
 
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
2b05b19
 
b1f38ad
8ced8b5
b1f38ad
 
8ced8b5
b1f38ad
 
 
 
 
 
 
 
8ced8b5
 
 
 
b1f38ad
 
8ced8b5
b1f38ad
 
 
8ced8b5
b1f38ad
 
8ced8b5
b1f38ad
8ced8b5
b1f38ad
 
 
 
 
8ced8b5
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ced8b5
 
b1f38ad
8ced8b5
b1f38ad
 
 
 
8ced8b5
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
 
8ced8b5
b1f38ad
 
 
 
8ced8b5
b1f38ad
 
 
 
 
 
 
8ced8b5
b1f38ad
 
 
 
 
 
 
 
 
8ced8b5
b1f38ad
 
 
8ced8b5
b1f38ad
 
 
 
 
8ced8b5
b1f38ad
 
867cda8
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
 
 
8ced8b5
b1f38ad
 
8ced8b5
b1f38ad
 
867cda8
8ced8b5
b1f38ad
 
 
 
867cda8
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
 
 
8ced8b5
b1f38ad
 
 
 
 
8ced8b5
b1f38ad
8ced8b5
b1f38ad
 
 
 
8ced8b5
b1f38ad
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""
HMM-SVR Trading Bot with Simulated Exchange
Long-term trading strategy using HMM regime detection and SVR volatility prediction.
Checks for trading signals every 3 hours - designed for position trading, not high-frequency.
"""
from datetime import datetime, timedelta
from typing import Optional
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
import simulated_exchange
from models import TradingSession, Trade
from sqlmodel import Session, select
from database import engine
import uuid
from strategy_handlers import HMMSVRStrategyHandler

# Active trading sessions
simulated_sessions = {}


class SimulatedTradingSession:
    """
    HMM-SVR Trading Bot Session
    Long-only strategy using regime detection - checks every 3 hours
    """
    
    def __init__(self, session_id: str, user_email: str, symbol: str, 
                 trade_amount: float, duration_minutes: int):
        self.session_id = session_id
        self.user_email = user_email
        self.strategy = "hmm_svr"  # Only strategy supported
        self.symbol = symbol  # e.g., "BTCUSDT"
        self.trade_amount = trade_amount
        self.duration_minutes = duration_minutes
        
        # Parse trading pair (e.g., BTCUSDT -> BTC, USDT)
        if symbol.endswith("USDT"):
            self.base_asset = symbol[:-4]
            self.quote_asset = "USDT"
        else:
            self.base_asset = symbol
            self.quote_asset = "USDT"
        
        # Session state
        self.is_running = True
        self.start_time = datetime.now()
        self.end_time = self.start_time + timedelta(minutes=duration_minutes)
        self.total_pnl = 0.0
        self.trades_count = 0
        self.position = None  # None or 'LONG' (no SHORT for long-term strategy)
        self.entry_price = None
        
        print(f"[HMM-SVR Bot] {symbol} -> {self.base_asset}/{self.quote_asset}")
        
        # Auto-train model if not exists
        self._ensure_model_trained()
        
        # Initialize HMM-SVR strategy handler
        try:
            self.handler = HMMSVRStrategyHandler(symbol=self.base_asset)
            print(f"[HMM-SVR Bot] βœ… Strategy initialized")
        except Exception as e:
            print(f"[HMM-SVR Bot] ❌ Init failed: {e}")
            raise
        
        # Scheduler - checks every 3 hours
        self.scheduler = BackgroundScheduler()
        self.scheduler.add_job(
            func=self._trading_loop,
            trigger=IntervalTrigger(hours=3),
            id=f"hmm_svr_{session_id}",
            name=f"HMM-SVR Bot - {symbol}",
            replace_existing=True
        )
        
        print(f"[HMM-SVR Bot] Session created | Duration: {duration_minutes}min | Amount: ${trade_amount}")
    
    def _ensure_model_trained(self):
        """Check if model exists, train if not"""
        try:
            from model_manager import load_model, train_and_save_model
            
            # Check if model exists
            model_data = load_model(self.base_asset)
            
            if model_data is None:
                print(f"[HMM-SVR Bot] πŸ”„ No model found for {self.base_asset}, training now...")
                print(f"[HMM-SVR Bot] ⏳ Training on historical data (this may take 30-60 seconds)...")
                
                # Train model
                result = train_and_save_model(self.base_asset, n_states=3)
                
                if result and 'error' not in result:
                    print(f"[HMM-SVR Bot] βœ… Model trained successfully for {self.base_asset}")
                else:
                    error_msg = result.get('error', 'Unknown error') if result else 'Training failed'
                    print(f"[HMM-SVR Bot] ⚠️ Model training failed: {error_msg}")
            else:
                print(f"[HMM-SVR Bot] βœ… Model already trained for {self.base_asset}")
                
        except Exception as e:
            print(f"[HMM-SVR Bot] ⚠️ Error checking/training model: {e}")
    
    def start(self):
        """Start the trading bot"""
        self.scheduler.start()
        self._trading_loop()  # First check immediately
        print(f"[HMM-SVR Bot] βœ… Started - next check in 3 hours")
    
    def stop(self, close_positions: bool = False):
        """Stop the trading bot"""
        self.is_running = False
        self.scheduler.shutdown(wait=False)
        
        if close_positions and self.position:
            self._close_position()
        
        print(f"[HMM-SVR Bot] ⏹️ Stopped | Trades: {self.trades_count} | P&L: ${self.total_pnl:.2f}")
    
    def _trading_loop(self):
        """Main check - runs every 3 hours"""
        try:
            if not self.is_running:
                return
            
            if datetime.now() >= self.end_time:
                print(f"[HMM-SVR Bot] Session expired")
                _cleanup_expired_session(self.session_id)
                return
            
            # Get current price
            price = simulated_exchange.get_current_price(self.base_asset, self.quote_asset)
            if price is None:
                print(f"[HMM-SVR Bot] ❌ Could not fetch {self.symbol} price")
                return
            
            # Get signal from HMM-SVR model
            signal, position_size = self.handler.get_signal(price)
            
            # Log check
            elapsed_hours = (datetime.now() - self.start_time).total_seconds() / 3600
            position_str = self.position or 'NONE'
            print(f"[HMM-SVR Bot] ⏰ Check | {elapsed_hours:.1f}h | ${price:,.2f} | {signal} {position_size}x | Pos: {position_str}")
            
            # Execute based on signal (long-only strategy)
            if signal == "BUY" and self.position is None:
                self._open_long_position(price, position_size)
            elif signal == "SELL" and self.position == "LONG":
                self._close_position(price)
            
        except Exception as e:
            print(f"[HMM-SVR Bot] ❌ Error: {e}")
    
    def _open_long_position(self, price: float, position_size: float = 1.0):
        """Open a LONG position (BUY) with leverage multiplier"""
        # Apply position size multiplier (0x, 1x, or 3x)
        leveraged_amount = self.trade_amount * position_size
        quantity = leveraged_amount / price
        
        success, trade_info = simulated_exchange.execute_buy(
            symbol=self.base_asset,
            quote_symbol=self.quote_asset,
            amount_to_buy=quantity,
            user_email=self.user_email
        )
        
        if success:
            self.position = "LONG"
            self.entry_price = price
            self._save_trade_to_db(trade_info)
            leverage_str = f" ({position_size}x)" if position_size != 1.0 else ""
            print(f"[HMM-SVR Bot] πŸ“ˆ LONG opened: {quantity:.8f} {self.base_asset} @ ${price:,.2f}{leverage_str}")
        else:
            print(f"[HMM-SVR Bot] ❌ Failed to open position")
    
    def _close_position(self, current_price: float = None):
        """Close LONG position by selling"""
        if not self.position:
            return
        
        if current_price is None:
            current_price = simulated_exchange.get_current_price(self.base_asset, self.quote_asset)
            if current_price is None:
                return
        
        # Sell all holdings to close position
        balance = simulated_exchange.get_balance(self.base_asset, self.user_email)
        if balance > 0.00001:
            success, trade_info = simulated_exchange.execute_sell(
                symbol=self.base_asset,
                quote_symbol=self.quote_asset,
                amount_to_sell=balance,
                user_email=self.user_email
            )
            if success:
                pnl = (current_price - self.entry_price) * balance
                self.total_pnl += pnl
                self._save_trade_to_db(trade_info, pnl=pnl)
                print(f"[HMM-SVR Bot] βœ… LONG closed | P&L: ${pnl:.2f}")
            else:
                print(f"[HMM-SVR Bot] ❌ Failed to close position")
        
        self.position = None
        self.entry_price = None
    
    def _save_trade_to_db(self, trade_info: dict, pnl: Optional[float] = None):
        """Save trade to database"""
        try:
            with Session(engine) as session:
                trade = Trade(
                    session_id=self.session_id,
                    user_email=self.user_email,
                    symbol=trade_info['symbol'],
                    side=trade_info['side'],
                    price=trade_info['price'],
                    quantity=trade_info['quantity'],
                    total=trade_info.get('total', trade_info.get('cost', 0)),
                    pnl=pnl,
                    executed_at=datetime.now()
                )
                session.add(trade)
                session.commit()
                
                # Only increment after successful DB save
                self.trades_count += 1
                
        except Exception as e:
            print(f"[SimTrading] Error saving trade: {e}")
    
    def get_status(self) -> dict:
        """Get current session status"""
        return {
            'session_id': self.session_id,
            'strategy': self.strategy,
            'symbol': self.symbol,
            'is_running': self.is_running,
            'position': self.position,
            'entry_price': self.entry_price,
            'trades_count': self.trades_count,
            'total_pnl': self.total_pnl,
            'start_time': self.start_time.isoformat(),
            'end_time': self.end_time.isoformat(),
            'time_remaining': max(0, (self.end_time - datetime.now()).total_seconds())
        }


def start_simulated_trading(user_email: str, symbol: str,
                           trade_amount: float, duration_minutes: int, **kwargs) -> dict:
    """
    Start HMM-SVR trading bot session
    
    Args:
        user_email: User identifier
        symbol: Trading pair (e.g., "BTCUSDT")
        trade_amount: Amount per trade in USDT
        duration_minutes: How long to run
    
    Returns:
        Session info dictionary
    """
    session_id = str(uuid.uuid4())
    
    # Create and start session
    session = SimulatedTradingSession(
        session_id=session_id,
        user_email=user_email,
        symbol=symbol,
        trade_amount=trade_amount,
        duration_minutes=duration_minutes
    )
    
    session.start()
    simulated_sessions[session_id] = session
    print(f"[HMM-SVR Bot] βœ… Session {session_id} active")
    
    # Save to database
    try:
        with Session(engine) as db_session:
            db_trading_session = TradingSession(
                session_id=session_id,
                user_email=user_email,
                strategy="hmm_svr",
                symbol=symbol,
                trade_amount=trade_amount,
                duration_minutes=duration_minutes,
                start_time=datetime.now(),
                is_running=True
            )
            db_session.add(db_trading_session)
            db_session.commit()
    except Exception as e:
        print(f"[HMM-SVR Bot] DB error: {e}")
    
    return {
        'session_id': session_id,
        'message': f'HMM-SVR trading bot started for {symbol}',
        'status': session.get_status()
    }


def _cleanup_expired_session(session_id: str):
    """Clean up expired session"""
    if session_id in simulated_sessions:
        session = simulated_sessions[session_id]
        session.stop(close_positions=False)
        
        # Update database
        try:
            with Session(engine) as db_session:
                stmt = select(TradingSession).where(TradingSession.session_id == session_id)
                db_trading_session = db_session.exec(stmt).first()
                if db_trading_session:
                    db_trading_session.is_running = False
                    db_trading_session.end_time = datetime.now()
                    db_trading_session.total_pnl = session.total_pnl
                    db_trading_session.trades_count = session.trades_count
                    db_session.add(db_trading_session)
                    db_session.commit()
        except Exception as e:
            print(f"[HMM-SVR Bot] DB error: {e}")
        
        del simulated_sessions[session_id]
        print(f"[HMM-SVR Bot] Session expired")


def stop_simulated_trading(session_id: str, close_positions: bool = False) -> dict:
    """Stop trading bot session"""
    if session_id not in simulated_sessions:
        return {'error': 'Session not found'}
    
    session = simulated_sessions[session_id]
    session.stop(close_positions=close_positions)
    
    # Update database
    try:
        with Session(engine) as db_session:
            stmt = select(TradingSession).where(TradingSession.session_id == session_id)
            db_trading_session = db_session.exec(stmt).first()
            if db_trading_session:
                db_trading_session.is_running = False
                db_trading_session.end_time = datetime.now()
                db_trading_session.total_pnl = session.total_pnl
                db_trading_session.trades_count = session.trades_count
                db_session.add(db_trading_session)
                db_session.commit()
    except Exception as e:
        print(f"[HMM-SVR Bot] DB error: {e}")
    
    del simulated_sessions[session_id]
    
    return {
        'session_id': session_id,
        'message': 'Bot stopped',
        'total_pnl': session.total_pnl,
        'trades_count': session.trades_count
    }


def get_simulated_session_status(session_id: str) -> dict:
    """Get bot session status"""
    if session_id not in simulated_sessions:
        return {'error': 'Session not found'}
    
    return simulated_sessions[session_id].get_status()