summaryrefslogtreecommitdiff
path: root/services/backtester/tests/test_simulator.py
blob: f85594f062ea5ba2c81e55802b8b0af1f8983fb7 (plain)
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
"""Tests for the OrderSimulator."""

from datetime import UTC, datetime
from decimal import Decimal

from backtester.simulator import OrderSimulator

from shared.models import OrderSide, Signal


def make_signal(
    symbol: str,
    side: OrderSide,
    price: str,
    quantity: str,
    strategy: str = "test",
) -> Signal:
    return Signal(
        strategy=strategy,
        symbol=symbol,
        side=side,
        price=Decimal(price),
        quantity=Decimal(quantity),
        reason="test",
    )


# ---------------------------------------------------------------------------
# Existing tests (backward compat: defaults slippage=0, fee=0)
# ---------------------------------------------------------------------------


def test_simulator_initial_balance():
    sim = OrderSimulator(Decimal("10000"))
    assert sim.balance == Decimal("10000")


def test_simulator_buy_reduces_balance():
    sim = OrderSimulator(Decimal("10000"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    result = sim.execute(signal)
    assert result is True
    assert sim.balance == Decimal("5000")
    assert sim.positions["AAPL"] == Decimal("0.1")


def test_simulator_sell_increases_balance():
    sim = OrderSimulator(Decimal("10000"))
    buy_signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(buy_signal)
    balance_after_buy = sim.balance

    sell_signal = make_signal("AAPL", OrderSide.SELL, "55000", "0.1")
    result = sim.execute(sell_signal)
    assert result is True
    assert sim.balance > balance_after_buy
    # Profit: sold at 55000, bought at 50000 -> gain 500
    assert sim.balance == Decimal("10000") - Decimal("5000") + Decimal("5500")


def test_simulator_reject_buy_insufficient_balance():
    sim = OrderSimulator(Decimal("100"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    result = sim.execute(signal)
    assert result is False
    assert sim.balance == Decimal("100")
    assert sim.positions.get("AAPL", Decimal("0")) == Decimal("0")


def test_simulator_trade_history():
    sim = OrderSimulator(Decimal("10000"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal)
    assert len(sim.trades) == 1
    trade = sim.trades[0]
    assert trade.symbol == "AAPL"
    assert trade.side == OrderSide.BUY
    assert trade.price == Decimal("50000")
    assert trade.quantity == Decimal("0.1")


# ---------------------------------------------------------------------------
# Slippage tests
# ---------------------------------------------------------------------------


def test_slippage_on_buy():
    """Buy price should increase by slippage_pct."""
    sim = OrderSimulator(Decimal("100000"), slippage_pct=0.01)  # 1%
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal)
    trade = sim.trades[0]
    expected_price = Decimal("50000") * Decimal("1.01")  # 50500
    assert trade.price == expected_price


def test_slippage_on_sell():
    """Sell price should decrease by slippage_pct."""
    sim = OrderSimulator(Decimal("100000"), slippage_pct=0.01)
    # Buy first (no slippage check here, just need a position)
    buy = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(buy)
    # Sell
    sell = make_signal("AAPL", OrderSide.SELL, "50000", "0.1")
    sim.execute(sell)
    trade = sim.trades[1]
    expected_price = Decimal("50000") * Decimal("0.99")  # 49500
    assert trade.price == expected_price


# ---------------------------------------------------------------------------
# Fee tests
# ---------------------------------------------------------------------------


def test_fee_deducted_from_balance():
    """Fees should reduce balance beyond the raw cost."""
    fee_pct = 0.001  # 0.1%
    sim = OrderSimulator(Decimal("100000"), taker_fee_pct=fee_pct)
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal)
    # cost = 50000 * 0.1 = 5000, fee = 5000 * 0.001 = 5
    expected_balance = Decimal("100000") - Decimal("5000") - Decimal("5")
    assert sim.balance == expected_balance
    assert sim.trades[0].fee == Decimal("5")


# ---------------------------------------------------------------------------
# Stop-loss / take-profit tests
# ---------------------------------------------------------------------------


def test_stop_loss_triggers():
    """Long position auto-closed when candle_low <= stop_loss."""
    sim = OrderSimulator(Decimal("100000"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal, stop_loss=Decimal("48000"))

    ts = datetime(2025, 1, 1, tzinfo=UTC)
    closed = sim.check_stops(
        candle_high=Decimal("50500"),
        candle_low=Decimal("47500"),  # below stop_loss
        timestamp=ts,
    )
    assert len(closed) == 1
    assert closed[0].side == OrderSide.SELL
    assert closed[0].price == Decimal("48000")
    assert len(sim.open_positions) == 0


def test_take_profit_triggers():
    """Long position auto-closed when candle_high >= take_profit."""
    sim = OrderSimulator(Decimal("100000"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal, take_profit=Decimal("55000"))

    ts = datetime(2025, 1, 1, tzinfo=UTC)
    closed = sim.check_stops(
        candle_high=Decimal("56000"),  # above take_profit
        candle_low=Decimal("50000"),
        timestamp=ts,
    )
    assert len(closed) == 1
    assert closed[0].side == OrderSide.SELL
    assert closed[0].price == Decimal("55000")
    assert len(sim.open_positions) == 0


def test_stop_not_triggered_within_range():
    """No auto-close when price stays within stop/tp range."""
    sim = OrderSimulator(Decimal("100000"))
    signal = make_signal("AAPL", OrderSide.BUY, "50000", "0.1")
    sim.execute(signal, stop_loss=Decimal("48000"), take_profit=Decimal("55000"))

    ts = datetime(2025, 1, 1, tzinfo=UTC)
    closed = sim.check_stops(
        candle_high=Decimal("52000"),
        candle_low=Decimal("49000"),
        timestamp=ts,
    )
    assert len(closed) == 0
    assert len(sim.open_positions) == 1


# ---------------------------------------------------------------------------
# Short selling tests
# ---------------------------------------------------------------------------


def test_short_sell_allowed():
    """Can open short position with allow_short=True."""
    sim = OrderSimulator(Decimal("100000"), allow_short=True)
    signal = make_signal("AAPL", OrderSide.SELL, "50000", "0.1")
    result = sim.execute(signal)
    assert result is True
    assert sim.positions["AAPL"] == Decimal("-0.1")
    assert len(sim.open_positions) == 1
    assert sim.open_positions[0].side == OrderSide.SELL


def test_short_sell_rejected():
    """Short rejected when allow_short=False (default)."""
    sim = OrderSimulator(Decimal("100000"), allow_short=False)
    signal = make_signal("AAPL", OrderSide.SELL, "50000", "0.1")
    result = sim.execute(signal)
    assert result is False
    assert sim.positions.get("AAPL", Decimal("0")) == Decimal("0")


def test_short_stop_loss():
    """Short position stop-loss triggers on candle high >= stop_loss."""
    sim = OrderSimulator(Decimal("100000"), allow_short=True)
    signal = make_signal("AAPL", OrderSide.SELL, "50000", "0.1")
    sim.execute(signal, stop_loss=Decimal("52000"))

    ts = datetime(2025, 1, 1, tzinfo=UTC)
    closed = sim.check_stops(
        candle_high=Decimal("53000"),  # above stop_loss
        candle_low=Decimal("49000"),
        timestamp=ts,
    )
    assert len(closed) == 1
    assert closed[0].side == OrderSide.BUY  # closing a short = buy
    assert closed[0].price == Decimal("52000")
    assert len(sim.open_positions) == 0