feat: 添加网格监控并修复程序卡死与打包启动
This commit is contained in:
@@ -9,7 +9,16 @@ from grid_trading.domain.calculations import (
|
||||
calculate_positions,
|
||||
estimate_fees,
|
||||
)
|
||||
from grid_trading.domain.models import Account, FeeRules, Instrument, QuoteSnapshot, Trade, TradeGroup, TradeSide
|
||||
from grid_trading.domain.models import (
|
||||
Account,
|
||||
FeeRules,
|
||||
GridDirection,
|
||||
Instrument,
|
||||
QuoteSnapshot,
|
||||
Trade,
|
||||
TradeGroup,
|
||||
TradeSide,
|
||||
)
|
||||
|
||||
|
||||
def make_trade(
|
||||
@@ -24,6 +33,7 @@ def make_trade(
|
||||
stamp_tax: str = "0",
|
||||
transfer_fee: str = "0",
|
||||
trade_group: TradeGroup = TradeGroup.GRID,
|
||||
grid_direction: GridDirection | None = None,
|
||||
) -> Trade:
|
||||
return Trade(
|
||||
id=trade_id,
|
||||
@@ -37,6 +47,7 @@ def make_trade(
|
||||
stamp_tax=Decimal(stamp_tax),
|
||||
transfer_fee=Decimal(transfer_fee),
|
||||
trade_group=trade_group,
|
||||
grid_direction=grid_direction,
|
||||
)
|
||||
|
||||
|
||||
@@ -100,7 +111,7 @@ def test_buy_sell_grid_profit_and_breakeven():
|
||||
assert summary.floating_pnl == Decimal("49.00")
|
||||
|
||||
|
||||
def test_t_plus_one_available_quantity_excludes_today_buys():
|
||||
def test_available_quantity_includes_today_buys():
|
||||
today = date(2026, 7, 8)
|
||||
instrument = Instrument(id=1, code="600000", name="浦发银行", manual_price=Decimal("10"))
|
||||
trades = [
|
||||
@@ -125,7 +136,48 @@ def test_t_plus_one_available_quantity_excludes_today_buys():
|
||||
[summary] = calculate_positions([instrument], trades, as_of=today)
|
||||
|
||||
assert summary.total_quantity == 300
|
||||
assert summary.available_quantity == 200
|
||||
assert summary.available_quantity == 300
|
||||
|
||||
|
||||
def test_reverse_grid_profit_is_realized_when_sell_is_bought_back():
|
||||
today = date(2026, 7, 8)
|
||||
instrument = Instrument(id=1, code="510300", name="沪深300ETF")
|
||||
trades = [
|
||||
make_trade(
|
||||
trade_id=1,
|
||||
trade_date=today - timedelta(days=1),
|
||||
side=TradeSide.BUY,
|
||||
price="9.00",
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.BASE,
|
||||
),
|
||||
make_trade(
|
||||
trade_id=2,
|
||||
trade_date=today,
|
||||
side=TradeSide.SELL,
|
||||
price="10.30",
|
||||
quantity=100,
|
||||
commission="1",
|
||||
trade_group=TradeGroup.BASE,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
),
|
||||
make_trade(
|
||||
trade_id=3,
|
||||
trade_date=today,
|
||||
side=TradeSide.BUY,
|
||||
price="10.00",
|
||||
quantity=100,
|
||||
commission="1",
|
||||
trade_group=TradeGroup.BASE,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
),
|
||||
]
|
||||
|
||||
[summary] = calculate_positions([instrument], trades, as_of=today)
|
||||
|
||||
assert summary.total_quantity == 100
|
||||
assert summary.available_quantity == 100
|
||||
assert summary.grid_profit == Decimal("28.00")
|
||||
|
||||
|
||||
def test_quote_snapshot_supplies_current_price_for_position_value():
|
||||
@@ -213,7 +265,7 @@ def test_account_summary_caps_capital_usage_when_cash_is_negative():
|
||||
assert summary.capital_usage_rate == Decimal("1.0000")
|
||||
|
||||
|
||||
def test_sell_more_than_group_position_raises():
|
||||
def test_sell_more_than_total_position_raises():
|
||||
today = date(2026, 7, 8)
|
||||
instrument = Instrument(id=1, code="159915", name="创业板ETF")
|
||||
trades = [
|
||||
@@ -235,10 +287,39 @@ def test_sell_more_than_group_position_raises():
|
||||
),
|
||||
]
|
||||
|
||||
with pytest.raises(CalculationError, match="Insufficient grid position"):
|
||||
with pytest.raises(CalculationError, match="总持仓不足"):
|
||||
calculate_positions([instrument], trades, as_of=today)
|
||||
|
||||
|
||||
def test_sell_can_use_holding_recorded_in_a_different_legacy_group():
|
||||
today = date(2026, 7, 8)
|
||||
instrument = Instrument(id=1, code="600588", name="用友网络")
|
||||
trades = [
|
||||
make_trade(
|
||||
trade_id=1,
|
||||
trade_date=today - timedelta(days=1),
|
||||
side=TradeSide.BUY,
|
||||
price="9.00",
|
||||
quantity=9400,
|
||||
trade_group=TradeGroup.BASE,
|
||||
),
|
||||
make_trade(
|
||||
trade_id=2,
|
||||
trade_date=today,
|
||||
side=TradeSide.SELL,
|
||||
price="9.56",
|
||||
quantity=9400,
|
||||
trade_group=TradeGroup.GRID,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
),
|
||||
]
|
||||
|
||||
[summary] = calculate_positions([instrument], trades, as_of=today)
|
||||
|
||||
assert summary.total_quantity == 0
|
||||
assert summary.realized_pnl == Decimal("5264.00")
|
||||
|
||||
|
||||
def test_estimate_fees_uses_min_commission_and_sell_tax():
|
||||
rules = FeeRules(
|
||||
commission_rate=Decimal("0.00025"),
|
||||
|
||||
38
tests/test_grid_alerts.py
Normal file
38
tests/test_grid_alerts.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from grid_trading.domain.grid_alerts import evaluate_grid_alert
|
||||
from grid_trading.domain.models import GridAlertState, TradeSide
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side", "current", "target", "expected"),
|
||||
[
|
||||
(TradeSide.BUY, "9.99", "10.00", GridAlertState.REACHED),
|
||||
(TradeSide.BUY, "10.04", "10.00", GridAlertState.NEAR),
|
||||
(TradeSide.BUY, "10.10", "10.00", GridAlertState.WAITING),
|
||||
(TradeSide.SELL, "10.01", "10.00", GridAlertState.REACHED),
|
||||
(TradeSide.SELL, "9.96", "10.00", GridAlertState.NEAR),
|
||||
(TradeSide.SELL, "9.90", "10.00", GridAlertState.WAITING),
|
||||
],
|
||||
)
|
||||
def test_evaluate_grid_alert_handles_buy_and_sell_directions(side, current, target, expected):
|
||||
result = evaluate_grid_alert(
|
||||
side=side,
|
||||
current_price=Decimal(current),
|
||||
target_price=Decimal(target),
|
||||
)
|
||||
|
||||
assert result.state is expected
|
||||
|
||||
|
||||
def test_evaluate_grid_alert_marks_missing_quote_unavailable():
|
||||
result = evaluate_grid_alert(
|
||||
side=TradeSide.BUY,
|
||||
current_price=None,
|
||||
target_price=Decimal("10"),
|
||||
)
|
||||
|
||||
assert result.state is GridAlertState.UNAVAILABLE
|
||||
assert result.distance_pct is None
|
||||
@@ -3,6 +3,7 @@ from decimal import Decimal
|
||||
import pytest
|
||||
|
||||
from grid_trading.domain.grid_levels import generate_grid_levels
|
||||
from grid_trading.domain.models import GridDirection
|
||||
|
||||
|
||||
def test_generate_grid_levels_compounds_percentage_spacing_and_rounds_values():
|
||||
@@ -46,6 +47,25 @@ def test_generate_grid_levels_uses_zero_quantity_when_amount_cannot_buy_one_lot(
|
||||
assert level.estimated_gross_profit == Decimal("0.00")
|
||||
|
||||
|
||||
def test_generate_reverse_grid_levels_sell_high_and_buy_back_lower():
|
||||
levels = generate_grid_levels(
|
||||
current_price=Decimal("10.00"),
|
||||
spacing=Decimal("0.03"),
|
||||
amount_per_grid=Decimal("10000"),
|
||||
lot_size=100,
|
||||
levels=2,
|
||||
direction=GridDirection.REVERSE,
|
||||
max_quantity=500,
|
||||
)
|
||||
|
||||
assert [item.direction for item in levels] == [GridDirection.REVERSE] * 2
|
||||
assert [item.sell_price for item in levels] == [Decimal("10.30"), Decimal("10.61")]
|
||||
assert [item.buy_price for item in levels] == [Decimal("10.00"), Decimal("10.30")]
|
||||
assert [item.suggested_quantity for item in levels] == [500, 500]
|
||||
assert levels[0].open_price == Decimal("10.30")
|
||||
assert levels[0].close_price == Decimal("10.00")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("current_price", "spacing", "amount_per_grid", "lot_size", "levels"),
|
||||
[
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from grid_trading.domain.models import Trade, TradeGroup, TradeSide
|
||||
from grid_trading.domain.models import GridDirection, Trade, TradeGroup, TradeSide
|
||||
from grid_trading.domain.open_grid_lots import calculate_grid_trade_matches, calculate_open_grid_lots
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ def make_trade(
|
||||
price: str,
|
||||
quantity: int,
|
||||
trade_group: TradeGroup = TradeGroup.GRID,
|
||||
grid_direction: GridDirection | None = None,
|
||||
commission: str = "0",
|
||||
) -> Trade:
|
||||
return Trade(
|
||||
id=trade_id,
|
||||
@@ -23,6 +25,8 @@ def make_trade(
|
||||
price=Decimal(price),
|
||||
quantity=quantity,
|
||||
trade_group=trade_group,
|
||||
grid_direction=grid_direction,
|
||||
commission=Decimal(commission),
|
||||
)
|
||||
|
||||
|
||||
@@ -149,3 +153,49 @@ def test_calculate_open_grid_lots_reports_not_reached_and_missing_quote_statuses
|
||||
assert not_reached.status == "未到价"
|
||||
assert missing_quote.current_price is None
|
||||
assert missing_quote.status == "未刷新行情"
|
||||
|
||||
|
||||
def test_reverse_grid_sell_opens_lot_and_buy_closes_it_fifo():
|
||||
today = date(2026, 7, 9)
|
||||
trades = [
|
||||
make_trade(
|
||||
trade_id=1,
|
||||
trade_date=today - timedelta(days=2),
|
||||
side=TradeSide.SELL,
|
||||
price="10.30",
|
||||
quantity=300,
|
||||
trade_group=TradeGroup.BASE,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
commission="3",
|
||||
),
|
||||
make_trade(
|
||||
trade_id=2,
|
||||
trade_date=today - timedelta(days=1),
|
||||
side=TradeSide.BUY,
|
||||
price="10.00",
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.BASE,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
commission="1",
|
||||
),
|
||||
]
|
||||
|
||||
[lot] = calculate_open_grid_lots(
|
||||
trades,
|
||||
spacing=Decimal("0.03"),
|
||||
current_price=Decimal("9.99"),
|
||||
as_of=today,
|
||||
)
|
||||
[match] = calculate_grid_trade_matches(trades, as_of=today)
|
||||
|
||||
assert lot.direction is GridDirection.REVERSE
|
||||
assert lot.open_trade_id == 1
|
||||
assert lot.remaining_quantity == 200
|
||||
assert lot.open_price == Decimal("10.30")
|
||||
assert lot.target_price == Decimal("10.00")
|
||||
assert lot.status == "可买回"
|
||||
assert match.direction is GridDirection.REVERSE
|
||||
assert match.sell_trade_id == 1
|
||||
assert match.buy_trade_id == 2
|
||||
assert match.gross_profit == Decimal("30.00")
|
||||
assert match.net_profit == Decimal("28.00")
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
import sqlite3
|
||||
|
||||
from grid_trading.domain.models import Account, Instrument, StrategyTemplate, Trade, TradeGroup, TradeSide
|
||||
from grid_trading.domain.models import (
|
||||
Account,
|
||||
GridAlertSource,
|
||||
GridAlertState,
|
||||
GridAlertTarget,
|
||||
GridDirection,
|
||||
GridMode,
|
||||
Instrument,
|
||||
StrategyTemplate,
|
||||
Trade,
|
||||
TradeGroup,
|
||||
TradeSide,
|
||||
)
|
||||
from grid_trading.storage.repositories import Repository
|
||||
|
||||
|
||||
@@ -103,3 +116,100 @@ def test_trade_update_and_delete_are_persistent(tmp_path):
|
||||
reopened.delete_trade(trade.id)
|
||||
assert reopened.get_trade(trade.id) is None
|
||||
assert reopened.list_trades(account_id=account.id) == []
|
||||
|
||||
|
||||
def test_instrument_delete_is_persistent(tmp_path):
|
||||
repo = Repository(tmp_path / "grid.db")
|
||||
repo.initialize()
|
||||
instrument = repo.save_instrument(Instrument(id=None, code="600000", name="浦发银行"))
|
||||
|
||||
repo.delete_instrument(instrument.id)
|
||||
|
||||
assert repo.get_instrument(instrument.id) is None
|
||||
assert repo.list_instruments() == []
|
||||
|
||||
|
||||
def test_grid_alert_target_round_trips_and_updates_state(tmp_path):
|
||||
repo = Repository(tmp_path / "grid.db")
|
||||
repo.initialize()
|
||||
instrument = repo.save_instrument(Instrument(id=None, code="510300", name="沪深300ETF"))
|
||||
target = repo.save_grid_alert_target(
|
||||
GridAlertTarget(
|
||||
id=None,
|
||||
target_key="manual:test",
|
||||
instrument_id=instrument.id,
|
||||
side=TradeSide.BUY,
|
||||
target_price=Decimal("3.88"),
|
||||
quantity=1200,
|
||||
source=GridAlertSource.MANUAL,
|
||||
)
|
||||
)
|
||||
|
||||
assert target.id is not None
|
||||
repo.update_grid_alert_state(
|
||||
target.target_key,
|
||||
state=GridAlertState.REACHED,
|
||||
alerted=True,
|
||||
last_alerted_at=None,
|
||||
)
|
||||
updated = repo.get_grid_alert_target(target.target_key)
|
||||
|
||||
assert updated.last_state is GridAlertState.REACHED
|
||||
assert updated.alerted
|
||||
|
||||
repo.delete_grid_alert_target(target.target_key)
|
||||
assert repo.get_grid_alert_target(target.target_key) is None
|
||||
|
||||
|
||||
def test_initialize_migrates_legacy_grid_columns(tmp_path):
|
||||
db_path = tmp_path / "legacy.db"
|
||||
connection = sqlite3.connect(db_path)
|
||||
connection.executescript(
|
||||
"""
|
||||
CREATE TABLE strategy_templates (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
grid_spacing_pct TEXT NOT NULL,
|
||||
amount_per_grid TEXT NOT NULL,
|
||||
base_target_amount TEXT NOT NULL,
|
||||
max_position_amount TEXT NOT NULL,
|
||||
min_lot INTEGER NOT NULL,
|
||||
is_default INTEGER NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE trades (
|
||||
id INTEGER PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL,
|
||||
instrument_id INTEGER NOT NULL,
|
||||
trade_date TEXT NOT NULL,
|
||||
side TEXT NOT NULL,
|
||||
price TEXT NOT NULL,
|
||||
quantity INTEGER NOT NULL,
|
||||
commission TEXT NOT NULL DEFAULT '0',
|
||||
stamp_tax TEXT NOT NULL DEFAULT '0',
|
||||
transfer_fee TEXT NOT NULL DEFAULT '0',
|
||||
trade_group TEXT NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
INSERT INTO strategy_templates
|
||||
(id, name, grid_spacing_pct, amount_per_grid, base_target_amount,
|
||||
max_position_amount, min_lot, is_default)
|
||||
VALUES (1, '旧策略', '0.03', '5000', '0', '80000', 100, 1);
|
||||
INSERT INTO trades
|
||||
(id, account_id, instrument_id, trade_date, side, price, quantity, trade_group)
|
||||
VALUES (1, 1, 1, '2026-07-01', 'buy', '4.00', 100, 'grid');
|
||||
"""
|
||||
)
|
||||
connection.commit()
|
||||
connection.close()
|
||||
|
||||
repo = Repository(db_path)
|
||||
repo.initialize()
|
||||
|
||||
template = repo.get_default_strategy_template()
|
||||
trade = repo.get_trade(1)
|
||||
assert template.grid_mode is GridMode.FORWARD
|
||||
assert trade.grid_direction is GridDirection.FORWARD
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
from datetime import date, timedelta
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from grid_trading.domain.models import Instrument, QuoteSnapshot, Trade, TradeGroup, TradeSide
|
||||
from grid_trading.domain.models import (
|
||||
GridAlertSource,
|
||||
GridAlertState,
|
||||
GridDirection,
|
||||
GridMode,
|
||||
Instrument,
|
||||
QuoteSnapshot,
|
||||
Trade,
|
||||
TradeGroup,
|
||||
TradeSide,
|
||||
)
|
||||
from grid_trading.services.trading_service import TradingService
|
||||
|
||||
|
||||
@@ -21,6 +31,40 @@ class FakeQuoteProvider:
|
||||
}
|
||||
|
||||
|
||||
def test_service_deletes_instrument_without_trades(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
instrument = service.add_instrument(Instrument(id=None, code="600000", name="浦发银行"))
|
||||
|
||||
service.delete_instrument(instrument.id)
|
||||
|
||||
assert service.list_instruments() == []
|
||||
service.close()
|
||||
|
||||
|
||||
def test_service_refuses_to_delete_instrument_with_trades(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
instrument = service.add_instrument(Instrument(id=None, code="600000", name="浦发银行"))
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date(2026, 7, 28),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("10"),
|
||||
quantity=100,
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="已有成交记录"):
|
||||
service.delete_instrument(instrument.id)
|
||||
|
||||
assert service.list_instruments() == [instrument]
|
||||
service.close()
|
||||
|
||||
|
||||
def test_service_creates_default_account_and_computes_summary(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
service.ensure_defaults()
|
||||
@@ -72,7 +116,7 @@ def test_service_creates_default_account_and_computes_summary(tmp_path):
|
||||
assert summary.total_assets == Decimal("98138.97")
|
||||
|
||||
|
||||
def test_service_validates_lot_size_and_available_sell_quantity(tmp_path):
|
||||
def test_service_validates_lot_size_and_allows_same_day_sell(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
@@ -105,32 +149,6 @@ def test_service_validates_lot_size_and_available_sell_quantity(tmp_path):
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="T\\+1"):
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date(2026, 7, 8),
|
||||
side=TradeSide.SELL,
|
||||
price=Decimal("10.1"),
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date(2026, 7, 8) - timedelta(days=1),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("9.9"),
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
saved_sell = service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
@@ -143,9 +161,22 @@ def test_service_validates_lot_size_and_available_sell_quantity(tmp_path):
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
|
||||
assert saved_sell.id is not None
|
||||
|
||||
with pytest.raises(ValueError, match="总持仓不足"):
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date(2026, 7, 8),
|
||||
side=TradeSide.SELL,
|
||||
price=Decimal("10.2"),
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_service_rejects_historical_changes_that_break_future_sells(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
@@ -260,6 +291,39 @@ def test_service_returns_empty_grid_levels_without_realtime_price(tmp_path):
|
||||
assert service.get_grid_level_suggestions(instrument.id, levels=10) == []
|
||||
|
||||
|
||||
def test_service_generates_reverse_levels_capped_by_current_holding(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db", quote_provider=FakeQuoteProvider())
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
instrument = service.add_instrument(
|
||||
Instrument(id=None, code="510300", name="沪深300ETF", market="ETF")
|
||||
)
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date.today(),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("4.00"),
|
||||
quantity=500,
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
service.refresh_quotes()
|
||||
|
||||
[level] = service.get_grid_level_suggestions(
|
||||
instrument.id,
|
||||
levels=1,
|
||||
mode=GridMode.REVERSE,
|
||||
)
|
||||
|
||||
assert level.direction is GridDirection.REVERSE
|
||||
assert level.sell_price == Decimal("4.24")
|
||||
assert level.buy_price == Decimal("4.12")
|
||||
assert level.suggested_quantity == 500
|
||||
|
||||
|
||||
def test_service_returns_open_grid_lots_with_suggested_sell_price(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db", quote_provider=FakeQuoteProvider())
|
||||
service.ensure_defaults()
|
||||
@@ -350,3 +414,112 @@ def test_service_returns_grid_trade_matches(tmp_path):
|
||||
assert matches[0].gross_profit == Decimal("90.00")
|
||||
assert matches[1].matched_quantity == 100
|
||||
assert matches[1].gross_profit == Decimal("80.00")
|
||||
|
||||
|
||||
def test_service_persists_buy_alert_and_synchronizes_open_sell_alert(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db", quote_provider=FakeQuoteProvider())
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
instrument = service.add_instrument(
|
||||
Instrument(id=None, code="510300", name="沪深300ETF", market="ETF")
|
||||
)
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date.today(),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("4.00"),
|
||||
quantity=1000,
|
||||
trade_group=TradeGroup.GRID,
|
||||
)
|
||||
)
|
||||
buy_target = service.add_buy_grid_alert(
|
||||
instrument.id,
|
||||
target_price=Decimal("4.10"),
|
||||
quantity=1200,
|
||||
)
|
||||
service.refresh_quotes()
|
||||
|
||||
first = service.evaluate_grid_alerts()
|
||||
second = service.evaluate_grid_alerts()
|
||||
|
||||
assert buy_target.source is GridAlertSource.MANUAL
|
||||
assert {item.side for item in first.items} == {TradeSide.BUY, TradeSide.SELL}
|
||||
assert any(item.side is TradeSide.SELL and item.state is GridAlertState.REACHED for item in first.items)
|
||||
assert len(first.newly_reached) == 1
|
||||
assert second.newly_reached == []
|
||||
|
||||
|
||||
def test_service_rearms_alert_only_after_price_leaves_near_zone(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
service.ensure_defaults()
|
||||
instrument = service.add_instrument(Instrument(id=None, code="510300", name="沪深300ETF"))
|
||||
service.add_buy_grid_alert(
|
||||
instrument.id,
|
||||
target_price=Decimal("4.00"),
|
||||
quantity=100,
|
||||
)
|
||||
|
||||
def apply(price):
|
||||
service.apply_quote_snapshots(
|
||||
{
|
||||
"510300": QuoteSnapshot(
|
||||
symbol="sh510300",
|
||||
code="510300",
|
||||
name="沪深300ETF",
|
||||
price=Decimal(price),
|
||||
source="test",
|
||||
)
|
||||
}
|
||||
)
|
||||
return service.evaluate_grid_alerts()
|
||||
|
||||
assert len(apply("4.00").newly_reached) == 1
|
||||
assert apply("4.01").newly_reached == []
|
||||
assert apply("4.00").newly_reached == []
|
||||
assert apply("4.10").newly_reached == []
|
||||
assert len(apply("4.00").newly_reached) == 1
|
||||
|
||||
|
||||
def test_reverse_sell_automatically_creates_buyback_alert(tmp_path):
|
||||
service = TradingService(tmp_path / "grid.db", quote_provider=FakeQuoteProvider())
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
instrument = service.add_instrument(
|
||||
Instrument(id=None, code="510300", name="沪深300ETF", market="ETF")
|
||||
)
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date.today(),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("4.00"),
|
||||
quantity=500,
|
||||
trade_group=TradeGroup.BASE,
|
||||
)
|
||||
)
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date.today(),
|
||||
side=TradeSide.SELL,
|
||||
price=Decimal("4.24"),
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.OTHER,
|
||||
grid_direction=GridDirection.REVERSE,
|
||||
)
|
||||
)
|
||||
service.refresh_quotes()
|
||||
|
||||
snapshot = service.evaluate_grid_alerts()
|
||||
|
||||
[target] = snapshot.items
|
||||
assert target.side is TradeSide.BUY
|
||||
assert target.target_price == Decimal("4.12")
|
||||
assert target.state is GridAlertState.REACHED
|
||||
|
||||
229
tests/test_ui.py
229
tests/test_ui.py
@@ -1,7 +1,19 @@
|
||||
from decimal import Decimal
|
||||
from datetime import date, datetime
|
||||
import threading
|
||||
import time
|
||||
|
||||
from grid_trading.domain.models import Instrument
|
||||
from grid_trading.domain.models import (
|
||||
GridDirection,
|
||||
GridAlertSource,
|
||||
GridAlertState,
|
||||
GridMonitorItem,
|
||||
GridMonitorSnapshot,
|
||||
Instrument,
|
||||
Trade,
|
||||
TradeGroup,
|
||||
TradeSide,
|
||||
)
|
||||
|
||||
|
||||
def test_formatters_render_money_percent_and_empty_values():
|
||||
@@ -28,7 +40,14 @@ def test_main_window_can_be_constructed_offscreen(tmp_path, monkeypatch):
|
||||
|
||||
assert window.windowTitle() == "Grid Trading Manager"
|
||||
assert window.holdings_table.columnCount() > 0
|
||||
assert window.holdings_table.columnCount() == 11
|
||||
assert "底仓" not in window.HOLDING_COLUMNS
|
||||
assert "网格仓" not in window.HOLDING_COLUMNS
|
||||
assert window.trades_table.columnCount() == 9
|
||||
assert window.TRADE_COLUMNS[:2] == ["代码", "名称"]
|
||||
assert "分组" not in window.TRADE_COLUMNS
|
||||
assert any(button.text() == "刷新行情" for button in window.findChildren(QPushButton))
|
||||
assert any(button.text() == "删除标的" for button in window.findChildren(QPushButton))
|
||||
summary_titles = [label.text() for label in window.findChildren(QLabel)]
|
||||
assert "账户权益" in summary_titles
|
||||
assert "总资产" not in summary_titles
|
||||
@@ -50,9 +69,10 @@ def test_main_window_contains_grid_level_table(tmp_path, monkeypatch):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
window = MainWindow(service)
|
||||
|
||||
assert window.grid_levels_table.columnCount() == 7
|
||||
assert window.grid_levels_table.columnCount() == 9
|
||||
assert window.GRID_LEVEL_COLUMNS[:2] == ["代码", "名称"]
|
||||
tab_titles = _tab_titles(window.details_tabs)
|
||||
assert tab_titles == ["网格档位", "待卖网格", "配对明细", "最近成交"]
|
||||
assert tab_titles == ["网格档位", "未完成网格", "配对明细", "最近成交"]
|
||||
assert isinstance(window.details_tabs, QTabWidget)
|
||||
|
||||
window.close()
|
||||
@@ -72,9 +92,11 @@ def test_main_window_contains_open_grid_lots_table(tmp_path, monkeypatch):
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
window = MainWindow(service)
|
||||
|
||||
assert window.open_grid_lots_table.columnCount() == 8
|
||||
assert "待卖网格" in _tab_titles(window.details_tabs)
|
||||
assert window.grid_matches_table.columnCount() == 9
|
||||
assert window.open_grid_lots_table.columnCount() == 11
|
||||
assert window.OPEN_GRID_LOT_COLUMNS[:2] == ["代码", "名称"]
|
||||
assert "未完成网格" in _tab_titles(window.details_tabs)
|
||||
assert window.grid_matches_table.columnCount() == 13
|
||||
assert window.GRID_MATCH_COLUMNS[:2] == ["代码", "名称"]
|
||||
assert "配对明细" in _tab_titles(window.details_tabs)
|
||||
|
||||
window.close()
|
||||
@@ -82,6 +104,98 @@ def test_main_window_contains_open_grid_lots_table(tmp_path, monkeypatch):
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def test_detail_tables_show_and_follow_selected_instrument(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from grid_trading.services.trading_service import TradingService
|
||||
from grid_trading.ui.main_window import MainWindow
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
service.ensure_defaults()
|
||||
account = service.get_active_account()
|
||||
first = service.add_instrument(Instrument(id=None, code="000001", name="平安银行"))
|
||||
second = service.add_instrument(Instrument(id=None, code="600000", name="浦发银行"))
|
||||
for instrument in (first, second):
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=instrument.id,
|
||||
trade_date=date(2026, 7, 27),
|
||||
side=TradeSide.BUY,
|
||||
price=Decimal("10"),
|
||||
quantity=200,
|
||||
trade_group=TradeGroup.GRID,
|
||||
grid_direction=GridDirection.FORWARD,
|
||||
)
|
||||
)
|
||||
service.save_trade(
|
||||
Trade(
|
||||
id=None,
|
||||
account_id=account.id,
|
||||
instrument_id=first.id,
|
||||
trade_date=date(2026, 7, 28),
|
||||
side=TradeSide.SELL,
|
||||
price=Decimal("10.3"),
|
||||
quantity=100,
|
||||
trade_group=TradeGroup.GRID,
|
||||
grid_direction=GridDirection.FORWARD,
|
||||
)
|
||||
)
|
||||
window = MainWindow(service)
|
||||
|
||||
window.holdings_table.selectRow(0)
|
||||
app.processEvents()
|
||||
assert window.trades_table.item(0, 0).text() == "000001"
|
||||
assert window.trades_table.item(0, 1).text() == "平安银行"
|
||||
assert window.open_grid_lots_table.item(0, 0).text() == "000001"
|
||||
assert window.open_grid_lots_table.item(0, 1).text() == "平安银行"
|
||||
assert window.grid_matches_table.item(0, 0).text() == "000001"
|
||||
assert window.grid_matches_table.item(0, 1).text() == "平安银行"
|
||||
|
||||
window.holdings_table.selectRow(1)
|
||||
app.processEvents()
|
||||
assert window.trades_table.item(0, 0).text() == "600000"
|
||||
assert window.trades_table.item(0, 1).text() == "浦发银行"
|
||||
assert window.open_grid_lots_table.item(0, 0).text() == "600000"
|
||||
assert window.open_grid_lots_table.item(0, 1).text() == "浦发银行"
|
||||
|
||||
window.close()
|
||||
service.close()
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def test_main_window_deletes_selected_instrument(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
|
||||
from grid_trading.services.trading_service import TradingService
|
||||
from grid_trading.ui.main_window import MainWindow
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
service = TradingService(tmp_path / "grid.db")
|
||||
instrument = service.add_instrument(Instrument(id=None, code="600000", name="浦发银行"))
|
||||
window = MainWindow(service)
|
||||
window.holdings_table.selectRow(0)
|
||||
monkeypatch.setattr(
|
||||
QMessageBox,
|
||||
"question",
|
||||
lambda *args, **kwargs: QMessageBox.StandardButton.Yes,
|
||||
)
|
||||
|
||||
window._delete_selected_instrument()
|
||||
|
||||
assert service.list_instruments() == []
|
||||
assert service.repository.get_instrument(instrument.id) is None
|
||||
window.close()
|
||||
service.close()
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def test_main_window_applies_light_theme(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
@@ -144,8 +258,8 @@ def test_profit_and_loss_cells_use_a_share_colors(tmp_path, monkeypatch):
|
||||
window._fill_holdings_table()
|
||||
window.holdings_table.blockSignals(False)
|
||||
|
||||
profit_item = window.holdings_table.item(0, 10)
|
||||
loss_item = window.holdings_table.item(0, 11)
|
||||
profit_item = window.holdings_table.item(0, 8)
|
||||
loss_item = window.holdings_table.item(0, 9)
|
||||
assert profit_item.foreground().color() == QColor("#c62828")
|
||||
assert profit_item.font().bold()
|
||||
assert loss_item.foreground().color() == QColor("#2e7d32")
|
||||
@@ -210,12 +324,56 @@ def test_trade_dialog_labels_price_as_trade_price(tmp_path, monkeypatch):
|
||||
|
||||
labels = [label.text() for label in dialog.findChildren(QLabel)]
|
||||
assert "成交价" in labels
|
||||
assert "交易类型" in labels
|
||||
assert "分组" not in labels
|
||||
assert not hasattr(dialog, "group_edit")
|
||||
assert dialog.to_trade().trade_group is TradeGroup.OTHER
|
||||
|
||||
dialog.close()
|
||||
service.close()
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def test_floating_monitor_renders_reached_target_offscreen(monkeypatch):
|
||||
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from grid_trading.ui.floating_monitor import FloatingMonitorWindow
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
window = FloatingMonitorWindow()
|
||||
window.update_snapshot(
|
||||
GridMonitorSnapshot(
|
||||
items=[
|
||||
GridMonitorItem(
|
||||
target_key="manual:test",
|
||||
instrument_id=1,
|
||||
code="510300",
|
||||
name="沪深300ETF",
|
||||
side=TradeSide.BUY,
|
||||
target_price=Decimal("3.88"),
|
||||
quantity=1200,
|
||||
current_price=Decimal("3.87"),
|
||||
state=GridAlertState.REACHED,
|
||||
distance_pct=Decimal("-0.0025"),
|
||||
source=GridAlertSource.MANUAL,
|
||||
)
|
||||
],
|
||||
newly_reached=[],
|
||||
evaluated_at=datetime(2026, 7, 17, 10, 30),
|
||||
)
|
||||
)
|
||||
|
||||
assert window.table.rowCount() == 1
|
||||
assert window.table.item(0, 5).text() == "已到价"
|
||||
window.table.selectRow(0)
|
||||
assert window.remove_button.isEnabled()
|
||||
|
||||
window.close_permanently()
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def _tab_titles(tabs):
|
||||
return [tabs.tabText(index) for index in range(tabs.count())]
|
||||
|
||||
@@ -246,12 +404,63 @@ def test_quote_refresh_does_not_block_main_window(tmp_path, monkeypatch):
|
||||
assert elapsed < 0.15
|
||||
|
||||
deadline = time.perf_counter() + 2
|
||||
while getattr(window, "_quote_thread", None) is not None and time.perf_counter() < deadline:
|
||||
while window.quote_monitor.is_refreshing and time.perf_counter() < deadline:
|
||||
app.processEvents()
|
||||
time.sleep(0.01)
|
||||
|
||||
assert getattr(window, "_quote_thread", None) is None
|
||||
assert not window.quote_monitor.is_refreshing
|
||||
|
||||
window.close()
|
||||
service.close()
|
||||
app.processEvents()
|
||||
|
||||
|
||||
def test_close_during_quote_refresh_does_not_block_main_window(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from grid_trading.services.trading_service import TradingService
|
||||
from grid_trading.ui.main_window import MainWindow
|
||||
|
||||
request_started = threading.Event()
|
||||
release_request = threading.Event()
|
||||
|
||||
class BlockingQuoteProvider:
|
||||
def fetch_quotes(self, instruments):
|
||||
request_started.set()
|
||||
release_request.wait(1)
|
||||
return {}
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
service = TradingService(tmp_path / "grid.db", quote_provider=BlockingQuoteProvider())
|
||||
service.ensure_defaults()
|
||||
service.add_instrument(Instrument(id=None, code="000001", name="Ping An Bank"))
|
||||
window = MainWindow(service)
|
||||
window.show()
|
||||
window._refresh_quotes()
|
||||
|
||||
deadline = time.perf_counter() + 1
|
||||
while not request_started.is_set() and time.perf_counter() < deadline:
|
||||
app.processEvents()
|
||||
time.sleep(0.01)
|
||||
assert request_started.is_set()
|
||||
|
||||
started_at = time.perf_counter()
|
||||
window.close()
|
||||
elapsed = time.perf_counter() - started_at
|
||||
|
||||
assert elapsed < 0.15
|
||||
assert not window.isVisible()
|
||||
assert window.quote_monitor.is_refreshing
|
||||
|
||||
release_request.set()
|
||||
deadline = time.perf_counter() + 2
|
||||
while (window.quote_monitor.is_refreshing or window._close_pending) and time.perf_counter() < deadline:
|
||||
app.processEvents()
|
||||
time.sleep(0.01)
|
||||
|
||||
assert not window.quote_monitor.is_refreshing
|
||||
assert not window._close_pending
|
||||
service.close()
|
||||
app.processEvents()
|
||||
|
||||
Reference in New Issue
Block a user