flowchart TD
A["Start Backtest"] --> B["Create Backtest Engine with Config"]
B --> C["Clear Global State<br/>(TOKEN_METRICS, TOKEN_TRACKING, HISTORICAL_TRADES)"]
C --> D["Initialize tokens_bought HashSet"]
D --> E["For Each Historical Trade"]
E --> F{"Is Buy Trade?"}
F -->|Yes| G["Calculate token_amount & sol_amount"]
G --> H{"Valid amounts?<br/>(token_amount > 0 && sol_amount > 0)"}
H -->|Yes| I["Record Buy Transaction"]
I --> J["Add to tokens_bought set"]
H -->|No| K["Skip Trade"]
F -->|No| L{"Do we own this token?<br/>(in tokens_bought set)"}
L -->|Yes| M["Call monitor_and_sell()"]
L -->|No| K
M --> N["Update TOKEN_METRICS with current price"]
N --> O["Check Selling Conditions"]
O --> P["Check Liquidity Conditions"]
O --> Q["Check Volume Conditions"]
O --> R["Check Price Conditions"]
O --> S["Check Time Conditions"]
O --> T["Check Wash Trading"]
O --> U["Check Large Holder Actions"]
P --> V["Collect sell_reasons"]
Q --> V
R --> V
S --> V
T --> V
U --> V
V --> W{"Any sell conditions met?<br/>(!sell_reasons.is_empty())"}
W -->|Yes| X["Determine Best Protocol"]
X --> Y["Create Enhanced Trade Info"]
Y --> Z["Execute Progressive Sell"]
Z --> AA["Record Trade Execution"]
AA --> BB["Remove from tokens_bought"]
W -->|No| CC["Continue Monitoring"]
J --> DD["Next Trade"]
K --> DD
BB --> DD
CC --> DD
DD --> EE{"More trades?"}
EE -->|Yes| E
EE -->|No| FF["Generate Backtest Report"]
FF --> GG["Calculate Statistics:<br/>• Total PnL<br/>• Win/Loss Ratio<br/>• Average Win/Loss<br/>• Hold Times<br/>• Exit Reasons"]
GG --> HH["Return Trade Records & Report"]
style A fill:#e1f5fe
style HH fill:#c8e6c9
style W fill:#fff3e0
style F fill:#fff3e0
style L fill:#fff3e0
style H fill:#fff3e0