52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
"""
|
|
止损模块单元测试
|
|
关羽 guanyu-dev
|
|
"""
|
|
|
|
import math
|
|
import pytest
|
|
from stop_loss import FixedStopLoss, TrailingStopLoss
|
|
|
|
|
|
class TestFixedStopLoss:
|
|
"""固定止损测试。"""
|
|
|
|
def test_triggered(self):
|
|
sl = FixedStopLoss(stop_price=100.0)
|
|
assert sl.check(99.9) is True
|
|
|
|
def test_triggered_at_stop(self):
|
|
sl = FixedStopLoss(stop_price=100.0)
|
|
assert sl.check(100.0) is True # 等于止损价也触发
|
|
|
|
def test_not_triggered(self):
|
|
sl = FixedStopLoss(stop_price=100.0)
|
|
assert sl.check(100.1) is False
|
|
|
|
|
|
class TestTrailingStopLoss:
|
|
"""追踪止损测试。"""
|
|
|
|
def test_not_activated_below_activation(self):
|
|
tsl = TrailingStopLoss(activation_price=100.0, trail_percent=0.05)
|
|
tsl.update(95.0)
|
|
assert tsl.check(95.0) is False
|
|
|
|
def test_activated_and_update_high(self):
|
|
tsl = TrailingStopLoss(activation_price=100.0, trail_percent=0.05)
|
|
tsl.update(100.0) # activate, high=100
|
|
tsl.update(110.0) # high=110, stop=104.5
|
|
assert math.isclose(tsl.stop_price, 104.5)
|
|
|
|
def test_triggered_after_pullback(self):
|
|
tsl = TrailingStopLoss(activation_price=100.0, trail_percent=0.05)
|
|
tsl.update(100.0) # activate, high=100
|
|
tsl.update(110.0) # high=110, stop=104.5
|
|
assert tsl.check(104.4) is True
|
|
|
|
def test_not_triggered_in_trail(self):
|
|
tsl = TrailingStopLoss(activation_price=100.0, trail_percent=0.05)
|
|
tsl.update(100.0)
|
|
tsl.update(110.0) # stop=104.5
|
|
assert tsl.check(105.0) is False
|