|
|
|
|
|
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" |
|
|
) |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
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 |
|
|
|