File size: 5,287 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

from __future__ import annotations
from typing import Optional, Literal
import pandas as pd
from datetime import datetime
from .models import TradePlan, PositionState

def _hits_level(low: float, high: float, level: float) -> bool:
    return low <= level <= high

def _decide_exit_on_bar(
    side: Literal["long", "short"], low: float, high: float, target: float, stoploss: float,
    tiebreaker: Literal["stoploss_first", "target_first"] = "stoploss_first",
) -> Optional[dict]:
    if side == "long":
        hit_target = high >= target
        hit_stop = low <= stoploss
    else:
        hit_target = low <= target
        hit_stop = high >= stoploss

    if not hit_target and not hit_stop:
        return None
    if hit_target and hit_stop:
        return {"reason": "stoploss" if tiebreaker == "stoploss_first" else "target",
                "price": stoploss if tiebreaker == "stoploss_first" else target}
    return {"reason": "target", "price": target} if hit_target else {"reason": "stoploss", "price": stoploss}

def simulate_trade_from_signal(
    df: pd.DataFrame,
    trade: TradePlan,
    *,
    dt_col: str = "datetime",
    tiebreaker: Literal["stoploss_first", "target_first"] = "stoploss_first",
    lookback_minutes: int = 60,
    state: PositionState,
) -> PositionState:
    
    required = {"open","high","low","close", dt_col}
    if missing := [c for c in required if c not in df.columns]:
        raise ValueError(f"Missing columns: {missing}")

    if trade.status == "No trade":
        return state

    side = trade.type
    entry_at = float(trade.entry_at)
    target = float(trade.target)
    stoploss = float(trade.stoploss)

    ts = pd.to_datetime(df[dt_col])

    entered = state.entered
    exited = state.exited
    entry_time = state.entry_time
    entry_price = state.entry_price
    exit_time = state.exit_time
    exit_price = state.exit_price
    exit_reason = state.exit_reason

    if not entered:
        if side=="long" and entry_at<=stoploss:
            return PositionState(
            entered=entered, entry_time=entry_time, entry_price=entry_price, side=side,
            exited=exited, exit_time=exit_time, exit_price=exit_price, exit_reason=exit_reason,
            pnl_pct=state.pnl_pct, open_position=state.open_position, unrealized_pct=state.unrealized_pct,
            note="Error in pricing: Stoploss is higher than entry price for long side position, please adjust stoploss or entry price"
        )
        elif side=="short" and entry_at>=stoploss:
            return PositionState(
            entered=entered, entry_time=entry_time, entry_price=entry_price, side=side,
            exited=exited, exit_time=exit_time, exit_price=exit_price, exit_reason=exit_reason,
            pnl_pct=state.pnl_pct, open_position=state.open_position, unrealized_pct=state.unrealized_pct,
            note="Error in pricing: Stoploss is lower than entry price for short side position, please adjust stoploss or entry price"
            )

    # iterate last 'lookback_minutes' rows (assumes 1m bars)
    start_idx = max(0, abs(len(df) - int(lookback_minutes)))

    for i in range(start_idx, len(df)):
        row = df.iloc[i]
        time_i, o, h, l, c = ts.iloc[i], float(row['open']), float(row['high']), float(row['low']), float(row['close'])

        if not entered:
            if _hits_level(l, h, entry_at):
                entered = True
                entry_time = time_i
                entry_price = entry_at
                out = _decide_exit_on_bar(side, l, h, target, stoploss, tiebreaker)
                if out:
                    exited = True
                    exit_time = time_i
                    exit_price = out["price"]
                    exit_reason = out["reason"]
                    break
        else:
            out = _decide_exit_on_bar(side, l, h, target, stoploss, tiebreaker)
            if out:
                exited = True
                exit_time = time_i
                exit_price = out["price"]
                exit_reason = out["reason"]
                break

    def _pnl_pct(entry: float, exit_: float, side_: str) -> float:
        raw = (exit_ - entry) / entry
        return (raw if side_ == "long" else -raw) * 100.0

    if entered and exited:
        pnl = round(_pnl_pct(entry_price, exit_price, side), 4)
        return PositionState(
            entered=True, entry_time=entry_time, entry_price=entry_price, side=side,
            exited=True, exit_time=exit_time, exit_price=exit_price, exit_reason=exit_reason,
            pnl_pct=pnl, open_position=False, unrealized_pct=None,
        )

    if entered and not exited:
        last_close = float(df.iloc[-1]["close"]) if len(df) else entry_price
        upnl = round(_pnl_pct(entry_price, last_close, side), 4)
        return PositionState(
            entered=True, entry_time=entry_time, entry_price=entry_price, side=side,
            exited=False, open_position=True, unrealized_pct=upnl,
        )

    return state  # entry level never touched

def slice_intraday(df_1m: pd.DataFrame, start: datetime, end: datetime, dt_col: str = "datetime") -> pd.DataFrame:
    mask = (df_1m[dt_col] >= start) & (df_1m[dt_col] < end)
    out = df_1m.loc[mask].copy()
    out.reset_index(drop=True, inplace=True)
    return out