Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(connectors): close four minor-batch gaps from #1207

Yufeng He170c753a1c34
diff --git a/agent/backtest/engines/_market_hooks.py b/agent/backtest/engines/_market_hooks.py
index 6220aa271..8c831975c 100644
--- a/agent/backtest/engines/_market_hooks.py
+++ b/agent/backtest/engines/_market_hooks.py
@@ -48,6 +48,12 @@ _MARKET_PATTERNS = [
# yfinance's native crypto spelling (BTC-USD, ETH-USD). Distinct from
# USDT pairs only in the quote currency; both belong to CryptoEngine.
(re.compile(r"^[A-Z]+-USD$", re.I), "crypto"),
+ # Concatenated spot pairs (BTCUSDT, ETHUSDC) with no separator. Same
+ # quote-asset table the trade-journal parser uses; without it these fell
+ # through every pattern and got a_share rules (T+1, no shorting) on a
+ # perpetual. Bare metals/FX (XAUUSD) end in USD, not USDT/USDC/BUSD, so
+ # they still reach the forex whitelist below.
+ (re.compile(r"^[A-Z]{2,}(?:USDT|USDC|BUSD)$", re.I), "crypto"),
# China futures: product+delivery.exchange (e.g. IF2406.CFFEX, rb2410.SHFE)
(re.compile(r"^[A-Za-z]{1,2}\d{3,4}\.(ZCE|DCE|SHFE|INE|CFFEX|GFEX)$", re.I), "futures"),
# Global futures: product+month-code (e.g. ESZ4, CLF25, GCM2025)
@@ -89,8 +95,8 @@ _MARKET_PATTERNS = [
# Bare US tickers (AAPL, MSFT, SPY, T, ...). Must stay LAST so every
# suffixed equity / futures / crypto / forex form above wins first.
# ``{1,5}`` covers every standard US ticker length while 6-char bare
- # forex/metals (now caught by the whitelist above) and longer crypto
- # codes (``BTCUSDT``) fall through to the a_share default.
+ # forex/metals (caught by the whitelist above) and longer unknown codes
+ # fall through to the a_share default.
(re.compile(r"^[A-Z]{1,5}$", re.I), "us_equity"),
]
@@ -184,7 +190,8 @@ def _detect_market(code: str) -> str:
ca_equity/crypto/futures/forex).
Bare 1-5 letter alphabetic tickers resolve to ``us_equity``;
bare 6-letter codes that start with a precious-metal or G10
- currency code (whitelist) resolve to ``forex``; Yahoo's
+ currency code (whitelist) resolve to ``forex``; concatenated
+ crypto pairs (``BTCUSDT``) resolve to ``crypto``; Yahoo's
``=F`` (futures) and ``=X`` (forex) notations are recognized;
any other unknown format defaults to ``a_share``.
"""
diff --git a/agent/src/trading/connectors/etoro/trading.py b/agent/src/trading/connectors/etoro/trading.py
index cf09729fd..67ed7ecfd 100644
--- a/agent/src/trading/connectors/etoro/trading.py
+++ b/agent/src/trading/connectors/etoro/trading.py
@@ -56,6 +56,10 @@ def place_order(
clean_type = str(order_type or "market").strip().lower()
if clean_type not in ("market", "limit"):
return _order_error(cfg, "order_type must be 'market' or 'limit'", symbol=symbol, side=clean_side)
+ if clean_type == "limit" and limit_price is None:
+ # eToro limit orders are MIT orders keyed on TriggerRate; without one
+ # the order rests untriggered while looking accepted.
+ return _order_error(cfg, "limit orders require limit_price", symbol=symbol, side=clean_side)
try:
instrument_ref = _order_instrument_ref(symbol, cfg)
diff --git a/agent/src/trading/connectors/futu/sdk.py b/agent/src/trading/connectors/futu/sdk.py
index c72facd85..3a3624175 100644
--- a/agent/src/trading/connectors/futu/sdk.py
+++ b/agent/src/trading/connectors/futu/sdk.py
@@ -415,7 +415,12 @@ def get_historical_bars(
limit: int = 90,
**_: Any,
) -> dict[str, Any]:
- """Fetch historical K-line bars for ``symbol`` (e.g. ``US.AAPL``)."""
+ """Fetch historical K-line bars for ``symbol`` (e.g. ``US.AAPL``).
+
+ Bars are forward-adjusted (Futu ``AuType.QFQ``, the SDK default, passed
+ explicitly so a futu-side default change cannot silently switch the
+ caliber). The response declares the caliber in ``adjustment``.
+ """
cfg = config or load_config()
futu = _require_futu()
ktype_name = _KLTYPE_MAP.get(period.strip(), "K_DAY")
@@ -423,11 +428,16 @@ def get_historical_bars(
quote_ctx = _quote_ctx(cfg)
try:
code = symbol.strip().upper()
- rows = _records(_unwrap(quote_ctx.request_history_kline(code, ktype=ktype, max_count=int(limit))))
+ autype = getattr(getattr(futu, "AuType", None), "QFQ", None)
+ request: dict[str, Any] = {"ktype": ktype, "max_count": int(limit)}
+ if autype is not None:
+ request["autype"] = autype
+ rows = _records(_unwrap(quote_ctx.request_history_kline(code, **request)))
return {
"status": "ok",
"symbol": code,
"period": period,
+ "adjustment": "qfq",
"bars": [_bar_to_dict(row) for row in rows],
}
finally:
diff --git a/agent/src/trading/connectors/mt5/orders.py b/agent/src/trading/connectors/mt5/orders.py
index 96f6a46d8..3377cbe69 100644
--- a/agent/src/trading/connectors/mt5/orders.py
+++ b/agent/src/trading/connectors/mt5/orders.py
@@ -245,7 +245,10 @@ def _sized_volume(
volume = math.floor(raw / step + 1e-9) * step
volume = round(volume, 8)
if volume > volume_max:
- volume = volume_max
+ return (
+ f"order volume {volume} lots exceeds the symbol maximum {volume_max} "
+ f"for {name!r}; split the order or lower the size"
+ )
if volume < volume_min:
return (
f"order volume {volume} lots is below the symbol minimum {volume_min} "
diff --git a/agent/tests/test_etoro_connector.py b/agent/tests/test_etoro_connector.py
index 18b512c31..d3cbbec21 100644
--- a/agent/tests/test_etoro_connector.py
+++ b/agent/tests/test_etoro_connector.py
@@ -298,6 +298,31 @@ def test_limit_place_order_sets_trigger_rate(monkeypatch) -> None:
assert captured["json"]["TriggerRate"] == 10000.0
+def test_limit_without_limit_price_errors_before_sending(monkeypatch) -> None:
+ # A limit order with no limit_price would go out as an MIT with no
+ # TriggerRate and rest untriggered while looking accepted.
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ sent: list[str] = []
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ sent.append(url)
+ return _FakeResponse(200, {"orderID": 7})
+
+ monkeypatch.setattr("src.trading.connectors.etoro.trading.resolve_instrument_id", lambda symbol, c: 100000)
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+
+ result = etoro_sdk.place_order(
+ cfg,
+ symbol="BTC",
+ side="buy",
+ notional=50.0,
+ order_type="limit",
+ )
+ assert result["status"] == "error"
+ assert "limit_price" in result["error"]
+ assert sent == []
+
+
def test_cancel_order_uses_demo_delete_path(monkeypatch) -> None:
cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
captured: dict[str, Any] = {}
diff --git a/agent/tests/test_futu_connector_period_hour_case.py b/agent/tests/test_futu_connector_period_hour_case.py
index 221247b71..14aef00bc 100644
--- a/agent/tests/test_futu_connector_period_hour_case.py
+++ b/agent/tests/test_futu_connector_period_hour_case.py
@@ -65,3 +65,55 @@ def test_history_4H_uses_240m_not_60m(monkeypatch) -> None:
cfg = futu_sdk.FutuConfig(host="127.0.0.1", port=11111, profile="paper")
futu_sdk.get_historical_bars("US.AAPL", config=cfg, period="4H", limit=24)
assert calls[-1] == "K_240M"
+
+
+def test_history_declares_qfq_caliber_and_passes_autype(monkeypatch) -> None:
+ seen: dict[str, object] = {}
+
+ class _KLType:
+ K_DAY = "K_DAY"
+
+ class _AuType:
+ QFQ = "QFQ"
+
+ class _Futu:
+ KLType = _KLType
+ AuType = _AuType
+
+ class _QuoteCtx:
+ def request_history_kline(self, code, **kwargs):
+ seen.update(kwargs)
+ return 0, None
+
+ monkeypatch.setattr(futu_sdk, "_require_futu", lambda: _Futu)
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: _QuoteCtx())
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+ monkeypatch.setattr(futu_sdk, "_unwrap", lambda result: result)
+ monkeypatch.setattr(futu_sdk, "_records", lambda data: [])
+ cfg = futu_sdk.FutuConfig(host="127.0.0.1", port=11111, profile="paper")
+ result = futu_sdk.get_historical_bars("US.AAPL", config=cfg, period="1D", limit=24)
+ assert seen["autype"] == "QFQ"
+ assert result["adjustment"] == "qfq"
+
+
+def test_history_without_autype_stub_keeps_implicit_default(monkeypatch) -> None:
+ # SDK stubs without AuType fall back to the SDK's own default rather
+ # than blowing up; the declared caliber is still qfq.
+ class _KLType:
+ K_DAY = "K_DAY"
+
+ class _Futu:
+ KLType = _KLType
+
+ class _QuoteCtx:
+ def request_history_kline(self, code, ktype=None, max_count=None):
+ return 0, None
+
+ monkeypatch.setattr(futu_sdk, "_require_futu", lambda: _Futu)
+ monkeypatch.setattr(futu_sdk, "_quote_ctx", lambda cfg: _QuoteCtx())
+ monkeypatch.setattr(futu_sdk, "_close", lambda ctx: None)
+ monkeypatch.setattr(futu_sdk, "_unwrap", lambda result: result)
+ monkeypatch.setattr(futu_sdk, "_records", lambda data: [])
+ cfg = futu_sdk.FutuConfig(host="127.0.0.1", port=11111, profile="paper")
+ result = futu_sdk.get_historical_bars("US.AAPL", config=cfg, period="1D", limit=24)
+ assert result["adjustment"] == "qfq"
diff --git a/agent/tests/test_market_detection.py b/agent/tests/test_market_detection.py
index 3e32f628e..8b390cb4d 100644
--- a/agent/tests/test_market_detection.py
+++ b/agent/tests/test_market_detection.py
@@ -123,6 +123,22 @@ class TestDetectMarket:
assert _detect_market("123456") == "a_share"
assert _detect_market("@#$") == "a_share"
+ def test_concatenated_crypto_pairs_route_to_crypto(self) -> None:
+ # Separator-less spot pairs (the Binance spelling) used to fall
+ # through every pattern and pick up a_share rules, T+1 and no
+ # shorting on a perpetual. The quote-asset table mirrors the
+ # trade-journal parser.
+ assert _detect_market("BTCUSDT") == "crypto"
+ assert _detect_market("ETHUSDT") == "crypto"
+ assert _detect_market("ETHUSDC") == "crypto"
+ assert _detect_market("DOGEUSDT") == "crypto"
+ assert code_currency("BTCUSDT") == "USD"
+ # Metals and G10 FX end in USD, not a stablecoin quote, and stay forex.
+ assert _detect_market("XAUUSD") == "forex"
+ assert _detect_market("EURUSD") == "forex"
+ # A bare 6-letter code outside every table still hits the default.
+ assert _detect_market("NFLXLI") == "a_share"
+
# ---------------------------------------------------------------------------
# Issue #986 — bare US tickers must route to the us_equity chain
diff --git a/agent/tests/test_mt5_connector.py b/agent/tests/test_mt5_connector.py
index b49f1454f..e0f70863d 100644
--- a/agent/tests/test_mt5_connector.py
+++ b/agent/tests/test_mt5_connector.py
@@ -644,6 +644,35 @@ class TestPlaceOrder:
assert result["status"] == "error"
assert fake_mt5.order_send_requests == []
+ def test_symbol_max_volume_errors_instead_of_clamping(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ # Connector guards sit above the symbol cap, so the symbol's own
+ # volume_max is the binding constraint: 150 lots asked, 100 allowed.
+ cfg = _paper_config(max_order_volume=500.0, max_order_notional_usd=100_000_000.0)
+ result = sdk.place_order(
+ cfg,
+ symbol="EURUSD", side="buy", quantity=150.0, notional=None,
+ order_type="market", limit_price=None, time_in_force="day",
+ )
+ assert result["status"] == "error"
+ assert "symbol maximum" in result["error"]
+ assert fake_mt5.order_send_requests == []
+
+ def test_notional_over_symbol_max_volume_errors(self, fake_mt5: FakeMT5) -> None:
+ from src.trading.connectors.mt5 import sdk
+
+ # 20M USD / (100k * 1.08 per lot) ~= 185 lots, over the symbol's 100.
+ cfg = _paper_config(max_order_volume=500.0, max_order_notional_usd=100_000_000.0)
+ result = sdk.place_order(
+ cfg,
+ symbol="EURUSD", side="buy", quantity=None, notional=20_000_000.0,
+ order_type="market", limit_price=None, time_in_force="day",
+ )
+ assert result["status"] == "error"
+ assert "symbol maximum" in result["error"]
+ assert fake_mt5.order_send_requests == []
+
def test_exactly_one_size_required(self, fake_mt5: FakeMT5) -> None:
assert self._place(fake_mt5, quantity=None, notional=None)["status"] == "error"
assert self._place(fake_mt5, quantity=0.05, notional=1000.0)["status"] == "error"