File size: 32,990 Bytes
45a77a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
from __future__ import annotations
import pandas as pd
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, List, Literal, Hashable, cast

from .models import PositionState, TradePlan, SummaryBankNifty, DecisionOutput
from .llm import LLMClient
from .prompts import (
    USER_MORNING,
    USER_DECIDE_TRADE,
    USER_INTRAHOUR_UPDATE,
    USER_INTRAHOUR_UPDATE_2,
    USER_CLOSING,
)
from .utils import hour_passed, hourly_ohlc_dict
from .simulator import simulate_trade_from_signal, slice_intraday
from .news import summaries_between
from .writer import to_excel_safely
from .checkpoint import CheckpointManager


class Engine:
    def __init__(self, *, llm: LLMClient, logger, bundle, out_dir, checkpoint: CheckpointManager):
        self.llm = llm
        self.log = logger
        self.bundle = bundle
        self.out_dir = out_dir
        self.ckpt = checkpoint

        # --- Restore from checkpoint if available ---
        (
            self.last_timestamp_processed,
            self.state,
            self.current_plan,
            self.last_close_plan,
            self.memory_str,
            loaded_logs,
        ) = self.ckpt.load()

        # In-memory logs we keep appending to this run
        def _seed(df: pd.DataFrame) -> List[Dict[str, Any]]:
            return cast(List[Dict[str, Any]],
                        df.to_dict(orient="records") if not df.empty else [])


        self.trade_log   = _seed(loaded_logs["trade"])
        self.stats_log   = _seed(loaded_logs["stats"])
        self.expert_log  = _seed(loaded_logs["expert"])
        self.summary_log = _seed(loaded_logs["summary"])

        # Rolling context across ticks
        self.last_summary_bn: Optional[SummaryBankNifty] = None
        self.last_sentiment: Optional[str] = None
        self.morning_summary_full = None  # morning Summary (banknifty/nifty prep)
        self.last_slice_start: Optional[datetime] = None  # anchor for intraday sim slices

    # ------------------------------------------------------------------
    # Utilities for saving, market data extraction, and forced exits
    # ------------------------------------------------------------------

    def _flush_to_excels(self):
        """Write human-friendly Excel snapshots at the very end of run()."""
        to_excel_safely(pd.DataFrame(self.stats_log),   self.out_dir / "stats_log.xlsx")
        to_excel_safely(pd.DataFrame(self.trade_log),   self.out_dir / "trade_log.xlsx")
        to_excel_safely(pd.DataFrame(self.expert_log),  self.out_dir / "expert_log.xlsx")
        to_excel_safely(pd.DataFrame(self.summary_log), self.out_dir / "summary_log.xlsx")

    def _save_checkpoint_now(self, ts: datetime):
        """Persist all critical state + logs after processing timestamp ts."""
        self.ckpt.save(
            last_ts=ts,
            state=self.state,
            current_plan=self.current_plan,
            last_close_plan=self.last_close_plan,
            memory_str=self.memory_str,
            trade_log=self.trade_log,
            stats_log=self.stats_log,
            expert_log=self.expert_log,
            summary_log=self.summary_log,
        )
        self.last_timestamp_processed = ts

    def _sentiment_for(self, day: datetime):
        df = self.bundle.df_sentiment
        row = df[df["predicted_for"].dt.date == day.date()]
        if row.empty:
            return ("neutral", "No sentiment row found")
        return (
            row.iloc[0]["proposed_sentiment"],
            row.iloc[0].get("reasoning", ""),
        )

    def _expert_text(self, day: datetime) -> str:
        df = self.bundle.df_transcript
        # try to detect a column like "Prediction_for_date"
        date_cols = [c for c in df.columns if c.lower().startswith("prediction_for")]
        dt_col = date_cols[0] if date_cols else "Prediction_for_date"
        row = df[df[dt_col].dt.date == day.date()]
        if row.empty:
            return "No expert analysis is available; use technicals."
        return row.iloc[0]["Transcript"]

    def _day_ohlc(self, df: pd.DataFrame, dt_col: str, day: datetime):
        d = df[df[dt_col].dt.date == day.date()]
        if d.empty:
            raise ValueError(f"No data for {day.date()}")
        o = float(d.iloc[0]["open"])
        h = float(d["high"].max())
        l = float(d["low"].min())
        c = float(d.iloc[-1]["close"])
        return {"open": o, "high": h, "low": l, "close": c}

    def _nifty_prev(self, day: datetime):
        ohlc = self._day_ohlc(self.bundle.df_nifty_daily, "datetime", day)
        row = self.bundle.df_nifty_daily[
            self.bundle.df_nifty_daily["datetime"].dt.date == day.date()
        ].iloc[0]
        return {
            "ohlc": ohlc,
            "ind": {
                "RSI": round(float(row["RSI"]), 2),
                "MACD_Line": round(float(row["MACD_Line"]), 2),
                "MACD_Signal": round(float(row["Signal_Line"]), 2),
            },
        }

    def _bn_prev(self, ts_prev: datetime):
        ohlc = self._day_ohlc(self.bundle.df_bn_hourly, "datetime", ts_prev)
        row = self.bundle.df_bn_hourly[
            self.bundle.df_bn_hourly["datetime"] == ts_prev
        ].iloc[0]
        return {
            "ohlc": ohlc,
            "ind": {
                "RSI": round(float(row["RSI"]), 2),
                "MACD_Line": round(float(row["MACD_Line"]), 2),
                "MACD_Signal": round(float(row["Signal_Line"]), 2),
            },
        }
    def _prev_hour_ts(self, ts: datetime) -> Optional[datetime]:
        """
        Return the last hourly timestamp strictly before `ts` from df_bn_hourly.
        Used to avoid lookahead when we need 'previous bar' context.
        """
        df = self.bundle.df_bn_hourly
        col = df["datetime"]
        prev_candidates = col[col < ts]
        if prev_candidates.empty:
            return None
        return prev_candidates.max()


    def _force_flatten_position(self, ts: datetime, reason: Literal["target", "stoploss", "Exited at market price","market close"]):
        """
        Exit any open position at the close of timestamp ts.
        This logs realized stats, updates memory_str, and resets self.state.
        """
        # grab that hour's close as "market exit"
        close_px = float(
            self.bundle.df_bn_1m[
                self.bundle.df_bn_1m["datetime"] == ts
            ]["close"].values[0]
        )

        pnl_pct_val = None
        if self.state.entered and self.state.entry_price is not None:
            raw = (close_px - self.state.entry_price) / self.state.entry_price
            if self.state.side == "short":
                raw = -raw
            pnl_pct_val = round(raw * 100.0, 4)

        exited_state = PositionState(
            entered=True,
            entry_time=self.state.entry_time,
            entry_price=self.state.entry_price,
            side=self.state.side,
            exited=True,
            exit_time=ts,
            exit_price=close_px,
            exit_reason=reason,
            pnl_pct=pnl_pct_val,
            open_position=False,
            unrealized_pct=None,
        )

        # log exit stats snapshot
        self.stats_log.append({**exited_state.model_dump(), "datetime": ts})

        # update "memory_str" to feed LLM next turn
        if exited_state.side is not None:
            self.memory_str = (
                "{"
                f"\"side\": \"{exited_state.side}\", "
                f"\"entry_price\": {exited_state.entry_price}, "
                f"\"exit_price\": {exited_state.exit_price}, "
                f"\"pnl_pct\": {exited_state.pnl_pct}, "
                f"\"exit_reason\": \"{exited_state.exit_reason}\""
                "}"
            )
        else:
            self.memory_str = "No trade completed"

        # reset to flat
        self.state = PositionState()

    # ------------------------------------------------------------------
    # Main replay / inference loop with resume + carry-forward
    # ------------------------------------------------------------------
    def run(self, start_ts: datetime, end_ts: datetime):
        # Build the list of timestamps to iterate
        hourly_ts = self.bundle.df_bn_hourly["datetime"]
        timeline = (
            hourly_ts[(hourly_ts >= start_ts) & (hourly_ts <= end_ts)]
            .sort_values()
            .tolist()
        )

        if len(timeline) < 2:
            raise ValueError("Not enough hourly timestamps in range")

        # Skip timestamps we've already processed (resume support)
        if self.last_timestamp_processed is not None:
            timeline = [t for t in timeline if t > self.last_timestamp_processed]

        # Initialize slice anchor for intraday sim if first time
        if self.last_slice_start is None:
            if self.last_timestamp_processed is not None:
                self.last_slice_start = self.last_timestamp_processed
            elif timeline:
                self.last_slice_start = timeline[0]
        
        post_must_flatten=False
        side_change=False
        for i, ts in enumerate(timeline):
            self.log.info(f"[Engine] Tick {i}: {ts}")
            print(ts)
            # ------------------------------------------------------
            # Define "previous bar" for this tick (no lookahead)
            # ------------------------------------------------------
            if i > 0:
                # previous bar within this run
                prev_ts = timeline[i - 1]
            elif self.last_timestamp_processed is not None:
                # first bar after a resume: use last processed bar
                prev_ts = self.last_timestamp_processed
            else:
                # cold start: pull previous bar from the full dataset
                prev_ts = self._prev_hour_ts(ts)
            # ----------------------------------------------------------
            # 09:15 block (morning prep and first plan of the session)
            # ----------------------------------------------------------
            if ts.time().hour == 9 and ts.time().minute == 15:
                if prev_ts is None:
                    raise ValueError("No previous timestamp available for 09:15 logic")
                bn_prev = self._bn_prev(prev_ts)
                nf_prev = self._nifty_prev(prev_ts)
                sentiment, sent_reason = self._sentiment_for(ts)
                expert_text = self._expert_text(ts)
                # news = summaries_between(
                #     self.bundle.df_news, "datetime_ist", ts - timedelta(hours=17,minutes=45), ts
                # )

                # 1) Morning summary from LLM
                user_morning = USER_MORNING.format(
                    nifty_ohlc=nf_prev["ohlc"],
                    nifty_ind=nf_prev["ind"],
                    bn_ohlc=bn_prev["ohlc"],
                    bn_ind=bn_prev["ind"],
                    sentiment=sentiment,
                    sentiment_reason=sent_reason,
                    expert=expert_text,
                    # news=news
                )
                morning_summary = self.llm.morning_summary(user_morning)
                self.expert_log.append(
                    {**morning_summary.model_dump(), "predicted_for": ts.date()}
                )

                # 2) Build the morning trade decision prompt
                # priority:
                #   (a) last_close_plan from previous session
                #   (b) current_plan we carried through resume
                #   (c) default "No trade"
                if self.last_close_plan is not None:
                    opening_trade_context = self.last_close_plan.model_dump()
                elif self.current_plan is not None:
                    opening_trade_context = self.current_plan.model_dump()
                else:
                    opening_trade_context = {
                        "status": "No trade",
                        "brief_reason": "init",
                        "type": "none",
                        "entry_at": 0,
                        "target": 0,
                        "stoploss": 0,
                    }

                user_decide = USER_DECIDE_TRADE.format(
                    major_concern=morning_summary.major_concern_banknifty,
                    sentiment=sentiment,
                    strategy=morning_summary.trade_strategy_banknifty,
                    reason=morning_summary.trade_reasoning_banknifty,
                    bn_ohlc=bn_prev["ohlc"],
                    bn_ind=bn_prev["ind"],
                    trade=opening_trade_context,
                    position=self.state.to_compact(ts),
                    memory=self.memory_str,
                )

                first_plan = self.llm.trade_plan(user_decide)
                
                self.current_plan = first_plan

                post_must_flatten = False
                side_change = False
                if self.state.open_position and self.current_plan is not None:
                    
                    if self.current_plan.status == "No trade":
                        post_must_flatten = True
                    elif (
                        self.current_plan.status == "Trade"
                        and self.current_plan.type != self.state.side
                    ):
                        post_must_flatten = True
                        side_change=True
                    if post_must_flatten:
                        self._force_flatten_position(ts, reason="Exited at market price")
                        self.last_slice_start = ts
                        if side_change:
                            post_must_flatten=False

                # Commit plan+context
                self.current_plan = first_plan
                self.trade_log.append({**first_plan.model_dump(), "datetime": ts})

                self.last_sentiment = sentiment
                self.morning_summary_full = morning_summary
                self.last_slice_start = ts
                self._save_checkpoint_now(ts)
                
            # ----------------------------------------------------------
            # 10:15 block (first intraday decision after open)
            # ----------------------------------------------------------
            elif ts.time().hour == 10 and ts.time().minute == 15:

                # STEP 1: simulate last slice (last_slice_start -> ts)
                if self.last_slice_start and self.current_plan and post_must_flatten==False:
                    intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start, ts)
                    if not intraday.empty:
                        new_state = simulate_trade_from_signal(
                            df=intraday,
                            trade=self.current_plan,
                            dt_col="datetime",
                            state=self.state,
                            lookback_minutes=60,
                        )
                        if self.state.model_dump() != new_state.model_dump():
                            # We log the transition
                            self.stats_log.append({**new_state.model_dump(), "datetime": ts})
                        # If the new_state is exited (trade is fully closed), finalize it
                        if new_state.exited and not new_state.open_position:
                            # update memory_str once
                            if new_state.side is not None:
                                self.memory_str = (
                                    "{"
                                    f"\"side\": \"{new_state.side}\", "
                                    f"\"entry_price\": {new_state.entry_price}, "
                                    f"\"exit_price\": {new_state.exit_price}, "
                                    f"\"pnl_pct\": {new_state.pnl_pct}, "
                                    f"\"exit_reason\": \"{new_state.exit_reason}\""
                                    "}"
                                )
                            else:
                                self.memory_str = "No trade completed"

                            # reset engine state to flat so we don't keep re-logging this closed trade
                            self.state = PositionState()
                            # after closing, next slice should start from here
                            self.last_slice_start = ts

                        else:
                            # still in position (or haven't entered yet) -> keep tracking
                            self.state = new_state

                self.last_slice_start = ts

                # STEP 2: ask LLM for updated decision at 10:15
                news_last_hour = summaries_between(
                    self.bundle.df_news, "datetime_ist", ts - timedelta(hours=1), ts
                )
                hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts)

                if prev_ts is None:
                    raise ValueError("No previous timestamp available for after 11:15 logic")
                prev_ts_for_ind = prev_ts
                bn_now = self._bn_prev(prev_ts_for_ind)

                user_update = USER_INTRAHOUR_UPDATE.format(
                    news=news_last_hour,
                    hourly_ohlc=hourly_dict,
                    bn_ind=bn_now["ind"],
                    trade=self.current_plan.model_dump() if self.current_plan else {},
                    position=self.state.to_compact(ts),
                    hours_since_open=hour_passed(ts),
                    major_concern=self.morning_summary_full.major_concern_banknifty
                    if self.morning_summary_full else "",
                    sentiment=self.last_sentiment if self.last_sentiment else "",
                    strategy=self.morning_summary_full.trade_strategy_banknifty
                    if self.morning_summary_full else "",
                    reason=self.morning_summary_full.trade_reasoning_banknifty
                    if self.morning_summary_full else "",
                    memory=self.memory_str,
                )

                decision: DecisionOutput = self.llm.trade_decision_output(user_update)
                new_plan = decision.trade
                self.last_summary_bn = decision.summary_banknifty

                # STEP 3: enforce the NEW decision right away
                post_must_flatten = False
                side_change=False
                if self.state.open_position:
                    if new_plan.status == "No trade":
                        post_must_flatten = True
                    elif new_plan.status == "Trade" and new_plan.type != self.state.side:
                        post_must_flatten = True
                        side_change=True

                if post_must_flatten:
                    self._force_flatten_position(ts, reason="Exited at market price")
                    self.last_slice_start = ts
                    if side_change:
                        post_must_flatten=False

                # STEP 4: accept/record plan + summary
                self.current_plan = new_plan
                self.trade_log.append({**new_plan.model_dump(), "datetime": ts})
                self.summary_log.append(
                    {**decision.summary_banknifty.model_dump(), "datetime": ts}
                )
                self._save_checkpoint_now(ts)
            # ----------------------------------------------------------
            # Intraday updates for 11:15 .. 15:15 
            # ----------------------------------------------------------
            else:

                # STEP 1: simulate previous slice with current plan
                if self.last_slice_start and self.current_plan and post_must_flatten==False:
                    intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start, ts)
                    if not intraday.empty:
                        new_state = simulate_trade_from_signal(
                            df=intraday,
                            trade=self.current_plan,
                            dt_col="datetime",
                            state=self.state,
                            lookback_minutes=60,
                        )
                        if self.state.model_dump() != new_state.model_dump():
                            # We log the transition
                            self.stats_log.append({**new_state.model_dump(), "datetime": ts})
                        # If the new_state is exited (trade is fully closed), finalize it
                        if new_state.exited and not new_state.open_position:
                            # update memory_str once
                            if new_state.side is not None:
                                self.memory_str = (
                                    "{"
                                    f"\"side\": \"{new_state.side}\", "
                                    f"\"entry_price\": {new_state.entry_price}, "
                                    f"\"exit_price\": {new_state.exit_price}, "
                                    f"\"pnl_pct\": {new_state.pnl_pct}, "
                                    f"\"exit_reason\": \"{new_state.exit_reason}\""
                                    "}"
                                )
                            else:
                                self.memory_str = "No trade completed"

                            # reset engine state to flat so we don't keep re-logging this closed trade
                            self.state = PositionState()
                            # after closing, next slice should start from here
                            self.last_slice_start = ts

                        else:
                            # still in position (or haven't entered yet) -> keep tracking
                            self.state = new_state
                self.last_slice_start = ts

                # STEP 2: query LLM for updated decision
                news_last_hour = summaries_between(
                    self.bundle.df_news, "datetime_ist", ts - timedelta(hours=1), ts
                )
                hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts)
                
                if prev_ts is None:
                    raise ValueError("No previous timestamp available for after 11:15 logic")
                prev_ts_for_ind = prev_ts
                bn_now = self._bn_prev(prev_ts_for_ind)
                

                user_update2 = USER_INTRAHOUR_UPDATE_2.format(
                    news=news_last_hour,
                    news_summary=self.last_summary_bn.news_summary if self.last_summary_bn else "",
                    hourly_ohlc=hourly_dict,
                    bn_ind=bn_now["ind"],
                    trade=self.current_plan.model_dump() if self.current_plan else {},
                    position=self.state.to_compact(ts),
                    hours_since_open=hour_passed(ts),
                    major_concern=self.last_summary_bn.major_concern if self.last_summary_bn else "",
                    sentiment=self.last_summary_bn.sentiment if self.last_summary_bn else "",
                    strategy=self.last_summary_bn.trade_strategy if self.last_summary_bn else "",
                    reason=self.last_summary_bn.reasoning if self.last_summary_bn else "",
                    memory=self.memory_str,
                )

                decision: DecisionOutput = self.llm.trade_decision_output(user_update2)
                new_plan = decision.trade
                self.last_summary_bn = decision.summary_banknifty

                # STEP 3: enforce the NEW decision
                post_must_flatten = False
                side_change=False
                if self.state.open_position:
                    if new_plan.status == "No trade":
                        post_must_flatten = True
                    elif new_plan.status == "Trade" and new_plan.type != self.state.side:
                        post_must_flatten = True
                        side_change=True

                if post_must_flatten:
                    self._force_flatten_position(ts, reason="Exited at market price")
                    self.last_slice_start = ts
                    if side_change:
                        post_must_flatten=False

                # STEP 4: record plan + summary
                self.current_plan = new_plan
                self.trade_log.append({**new_plan.model_dump(), "datetime": ts})
                self.summary_log.append(
                    {**decision.summary_banknifty.model_dump(), "datetime": ts}
                )
                self._save_checkpoint_now(ts)
               #################### #15-15 block

                if (ts.time().hour == 15 and ts.time().minute == 15):
                    print(ts+timedelta(minutes=14))

                    # STEP 1: simulate previous slice with current plan
                    if self.last_slice_start and self.current_plan and post_must_flatten == False:
                        intraday = slice_intraday(self.bundle.df_bn_1m, self.last_slice_start,(ts+timedelta(minutes=14)))
                        if not intraday.empty:
                            new_state = simulate_trade_from_signal(
                                df=intraday,
                                trade=self.current_plan,
                                dt_col="datetime",
                                state=self.state,
                                lookback_minutes=14,
                            )
                            if self.state.model_dump() != new_state.model_dump():
                                # We log the transition
                                self.stats_log.append({**new_state.model_dump(), "datetime": ts+timedelta(minutes=14)})
                            # If the new_state is exited (trade is fully closed), finalize it
                            if new_state.exited and not new_state.open_position:
                                # update memory_str once
                                if new_state.side is not None:
                                    self.memory_str = (
                                        "{"
                                        f"\"side\": \"{new_state.side}\", "
                                        f"\"entry_price\": {new_state.entry_price}, "
                                        f"\"exit_price\": {new_state.exit_price}, "
                                        f"\"pnl_pct\": {new_state.pnl_pct}, "
                                        f"\"exit_reason\": \"{new_state.exit_reason}\""
                                        "}"
                                    )
                                else:
                                    self.memory_str = "No trade completed"

                                # reset engine state to flat so we don't keep re-logging this closed trade
                                self.state = PositionState()
                                # after closing, next slice should start from here
                                self.last_slice_start = (ts+timedelta(minutes=14))

                            else:
                                # still in position (or haven't entered yet) -> keep tracking
                                self.state = new_state
                    self.last_slice_start = (ts+timedelta(minutes=14))

                    #decision of carry forward or not at 15-30
                    news_last_15m = summaries_between( self.bundle.df_news, "datetime_ist", ts, ts + timedelta(minutes=14)) 
                    hourly_dict = hourly_ohlc_dict(self.bundle.df_bn_hourly, "datetime", ts + timedelta(minutes=15)) 
                    
                    prev_ts_for_ind = ts
                    bn_prev_for_ind = self._bn_prev(prev_ts_for_ind) 
                    
                    user_close = USER_CLOSING.format( news=news_last_15m, news_summary=self.last_summary_bn.news_summary if self.last_summary_bn else "",
                                                    hourly_ohlc=hourly_dict, bn_ind=bn_prev_for_ind["ind"], 
                                                    trade=self.current_plan.model_dump() if self.current_plan else {}, 
                                                    position=self.state.to_compact(ts), 
                                                    major_concern=self.last_summary_bn.major_concern if self.last_summary_bn else "", 
                                                    sentiment=self.last_summary_bn.sentiment if self.last_summary_bn else "", 
                                                    strategy=self.last_summary_bn.trade_strategy if self.last_summary_bn else "", 
                                                    reason=self.last_summary_bn.reasoning if self.last_summary_bn else "", 
                                                    memory=self.memory_str, ) 
                    close_plan = self.llm.trade_plan(user_close)
                    last_1_min=ts+timedelta(minutes=14)
                    intraday_data = slice_intraday(self.bundle.df_bn_1m, last_1_min, (ts+timedelta(minutes=15)))  # Get the data for last minute

                    post_must_flatten = False
                    side_change=False
                    if self.state.open_position:
                        if close_plan.status == "No trade":
                            post_must_flatten = True
                        elif close_plan.status == "Trade" and close_plan.type != self.state.side:
                            post_must_flatten = True
                            side_change=True

                    if post_must_flatten:
                        self._force_flatten_position((ts+timedelta(minutes=14)), reason="market close")
                        self.last_slice_start = ts
                        if side_change:
                            post_must_flatten=False
                    
                    if not intraday_data.empty and post_must_flatten == False:
                        # Simulate the trade for the last 1 minutes
                        new_state = simulate_trade_from_signal(
                            df=intraday_data, trade=close_plan, 
                            dt_col="datetime", state=self.state, lookback_minutes=1
                        )

                        # Check if the state has actually changed
                        if self.state.model_dump() != new_state.model_dump():
                            # Log the transition
                            self.stats_log.append({**new_state.model_dump(), "datetime": ts+timedelta(minutes=15)})

                        # If the new state is exited (trade is fully closed), finalize it
                        if new_state.exited and not new_state.open_position:
                            # Update memory_str once the trade is closed
                            if new_state.side is not None:
                                self.memory_str = (
                                    "{"
                                    f"\"side\": \"{new_state.side}\", "
                                    f"\"entry_price\": {new_state.entry_price}, "
                                    f"\"exit_price\": {new_state.exit_price}, "
                                    f"\"pnl_pct\": {new_state.pnl_pct}, "
                                    f"\"exit_reason\": \"{new_state.exit_reason}\""
                                    "}"
                                )
                            else:
                                self.memory_str = "No trade completed"

                            # Reset engine state to flat so we don't keep re-logging this closed trade
                            self.state = PositionState()

                            # After closing, next slice should start from here
                            self.last_slice_start = (ts+timedelta(minutes=15))
                        else:
                            # Still in position (or haven't entered yet) -> keep tracking
                            self.state = new_state
                    
                    
                    # Record the closing plan for next day at 09:15
                    self.current_plan = close_plan
                    self.last_close_plan = close_plan
                    self.trade_log.append({**close_plan.model_dump(), "datetime": ts+timedelta(minutes=14)})
                    # self._save_checkpoint_now(ts+timedelta(minutes=14))
                    # If we did NOT flatten, self.state still shows that position is open, so we carry overnight.
                    # We'll resume tomorrow with that.

            # ----------------------------------------------------------
            # Save checkpoint after every timestamp
            # ----------------------------------------------------------
            

        # After loop completes, dump friendly Excel snapshots
        self._flush_to_excels()