|
| 1 | +from types import SimpleNamespace |
| 2 | +from unittest.mock import Mock |
| 3 | +import time |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | +import pytest |
| 7 | + |
| 8 | +from app.services import trading_executor as runtime |
| 9 | +from app.services.live_trading.gate import GateStockClient |
| 10 | + |
| 11 | + |
| 12 | +SYMBOL = "Crypto:NVDA/USD@gate:spot" |
| 13 | +CODE = ''' |
| 14 | +def initialize(context): |
| 15 | + g.symbol = "Crypto:NVDA/USD@gate:spot" |
| 16 | + context.set_universe([g.symbol]) |
| 17 | + context.subscribe(frequency="1m", fields=["close"]) |
| 18 | + context.set_warmup(50) |
| 19 | + context.set_benchmark(g.symbol) |
| 20 | + context.set_metadata(direction_mode="long_only", strategy_family="ema_crossover") |
| 21 | +
|
| 22 | +def handle_data(context, data): |
| 23 | + bars = data.history(g.symbol, count=500, fields=["close"]) |
| 24 | + if len(bars) >= 32: |
| 25 | + fast = bars.close.ewm(span=10, adjust=False).mean() |
| 26 | + slow = bars.close.ewm(span=30, adjust=False).mean() |
| 27 | + if fast.iloc[-1] > slow.iloc[-1] and fast.iloc[-2] <= slow.iloc[-2]: |
| 28 | + order_target_percent(g.symbol, 0.95) |
| 29 | +''' |
| 30 | + |
| 31 | + |
| 32 | +@pytest.mark.parametrize("account_options", [{}, {"environment": "testnet"}, {"enable_demo_trading": True}]) |
| 33 | +def test_gate_stock_complete_live_loop_uses_exchange_quotes(monkeypatch, account_options): |
| 34 | + product = { |
| 35 | + "symbol": "NVDA/USD", "exchange_id": "gate", "market_type": "spot", |
| 36 | + "instrument_id": "NVDA", "product_type": "direct_equity", "api_family": "stock", |
| 37 | + "underlying_market": "USStock", "underlying_symbol": "NVDA", |
| 38 | + } |
| 39 | + strategy = { |
| 40 | + "id": 1, "user_id": 1, "execution_mode": "live", "initial_capital": 1000, |
| 41 | + "trading_config": {"instrument_products": [product], "risk_tick_seconds": 0.25}, |
| 42 | + "exchange_config": {"exchange_id": "gate", "api_key": "test", "secret_key": "test", **(account_options or {})}, |
| 43 | + } |
| 44 | + executor = runtime.TradingExecutor() |
| 45 | + monkeypatch.setattr(executor, "_load_strategy", lambda _: strategy) |
| 46 | + monkeypatch.setattr(executor, "_load_source", lambda _: (1, CODE)) |
| 47 | + monkeypatch.setattr(executor, "_load_schedule_timezone", lambda _: "UTC") |
| 48 | + monkeypatch.setattr(executor, "_positions_by_symbol", lambda *a, **kw: {}) |
| 49 | + monkeypatch.setattr(executor, "_calculate_current_equity", lambda *a, **kw: 1000) |
| 50 | + submit = Mock(return_value=True) |
| 51 | + monkeypatch.setattr(executor, "_execute_strategy_v2_intent", submit) |
| 52 | + cycles = iter([True, True, True, False]) |
| 53 | + monkeypatch.setattr(executor, "_is_strategy_running", lambda *a: next(cycles)) |
| 54 | + heartbeats = [] |
| 55 | + monkeypatch.setattr(executor, "_heartbeat", lambda *a, **kw: heartbeats.append((dict(a[3]), kw))) |
| 56 | + monkeypatch.setattr(executor, "_mark_stopped", lambda *a: None) |
| 57 | + logs = [] |
| 58 | + monkeypatch.setattr(runtime, "append_strategy_log", lambda *a: logs.append(a)) |
| 59 | + monkeypatch.setattr(runtime, "ensure_strategy_run", lambda **kw: SimpleNamespace(strategy_run_id=1)) |
| 60 | + monkeypatch.setattr(runtime, "finish_strategy_run", lambda *a, **kw: None) |
| 61 | + store = Mock() |
| 62 | + store.load.return_value = {} |
| 63 | + monkeypatch.setattr(runtime, "RuntimeStateStore", lambda **kw: store) |
| 64 | + monkeypatch.setattr(runtime, "persist_cancellations", lambda *a: None) |
| 65 | + monkeypatch.setattr(runtime, "time", SimpleNamespace(monotonic=time.monotonic, sleep=lambda _: None, time=time.time)) |
| 66 | + frame = pd.DataFrame( |
| 67 | + {"open": 200., "high": 201., "low": 199., "close": 200., "volume": 1.}, |
| 68 | + index=pd.date_range("2026-09-14 14:00", periods=60, freq="min", tz="UTC"), |
| 69 | + ) |
| 70 | + monkeypatch.setattr(runtime.StrategyV2BacktestService, "fetch_frequency_frames", lambda *a, **kw: ({"1m": {SYMBOL: frame}}, [])) |
| 71 | + request = Mock(return_value=(200, {"data": {"bids": [{"p": "210.1"}], "asks": [{"p": "210.3"}]}}, "")) |
| 72 | + monkeypatch.setattr(GateStockClient, "_request", request) |
| 73 | + |
| 74 | + executor._run_strategy_loop(1) |
| 75 | + |
| 76 | + if account_options: |
| 77 | + assert executor._last_exit_reason == {1: "strategyV2.gateStockTestnetUnsupported"} |
| 78 | + assert not heartbeats |
| 79 | + request.assert_not_called() |
| 80 | + submit.assert_not_called() |
| 81 | + assert logs == [(1, "error", "strategyV2.gateStockTestnetUnsupported")] |
| 82 | + return |
| 83 | + assert executor._last_exit_reason == {}, logs |
| 84 | + assert len(heartbeats) == 4, logs |
| 85 | + assert all(prices.get(SYMBOL) == 210.2 for prices, _ in heartbeats[1:]), logs |
| 86 | + assert all(meta["status"] == "healthy" for _, meta in heartbeats[1:]), logs |
| 87 | + assert request.call_count == 3 |
| 88 | + |
| 89 | + |
| 90 | +def test_gate_stock_testnet_rejected_before_deployment_is_saved(monkeypatch): |
| 91 | + from app.services import exchange_execution |
| 92 | + from app.services.strategy_v2 import deployment |
| 93 | + |
| 94 | + monkeypatch.setattr(deployment, "get_script_source_service", lambda: SimpleNamespace( |
| 95 | + get_source=lambda *a, **kw: {"name": "Gate NVDA", "code": CODE}, |
| 96 | + )) |
| 97 | + monkeypatch.setattr(deployment.StrategyV2DeploymentService, "_credential_exchange", lambda *a: "gate") |
| 98 | + monkeypatch.setattr(deployment, "get_catalog_product", lambda **kw: { |
| 99 | + "instrument_id": "NVDA", "api_family": "stock", "product_type": "direct_equity", |
| 100 | + }) |
| 101 | + resolve = Mock(return_value={"exchange_id": "gate", "environment": "testnet"}) |
| 102 | + monkeypatch.setattr(exchange_execution, "resolve_exchange_config", resolve) |
| 103 | + database = Mock(side_effect=AssertionError("No deployment should be persisted")) |
| 104 | + monkeypatch.setattr(deployment, "get_db_connection", database) |
| 105 | + |
| 106 | + with pytest.raises(deployment.StrategyV2ContractError, match="gateStockTestnetUnsupported"): |
| 107 | + deployment.StrategyV2DeploymentService().save(user_id=7, payload={ |
| 108 | + "sourceId": 1, "initialCapital": 1000, "credentialId": 23, "executionMode": "live", |
| 109 | + }) |
| 110 | + |
| 111 | + resolve.assert_called_once_with({"credential_id": 23, "exchange_id": "gate"}, user_id=7) |
| 112 | + database.assert_not_called() |
| 113 | + |
| 114 | + |
| 115 | +def test_gate_stock_testnet_rejected_before_starting_thread(monkeypatch): |
| 116 | + from app.services import exchange_execution |
| 117 | + |
| 118 | + executor = runtime.TradingExecutor() |
| 119 | + strategy = { |
| 120 | + "id": 1, "user_id": 7, "execution_mode": "live", "market_type": "spot", |
| 121 | + "trading_config": {"instrument_products": [{"exchange_id": "gate", "api_family": "stock"}]}, |
| 122 | + "exchange_config": {"credential_id": 23}, |
| 123 | + } |
| 124 | + monkeypatch.setattr(executor, "_load_strategy", lambda _: strategy) |
| 125 | + monkeypatch.setattr(exchange_execution, "resolve_exchange_config", lambda *a, **kw: { |
| 126 | + "exchange_id": "gate", "use_testnet": True, |
| 127 | + }) |
| 128 | + |
| 129 | + assert executor.start_strategy(1) is False |
| 130 | + assert executor._last_start_failure == "strategyV2.gateStockTestnetUnsupported" |
| 131 | + assert not executor.running_strategies |
0 commit comments