diff --git a/backend_api_python/app/openapi/schemas/high_risk.py b/backend_api_python/app/openapi/schemas/high_risk.py index eb2fe07e6..c27af8eb6 100644 --- a/backend_api_python/app/openapi/schemas/high_risk.py +++ b/backend_api_python/app/openapi/schemas/high_risk.py @@ -135,6 +135,11 @@ class QuickTradeOrderRequestSchema(Schema): ) tp_price = fields.Float(load_default=0, validate=validate.Range(min=0)) sl_price = fields.Float(load_default=0, validate=validate.Range(min=0)) + trailing_stop_pct = fields.Float( + load_default=0, validate=validate.Range(min=0, max=1, max_inclusive=False), + metadata={"exclusiveMaximum": True, "description": "Decimal trailing ratio: 0.02 means 2%."}, + ) + trailing_activation_pct = fields.Float(load_default=0, validate=validate.Range(min=0)) source = fields.String(load_default="manual", validate=validate.Length(max=64)) margin_mode = fields.String(load_default="", validate=validate.Length(max=16)) marginMode = fields.String(load_default="", validate=validate.Length(max=16)) @@ -146,6 +151,16 @@ class QuickTradeOrderRequestSchema(Schema): @pre_load def normalize_values(self, data, **kwargs): normalized = dict(data or {}) + from app.services.quick_trade.protection_policy import ALIASES, protection_error_code, protection_values + try: + values = protection_values(normalized) + except ValueError as exc: + raise ValidationError(protection_error_code(exc)) from exc + for key in ("trailing_stop_pct", "trailing_activation_pct"): + for alias in ALIASES[key]: + if alias in normalized: + normalized[key] = values[key] + normalized.pop(alias) for key in ("side", "order_type", "market_type", "margin_mode", "marginMode", "product_type", "api_family"): if key in normalized: normalized[key] = str(normalized[key] or "").strip().lower() diff --git a/backend_api_python/app/routes/agent_v1/quick_trade.py b/backend_api_python/app/routes/agent_v1/quick_trade.py index 7c967cc0e..47ce46de4 100644 --- a/backend_api_python/app/routes/agent_v1/quick_trade.py +++ b/backend_api_python/app/routes/agent_v1/quick_trade.py @@ -13,6 +13,7 @@ from __future__ import annotations import os +import math import time import uuid from typing import Any @@ -36,6 +37,7 @@ _ORDER_FIELDS = { "market", "symbol", "side", "qty", "order_type", "limit_price", "credential_id", "market_type", "leverage", "margin_mode", "tp_price", "sl_price", + "trailing_stop_pct", "trailing_activation_pct", } @@ -260,6 +262,12 @@ def _place_live_order(*, body: dict, user_id: int) -> dict: if reject is not None: raise ValueError("Quick Trade currently supports crypto exchange API keys only.") + from app.services.quick_trade.protection_policy import validate_manual_protection + protection = validate_manual_protection(body, exchange_id=exchange_id, market_type=market_type) + tp_price, sl_price = protection["tp_price"], protection["sl_price"] + trailing_stop_pct = protection["trailing_stop_pct"] + trailing_activation_pct = protection["trailing_activation_pct"] + client = create_exchange_client(exchange_config, market_type=market_type) if market_type == "swap": @@ -338,28 +346,7 @@ def _place_live_order(*, body: dict, user_id: int) -> dict: fill_price=avg_fill, ) - tp_price = float(body.get("tp_price") or body.get("tpPrice") or 0) - sl_price = float(body.get("sl_price") or body.get("slPrice") or 0) - protection_result = [] - protection_error = "" - try: - protection_result = attach_quick_trade_protection( - client, - symbol=symbol, - side=side, - filled_qty=filled, - avg_price=avg_fill, - tp_price=tp_price, - sl_price=sl_price, - market_type=market_type, - exchange_config=exchange_config, - leverage=leverage, - margin_mode=margin_mode, - client_order_id=f"{client_order_id}p", - ) - except Exception as protection_exc: - protection_error = str(protection_exc) - + protection_status = ("dispatching" if filled > 0 and avg_fill > 0 else "pending_fill") if (tp_price > 0 or sl_price > 0 or trailing_stop_pct > 0) else "not_requested" status = quick_order_status( requested_qty=qty, filled_qty=filled, @@ -370,9 +357,11 @@ def _place_live_order(*, body: dict, user_id: int) -> dict: "client_order_id": client_order_id, "requested_base_qty": qty, "exchange_status": exchange_status, - "native_protection": protection_result, - "native_protection_error": protection_error, - "protected_filled_qty": filled if protection_result else 0.0, + **protection, + "protection_status": protection_status, + "native_protection": [], + "native_protection_error": "", + "protected_filled_qty": filled if protection_status == "attached" else 0.0, "margin_mode": margin_mode, "fees_by_ccy": dict(enrich.get("fees_by_ccy") or {}), "fee_status": str(enrich.get("fee_status") or "pending"), @@ -403,6 +392,16 @@ def _place_live_order(*, body: dict, user_id: int) -> dict: commission_quote=commission_quote, ) + from app.services.quick_trade.protection_submission import finish_recorded_protection + protection_status, protection_error = finish_recorded_protection( + trade_id, raw_record["_quick_trade"], client, submit=attach_quick_trade_protection, + symbol=symbol, side=side, filled_qty=filled, avg_price=avg_fill, + tp_price=tp_price, sl_price=sl_price, market_type=market_type, + exchange_config=exchange_config, leverage=leverage, margin_mode=margin_mode, + client_order_id=f"{client_order_id}p", trailing_stop_pct=trailing_stop_pct, + trailing_activation_pct=trailing_activation_pct, + ) + return { "trade_id": trade_id, "exchange_order_id": exchange_order_id, @@ -415,7 +414,7 @@ def _place_live_order(*, body: dict, user_id: int) -> dict: "filled": filled, "avg_price": avg_fill, "status": status, - "protection_status": "failed" if protection_error else ("attached" if protection_result else "not_requested"), + "protection_status": protection_status, "protection_error": protection_error, "paper": False, } @@ -444,7 +443,7 @@ def place_order(): return error(400, "side must be 'buy' or 'sell'") try: qty_f = float(qty) - if qty_f <= 0: + if isinstance(qty, bool) or not math.isfinite(qty_f) or qty_f <= 0: raise ValueError except Exception: return error(400, "qty must be a positive number") @@ -457,6 +456,13 @@ def place_order(): except (TypeError, ValueError): return error(400, "limit_price is required for limit orders") + from app.services.quick_trade.protection_policy import protection_error_code, protection_values + try: + protection = protection_values(body) + if paper_only() and any(protection.values()): + return error(400, "quickTrade.protection.unsupported", http=400) + except ValueError as exc: + return error(400, protection_error_code(exc), http=400) body = dict(body) body["qty"] = qty_f body["order_type"] = order_type @@ -498,7 +504,10 @@ def place_order(): http=403, ) try: - result = _place_live_order(body=body, user_id=current_user_id()) + from app.services.quick_trade.order_safety import quick_trade_execution_key + from app.services.live_trading.execution_lock import trade_execution_lock + with trade_execution_lock(quick_trade_execution_key(body, user_id=current_user_id())): + result = _place_live_order(body=body, user_id=current_user_id()) except ValueError as exc: _finish_live_notional("failed") return error(400, str(exc), http=400) diff --git a/backend_api_python/app/routes/alpaca.py b/backend_api_python/app/routes/alpaca.py index 5c3c9165f..4c9f34550 100644 --- a/backend_api_python/app/routes/alpaca.py +++ b/backend_api_python/app/routes/alpaca.py @@ -480,12 +480,16 @@ def place_order(): market_type = data.get('marketType', 'USStock') order_type = (data.get('orderType') or 'market').lower() + if order_type not in {"market", "limit"}: + return jsonify({"success": False, "error": "brokerAccounts.unsupportedOrderType"}), 400 try: - take_profit_price = order_number(data.get('take_profit_price'), allow_zero=True) - stop_loss_price = order_number(data.get('stop_loss_price'), allow_zero=True) - except (TypeError, ValueError): - return jsonify({"success": False, "error": "brokerAccounts.invalidOrder"}), 400 + from app.services.quick_trade.protection_policy import protection_error_code, validate_manual_protection + protection = validate_manual_protection(data, exchange_id="alpaca", market_type=market_type) + take_profit_price = protection["tp_price"] + stop_loss_price = protection["sl_price"] + except ValueError as exc: + return jsonify({"success": False, "error": protection_error_code(exc, "brokerAccounts.invalidOrder")}), 400 protection_requested = take_profit_price > 0 or stop_loss_price > 0 if order_type == 'limit': @@ -518,11 +522,8 @@ def place_order(): "data": { "orderId": result.order_id, "filled": result.filled, "avgPrice": result.avg_price, "status": result.status, "raw": result.raw, - "protection_status": ( - "attached" - if protection_requested and str(market_type).strip().lower() == "usstock" - else "unsupported_market" if protection_requested else "not_requested" - ), + "protection_status": result.raw.get("protection_status", "dispatching") if protection_requested else "not_requested", + "protection_error": result.raw.get("protection_error", "quickTrade.protection.reviewRequired") if protection_requested else "", }, }) return jsonify({"success": False, "error": result.message, "data": result.raw}), 400 diff --git a/backend_api_python/app/routes/ibkr.py b/backend_api_python/app/routes/ibkr.py index 50ae745e5..28d70133c 100644 --- a/backend_api_python/app/routes/ibkr.py +++ b/backend_api_python/app/routes/ibkr.py @@ -299,28 +299,29 @@ def place_order(): market_type = data.get('marketType', 'USStock') order_type = data.get('orderType', 'market').lower() - # Place order - if order_type == 'limit': - try: - price = order_number(data.get('price')) - except BrokerOrderValidationError: - return jsonify({"success": False, "error": "brokerAccounts.invalidOrder"}), 400 - if not price or float(price) <= 0: - return jsonify({"success": False, "error": "Limit order requires price"}), 400 - + from app.services.quick_trade.protection_policy import protection_error_code, validate_manual_protection + try: + protection = validate_manual_protection(data, exchange_id="ibkr", market_type=market_type) + price = order_number(data.get("price"), allow_zero=order_type != "limit") + except ValueError as exc: + return jsonify({"success": False, "error": protection_error_code(exc, "brokerAccounts.invalidOrder")}), 400 + if order_type not in {"market", "limit"}: + return jsonify({"success": False, "error": "brokerAccounts.unsupportedOrderType"}), 400 + protection_requested = any(protection.values()) + if protection_requested: + result = client.place_bracket_order( + symbol=symbol, side=side, quantity=float(quantity), market_type=market_type, + limit_price=price if order_type == "limit" else 0, + take_profit_price=protection["tp_price"], stop_loss_price=protection["sl_price"], + trailing_stop_pct=protection["trailing_stop_pct"], + ) + elif order_type == "limit": result = client.place_limit_order( - symbol=symbol, - side=side, - quantity=float(quantity), - price=float(price), - market_type=market_type + symbol=symbol, side=side, quantity=float(quantity), price=price, market_type=market_type, ) else: result = client.place_market_order( - symbol=symbol, - side=side, - quantity=float(quantity), - market_type=market_type + symbol=symbol, side=side, quantity=float(quantity), market_type=market_type, ) if result.success: @@ -332,7 +333,9 @@ def place_order(): "filled": result.filled, "avgPrice": result.avg_price, "status": result.status, - "raw": result.raw + "raw": result.raw, + "protection_status": result.raw.get("protection_status", "dispatching") if protection_requested else "not_requested", + "protection_error": result.raw.get("protection_error", "quickTrade.protection.reviewRequired") if protection_requested else "" } }) else: diff --git a/backend_api_python/app/routes/openapi_brokers.py b/backend_api_python/app/routes/openapi_brokers.py index 085ebe0c2..e8d51d55a 100644 --- a/backend_api_python/app/routes/openapi_brokers.py +++ b/backend_api_python/app/routes/openapi_brokers.py @@ -58,6 +58,8 @@ def _public_error(exc: BaseException, fallback: str) -> str: "unsupportedMarket", "contractRequired", "referencePriceRequired", "contractMetadataRequired", "protectionUnsupported", "canonicalSymbolRequired", )}: return value + if value in {"quickTrade.protection.unsupported", "quickTrade.protection.invalidParameters"}: + return value return _PUBLIC_ERROR_KEYS.get(value, fallback) @@ -604,13 +606,11 @@ def place_order(broker: str): order_number(data.get("quantity"), allow_zero=True) or order_number(data.get("size"), allow_zero=True) ) - if broker == "forthright" and any(data.get(key) for key in ( - "take_profit_price", "stop_loss_price", "takeProfitPrice", "stopLossPrice", - )): - raise ValueError("brokerAccounts.forthright.protectionUnsupported") + from app.services.quick_trade.protection_policy import validate_manual_protection + protection = validate_manual_protection(data, exchange_id=broker, market_type=str(data.get("marketType") or "USStock")) price = order_number(data.get("price"), allow_zero=True) or order_number(data.get("limitPrice"), allow_zero=True) price = order_number(price, allow_zero=order_type != "limit") - extra = {} + extra = dict(protection) if any(protection.values()) else {} if broker == "forthright": extra["reference_price"] = ( order_number(data.get("referencePrice"), allow_zero=True) @@ -635,6 +635,8 @@ def place_order(broker: str): "avgPrice": result.avg_price, "status": result.status, "raw": result.raw, + "protection_status": result.raw.get("protection_status", "dispatching") if any(protection.values()) else "not_requested", + "protection_error": result.raw.get("protection_error", "quickTrade.protection.reviewRequired") if any(protection.values()) else "", }}) except ValueError as exc: return jsonify({"success": False, "error": _public_error( diff --git a/backend_api_python/app/routes/quick_trade.py b/backend_api_python/app/routes/quick_trade.py index 9b46badf9..b2174612f 100644 --- a/backend_api_python/app/routes/quick_trade.py +++ b/backend_api_python/app/routes/quick_trade.py @@ -46,7 +46,6 @@ attach_quick_trade_protection, enrich_fill, limit_order_kwargs, - quick_trade_protection_status, quick_order_status, ) from app.services.quick_trade.symbols import is_supported_crypto_exchange, symbols_match as quick_trade_symbols_match @@ -255,6 +254,13 @@ def place_order(body): market_type = str(body.get("market_type") or "").strip().lower() tp_price = float(body.get("tp_price") or 0) sl_price = float(body.get("sl_price") or 0) + from app.services.quick_trade.protection_policy import protection_error_code, protection_values, validate_manual_protection + try: + protection = protection_values(body) + except ValueError as exc: + return jsonify({"code": 0, "msg": protection_error_code(exc)}), 400 + trailing_stop_pct = protection["trailing_stop_pct"] + trailing_activation_pct = protection["trailing_activation_pct"] source = str(body.get("source") or "manual").strip() margin_mode = str(body.get("margin_mode") or body.get("marginMode") or "").strip().lower() if margin_mode in ("cross", "crossed"): @@ -310,6 +316,10 @@ def place_order(body): qt_rej = _reject_quick_trade_if_desktop_broker(exchange_id) if qt_rej is not None: return qt_rej + try: + validate_manual_protection(body, exchange_id=exchange_id, market_type=market_type) + except ValueError as exc: + return jsonify({"code": 0, "msg": protection_error_code(exc)}), 400 client = create_exchange_client(exchange_config, market_type=market_type) strategy_conflict = _recent_strategy_conflict( @@ -502,7 +512,7 @@ def place_order(body): exchange_status = "" enrich = {"fee_status": "pending", "fees_by_ccy": {}} if exchange_order_id and ( - order_type == "limit" or tp_price > 0 or sl_price > 0 + order_type == "limit" or tp_price > 0 or sl_price > 0 or trailing_stop_pct > 0 ): enrich = enrich_fill( client, @@ -535,36 +545,7 @@ def place_order(body): fill_price=avg_fill, ) - protection_result: list[Dict[str, Any]] = [] - protection_error = "" - try: - protection_result = attach_quick_trade_protection( - client, - symbol=symbol, - side=side, - filled_qty=filled, - avg_price=avg_fill, - tp_price=tp_price, - sl_price=sl_price, - market_type=market_type, - exchange_config=exchange_config, - leverage=leverage, - margin_mode=margin_mode, - client_order_id=f"{client_order_id}p", - ) - except Exception as protection_exc: - protection_error = str(protection_exc) - logger.error("Quick Trade native protection failed order=%s: %s", exchange_order_id, protection_exc) - - protection_status, protection_error = quick_trade_protection_status( - requested=tp_price > 0 or sl_price > 0, - market_type=market_type, - filled_qty=filled, - avg_price=avg_fill, - responses=protection_result, - error=protection_error, - ) - + protection_status = ("dispatching" if filled > 0 and avg_fill > 0 else "pending_fill") if (tp_price > 0 or sl_price > 0 or trailing_stop_pct > 0) else "not_requested" status = quick_order_status( requested_qty=status_base_qty, filled_qty=filled, @@ -581,10 +562,14 @@ def place_order(body): "amount_semantics": "base_quantity" if uses_base_quantity else ("margin" if market_type == "swap" else "quote_notional"), "input_base_quantity": requested_base_quantity if uses_base_quantity else None, "exchange_status": exchange_status, - "native_protection": protection_result, - "native_protection_error": protection_error, + "tp_price": tp_price if tp_price > 0 else None, + "sl_price": sl_price if sl_price > 0 else None, + "trailing_stop_pct": trailing_stop_pct if trailing_stop_pct > 0 else None, + "trailing_activation_pct": trailing_activation_pct if trailing_activation_pct > 0 else None, + "native_protection": [], + "native_protection_error": "", "protection_status": protection_status, - "protected_filled_qty": filled if protection_result else 0.0, + "protected_filled_qty": filled if protection_status == "attached" else 0.0, "margin_mode": margin_mode, "client_order_id": client_order_id, "instrument_id": str((resolved_product or {}).get("instrument_id") or ""), @@ -613,7 +598,7 @@ def place_order(body): exchange_order_id=exchange_order_id, filled=filled, avg_price=avg_fill, - error_msg=protection_error, + error_msg="", source=source, raw_result=raw_record, commission=commission, @@ -622,6 +607,16 @@ def place_order(body): client_order_id=client_order_id, ) + from app.services.quick_trade.protection_submission import finish_recorded_protection + protection_status, protection_error = finish_recorded_protection( + trade_id, raw_record["_quick_trade"], client, submit=attach_quick_trade_protection, + symbol=symbol, side=side, filled_qty=filled, avg_price=avg_fill, + tp_price=tp_price, sl_price=sl_price, market_type=market_type, + exchange_config=exchange_config, leverage=leverage, margin_mode=margin_mode, + client_order_id=f"{client_order_id}p", trailing_stop_pct=trailing_stop_pct, + trailing_activation_pct=trailing_activation_pct, + ) + return jsonify({ "code": 1, "msg": "Order placed successfully", @@ -1758,7 +1753,8 @@ def cancel_order(body): commission = %s, commission_ccy = %s, commission_quote = %s, - raw_result = %s + raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), '{_quick_trade}', + COALESCE(raw_result->'_quick_trade', '{}'::jsonb) || %s::jsonb) WHERE id = %s AND user_id = %s AND status IN ('new', 'open', 'pending', 'accepted', 'submitted', 'partial', 'partially_filled') """, @@ -1769,7 +1765,7 @@ def cancel_order(body): commission, commission_ccy, commission_quote, - json.dumps(stored_raw, ensure_ascii=False), + json.dumps({key: metadata[key] for key in ("cancelled_at", "cancel_outcome", "exchange_status")}), trade_id, user_id, ), @@ -1908,6 +1904,11 @@ def get_history(): }) data = resolve_trade_history(trades, user_id, credential_id, symbol, market_type, limit, offset) + data["protection_alerts"] = [ + {"trade_id": item["id"], "status": item["protection_status"], + "message": "quickTrade.protection.reviewRequired"} + for item in trades if item.get("protection_status") == "failed" + ] return jsonify({"code": 1, "msg": "success", "data": data}) except Exception as e: logger.error(f"get_history failed: {e}") diff --git a/backend_api_python/app/services/alpaca_trading/client.py b/backend_api_python/app/services/alpaca_trading/client.py index c6f802a61..5ab828c8e 100644 --- a/backend_api_python/app/services/alpaca_trading/client.py +++ b/backend_api_python/app/services/alpaca_trading/client.py @@ -152,7 +152,7 @@ def _ensure_alpaca(): from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, LimitOrderRequest, GetOrdersRequest, - TakeProfitRequest, StopLossRequest, + TakeProfitRequest, StopLossRequest, GetOrderByIdRequest, ) from alpaca.trading.enums import OrderSide, TimeInForce, QueryOrderStatus, OrderClass from alpaca.data.historical import StockHistoricalDataClient, CryptoHistoricalDataClient @@ -164,6 +164,7 @@ def _ensure_alpaca(): "GetOrdersRequest": GetOrdersRequest, "TakeProfitRequest": TakeProfitRequest, "StopLossRequest": StopLossRequest, + "GetOrderByIdRequest": GetOrderByIdRequest, "OrderSide": OrderSide, "TimeInForce": TimeInForce, "QueryOrderStatus": QueryOrderStatus, @@ -296,6 +297,36 @@ def _ensure_connected(self): # ==================== Order Methods ==================== + @staticmethod + def _protection_snapshot(order: Any, take: float, stop: float) -> Dict[str, Any]: + expected = int(take > 0) + int(stop > 0) + if not expected: + return {} + legs = list(getattr(order, "legs", None) or []) + statuses = [_enum_value(getattr(leg, "status", "")).lower() for leg in legs] + confirmed = len(legs) == expected and all( + getattr(leg, "id", None) and status in {"new", "accepted", "held", "partially_filled", "filled"} + for leg, status in zip(legs, statuses) + ) + rejected = any(status in {"rejected", "canceled", "cancelled", "expired"} for status in statuses) + return { + "protection_status": "attached" if confirmed else "failed" if rejected else "dispatching", + "protection_error": "" if confirmed else "quickTrade.protection.reviewRequired", + "protection_orders": [{"id": str(getattr(leg, "id", "") or ""), "status": status} + for leg, status in zip(legs, statuses)], + } + + def _refresh_accepted_order(self, order: Any, *, protection: bool = False) -> Any: + try: + if protection: + options = _ensure_alpaca()["GetOrderByIdRequest"](nested=True) + return self._trading_client.get_order_by_id(order.id, filter=options) + return self._trading_client.get_order_by_id(order.id) + except Exception: + # A read failure must not turn a known accepted entry into a retryable failure. + logger.warning("Alpaca accepted order status requires reconciliation") + return order + @staticmethod def _order_commission_snapshot(order: Any) -> Dict[str, Any]: commission = _num(getattr(order, "commission", 0)) @@ -413,7 +444,7 @@ def place_market_order( # Brief poll for fill status time.sleep(2) - order = self._trading_client.get_order_by_id(order.id) + order = self._refresh_accepted_order(order, protection=take_profit_price > 0 or stop_loss_price > 0) filled_qty = float(order.filled_qty or 0) avg_price = float(order.filled_avg_price or 0) @@ -438,6 +469,7 @@ def place_market_order( "submitted_at": str(order.submitted_at), "client_order_id": str(getattr(order, "client_order_id", "") or client_order_id), **self._order_commission_snapshot(order), + **self._protection_snapshot(order, take_profit_price, stop_loss_price), }, ) except Exception as e: @@ -509,7 +541,7 @@ def place_limit_order( req = modules["LimitOrderRequest"](**request_kwargs) order = self._trading_client.submit_order(order_data=req) time.sleep(1) - order = self._trading_client.get_order_by_id(order.id) + order = self._refresh_accepted_order(order, protection=take_profit_price > 0 or stop_loss_price > 0) filled_qty = float(order.filled_qty or 0) avg_price = float(order.filled_avg_price or 0) @@ -530,6 +562,7 @@ def place_limit_order( "extended_hours": extended_hours, "client_order_id": str(getattr(order, "client_order_id", "") or client_order_id), **self._order_commission_snapshot(order), + **self._protection_snapshot(order, take_profit_price, stop_loss_price), }, ) except Exception as e: diff --git a/backend_api_python/app/services/ibkr_trading/client.py b/backend_api_python/app/services/ibkr_trading/client.py index 9c4378a96..3da18de67 100644 --- a/backend_api_python/app/services/ibkr_trading/client.py +++ b/backend_api_python/app/services/ibkr_trading/client.py @@ -407,16 +407,24 @@ def place_bracket_order( *, take_profit_price: float = 0.0, stop_loss_price: float = 0.0, + trailing_stop_pct: float = 0.0, limit_price: float = 0.0, market_type: str = "USStock", client_order_id: str = "", ) -> OrderResult: - """Submit a parent order and attached take-profit/stop-loss orders atomically.""" + """Submit a bracket and report child acknowledgements separately from entry.""" try: quantity = order_number(quantity) limit_price = order_number(limit_price, allow_zero=True) take_profit_price = order_number(take_profit_price, allow_zero=True) stop_loss_price = order_number(stop_loss_price, allow_zero=True) + from app.services.quick_trade.protection_policy import validate_manual_protection + protection = validate_manual_protection({ + "tp_price": take_profit_price, "sl_price": stop_loss_price, + "trailing_stop_pct": trailing_stop_pct, + "order_type": "limit" if limit_price else "market", + }, exchange_id="ibkr", market_type=market_type) + trailing_stop_pct = protection["trailing_stop_pct"] self._ensure_connected() _ensure_ib_insync() contract = self._create_contract(symbol, market_type) @@ -425,7 +433,7 @@ def place_bracket_order( take_profit_price = float(take_profit_price or 0.0) stop_loss_price = float(stop_loss_price or 0.0) - if take_profit_price <= 0 and stop_loss_price <= 0: + if take_profit_price <= 0 and stop_loss_price <= 0 and trailing_stop_pct <= 0: return OrderResult(success=False, message="Bracket order requires a protection price") action = "BUY" if side.lower() == "buy" else "SELL" @@ -463,17 +471,38 @@ def place_bracket_order( transmit=False, ) children.append(child) + if trailing_stop_pct > 0: + children.append(ib_insync.Order( + action=exit_action, totalQuantity=quantity, orderType="TRAIL", + trailingPercent=float(trailing_stop_pct) * 100, + account=self._account, parentId=parent.orderId, tif="GTC", transmit=False, + )) children[-1].transmit = True trade = self._ib.placeOrder(contract, parent) - for child in children: - self._ib.placeOrder(contract, child) - self._ib.sleep(0.05) - self._ib.sleep(2) + child_trades = [] + submission_uncertain = False + try: + for child in children: + child_trades.append(self._ib.placeOrder(contract, child)) + self._ib.sleep(0.05) + self._ib.sleep(2) + except Exception: + submission_uncertain = True + logger.warning("IBKR bracket child submission requires reconciliation", exc_info=True) result = self._trade_result(trade, message_prefix="Bracket order") result.raw["childOrderIds"] = [int(getattr(child, "orderId", 0) or 0) for child in children] + child_statuses = [str(getattr(getattr(item, "orderStatus", None), "status", "") or "Unknown") for item in child_trades] + result.raw["childOrderStatuses"] = child_statuses + confirmed = not submission_uncertain and len(child_statuses) == len(children) and all( + status.lower() in {"presubmitted", "submitted", "filled"} for status in child_statuses + ) + rejected = any(status.lower() in {"cancelled", "apicancelled", "inactive"} for status in child_statuses) + result.raw["protection_status"] = "attached" if confirmed else "failed" if rejected else "dispatching" + result.raw["protection_error"] = "" if confirmed else "quickTrade.protection.reviewRequired" result.raw["takeProfitPrice"] = take_profit_price result.raw["stopLossPrice"] = stop_loss_price + result.raw["trailingStopPct"] = trailing_stop_pct return result except Exception as e: logger.error(f"Bracket order failed: {e}") diff --git a/backend_api_python/app/services/live_trading/native_protection.py b/backend_api_python/app/services/live_trading/native_protection.py index 6ef28b26a..bca89d2ea 100644 --- a/backend_api_python/app/services/live_trading/native_protection.py +++ b/backend_api_python/app/services/live_trading/native_protection.py @@ -147,7 +147,11 @@ def place_native_protection_orders( """Place reduce-only native protection and return exchange responses.""" side = str(request.pos_side or "").strip().lower() qty = float(request.quantity or 0.0) - if side not in ("long", "short") or qty <= 0: + numbers = (qty, request.entry_price, request.stop_loss_price, request.take_profit_price, + request.trailing_stop_pct, request.trailing_activation_pct) + if side not in ("long", "short") or qty <= 0 or any(not math.isfinite(v) or v < 0 for v in numbers): + raise LiveTradingError("invalid_native_protection_request") + if request.trailing_stop_pct >= 1 or (side == "short" and request.trailing_activation_pct >= 1): raise LiveTradingError("invalid_native_protection_request") if request.stop_loss_price <= 0 and request.take_profit_price <= 0 and request.trailing_stop_pct <= 0: return [] @@ -227,7 +231,10 @@ def _place_binance(client: Any, request: NativeProtectionRequest) -> List[Dict[s ], )) if request.trailing_stop_pct > 0: - callback = min(10.0, max(0.1, request.trailing_stop_pct * 100.0)) + callback = request.trailing_stop_pct * 100.0 + if not 0.1 <= callback <= 10.0: + responses.append({"managed_by": "strategy_runtime", "type": "trailing_stop"}) + return responses body = dict(base, type="TRAILING_STOP_MARKET", callbackRate=str(callback)) activation = _activation_price(request) if activation > 0: @@ -583,35 +590,9 @@ def _place_bybit(client: Any, request: NativeProtectionRequest) -> List[Dict[str ], )) if request.trailing_stop_pct > 0: - trailing_stop, price_precision = client._normalize_price( - symbol=request.symbol, - price=request.entry_price * request.trailing_stop_pct, - ) - activation_price, _ = client._normalize_price( - symbol=request.symbol, - price=_activation_price(request) or request.entry_price, - ) - if trailing_stop <= 0 or activation_price <= 0: - raise LiveTradingError("bybit_native_protection_price_below_minimum") - body = { - "category": "linear", - "symbol": to_bybit_symbol(request.symbol), - "positionIdx": base["positionIdx"], - "tpslMode": "Full", - "trailingStop": client._dec_str(trailing_stop, strict_precision=price_precision), - "activePrice": client._dec_str(activation_price, strict_precision=price_precision), - } - raw = client._signed_request("POST", "/v5/position/trading-stop", json_body=body) - data = _response_data(raw) - responses.append(_annotate_protection_response( - raw, - role="trailing_stop", - identifiers=[ - ("exchange_order_id", data.get("orderId")), - ("parent_order_id", data.get("orderId")), - ("client_order_id", data.get("orderLinkId")), - ], - )) + # Bybit accepts a fixed price distance for the whole position, not a + # percentage of the running extreme for this entry's quantity. + responses.append({"managed_by": "strategy_runtime", "type": "trailing_stop"}) return responses @@ -695,7 +676,30 @@ def _place_gate(client: Any, request: NativeProtectionRequest) -> List[Dict[str, ], )) if request.trailing_stop_pct > 0: - responses.append({"managed_by": "strategy_runtime", "type": "trailing_stop"}) + activation = _activation_price(request) + if activation: + activation, _ = client._normalize_price(contract=contract, price=activation) + if activation <= 0: + raise LiveTradingError("gate_native_protection_price_below_minimum") + body = { + "contract": contract, "amount": str(size), "price_type": 1, + "activation_price": str(activation), "is_gte": request.pos_side == "long", + "price_offset": f"{Decimal(str(request.trailing_stop_pct)) * 100:f}%", + "reduce_only": True, + } + if safe_text: + body["text"] = f"t-{safe_text}-tr" + raw = client._signed_request( + "POST", "/api/v4/futures/usdt/autoorder/v1/trail/create", json_body=body, + ) + data = _response_data(raw) + if str(raw.get("code", 0)) != "0" or not data.get("id"): + raise LiveTradingError("gate_trailing_protection_not_acknowledged") + responses.append(_annotate_protection_response( + raw, role="trailing_stop", identifiers=[ + ("parent_order_id", data["id"]), ("client_order_id", body.get("text")), + ], + )) return responses @@ -753,7 +757,34 @@ def _place_htx(client: Any, request: NativeProtectionRequest) -> List[Dict[str, ], )) if request.trailing_stop_pct > 0: - responses.append({"managed_by": "strategy_runtime", "type": "trailing_stop"}) + if request.trailing_stop_pct < 0.001: + responses.append({"managed_by": "strategy_runtime", "type": "trailing_stop"}) + return responses + activation = _activation_price(request) or request.entry_price + activation, _ = client._normalize_price(symbol=request.symbol, price=activation) + if activation <= 0: + raise LiveTradingError("htx_native_protection_price_below_minimum") + tracking = { + "contract_code": body["contract_code"], "direction": body["direction"], + "volume": volume, "reduce_only": 1, + "callback_rate": request.trailing_stop_pct, "active_price": float(activation), + "order_price_type": "optimal_20", + } + hedge = client.detect_swap_hedge_mode(symbol=request.symbol) + if hedge is None: + raise LiveTradingError("htx_position_mode_unknown") + tracking["offset"] = "close" if hedge else "both" + path = "/linear-swap-api/v1/" + ( + "swap_track_order" if request.margin_mode == "isolated" else "swap_cross_track_order" + ) + raw = client._swap_private_request_raw("POST", path, json_body=tracking) + data = _response_data(raw) + order_id = data.get("order_id_str") or data.get("order_id") + if raw.get("status") != "ok" or not order_id: + raise LiveTradingError("htx_trailing_protection_not_acknowledged") + responses.append(_annotate_protection_response( + raw, role="trailing_stop", identifiers=[("parent_order_id", order_id)], + )) return responses diff --git a/backend_api_python/app/services/openapi_brokers/tiger.py b/backend_api_python/app/services/openapi_brokers/tiger.py index e5cb2bb27..77169d388 100644 --- a/backend_api_python/app/services/openapi_brokers/tiger.py +++ b/backend_api_python/app/services/openapi_brokers/tiger.py @@ -36,7 +36,7 @@ def _sdk(): try: from tigeropen.common.consts import Currency, Market, SecurityType from tigeropen.common.util.contract_utils import stock_contract - from tigeropen.common.util.order_utils import limit_order, market_order + from tigeropen.common.util.order_utils import limit_order, market_order, limit_order_with_legs, order_leg from tigeropen.tiger_open_config import TigerOpenClientConfig from tigeropen.trade.trade_client import TradeClient return { @@ -46,6 +46,8 @@ def _sdk(): "stock_contract": stock_contract, "limit_order": limit_order, "market_order": market_order, + "limit_order_with_legs": limit_order_with_legs, + "order_leg": order_leg, "TigerOpenClientConfig": TigerOpenClientConfig, "TradeClient": TradeClient, } @@ -279,9 +281,13 @@ def _instrument(symbol: str, market_type: str) -> tuple[str, str]: return value.removesuffix(".US").removeprefix("US."), "USD" def _place_order(self, *, symbol: str, side: str, quantity: float, order_type: str, price: float = 0.0, - market_type: str = "USStock", client_order_id: str = "", **_: Any) -> BrokerOrderResult: + market_type: str = "USStock", client_order_id: str = "", **kwargs: Any) -> BrokerOrderResult: quantity = order_number(quantity) price = order_number(price, allow_zero=order_type != "limit") + from app.services.quick_trade.protection_policy import validate_manual_protection + protection = validate_manual_protection( + {**kwargs, "order_type": order_type}, exchange_id="tiger", market_type=market_type, + ) ticker, currency = self._instrument(symbol, market_type) if currency == "HKD": from app.services.market.hk_board_lots import validate_board_lot @@ -291,7 +297,21 @@ def _place_order(self, *, symbol: str, side: str, quantity: float, order_type: s action = str(side or "").strip().upper() if action not in ("BUY", "SELL"): raise ValueError("brokerAccounts.invalidOrder") - if order_type == "limit": + if any(protection.values()): + legs = [] + if protection["tp_price"]: + legs.append(sdk["order_leg"]("PROFIT", protection["tp_price"], outside_rth=False)) + if protection["sl_price"]: + legs.append(sdk["order_leg"]("LOSS", protection["sl_price"], outside_rth=False)) + if protection["trailing_stop_pct"]: + pct = protection["trailing_stop_pct"] + legs.append(sdk["order_leg"]("LOSS", trailing_percent=pct * 100, outside_rth=False)) + order = sdk["limit_order_with_legs"]( + self.account_id, contract, action, quantity, limit_price=float(price), + order_legs=legs, time_in_force="DAY", + ) + order.outside_rth = False + elif order_type == "limit": order = sdk["limit_order"](self.account_id, contract, action, quantity, float(price), time_in_force="DAY") else: order = sdk["market_order"](self.account_id, contract, action, quantity, time_in_force="DAY") @@ -300,6 +320,20 @@ def _place_order(self, *, symbol: str, side: str, quantity: float, order_type: s raw = self._normalize_order(order) raw["id"] = str(order_id or getattr(order, "id", None) or "") raw["order_id"] = raw["id"] + if any(protection.values()): + # Parent acknowledgement is not proof that every child is active. + raw.update(protection_status="dispatching", protection_error="quickTrade.protection.reviewRequired") + try: + children = self._ensure_client().get_open_orders(account=self.account_id, parent_id=int(raw["id"])) + children = list(children or []) + raw["protection_orders"] = [self._normalize_order(child) for child in children] + if len(children) == len(legs) and all(getattr(child, "status", None) for child in children) and all( + child["id"] and child["status"] in {"submitted", "new", "held", "filled", "partially_filled"} + for child in raw["protection_orders"] + ): + raw.update(protection_status="attached", protection_error="") + except Exception: + pass return BrokerOrderResult( True, order_id=raw["id"], diff --git a/backend_api_python/app/services/openapi_brokers/webull.py b/backend_api_python/app/services/openapi_brokers/webull.py index fe3060fbe..9461b471e 100644 --- a/backend_api_python/app/services/openapi_brokers/webull.py +++ b/backend_api_python/app/services/openapi_brokers/webull.py @@ -243,9 +243,15 @@ def _normalize_order(row: dict) -> dict: } def _place_order(self, *, symbol: str, side: str, quantity: float, order_type: str, price: float = 0.0, - market_type: str = "USStock", client_order_id: str = "", **_: Any) -> BrokerOrderResult: + market_type: str = "USStock", client_order_id: str = "", **kwargs: Any) -> BrokerOrderResult: quantity = order_number(quantity) price = order_number(price, allow_zero=order_type.upper() != "LIMIT") + from app.services.quick_trade.protection_policy import validate_manual_protection + protection = validate_manual_protection( + {**kwargs, "order_type": order_type}, exchange_id="webull", market_type=market_type, + ) + if any(protection.values()) and not float(quantity).is_integer(): + raise ValueError("quickTrade.protection.invalidParameters") if str(market_type).strip().lower() not in ("usstock", "stock", "equity", "spot"): raise BrokerApiError("brokerAccounts.webull.usStocksOnly") ticker = str(symbol or "").strip().upper() @@ -267,16 +273,48 @@ def _place_order(self, *, symbol: str, side: str, quantity: float, order_type: s } if order_type.upper() == "LIMIT": order["limit_price"] = str(price) - payload = self._request("POST", "/trading/orders/place", body={"account_id": self.account_id, "new_orders": [order]}) + body = {"account_id": self.account_id, "new_orders": [order]} + if any(protection.values()): + order["combo_type"] = "MASTER" + body["client_combo_order_id"] = uuid.uuid4().hex + for role, key in (("STOP_PROFIT", "tp_price"), ("STOP_LOSS", "sl_price")): + if protection[key] <= 0: + continue + leg = {**order, "client_order_id": uuid.uuid4().hex, "combo_type": role, + "side": "SELL" if order["side"] == "BUY" else "BUY", + "order_type": "LIMIT" if role == "STOP_PROFIT" else "STOP_LOSS"} + leg.pop("limit_price", None) + leg["limit_price" if role == "STOP_PROFIT" else "stop_price"] = str(protection[key]) + body["new_orders"].append(leg) + payload = self._request("POST", "/trading/orders/place", body=body) raw = payload if isinstance(payload, dict) else {"data": payload} rows = _data_list(raw, "orders", "order_list") - result = rows[0] if rows else raw + result = next((row for row in rows if str(row.get("client_order_id") or row.get("clientOrderId") or "") == order["client_order_id"]), None) + if result is None: + result = (rows[0] if rows else raw) if not any(protection.values()) else {} client_id = str(result.get("client_order_id") or result.get("clientOrderId") or order["client_order_id"]) raw = { **raw, "client_order_id": client_id, "broker_order_id": result.get("order_id") or result.get("orderId"), } + if any(protection.values()): + raw.update( + client_combo_order_id=body["client_combo_order_id"], + protection_client_order_ids=[leg["client_order_id"] for leg in body["new_orders"][1:]], + protection_status="dispatching", protection_error="quickTrade.protection.reviewRequired", + ) + expected = set(raw["protection_client_order_ids"]) + children = {str(row.get("client_order_id") or row.get("clientOrderId") or ""): row for row in rows} + verified = [children[key] for key in expected if key in children] + raw["protection_orders"] = [self._normalize_order(row) for row in verified] + if len(verified) == len(expected) and all( + (row.get("order_id") or row.get("orderId")) + and (row.get("status") or row.get("order_status")) + and _canonical_order_status(row.get("status") or row.get("order_status")) in {"submitted", "new", "accepted", "held", "partially_filled", "filled"} + for row in verified + ): + raw.update(protection_status="attached", protection_error="") return BrokerOrderResult( True, order_id=client_id, diff --git a/backend_api_python/app/services/pending_order_worker.py b/backend_api_python/app/services/pending_order_worker.py index 8f03451f2..bfb932a44 100644 --- a/backend_api_python/app/services/pending_order_worker.py +++ b/backend_api_python/app/services/pending_order_worker.py @@ -214,6 +214,12 @@ def _sync_quick_trade_orders(self, limit: int = 50) -> None: FROM qd_quick_trades WHERE ( status IN ('submitted', 'partially_filled') + OR raw_result->'_quick_trade'->>'protection_status' IN ('pending_fill', 'dispatching') + OR ( + raw_result->'_quick_trade'->>'protection_status' = 'attached' + AND COALESCE(filled_amount, 0) > COALESCE( + (raw_result->'_quick_trade'->>'protected_filled_qty')::numeric, 0) + ) OR ( status = 'filled' AND COALESCE(filled_amount, 0) > 0 @@ -240,7 +246,19 @@ def _sync_quick_trade_orders(self, limit: int = 50) -> None: for raw_row in rows: row = dict(raw_row) try: - self._sync_one_quick_trade_order(row) + from app.services.live_trading.execution_lock import trade_execution_key, trade_execution_lock + key = trade_execution_key( + user_id=int(row.get("user_id") or 0), credential_id=int(row.get("credential_id") or 0), + market_type=str(row.get("market_type") or "swap"), symbol=str(row.get("symbol") or ""), + ) + with trade_execution_lock(key, timeout_sec=0): + with get_db_connection() as db: + cur = db.cursor() + cur.execute("SELECT * FROM qd_quick_trades WHERE id = %s", (row["id"],)) + fresh = cur.fetchone() + cur.close() + if fresh: + self._sync_one_quick_trade_order(dict(fresh)) except Exception as exc: logger.warning( "Quick Trade reconciliation failed trade_id=%s: %s", @@ -288,44 +306,23 @@ def _sync_one_quick_trade_order(self, row: Dict[str, Any]) -> None: max_wait_sec=0.25, ) observed_filled = max(0.0, float(enrich.get("filled") or 0.0)) - cumulative_avg = max(0.0, float(enrich.get("avg_price") or 0.0)) + cumulative_avg = max(0.0, float(enrich.get("avg_price") or row.get("avg_fill_price") or 0.0)) previous_filled = max(0.0, float(row.get("filled_amount") or 0.0)) cumulative_filled = max(previous_filled, observed_filled) if observed_filled + ALPACA_FILL_DELTA_EPSILON < previous_filled: cumulative_avg = float(row.get("avg_fill_price") or 0.0) - protected_filled = max(0.0, float(metadata.get("protected_filled_qty") or 0.0)) - delta_to_protect = cumulative_filled - protected_filled - protection_error = "" - metadata_changed = False - if delta_to_protect > ALPACA_FILL_DELTA_EPSILON and cumulative_avg > 0: - try: - protection_result = attach_quick_trade_protection( - client, - symbol=str(row.get("symbol") or ""), - side=str(row.get("side") or ""), - filled_qty=delta_to_protect, - avg_price=cumulative_avg, - tp_price=float(row.get("tp_price") or 0.0), - sl_price=float(row.get("sl_price") or 0.0), - market_type=market_type, - exchange_config=exchange_config, - leverage=float(row.get("leverage") or 1.0), - margin_mode=margin_mode, - client_order_id=f"qdsync{trade_id}", - ) - if protection_result: - prior = metadata.get("native_protection") - metadata["native_protection"] = ( - list(prior) if isinstance(prior, list) else [] - ) + protection_result - metadata["protected_filled_qty"] = cumulative_filled - metadata["native_protection_error"] = "" - metadata["protection_status"] = "attached" - metadata_changed = True - except Exception as exc: - protection_error = str(exc) - metadata["native_protection_error"] = protection_error - metadata["protection_status"] = "failed" + from app.services.quick_trade.protection_submission import reconcile_filled_protection + outcome = reconcile_filled_protection( + row, metadata, client, cumulative_filled=cumulative_filled, cumulative_avg=cumulative_avg, + epsilon=ALPACA_FILL_DELTA_EPSILON, exchange_config=exchange_config, + market_type=market_type, margin_mode=margin_mode, + client_order_id=self._protection_client_order_id(trade_id, cumulative_filled), + submit=attach_quick_trade_protection, + ) + if outcome is None: + return + metadata_changed, protection_error = outcome + blocked = metadata.get("protection_status") in {"failed", "dispatching"} status_qty, quantity_changed = quick_trade_status_quantity( client, row=row, metadata=metadata, market_type=market_type, @@ -337,9 +334,11 @@ def _sync_one_quick_trade_order(self, row: Dict[str, Any]) -> None: filled_qty=cumulative_filled, exchange_status=str(enrich.get("status") or ""), ) + if status in {"cancelled", "failed"} and cumulative_filled <= 0 and not blocked: + metadata["protection_status"] = "not_requested" + metadata_changed = True metadata["exchange_status"] = str(enrich.get("status") or "") metadata["last_reconciled_at"] = int(time.time()) - stored_raw["_quick_trade"] = metadata avg_to_store = cumulative_avg or float(row.get("avg_fill_price") or 0.0) fee_to_store = max(float(row.get("commission") or 0.0), float(enrich.get("fee") or 0.0)) fee_ccy = str(enrich.get("fee_ccy") or row.get("commission_ccy") or "").strip().upper() @@ -360,7 +359,6 @@ def _sync_one_quick_trade_order(self, row: Dict[str, Any]) -> None: fee_quote = fee_update.get("commission_quote") metadata["fee_status"] = fee_update["fee_status"] metadata["fees_by_ccy"] = fee_update["fees_by_ccy"] - stored_raw["_quick_trade"] = metadata else: from app.services.live_trading.fee_quote import fee_to_quote fee_quote = fee_to_quote( @@ -387,26 +385,28 @@ def _sync_one_quick_trade_order(self, row: Dict[str, Any]) -> None: cur.execute( """ UPDATE qd_quick_trades - SET status = %s, - filled_amount = %s, - avg_fill_price = %s, + SET status = CASE WHEN status IN ('filled', 'cancelled', 'failed') THEN status ELSE %s END, + filled_amount = GREATEST(COALESCE(filled_amount, 0), %s), + avg_fill_price = CASE WHEN COALESCE(filled_amount, 0) <= %s THEN %s ELSE avg_fill_price END, commission = %s, commission_ccy = %s, commission_quote = %s, error_msg = %s, - raw_result = %s + raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), '{_quick_trade}', + COALESCE(raw_result->'_quick_trade', '{}'::jsonb) || %s::jsonb) WHERE id = %s - AND status IN ('submitted', 'partially_filled', 'filled') + AND status IN ('submitted', 'partially_filled', 'filled', 'cancelled', 'failed') """, ( status, cumulative_filled, + cumulative_filled, avg_to_store, fee_to_store, fee_ccy, fee_quote, error_msg, - json.dumps(stored_raw, ensure_ascii=False), + json.dumps(metadata, ensure_ascii=False), trade_id, ), ) diff --git a/backend_api_python/app/services/quick_trade/fee_reconciliation.py b/backend_api_python/app/services/quick_trade/fee_reconciliation.py index a01efc93c..1d954b6a1 100644 --- a/backend_api_python/app/services/quick_trade/fee_reconciliation.py +++ b/backend_api_python/app/services/quick_trade/fee_reconciliation.py @@ -239,14 +239,15 @@ def reconcile_quick_trade_fees( SET commission = %s, commission_ccy = %s, commission_quote = %s, - raw_result = %s + raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), '{_quick_trade}', + COALESCE(raw_result->'_quick_trade', '{}'::jsonb) || %s::jsonb) WHERE id = %s AND user_id = %s AND credential_id = %s """, ( update["commission"], update["commission_ccy"], update["commission_quote"], - json.dumps(stored_raw, ensure_ascii=False), + json.dumps({"fee_status": update["fee_status"], "fees_by_ccy": update["fees_by_ccy"]}), row.get("id"), user_id, credential_id, diff --git a/backend_api_python/app/services/quick_trade/history.py b/backend_api_python/app/services/quick_trade/history.py index c2e11e96a..ab7fe695b 100644 --- a/backend_api_python/app/services/quick_trade/history.py +++ b/backend_api_python/app/services/quick_trade/history.py @@ -25,6 +25,10 @@ def parse_quick_trade_metadata(raw_result: Any) -> dict[str, Any]: candidate = raw_result.get("_quick_trade") if isinstance(raw_result, dict) else {} metadata = candidate if isinstance(candidate, dict) else {} return { + "protection_status": str(metadata.get("protection_status") or "not_requested"), + "trailing_stop_pct": _number(metadata.get("trailing_stop_pct")), + "trailing_activation_pct": _number(metadata.get("trailing_activation_pct")), + "protected_filled_qty": _number(metadata.get("protected_filled_qty")), "margin_mode": metadata.get("margin_mode") or "", "requested_base_qty": _number(metadata.get("requested_base_qty")), "notional_usdt": _number(metadata.get("notional_usdt")), diff --git a/backend_api_python/app/services/quick_trade/order_reconciliation.py b/backend_api_python/app/services/quick_trade/order_reconciliation.py index ad8534e7a..81d16ccba 100644 --- a/backend_api_python/app/services/quick_trade/order_reconciliation.py +++ b/backend_api_python/app/services/quick_trade/order_reconciliation.py @@ -142,17 +142,19 @@ def reconcile_quick_trade_orders( cur.execute( """ UPDATE qd_quick_trades - SET status = %s, - filled_amount = %s, - avg_fill_price = %s, - raw_result = %s + SET status = CASE WHEN status IN ('filled', 'cancelled') THEN status ELSE %s END, + filled_amount = GREATEST(COALESCE(filled_amount, 0), %s), + avg_fill_price = CASE WHEN COALESCE(filled_amount, 0) <= %s THEN %s ELSE avg_fill_price END, + raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), '{_quick_trade}', + COALESCE(raw_result->'_quick_trade', '{}'::jsonb) || %s::jsonb) WHERE id = %s AND user_id = %s AND credential_id = %s """, ( update["status"], update["filled_amount"], + update["filled_amount"], update["avg_fill_price"], - json.dumps(stored_raw, ensure_ascii=False), + json.dumps({"exchange_status": update["exchange_status"]}), row.get("id"), user_id, credential_id, diff --git a/backend_api_python/app/services/quick_trade/orders.py b/backend_api_python/app/services/quick_trade/orders.py index b17384b3e..3400214ae 100644 --- a/backend_api_python/app/services/quick_trade/orders.py +++ b/backend_api_python/app/services/quick_trade/orders.py @@ -9,6 +9,14 @@ logger = get_logger(__name__) +class ProtectionSubmissionError(Exception): + """Preserve acknowledged legs when another submission has an uncertain outcome.""" + + def __init__(self, responses): + super().__init__("quickTrade.protection.reviewRequired") + self.responses = list(responses) + + def normalize_order_status(status: str, order: Any = None) -> str: """Use native terminal evidence before comparing pre-rounding quantities.""" status = str(status or "").strip().lower() @@ -208,6 +216,8 @@ def quick_trade_protection_status( normalized_error = str(error or "").strip() if normalized_error: return "failed", normalized_error + if any(item.get("managed_by") == "strategy_runtime" for item in responses): + return "failed", "quickTrade.protection.unsupported" if responses: return "attached", "" if not requested: @@ -233,13 +243,23 @@ def attach_quick_trade_protection( leverage: float, margin_mode: str, client_order_id: str, + trailing_stop_pct: float = 0.0, + trailing_activation_pct: float = 0.0, ) -> list[Dict[str, Any]]: """Attach native protection to the filled part of a Quick Trade entry.""" if str(market_type or "").strip().lower() != "swap": return [] if float(filled_qty or 0.0) <= 0 or float(avg_price or 0.0) <= 0: return [] - if float(tp_price or 0.0) <= 0 and float(sl_price or 0.0) <= 0: + from app.services.quick_trade.protection_policy import protection_values + values = protection_values({ + "tp_price": tp_price, "sl_price": sl_price, + "trailing_stop_pct": trailing_stop_pct, + "trailing_activation_pct": trailing_activation_pct, + }) + trailing_stop_pct = values["trailing_stop_pct"] + trailing_activation_pct = values["trailing_activation_pct"] + if float(tp_price or 0.0) <= 0 and float(sl_price or 0.0) <= 0 and trailing_stop_pct <= 0: return [] from app.services.live_trading.native_protection import ( NativeProtectionRequest, @@ -254,13 +274,33 @@ def attach_quick_trade_protection( entry_price=float(avg_price), stop_loss_price=float(sl_price or 0.0), take_profit_price=float(tp_price or 0.0), + trailing_stop_pct=trailing_stop_pct, + trailing_activation_pct=trailing_activation_pct, margin_mode="isolated" if str(margin_mode).lower() in ("isolated", "iso") else "cross", leverage=float(leverage or 1.0), product_type=str(cfg.get("product_type") or cfg.get("productType") or "USDT-FUTURES"), margin_coin=str(cfg.get("margin_coin") or cfg.get("marginCoin") or "USDT"), client_order_id=str(client_order_id or ""), ) - return place_native_protection_orders(client, request) + from dataclasses import replace + responses = [] + for field, value in ( + ("stop_loss_price", request.stop_loss_price), + ("take_profit_price", request.take_profit_price), + ("trailing_stop_pct", request.trailing_stop_pct), + ): + if value <= 0: + continue + leg = replace(request, stop_loss_price=0, take_profit_price=0, trailing_stop_pct=0) + leg = replace(leg, **{field: value}) + try: + receipt = place_native_protection_orders(client, leg) + if not receipt or any(item.get("managed_by") == "strategy_runtime" for item in receipt): + raise ValueError("native_protection_not_acknowledged") + responses.extend(receipt) + except Exception as exc: + raise ProtectionSubmissionError(responses) from exc + return responses def limit_order_kwargs(client, symbol, amount, price, side, market_type, client_order_id): diff --git a/backend_api_python/app/services/quick_trade/protection_journal.py b/backend_api_python/app/services/quick_trade/protection_journal.py new file mode 100644 index 000000000..32b360b3a --- /dev/null +++ b/backend_api_python/app/services/quick_trade/protection_journal.py @@ -0,0 +1,44 @@ +"""Durable protection submission boundaries; uncertain writes are never replayed.""" + +import json + +from app.utils.db import get_db_connection + + +def save_protection_metadata(trade_id, metadata): + from app.services.live_trading.partner_attribution import redact_partner_attribution + metadata = redact_partner_attribution({key: metadata[key] for key in ( + "native_protection", "native_protection_error", "protection_status", "protected_filled_qty", + ) if key in metadata}) + if not trade_id: + raise ValueError("quickTrade.protection.reviewRequired") + with get_db_connection() as db: + cur = db.cursor() + cur.execute( + """UPDATE qd_quick_trades + SET raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), + '{_quick_trade}', COALESCE(raw_result->'_quick_trade', '{}'::jsonb) || %s::jsonb), error_msg = %s + WHERE id = %s""", + (json.dumps(metadata), str(metadata.get("native_protection_error") or ""), int(trade_id)), + ) + db.commit() + cur.close() + + +def claim_protection_submission(trade_id, previous_metadata, metadata): + """Commit before sending: a lost acknowledgement requires explicit review.""" + with get_db_connection() as db: + cur = db.cursor() + cur.execute( + """UPDATE qd_quick_trades + SET raw_result = jsonb_set(COALESCE(raw_result, '{}'::jsonb), + '{_quick_trade}', %s::jsonb) + WHERE id = %s + AND COALESCE(raw_result->'_quick_trade', '{}'::jsonb) = %s::jsonb + RETURNING id""", + (json.dumps(metadata), int(trade_id), json.dumps(previous_metadata)), + ) + claimed = cur.fetchone() is not None + db.commit() + cur.close() + return claimed diff --git a/backend_api_python/app/services/quick_trade/protection_policy.py b/backend_api_python/app/services/quick_trade/protection_policy.py new file mode 100644 index 000000000..1ec565cc1 --- /dev/null +++ b/backend_api_python/app/services/quick_trade/protection_policy.py @@ -0,0 +1,74 @@ +"""Validate manual protection before submitting an entry to a broker.""" + +import math + + +ALIASES = { + "tp_price": ("tpPrice", "take_profit_price", "takeProfitPrice"), + "sl_price": ("slPrice", "stop_loss_price", "stopLossPrice"), + "trailing_stop_pct": ("trailingStopPct",), + "trailing_activation_pct": ("trailingActivationPct",), +} + + +def protection_error_code(error, fallback="quickTrade.protection.invalidParameters"): + """Return public constants, never exception text, at request boundaries.""" + if str(error) == "quickTrade.protection.unsupported": + return "quickTrade.protection.unsupported" + if str(error) == "quickTrade.protection.invalidParameters": + return "quickTrade.protection.invalidParameters" + return fallback + + +def protection_values(body): + values = {} + for key, aliases in ALIASES.items(): + supplied = [body[name] for name in (key, *aliases) if body.get(name) is not None] + try: + numbers = [float(value) for value in supplied] + except (TypeError, ValueError, OverflowError): + raise ValueError("quickTrade.protection.invalidParameters") from None + if any(isinstance(value, bool) for value in supplied) or any( + not math.isfinite(value) or value < 0 for value in numbers + ) or len(set(numbers)) > 1: + raise ValueError("quickTrade.protection.invalidParameters") + values[key] = numbers[0] if numbers else 0.0 + if values["trailing_stop_pct"] >= 1 or ( + values["trailing_activation_pct"] > 0 and values["trailing_stop_pct"] <= 0 + ): + raise ValueError("quickTrade.protection.invalidParameters") + return values + + +def validate_manual_protection(body, *, exchange_id, market_type): + values = protection_values(body) + if not any(values.values()): + return values + broker = str(exchange_id).lower() + trailing = values["trailing_stop_pct"] + if str(body.get("side") or "").strip().lower() == "sell" and values["trailing_activation_pct"] >= 1: + raise ValueError("quickTrade.protection.invalidParameters") + order_type = str(body.get("orderType") or body.get("order_type") or "market").lower() + if broker in {"alpaca", "ibkr", "tiger", "webull"}: + supported = str(market_type).lower() in ( + {"usstock"} if broker in {"alpaca", "webull"} else {"usstock", "hkstock"} + ) + if broker == "tiger": + supported = supported and order_type == "limit" + if trailing: + supported = supported and broker in {"ibkr", "tiger"} and order_type == "limit" + if values["trailing_activation_pct"] or values["sl_price"]: + raise ValueError("quickTrade.protection.invalidParameters") + else: + supported = market_type == "swap" and broker in { + "binance", "okx", "bitget", "bybit", "gate", "gateio", "htx", "huobi", + } + if trailing: + supported = supported and broker in {"binance", "okx", "bitget", "gate", "gateio", "htx", "huobi"} + if not supported: + raise ValueError("quickTrade.protection.unsupported") + if trailing and broker == "binance" and not 0.001 <= trailing <= 0.1: + raise ValueError("quickTrade.protection.invalidParameters") + if trailing and broker in {"htx", "huobi"} and trailing < 0.001: + raise ValueError("quickTrade.protection.invalidParameters") + return values diff --git a/backend_api_python/app/services/quick_trade/protection_submission.py b/backend_api_python/app/services/quick_trade/protection_submission.py new file mode 100644 index 000000000..61c6754a6 --- /dev/null +++ b/backend_api_python/app/services/quick_trade/protection_submission.py @@ -0,0 +1,90 @@ +"""Submit persisted manual protection without replaying uncertain exchange writes.""" + +from app.services.quick_trade import protection_journal +from app.services.quick_trade.orders import quick_trade_protection_status +from app.services.quick_trade.protection_policy import validate_manual_protection + + +def finish_recorded_protection(trade_id, metadata, client, *, submit, **kwargs): + requested = any(float(kwargs.get(key) or 0) > 0 for key in ( + "tp_price", "sl_price", "trailing_stop_pct", + )) + responses, error = [], "" + try: + if requested and not trade_id: + raise ValueError("quickTrade.protection.reviewRequired") + responses = submit(client, **kwargs) + except Exception as exc: + responses = list(getattr(exc, "responses", [])) + error = str(exc) + status, error = quick_trade_protection_status( + requested=requested, market_type=kwargs["market_type"], + filled_qty=kwargs["filled_qty"], avg_price=kwargs["avg_price"], + responses=responses, error=error, + ) + metadata.update( + native_protection=responses, native_protection_error=error, + protection_status=status, + protected_filled_qty=kwargs["filled_qty"] if status == "attached" else 0.0, + ) + if requested: + try: + protection_journal.save_protection_metadata(trade_id, metadata) + except Exception: + return "failed", "quickTrade.protection.reviewRequired" + return status, error + + +def reconcile_filled_protection( + row, metadata, client, *, cumulative_filled, cumulative_avg, epsilon, + exchange_config, market_type, margin_mode, client_order_id, submit, +): + """Return changed/error, or None if another writer changed the claimed row.""" + delta = cumulative_filled - max(0.0, float(metadata.get("protected_filled_qty") or 0)) + previous_metadata = dict(metadata) + error = str(metadata.get("native_protection_error") or "") + if metadata.get("protection_status") == "dispatching": + error = "quickTrade.protection.reviewRequired" + metadata.update(protection_status="failed", native_protection_error=error) + return True, error + if metadata.get("protection_status") == "failed": + return False, error + requested = any(float(value or 0) > 0 for value in ( + row.get("tp_price"), row.get("sl_price"), metadata.get("trailing_stop_pct"), + )) + if not requested or delta <= epsilon or cumulative_avg <= 0: + return False, error + metadata["protection_status"] = "dispatching" + if not protection_journal.claim_protection_submission(row["id"], previous_metadata, metadata): + return None + prior = metadata.get("native_protection") + prior = list(prior) if isinstance(prior, list) else [] + try: + validate_manual_protection( + {**metadata, "tp_price": row.get("tp_price"), "sl_price": row.get("sl_price")}, + exchange_id=exchange_config.get("exchange_id"), market_type=market_type, + ) + responses = submit( + client, symbol=str(row.get("symbol") or ""), side=str(row.get("side") or ""), + filled_qty=delta, avg_price=cumulative_avg, + tp_price=float(row.get("tp_price") or 0), sl_price=float(row.get("sl_price") or 0), + market_type=market_type, exchange_config=exchange_config, + leverage=float(row.get("leverage") or 1), margin_mode=margin_mode, + client_order_id=client_order_id, + trailing_stop_pct=float(metadata.get("trailing_stop_pct") or 0), + trailing_activation_pct=float(metadata.get("trailing_activation_pct") or 0), + ) + if not responses or any(item.get("managed_by") == "strategy_runtime" for item in responses): + raise ValueError("quickTrade.protection.reviewRequired") + metadata.update( + native_protection=prior + responses, protected_filled_qty=cumulative_filled, + native_protection_error="", protection_status="attached", + ) + error = "" + except Exception as exc: + error = str(exc) + metadata.update( + native_protection=prior + list(getattr(exc, "responses", [])), + native_protection_error=error, protection_status="failed", + ) + return True, error diff --git a/backend_api_python/tests/test_broker_order_validation.py b/backend_api_python/tests/test_broker_order_validation.py index 6a6816d33..b5b6e734f 100644 --- a/backend_api_python/tests/test_broker_order_validation.py +++ b/backend_api_python/tests/test_broker_order_validation.py @@ -19,7 +19,7 @@ @pytest.fixture def broker_route(monkeypatch): result = SimpleNamespace(success=True, message="mock", order_id="mock", filled=0, avg_price=0, status="submitted", raw={}) - client = SimpleNamespace(place_market_order=Mock(return_value=result), place_limit_order=Mock(return_value=result)) + client = SimpleNamespace(place_market_order=Mock(return_value=result), place_limit_order=Mock(return_value=result), place_bracket_order=Mock(return_value=result)) monkeypatch.setattr(alpaca, "_require_connected_client", lambda: (client, None)) monkeypatch.setattr(ibkr, "_require_connected_client", lambda: (client, None)) monkeypatch.setattr(openapi_brokers, "_connected_client", lambda broker: (client, None)) @@ -79,7 +79,7 @@ def test_alpaca_rejects_overflow_or_underflow_in_limit_conversion(broker_route, client.place_limit_order.assert_not_called() -@pytest.mark.parametrize("broker,fail_at", [("alpaca", 6), ("ibkr", 1), ("ibkr", 2)]) +@pytest.mark.parametrize("broker,fail_at", [("alpaca", 5), ("ibkr", 1), ("ibkr", 2)]) def test_validation_response_does_not_expose_exception_details(broker_route, monkeypatch, broker, fail_at): send, client = broker_route calls = 0 @@ -186,3 +186,131 @@ def test_optional_zero_is_allowed_but_required_zero_is_rejected(): assert order_number("0.125") == .125 with pytest.raises(BrokerOrderValidationError): order_number(0) + + +@pytest.mark.parametrize("broker,field", [(broker, field) + for broker in ["tiger", "webull", "forthright"] + for field in ["take_profit_price", "stopLossPrice", "trailing_stop_pct"] + if broker != "webull" or field == "trailing_stop_pct"]) +def test_unsupported_broker_protection_rejected_before_entry(broker_route, broker, field): + send, client = broker_route + body, status = send(broker, **{field: 0.02 if field == "trailing_stop_pct" else 90}) + assert status == 400 + assert body["error"] == "quickTrade.protection.unsupported" + client.place_market_order.assert_not_called() + + +@pytest.mark.parametrize("market", ["USStock", "HKStock"]) +def test_ibkr_attaches_fixed_protection_to_parent(broker_route, market): + send, client = broker_route + client.place_bracket_order.return_value.raw = {"protection_status": "attached", "protection_error": ""} + body, status = send("ibkr", marketType=market, take_profit_price=110, stop_loss_price=90) + assert status == 200 + assert body["data"]["protection_status"] == "attached" + assert client.place_bracket_order.call_args.kwargs["take_profit_price"] == 110 + assert client.place_bracket_order.call_args.kwargs["stop_loss_price"] == 90 + client.place_market_order.assert_not_called() + + +@pytest.mark.parametrize("protection_status", ["failed", "dispatching"]) +def test_ibkr_does_not_report_entry_success_as_confirmed_protection(broker_route, protection_status): + send, client = broker_route + client.place_bracket_order.return_value.raw = {"protection_status": protection_status} + body, status = send("ibkr", stop_loss_price=90) + assert status == 200 + assert body["success"] is True + assert body["data"]["protection_status"] == protection_status + assert body["data"]["protection_error"] == "quickTrade.protection.reviewRequired" + + +@pytest.mark.parametrize("child_status,expected", [ + ("PreSubmitted", "attached"), ("Submitted", "attached"), + ("Inactive", "failed"), ("PendingSubmit", "dispatching"), + ("timeout", "dispatching"), +]) +def test_ibkr_bracket_checks_children_without_resubmitting_parent(monkeypatch, child_status, expected): + from app.services.ibkr_trading import client as module + parent = SimpleNamespace(orderId=1) + parent_trade = SimpleNamespace(order=parent) + child_trade = SimpleNamespace(orderStatus=SimpleNamespace(status=child_status)) + client = IBKRClient.__new__(IBKRClient) + client._account = "test" + client._ensure_connected = Mock() + client._create_contract = Mock(return_value=object()) + client._qualify_contract = Mock(return_value=True) + client._trade_result = Mock(return_value=module.OrderResult(success=True, order_id=1)) + client._ib = Mock() + client._ib.client.getReqId.return_value = 1 + client._ib.placeOrder.side_effect = [parent_trade, TimeoutError() if child_status == "timeout" else child_trade] + monkeypatch.setattr(module, "ib_insync", SimpleNamespace( + MarketOrder=Mock(return_value=parent), StopOrder=Mock(return_value=SimpleNamespace(orderId=2)), + )) + result = client.place_bracket_order("AAPL", "buy", 1, stop_loss_price=90) + assert result.success is True + assert result.order_id == 1 + assert result.raw["protection_status"] == expected + assert client._ib.placeOrder.call_count == 2 + + +@pytest.mark.parametrize("broker", ["alpaca", "ibkr"]) +def test_broker_protection_validation_does_not_expose_internal_exception(broker_route, monkeypatch, broker): + send, client = broker_route + monkeypatch.setattr("app.services.quick_trade.protection_policy.validate_manual_protection", Mock( + side_effect=ValueError("internal-only traceback /srv/private/config"), + )) + body, status = send(broker, stop_loss_price=90) + assert status == 400 + assert body == {"success": False, "error": "brokerAccounts.invalidOrder"} + client.place_market_order.assert_not_called() + client.place_bracket_order.assert_not_called() + + +@pytest.mark.parametrize("broker", ["alpaca", "ibkr"]) +def test_stock_trailing_rejected_instead_of_silently_ignored(broker_route, broker): + send, client = broker_route + body, status = send(broker, trailing_stop_pct=0.02) + assert status == 400 + client.place_market_order.assert_not_called() + client.place_bracket_order.assert_not_called() + + +@pytest.mark.parametrize("broker", ["alpaca", "tiger", "webull"]) +def test_stock_parent_receipt_alone_never_confirms_protection(broker_route, broker): + send, client = broker_route + body, status = send(broker, orderType="limit", price=100, stop_loss_price=90) + assert status == 200 and body["success"] + assert body["data"]["protection_status"] == "dispatching" + assert body["data"]["protection_error"] == "quickTrade.protection.reviewRequired" + client.place_limit_order.assert_called_once() + + +def test_alpaca_rejects_unknown_order_type_instead_of_placing_market_order(broker_route): + send, client = broker_route + assert send("alpaca", orderType="trailing_stop")[1] == 400 + client.place_market_order.assert_not_called() + + +@pytest.mark.parametrize("side,exit_side", [("buy", "SELL"), ("sell", "BUY")]) +def test_ibkr_attached_trailing_keeps_percent_and_transmit_contract(monkeypatch, side, exit_side): + from app.services.ibkr_trading import client as module + client = IBKRClient.__new__(IBKRClient) + client._account = "test" + client._ensure_connected = Mock() + client._create_contract = Mock(return_value=object()) + client._qualify_contract = Mock(return_value=True) + client._trade_result = Mock(return_value=module.OrderResult(success=True, order_id=1)) + client._ib = Mock() + client._ib.client.getReqId.return_value = 1 + parent = SimpleNamespace(orderId=1) + child = SimpleNamespace(orderId=2) + sdk = SimpleNamespace(LimitOrder=Mock(return_value=parent), Order=Mock(return_value=child)) + monkeypatch.setattr(module, "ib_insync", sdk) + client._ib.placeOrder.side_effect = [SimpleNamespace(order=parent), SimpleNamespace(orderStatus=SimpleNamespace(status="Submitted"))] + result = client.place_bracket_order("AAPL", side, 2, limit_price=100, trailing_stop_pct="0.02") + assert result.success and result.raw["protection_status"] == "attached" + assert sdk.Order.call_args.kwargs["action"] == exit_side + assert sdk.Order.call_args.kwargs["trailingPercent"] == 2 + assert sdk.Order.call_args.kwargs["totalQuantity"] == 2 + assert parent.transmit is False + assert child.transmit is True + assert client._ib.placeOrder.call_count == 2 diff --git a/backend_api_python/tests/test_extended_native_protection.py b/backend_api_python/tests/test_extended_native_protection.py new file mode 100644 index 000000000..7ff628c4e --- /dev/null +++ b/backend_api_python/tests/test_extended_native_protection.py @@ -0,0 +1,223 @@ +from decimal import Decimal +from unittest.mock import Mock + +import pytest + +from app.services.live_trading.base import LiveTradingError +from app.services.live_trading.native_protection import NativeProtectionRequest, place_native_protection_orders +from app.services.quick_trade.protection_policy import validate_manual_protection + + +def request(**overrides): + return NativeProtectionRequest(**dict( + dict(symbol="BTC/USDT", pos_side="long", quantity=0.002, entry_price=100, + trailing_stop_pct=0.02, trailing_activation_pct=0.05, client_order_id="entry-1"), + **overrides, + )) + + +@pytest.mark.parametrize("side,amount,activation,rises", [("long", "-2", "105.0", True), ("short", "2", "95.0", False)]) +def test_gate_native_trailing_preserves_percent_signed_quantity_and_activation(side, amount, activation, rises): + from app.services.live_trading.gate import GateUsdtFuturesClient + client = GateUsdtFuturesClient.__new__(GateUsdtFuturesClient) + client._resolve_order_size = Mock(return_value=(amount, None)) + client._normalize_price = lambda **kw: (Decimal(str(kw["price"])), 1) + client._signed_request = Mock(return_value={"code": 0, "data": {"id": "trail-1"}}) + receipt = place_native_protection_orders(client, request(pos_side=side)) + method, path = client._signed_request.call_args.args + body = client._signed_request.call_args.kwargs["json_body"] + assert method == "POST" and path.endswith("/trail/create") + assert body == dict(contract="BTC_USDT", amount=amount, activation_price=activation, + is_gte=rises, price_type=1, price_offset="2.00%", reduce_only=True, text="t-entry-1-tr") + assert receipt[0]["_qd_protection"]["identifiers"][0]["value"] == "trail-1" + + +@pytest.mark.parametrize("margin", ["cross", "isolated"]) +@pytest.mark.parametrize("hedge", [False, True]) +def test_htx_trailing_uses_verified_mode_and_contract_quantity(margin, hedge): + from app.services.live_trading.htx import HtxClient + client = HtxClient.__new__(HtxClient) + client._base_to_contracts = Mock(return_value=2) + client._normalize_price = lambda **kw: (Decimal(str(kw["price"])), 1) + client.detect_swap_hedge_mode = Mock(return_value=hedge) + client._swap_private_request_raw = Mock(return_value={"status": "ok", "data": {"order_id_str": "123"}}) + result = place_native_protection_orders(client, request(margin_mode=margin)) + path = client._swap_private_request_raw.call_args.args[1] + body = client._swap_private_request_raw.call_args.kwargs["json_body"] + assert path.endswith("swap_track_order" if margin == "isolated" else "swap_cross_track_order") + assert body["offset"] == ("close" if hedge else "both") + assert body["volume"] == 2 and body["reduce_only"] == 1 + assert body["callback_rate"] == 0.02 and body["active_price"] == 105 + assert result[0]["_qd_protection"]["role"] == "trailing_stop" + + +def test_htx_unknown_mode_never_sends_tracking_order(): + from app.services.live_trading.htx import HtxClient + client = HtxClient.__new__(HtxClient) + client._base_to_contracts = Mock(return_value=2) + client._normalize_price = lambda **kw: (Decimal("105"), 1) + client.detect_swap_hedge_mode = Mock(return_value=None) + client._swap_private_request_raw = Mock() + with pytest.raises(LiveTradingError, match="position_mode_unknown"): + place_native_protection_orders(client, request()) + client._swap_private_request_raw.assert_not_called() + + +@pytest.mark.parametrize("broker", ["ibkr", "tiger"]) +def test_stock_trailing_limit_entry_supported_with_explicit_limits(broker): + body = dict(trailing_stop_pct=0.02, order_type="limit") + assert validate_manual_protection(body, exchange_id=broker, market_type="USStock")["trailing_stop_pct"] == 0.02 + for incompatible in ({"order_type": "market"}, {"trailing_activation_pct": 0.1}, {"sl_price": 90}): + with pytest.raises(ValueError): + validate_manual_protection({**body, **incompatible}, exchange_id=broker, market_type="USStock") + + +@pytest.mark.parametrize("field", ["quantity", "entry_price", "trailing_stop_pct", "trailing_activation_pct"]) +def test_native_nonfinite_values_rejected_before_any_exchange_io(field): + with pytest.raises(LiveTradingError, match="invalid_native"): + place_native_protection_orders(Mock(), request(**{field: float("nan")})) + + +@pytest.mark.parametrize("take,stop,trail", [(120,90,0),(120,0,0.02),(0,0,0.02)]) +def test_tiger_attached_order_uses_sdk_signature_and_percent_units(monkeypatch, take, stop, trail): + from types import SimpleNamespace + from app.services.openapi_brokers import TigerClient, TigerConfig + from tests.test_openapi_brokers import FakeTigerTradeClient, fake_tiger_sdk + trade = FakeTigerTradeClient() + trade.get_open_orders = Mock(side_effect=TimeoutError("read failed")) + sdk = fake_tiger_sdk(trade) + sdk["order_leg"] = lambda leg_type, price=None, **kw: dict(leg_type=leg_type, price=price, **kw) + def bracket(account, contract, action, quantity, limit_price, order_legs=None, time_in_force="DAY"): + return SimpleNamespace(account=account, contract=contract, action=action, quantity=quantity, + limit_price=limit_price, order_type="LMT", order_legs=order_legs, status="NEW") + sdk["limit_order_with_legs"] = bracket + client = TigerClient(TigerConfig(tiger_id="t", account_id="a", private_key="pem")) + monkeypatch.setattr(client, "_sdk", lambda: sdk) + result = client.place_limit_order(symbol="AAPL", side="buy", quantity=2, price=100, + tp_price=take, sl_price=stop, trailing_stop_pct=trail) + placed = [call[1] for call in trade.calls if call[0] == "place_order"] + assert len(placed) == 1 and result.success + assert placed[0].outside_rth is False + assert len(placed[0].order_legs) == bool(take) + bool(stop) + bool(trail) + if trail: + assert placed[0].order_legs[-1]["trailing_percent"] == 2 + assert placed[0].order_legs[-1]["price"] is None + assert result.raw["protection_status"] == "dispatching" + + +def test_webull_combo_is_atomic_and_does_not_claim_child_acceptance(monkeypatch): + from app.services.openapi_brokers import WebullClient, WebullConfig + client = WebullClient(WebullConfig(app_key="k", app_secret="s", account_id="a")) + send = Mock(return_value={"orders": [{"order_id": "123"}]}) + monkeypatch.setattr(client, "_request", send) + result = client.place_limit_order(symbol="AAPL", side="buy", quantity=2, price=100, + tp_price=120, sl_price=90) + send.assert_called_once() + body = send.call_args.kwargs["body"] + parent, take, stop = body["new_orders"] + assert parent["combo_type"] == "MASTER" + assert parent["side"] == "BUY" and take["side"] == stop["side"] == "SELL" + assert take["limit_price"] == "120.0" and stop["stop_price"] == "90.0" + assert "limit_price" not in stop + assert len({body["client_combo_order_id"], *(o["client_order_id"] for o in body["new_orders"])}) == 4 + assert result.raw["protection_status"] == "dispatching" + + +def test_webull_fractional_protection_rejected_before_request(monkeypatch): + from app.services.openapi_brokers import WebullClient, WebullConfig + client = WebullClient(WebullConfig(app_key="k", app_secret="s", account_id="a")) + send = Mock() + monkeypatch.setattr(client, "_request", send) + with pytest.raises(ValueError, match="invalidParameters"): + client.place_market_order(symbol="AAPL", side="buy", quantity=0.1, sl_price=90) + send.assert_not_called() + + +@pytest.mark.parametrize("venue", ["gate", "htx"]) +def test_trailing_unknown_ack_is_not_success(venue): + from app.services.live_trading.gate import GateUsdtFuturesClient + from app.services.live_trading.htx import HtxClient + cls = GateUsdtFuturesClient if venue == "gate" else HtxClient + client = cls.__new__(cls) + client._resolve_order_size = Mock(return_value=("-2", None)) + client._base_to_contracts = Mock(return_value=2) + client._normalize_price = lambda **kw: (Decimal(str(kw["price"])), 1) + client.detect_swap_hedge_mode = Mock(return_value=False) + client._signed_request = Mock(return_value={"code": 0, "data": {}}) + client._swap_private_request_raw = Mock(return_value={"status": "ok", "data": {}}) + with pytest.raises(LiveTradingError, match="not_acknowledged"): + place_native_protection_orders(client, request()) + + +@pytest.mark.parametrize("statuses,expected", [ + ([], "dispatching"), (["new"], "dispatching"), + (["new", "held"], "attached"), (["new", "pending_new"], "dispatching"), + (["new", "rejected"], "failed"), +]) +def test_alpaca_nested_children_define_protection_status(statuses, expected): + from types import SimpleNamespace + from app.services.alpaca_trading.client import AlpacaClient + order = SimpleNamespace(legs=[SimpleNamespace(id=str(i+1), status=status) for i,status in enumerate(statuses)]) + result = AlpacaClient._protection_snapshot(order, 120, 90) + assert result["protection_status"] == expected + assert bool(result["protection_error"]) == (expected != "attached") + + +@pytest.mark.parametrize("kind", ["market", "limit"]) +@pytest.mark.parametrize("read_fails", [False, True]) +def test_alpaca_nested_read_failure_preserves_accepted_parent(monkeypatch, kind, read_fails): + from types import SimpleNamespace + from app.services.alpaca_trading import client as module + accepted = SimpleNamespace(id="parent", status="accepted", filled_qty=0, filled_avg_price=0, submitted_at="now", legs=[]) + snapshot = SimpleNamespace(**{**vars(accepted), "legs": [SimpleNamespace(id="stop", status="held")]}) + client = module.AlpacaClient.__new__(module.AlpacaClient) + client._ensure_connected = Mock() + client._trading_client = Mock() + client._trading_client.get_asset.return_value = SimpleNamespace(tradable=True, fractionable=True) + client._trading_client.submit_order.return_value = accepted + client._trading_client.get_order_by_id.side_effect = TimeoutError() if read_fails else lambda *a, **kw: snapshot + sdk = dict(OrderSide=SimpleNamespace(BUY="buy", SELL="sell"), TimeInForce=SimpleNamespace(DAY="day",GTC="gtc"), + OrderClass=SimpleNamespace(BRACKET="bracket",OTO="oto"), MarketOrderRequest=SimpleNamespace, + LimitOrderRequest=SimpleNamespace, TakeProfitRequest=SimpleNamespace, StopLossRequest=SimpleNamespace, + GetOrderByIdRequest=SimpleNamespace) + monkeypatch.setattr(module, "_ensure_alpaca", lambda: sdk) + monkeypatch.setattr(module.time, "sleep", lambda _: None) + method = client.place_market_order if kind == "market" else client.place_limit_order + result = method("AAPL", "buy", 2, stop_loss_price=90, **({"price":100} if kind=="limit" else {})) + assert result.success and result.order_id == "parent" + assert result.raw["protection_status"] == ("dispatching" if read_fails else "attached") + assert client._trading_client.get_order_by_id.call_args.kwargs["filter"].nested is True + client._trading_client.submit_order.assert_called_once() + + +@pytest.mark.parametrize("child_status,expected", [("NEW","attached"),(None,"dispatching"),("PENDING_NEW","dispatching")]) +def test_webull_matches_unordered_child_receipts_without_inventing_status(monkeypatch, child_status, expected): + from app.services.openapi_brokers import WebullClient, WebullConfig + client = WebullClient(WebullConfig(app_key="k", app_secret="s", account_id="a")) + def send(method, path, *, body): + assert method == "POST" + return {"orders": [dict(client_order_id=leg["client_order_id"],order_id=f"exchange-{i}",status=child_status if i else "NEW") for i,leg in reversed(list(enumerate(body["new_orders"])))]} + transport = Mock(side_effect=send) + monkeypatch.setattr(client, "_request", transport) + result = client.place_limit_order(symbol="AAPL", side="buy", quantity=2, price=100, tp_price=120, sl_price=90) + assert result.order_id == transport.call_args.kwargs["body"]["new_orders"][0]["client_order_id"] + assert result.raw["broker_order_id"] == "exchange-0" + assert result.raw["protection_status"] == expected + transport.assert_called_once() + + +@pytest.mark.parametrize("child_id,child_status,expected", [("321","NEW","attached"),("", "NEW","dispatching"),("321",None,"dispatching")]) +def test_tiger_empty_child_identity_or_status_never_confirms_protection(monkeypatch, child_id, child_status, expected): + from types import SimpleNamespace + from app.services.openapi_brokers import TigerClient, TigerConfig + from tests.test_openapi_brokers import FakeTigerTradeClient, fake_tiger_sdk + trade = FakeTigerTradeClient() + trade.get_open_orders = Mock(return_value=[SimpleNamespace(id=child_id,status=child_status)]) + sdk = fake_tiger_sdk(trade) + sdk["order_leg"] = lambda *args, **kwargs: object() + sdk["limit_order_with_legs"] = lambda *args, **kwargs: SimpleNamespace(status="NEW") + client = TigerClient(TigerConfig(tiger_id="t", account_id="a", private_key="pem")) + monkeypatch.setattr(client, "_sdk", lambda: sdk) + result = client.place_limit_order(symbol="AAPL", side="buy", quantity=2, price=100, sl_price=90) + assert result.success and result.raw["protection_status"] == expected + assert len([call for call in trade.calls if call[0] == "place_order"]) == 1 diff --git a/backend_api_python/tests/test_manual_protection_contract.py b/backend_api_python/tests/test_manual_protection_contract.py new file mode 100644 index 000000000..15923908e --- /dev/null +++ b/backend_api_python/tests/test_manual_protection_contract.py @@ -0,0 +1,319 @@ +import inspect +import json +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from flask import Flask +from flask_smorest import Api, Blueprint + +from app.openapi.schemas.high_risk import QuickTradeOrderRequestSchema +from app.services.quick_trade.protection_policy import protection_values, validate_manual_protection +from app.services.quick_trade import orders, protection_journal + + +@pytest.fixture +def schema_http(): + app = Flask(__name__) + app.config.update(API_TITLE="test", API_VERSION="1", OPENAPI_VERSION="3.0.3") + api = Api(app) + bp = Blueprint("contract", __name__) + + @bp.route("/order", methods=["POST"]) + @bp.arguments(QuickTradeOrderRequestSchema) + def endpoint(body): + return body + + api.register_blueprint(bp) + return app.test_client() + + +@pytest.mark.parametrize("camel", [False, True]) +def test_real_http_schema_accepts_trailing_parameters(schema_http, camel): + body = dict(credential_id=1, symbol="BTC/USDT", side="buy", amount=100, market_type="swap") + body.update({"trailingStopPct" if camel else "trailing_stop_pct": 0.02, + "trailingActivationPct" if camel else "trailing_activation_pct": 0.05}) + response = schema_http.post("/order", json=body) + assert response.status_code == 200 + assert response.json["trailing_stop_pct"] == 0.02 + assert response.json["trailing_activation_pct"] == 0.05 + + +@pytest.mark.parametrize("value", [-1, True, "NaN", "Infinity", 1, "bad"]) +def test_invalid_trailing_rejected_at_http_boundary(schema_http, value): + response = schema_http.post("/order", json=dict( + credential_id=1, symbol="BTC/USDT", side="buy", amount=100, trailing_stop_pct=value, + )) + assert response.status_code == 422 + + +@pytest.mark.parametrize("body", [ + {"trailing_activation_pct": 0.05}, + {"trailing_stop_pct": 0.02, "trailingStopPct": 0.03}, + {"tp_price": float("inf")}, +]) +def test_invalid_combination_rejected(body): + with pytest.raises(ValueError): + protection_values(body) + + +@pytest.mark.parametrize("boundary", ["protection_values", "validate_manual_protection"]) +@pytest.mark.parametrize("message,expected", [ + ("internal-only traceback /srv/private/config", "quickTrade.protection.invalidParameters"), + ("quickTrade.protection.unsupported", "quickTrade.protection.unsupported"), + ("quickTrade.protection.invalidParameters", "quickTrade.protection.invalidParameters"), +]) +def test_quick_trade_protection_errors_return_only_public_codes(monkeypatch, boundary, message, expected): + from flask import g + from app.routes import quick_trade + from app.services.quick_trade import protection_policy + monkeypatch.setattr(protection_policy, boundary, Mock(side_effect=ValueError(message))) + monkeypatch.setattr(quick_trade, "_build_product_aware_config", lambda *a, **k: ({"exchange_id": "binance"}, {})) + create = Mock() + monkeypatch.setattr(quick_trade, "create_exchange_client", create) + with Flask(__name__).test_request_context(): + g.user_id = 1 + response, status = inspect.unwrap(quick_trade.place_order)(dict( + credential_id=1, symbol="BTC/USDT", side="buy", amount=100, market_type="swap", + )) + assert status == 400 + assert response.json == {"code": 0, "msg": expected} + create.assert_not_called() + + +def test_schema_protection_validation_does_not_expose_internal_exception(schema_http, monkeypatch): + monkeypatch.setattr("app.services.quick_trade.protection_policy.protection_values", Mock( + side_effect=ValueError("internal-only traceback /srv/private/config"), + )) + response = schema_http.post("/order", json=dict(credential_id=1, symbol="BTC/USDT", side="buy", amount=100)) + assert response.status_code == 422 + assert "internal-only" not in response.get_data(as_text=True) + assert "quickTrade.protection.invalidParameters" in response.get_data(as_text=True) + + +@pytest.mark.parametrize("exchange", ["binance", "okx", "bitget", "gate", "htx"]) +def test_manual_percentage_trailing_supported(exchange): + assert validate_manual_protection({"trailing_stop_pct": 0.02}, exchange_id=exchange, market_type="swap")["trailing_stop_pct"] == 0.02 + + +@pytest.mark.parametrize("exchange", ["binance", "okx", "bitget", "gate", "htx"]) +@pytest.mark.parametrize("activation", [1, 1.5]) +def test_impossible_short_activation_rejected_before_entry(monkeypatch, exchange, activation): + from flask import g + from app.routes import quick_trade + monkeypatch.setattr(quick_trade, "_build_product_aware_config", lambda *a, **k: ({"exchange_id": exchange}, {})) + create = Mock() + monkeypatch.setattr(quick_trade, "create_exchange_client", create) + with Flask(__name__).test_request_context(): + g.user_id = 1 + response, status = inspect.unwrap(quick_trade.place_order)(dict( + credential_id=1, symbol="BTC/USDT", side="sell", amount=100, market_type="swap", + trailing_stop_pct=0.02, trailing_activation_pct=activation, + )) + assert status == 400 + assert response.json["msg"] == "quickTrade.protection.invalidParameters" + create.assert_not_called() + + +def test_large_long_activation_remains_valid(): + values = validate_manual_protection( + dict(side="buy", trailing_stop_pct=0.02, trailing_activation_pct=1.5), + exchange_id="gate", market_type="swap", + ) + assert values["trailing_activation_pct"] == 1.5 + + +@pytest.mark.parametrize("exchange,market", [ + ("bybit", "swap"), ("binance", "spot"), + ("alpaca", "USStock"), ("ibkr", "HKStock"), ("tiger", "HKStock"), + ("webull", "USStock"), ("forthright", "HKStock"), +]) +def test_unsupported_manual_trailing_rejected(exchange, market): + with pytest.raises(ValueError, match="unsupported"): + validate_manual_protection({"trailing_stop_pct": 0.02}, exchange_id=exchange, market_type=market) + + +@pytest.mark.parametrize("exchange", ["binance", "okx", "bitget", "bybit", "gate", "htx"]) +def test_fixed_derivative_protection_remains_supported(exchange): + assert validate_manual_protection({"sl_price": 90}, exchange_id=exchange, market_type="swap")["sl_price"] == 90 + + +def test_binance_does_not_silently_clamp_callback(): + with pytest.raises(ValueError, match="invalidParameters"): + validate_manual_protection({"trailing_stop_pct": 0.0001}, exchange_id="binance", market_type="swap") + + +def test_runtime_marker_cannot_be_reported_as_native_attached(): + status, _ = orders.quick_trade_protection_status( + requested=True, market_type="swap", filled_qty=1, avg_price=100, + responses=[{"managed_by": "strategy_runtime", "type": "trailing_stop"}], + ) + assert status == "failed" + + +def test_partial_native_acknowledgements_survive_later_timeout(monkeypatch): + receipt = {"algoId": "accepted-stop"} + native = Mock(side_effect=[[receipt], TimeoutError("connection lost")]) + monkeypatch.setattr("app.services.live_trading.native_protection.place_native_protection_orders", native) + with pytest.raises(orders.ProtectionSubmissionError) as caught: + orders.attach_quick_trade_protection( + object(), symbol="BTC/USDT", side="buy", filled_qty=1, avg_price=100, + tp_price=110, sl_price=90, market_type="swap", exchange_config={}, + leverage=1, margin_mode="cross", client_order_id="entry1", + ) + assert caught.value.responses == [receipt] + assert native.call_count == 2 + assert native.call_args_list[0].args[1].take_profit_price == 0 + assert native.call_args_list[1].args[1].stop_loss_price == 0 + + +def test_protection_claim_commits_before_external_submission(monkeypatch): + cursor = Mock() + cursor.fetchone.return_value = {"id": 1} + db = Mock() + db.cursor.return_value = cursor + + @contextmanager + def connection(): + yield db + + monkeypatch.setattr(protection_journal, "get_db_connection", connection) + assert protection_journal.claim_protection_submission(1, {"protection_status": "pending_fill"}, {"protection_status": "dispatching"}) + assert "RETURNING id" in cursor.execute.call_args.args[0] + assert json.loads(cursor.execute.call_args.args[1][2]) == {"protection_status": "pending_fill"} + db.commit.assert_called_once() + cursor.fetchone.return_value = None + assert not protection_journal.claim_protection_submission(1, {}, {}) + + +def test_protection_save_does_not_overwrite_concurrent_fee_or_cancel_metadata(monkeypatch): + cursor = Mock() + db = Mock() + db.cursor.return_value = cursor + + @contextmanager + def connection(): + yield db + + monkeypatch.setattr(protection_journal, "get_db_connection", connection) + protection_journal.save_protection_metadata(1, { + "protection_status": "attached", "protected_filled_qty": 1, + "fee_status": "pending", "exchange_status": "partially_filled", + }) + sql, params = cursor.execute.call_args.args + assert "COALESCE(raw_result->'_quick_trade', '{}'::jsonb) ||" in sql + assert json.loads(params[0]) == {"protection_status": "attached", "protected_filled_qty": 1} + + +@pytest.mark.parametrize("status", ["failed", "dispatching", "pending_fill", "attached", "rejected_unfilled"]) +def test_worker_never_replays_an_uncertain_protection_write(monkeypatch, status): + from app.services import pending_order_worker as module + worker = module.PendingOrderWorker.__new__(module.PendingOrderWorker) + client = object() + monkeypatch.setattr("app.services.quick_trade.credentials.build_exchange_config", lambda *a, **k: {"exchange_id": "binance"}) + monkeypatch.setattr("app.services.quick_trade.credentials.create_exchange_client", lambda *a, **k: client) + rejected = status == "rejected_unfilled" + monkeypatch.setattr(orders, "enrich_fill", lambda *a, **k: { + "filled": 0 if rejected else 1, "avg_price": 0 if rejected else 100, + "status": "rejected" if rejected else "filled", + }) + attach = Mock(return_value=[{"algoId": "protected"}]) + monkeypatch.setattr(orders, "attach_quick_trade_protection", attach) + monkeypatch.setattr(module, "quick_trade_status_quantity", lambda *a, **k: (1, False)) + monkeypatch.setattr("app.services.quick_trade.fee_reconciliation.fee_update_from_fill", lambda *a, **k: None) + monkeypatch.setattr("app.services.live_trading.fee_quote.fee_to_quote", lambda *a, **k: 0) + cursor = Mock() + db = Mock() + db.cursor.return_value = cursor + + @contextmanager + def connection(): + yield db + + monkeypatch.setattr(module, "get_db_connection", connection) + monkeypatch.setattr(protection_journal, "get_db_connection", connection) + worker._sync_one_quick_trade_order(dict( + id=1, user_id=1, credential_id=1, status="failed" if rejected else "submitted", symbol="BTC/USDT", side="buy", + filled_amount=0 if rejected else 1, avg_fill_price=0 if rejected else 100, raw_result={"_quick_trade": { + "trailing_stop_pct": 0.02, "trailing_activation_pct": 0.05, + "protection_status": "pending_fill" if rejected else status, + "protected_filled_qty": 0.4 if status == "attached" else 0, + }}, + )) + metadata = json.loads(cursor.execute.call_args.args[1][-2]) + if rejected: + attach.assert_not_called() + assert metadata["protection_status"] == "not_requested" + sql = cursor.execute.call_args.args[0] + assert "'failed'" in sql[sql.index("WHERE id"):] + assert cursor.execute.call_args.args[1][0] == "failed" + elif status in {"failed", "dispatching"}: + attach.assert_not_called() + assert metadata["protection_status"] == "failed" + else: + assert metadata["protection_status"] == "attached" + assert metadata["protected_filled_qty"] == 1 + assert attach.call_args.kwargs["filled_qty"] == (0.6 if status == "attached" else 1) + assert attach.call_args.kwargs["trailing_stop_pct"] == 0.02 + assert attach.call_args.kwargs["trailing_activation_pct"] == 0.05 + assert attach.call_args.kwargs["client_order_id"] == worker._protection_client_order_id(1, 1) + + +def test_agent_allows_trailing_fields_and_rejects_paper_protection_before_execution(monkeypatch): + from app.routes.agent_v1 import quick_trade as agent + assert {"trailing_stop_pct", "trailing_activation_pct"} <= agent._ORDER_FIELDS + monkeypatch.setattr(agent, "paper_only", lambda: True) + execute = Mock() + monkeypatch.setattr(agent, "_place_live_order", execute) + with Flask(__name__).test_request_context(json=dict( + market="Crypto", symbol="BTC/USDT", side="buy", qty=1, trailing_stop_pct=0.02, + )): + response = inspect.unwrap(agent.place_order)() + assert response[1] == 400 + execute.assert_not_called() + + +@pytest.mark.parametrize("symbol", ["Crypto:BTC/USDT", "USStock:AAPL", "HKStock:00700.HK"]) +def test_runtime_trailing_still_tracks_extremes_after_restore_across_markets(symbol): + from app.services.strategy_v2.protection import ProtectionSpec, ProtectionState, ProtectionEngine + state = ProtectionState.open( + symbol=symbol, side="long", entry_price=100, + spec=ProtectionSpec(trailing_stop_pct=0.02, trailing_activation_pct=0.05), + opened_at="2026-11-25T10:00:00", + ) + engine = ProtectionEngine() + assert engine.evaluate_price(state, timestamp="2026-11-25T10:01:00", price=150) is None + restored = ProtectionState.from_metadata(state.metadata()) + assert engine.evaluate_price(restored, timestamp="2026-11-25T10:02:00", price=147.5) is None + assert engine.evaluate_price(restored, timestamp="2026-11-25T10:03:00", price=147).reason == "trailing_stop" + + +@pytest.mark.parametrize("filled,expected", [(0, "pending_fill"), (0.1, "attached")]) +def test_agent_live_order_retains_protection_for_deferred_fills(monkeypatch, filled, expected): + from copy import deepcopy + from app.routes.agent_v1 import quick_trade as agent + from app.routes import quick_trade + captured = {} + monkeypatch.setattr("app.services.quick_trade.credentials.build_exchange_config", lambda *a, **k: {"exchange_id": "binance"}) + monkeypatch.setattr("app.services.quick_trade.credentials.create_exchange_client", lambda *a, **k: object()) + monkeypatch.setattr("app.services.live_trading.account_configuration.configure_derivatives_account", lambda *a, **k: None) + monkeypatch.setattr("app.services.live_trading.execution.place_order_from_signal", lambda **k: SimpleNamespace(exchange_order_id="entry", filled=filled, avg_price=100 if filled else 0, raw={})) + monkeypatch.setattr(orders, "enrich_fill", lambda *a, **k: {}) + def record(**kwargs): + captured["initial"] = deepcopy(kwargs["raw_result"]["_quick_trade"]) + return 1 + monkeypatch.setattr(quick_trade, "_record_quick_trade", record) + monkeypatch.setattr(protection_journal, "save_protection_metadata", lambda trade_id, meta: captured.update(final=deepcopy(meta))) + attach = Mock(return_value=[{"algoId": "trail"}]) + monkeypatch.setattr("app.services.live_trading.native_protection.place_native_protection_orders", attach) + result = agent._place_live_order(body=dict( + credential_id=1, market="Crypto", symbol="BTC/USDT", side="buy", qty=0.1, + market_type="swap", trailing_stop_pct=0.02, trailing_activation_pct=0.05, + ), user_id=1) + assert result["protection_status"] == expected + assert captured["initial"]["protection_status"] == ("dispatching" if filled else "pending_fill") + assert captured["final"]["trailing_stop_pct"] == 0.02 + assert captured["final"]["trailing_activation_pct"] == 0.05 + assert captured["final"]["protection_status"] == expected + assert attach.call_count == (1 if filled else 0) diff --git a/backend_api_python/tests/test_native_protection.py b/backend_api_python/tests/test_native_protection.py index 41d63793c..2a05e5eba 100644 --- a/backend_api_python/tests/test_native_protection.py +++ b/backend_api_python/tests/test_native_protection.py @@ -477,7 +477,7 @@ def test_bybit_conditional_orders_are_reduce_only(): assert {body["triggerDirection"] for body in calls} == {1, 2} -def test_bybit_snaps_trigger_and_trailing_prices_to_tick(): +def test_bybit_preserves_fixed_stop_and_keeps_percentage_trailing_runtime_owned(): from app.services.live_trading.bybit import BybitClient client = BybitClient.__new__(BybitClient) @@ -491,7 +491,7 @@ def test_bybit_snaps_trigger_and_trailing_prices_to_tick(): or {"retCode": 0} ) - place_native_protection_orders( + responses = place_native_protection_orders( client, _request( pos_side="short", @@ -504,8 +504,8 @@ def test_bybit_snaps_trigger_and_trailing_prices_to_tick(): ) assert calls[0]["triggerPrice"] == "77951.1" - assert calls[1]["trailingStop"] == "3802.4" - assert calls[1]["activePrice"] == "72247.4" + assert len(calls) == 1 + assert responses[-1] == {"managed_by": "strategy_runtime", "type": "trailing_stop"} def test_bybit_rejects_native_protection_quantity_below_exchange_minimum(): diff --git a/backend_api_python/tests/test_quick_trade_trailing_protection.py b/backend_api_python/tests/test_quick_trade_trailing_protection.py new file mode 100644 index 000000000..f65406896 --- /dev/null +++ b/backend_api_python/tests/test_quick_trade_trailing_protection.py @@ -0,0 +1,144 @@ +import inspect +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from flask import Flask, g + +from app.routes import quick_trade +from app.services.live_trading.native_protection import NativeProtectionRequest +from app.services.quick_trade import orders + + +def test_attach_quick_trade_protection_supports_trailing_stop_alone(monkeypatch): + """Verify that attach_quick_trade_protection does not exit when only trailing stop is specified.""" + captured_request = [] + + def mock_place_native(client, request): + captured_request.append(request) + return [{"role": "trailing_stop", "order_id": "trail-123"}] + + monkeypatch.setattr( + "app.services.live_trading.native_protection.place_native_protection_orders", + mock_place_native, + ) + + client = object() + result = orders.attach_quick_trade_protection( + client, + symbol="BTC/USDT", + side="buy", + filled_qty=0.5, + avg_price=50000.0, + tp_price=0.0, + sl_price=0.0, + market_type="swap", + exchange_config={"product_type": "USDT-FUTURES"}, + leverage=5.0, + margin_mode="cross", + client_order_id="testorder123", + trailing_stop_pct=0.02, + trailing_activation_pct=0.05, + ) + + assert len(result) == 1 + assert result[0]["role"] == "trailing_stop" + assert len(captured_request) == 1 + req = captured_request[0] + assert isinstance(req, NativeProtectionRequest) + assert req.symbol == "BTC/USDT" + assert req.pos_side == "long" + assert req.quantity == 0.5 + assert req.entry_price == 50000.0 + assert req.stop_loss_price == 0.0 + assert req.take_profit_price == 0.0 + assert req.trailing_stop_pct == 0.02 + assert req.trailing_activation_pct == 0.05 + + +def test_place_order_parses_and_attaches_trailing_stop(monkeypatch): + """Verify that place_order parses trailing_stop_pct and forwards it to attach_quick_trade_protection.""" + monkeypatch.setattr("app.services.quick_trade.protection_journal.save_protection_metadata", lambda *a: None) + captured_kwargs = {} + + def mock_attach(client, **kwargs): + captured_kwargs.update(kwargs) + return [{"role": "trailing_stop", "order_id": "trail-999"}] + + monkeypatch.setattr(quick_trade, "attach_quick_trade_protection", mock_attach) + monkeypatch.setattr( + quick_trade, + "_build_product_aware_config", + lambda *a, **k: ({"exchange_id": "binance"}, {}), + ) + monkeypatch.setattr(quick_trade, "configure_quick_trade_derivatives", lambda *a, **k: None) + monkeypatch.setattr(quick_trade, "create_exchange_client", lambda *a, **k: object()) + monkeypatch.setattr(quick_trade, "_recent_strategy_conflict", lambda *a, **k: None) + monkeypatch.setattr(quick_trade, "_convert_usdt_to_base_qty", lambda *a, **k: 0.1) + monkeypatch.setattr( + quick_trade, + "normalized_submission_quantity", + lambda *a, **k: (0.1, {}), + ) + + from app.services.live_trading import execution + monkeypatch.setattr( + execution, + "place_order_from_signal", + lambda *a, **k: SimpleNamespace( + exchange_order_id="binance-order-1", + filled=0.1, + avg_price=50000.0, + raw={}, + ), + ) + monkeypatch.setattr( + quick_trade, + "enrich_fill", + lambda *a, **k: { + "filled": 0.1, + "avg_price": 50000.0, + "fee": 0.0, + "fee_ccy": "", + "fees_by_ccy": {}, + "fee_status": "done", + "status": "filled", + }, + ) + recorded_trades = {} + monkeypatch.setattr( + quick_trade, + "_record_quick_trade", + lambda **kwargs: recorded_trades.update(kwargs) or 42, + ) + + app = Flask(__name__) + with app.test_request_context(): + g.user_id = 101 + payload = { + "credential_id": 1, + "symbol": "BTC/USDT", + "side": "buy", + "order_type": "market", + "amount": 5000.0, + "leverage": 5, + "market_type": "swap", + "trailing_stop_pct": 0.015, + "trailing_activation_pct": 0.03, + } + response = inspect.unwrap(quick_trade.place_order)(payload) + data = response.get_json() + + assert data["code"] == 1 + assert data["data"]["trade_id"] == 42 + assert data["data"]["protection_status"] == "attached" + + # Verify arguments forwarded to attach_quick_trade_protection + assert captured_kwargs["trailing_stop_pct"] == 0.015 + assert captured_kwargs["trailing_activation_pct"] == 0.03 + + # Verify metadata saved into trade record + raw_metadata = recorded_trades["raw_result"]["_quick_trade"] + assert raw_metadata["trailing_stop_pct"] == 0.015 + assert raw_metadata["trailing_activation_pct"] == 0.03 + assert raw_metadata["protection_status"] == "attached" diff --git a/docs/agent/agent-openapi.json b/docs/agent/agent-openapi.json index 5e635cb9a..14388ce63 100644 --- a/docs/agent/agent-openapi.json +++ b/docs/agent/agent-openapi.json @@ -168,7 +168,9 @@ "leverage": { "type": "integer", "default": 1 }, "margin_mode": { "type": "string", "enum": ["cross","isolated"], "nullable": true }, "tp_price": { "type": "number", "nullable": true, "description": "Optional take-profit price for live orders" }, - "sl_price": { "type": "number", "nullable": true, "description": "Optional stop-loss price for live orders" } + "sl_price": { "type": "number", "minimum": 0, "nullable": true, "description": "Optional stop-loss price for supported live swap orders" }, + "trailing_stop_pct": { "type": "number", "minimum": 0, "maximum": 1, "exclusiveMaximum": true, "description": "Live swap trailing ratio, e.g. 0.02 for 2%. Supported by Binance (0.001 to 0.1), OKX and Bitget. Zero disables trailing. Unsupported venues and paper orders reject protection before entry." }, + "trailing_activation_pct": { "type": "number", "minimum": 0, "description": "Favorable price move from entry before trailing activates, e.g. 0.05 for 5%. Requires trailing_stop_pct > 0." } } }, "StrategySourceWriteRequest": { diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index f1cbb051e..43d569170 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -564,6 +564,17 @@ components: type: number default: 0.0 minimum: 0.0 + trailing_stop_pct: + type: number + default: 0.0 + minimum: 0.0 + maximum: 1.0 + exclusiveMaximum: true + description: 'Decimal trailing ratio: 0.02 means 2%.' + trailing_activation_pct: + type: number + default: 0.0 + minimum: 0.0 source: type: string default: manual diff --git a/docs/trading/LIVE_TRADING_SAFETY.md b/docs/trading/LIVE_TRADING_SAFETY.md index 734567ab7..f38b0b9e7 100644 --- a/docs/trading/LIVE_TRADING_SAFETY.md +++ b/docs/trading/LIVE_TRADING_SAFETY.md @@ -208,3 +208,59 @@ For non-Binance REST coordination and official venue references, see [Exchange R 4. Before cancelling or reducing, confirm the action cannot cross protected manual inventory. 5. Stop the strategy or use emergency stop if risk continues to grow. 6. Do not restart until the root cause and ledger are reconciled. + + +## Attached protection capabilities and uncertain submissions + +Manual Quick Trade validates protection before placing the entry: + +| Path | Fixed TP/SL | Percentage trailing | +| --- | --- | --- | +| Binance / OKX / Bitget swaps | Native | Native; Binance accepts ratios 0.001–0.1 | +| Gate / HTX swaps | Native | Native; HTX minimum ratio 0.001 | +| Bybit swaps | Native | Percentage attachment rejected; native distance uses a different contract | +| Crypto spot | Rejected | Rejected | +| Alpaca US stocks | Native bracket/OTO | Rejected | +| IBKR US / HK stocks | Attached bracket children | Native trailing child on limit entries only | +| Tiger US / HK stocks | Native legs on limit entries only | Native trailing leg on limit entries only | +| Webull US stocks | Native combo; whole shares only | Attached trailing not integrated | +| Forthright manual orders | Unchanged; not integrated | Unchanged; not integrated | +| Agent paper orders | Rejected until simulated protection is implemented | Rejected | + +API ratios use decimals (`0.02` = 2%, `0.05` = 5%). Desktop and mobile inputs use percentages (`2` = 2%) and convert once. Activation without a trailing +ratio, negative/non-finite values, and conflicting aliases are invalid. +Short-entry activation ratios of 1 or more are rejected before entry because they would produce a nonpositive activation price. +Web, Agent and MCP calls share these checks. Stock strategy protection remains +runtime-owned by default; this table concerns manual entry APIs. + +Strategy percentage trailing on Bybit stays runtime-owned: its native +`trailingStop` is an absolute price distance for the account position, not a +percentage of the running extreme for a strategy allocation. HTX ratios below 0.001 and Binance ratios outside its native range stay runtime-owned rather than being silently clamped. Such markers must never be shown as native attachment. Gate and HTX native trailing uses filled contract quantities; unknown HTX position mode prevents submission. With no activation gain configured, Gate starts immediately and HTX uses the entry price as its activation threshold. Native order execution, price source and lifetime follow the venue rules; HTX uses `optimal_20`, which does not guarantee a complete fill. + +Quick Trade persists the entry and `dispatching` before sending protective +legs. The reconciler serializes account/instrument mutations, reloads the row, +and claims each new cumulative-fill boundary before submission. Partial fills +use distinct stable protection IDs. A fully filled order with pending +protection remains eligible even after fee/history reconciliation finishes. +Each acknowledged leg is retained if a later leg fails. + +A timeout/crash after the dispatch boundary leaves an uncertain exchange write. +It is **not automatically replayed**: the row becomes `failed` with a review +message, including any known acknowledgements. Check exchange orders and the +remaining position before repairing missing protection. Do not repeat the entry. +There is no local Quick Trade stop monitor as a fallback. Strategies retain their +existing runtime protection. Runtime protection still depends on a running +executor, usable prices and the market's execution session. + +Alpaca, IBKR, Tiger and Webull distinguish confirmed protection children from parent acceptance. Alpaca requests nested children; failure of that read preserves the accepted entry. Tiger checks child orders once. Webull verifies child identities and statuses when returned in the combo response; a parent-only response remains unconfirmed. Unknown/rejected child status requires broker-side review. Both tickets display that warning without repeating the entry. Stock broker orders use their broker order views, not the crypto Quick Trade protection journal. + +Stock percentage trailing cannot be combined with a fixed stop or an activation-gain parameter; a fixed take-profit is allowed. Desktop/mobile stock close tickets do not attach new opening protection. Tiger/Webull child orders use DAY validity and regular trading sessions; IBKR children use GTC. Expiration must not be mistaken for permanent coverage. Existing native order query/cancel screens are not a universal manager for every new conditional-order family: use the venue's order view to verify, modify or cancel orders not listed locally. Standalone Alpaca/Webull trailing orders, Bybit distance-based position trailing and crypto spot OCO are separate integrations, not implemented by these attached-entry controls. Forthright native strategy orders are explicitly deferred. + +No database migration is required; the journal is stored in existing +`qd_quick_trades.raw_result._quick_trade` metadata. Existing `failed` protection +rows require exchange reconciliation by the operator rather than blind retries. + +Deploy the backend and trading workers together with both clients. Offline adapter/receipt tests do not certify a live account, regional availability or venue execution. + +References: [Gate futures](https://www.gate.com/docs/developers/apiv4/en/futures/), [HTX USDT swaps](https://huobiapi.github.io/docs/usdt_swap/v1/en/), [Tiger orders](https://docs-en.itigerup.com/docs/place-order), [Webull stock orders](https://developer.webull.com/apis/docs/trade-api/stock/), [Alpaca orders](https://docs.alpaca.markets/us/docs/orders-at-alpaca), [IBKR trailing stops](https://www.interactivebrokers.com/docs/tws-api/order-types/trailing-stop), [Bybit trading-stop](https://bybit-exchange.github.io/docs/v5/position/trading-stop), +[Binance algo orders](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order). diff --git a/docs/trading/LIVE_TRADING_SAFETY_CN.md b/docs/trading/LIVE_TRADING_SAFETY_CN.md index 68ae76de8..08b86c42b 100644 --- a/docs/trading/LIVE_TRADING_SAFETY_CN.md +++ b/docs/trading/LIVE_TRADING_SAFETY_CN.md @@ -162,3 +162,37 @@ JEV 是一种 System One 模型:它针对整理好的状态与类型化问题 4. 撤单或减仓前确认不会越过受保护的手工仓位。 5. 风险继续扩大时停止策略或执行紧急停止。 6. 根因和账本核对完成前不要重新启动。 +## 手工下单的附带保护与提交结果不确定的处理 + +闪电交易会在提交开仓单之前检查保护参数和当前接入能力: + +| 下单入口 | 固定止盈止损 | 百分比移动止损 | +| --- | --- | --- | +| Binance / OKX / Bitget 合约 | 交易所原生保护 | 原生保护;Binance 比例范围为 0.001–0.1 | +| Gate / HTX 合约 | 交易所原生保护 | 原生保护;HTX 最小比例为 0.001 | +| Bybit 合约 | 交易所原生保护 | 拒绝百分比附带保护,原生价格距离是另一种语义 | +| 加密货币现货 | 拒绝此参数 | 拒绝此参数 | +| Alpaca 美股 | 原生 bracket / OTO | 拒绝此参数 | +| IBKR 美股 / 港股 | 附带 bracket 子单 | 限价开仓可附带原生移动止损 | +| Tiger 美股 / 港股 | 限价开仓可附带原生保护 | 限价开仓可附带原生移动止损 | +| Webull 美股 | 原生组合单,仅整股 | 尚未接入附带移动止损 | +| Forthright 手工下单 | 保持现状,暂不接入 | 保持现状,暂不接入 | +| Agent 模拟下单 | 尚未实现模拟保护,拒绝此参数 | 拒绝此参数 | + +API 比例使用小数,例如 `0.02` 表示 2%;桌面端和手机端输入百分数,例如填 `2` 表示 2%,客户端只转换一次。负数、非有限值、冲突的参数别名,以及只有激活比例而没有移动止损比例,均会被拒绝。做空激活比例达到或超过 1 会产生零或负的激活价,因此在开仓前拒绝。Web、Agent 和 MCP 使用同一规则。 + +此表仅说明手工下单 API。策略的股票保护仍默认由运行进程负责。Bybit 的原生 `trailingStop` 是整个账户持仓的固定价格距离,不等于单个策略分配数量的最高价回撤百分比,因此策略百分比移动止损继续由运行进程负责;HTX 小于 0.001 或超出 Binance 原生范围的比例仍标记为进程管理,不会冒充原生保护成功。Gate、HTX 新增原生移动止损使用已成交的合约数量;HTX 持仓模式未知时不提交。未设置盈利激活比例时,Gate 立即开始追踪,HTX 使用入场价作为激活门槛。执行价格来源、有效期和成交规则以交易所为准;HTX 使用 `optimal_20`,不保证全部成交。 + +闪电交易先保存开仓结果及 `dispatching` 状态,再提交保护单。后台对同一账户和标的串行处理,重新读取记录,并在每次新增累计成交量的保护提交前保存提交边界。部分成交使用不同且稳定的保护单标识;历史记录和手续费同步不会覆盖保护状态。某条保护腿失败时,已收到确认的保护腿仍会保留。 + +提交后的超时或进程退出可能使交易所结果不确定。系统不会盲目重发,而会标记为 `failed` 并要求核对交易所委托、持仓和已知保护单。请先修复缺失保护,不要重复开仓。闪电交易没有本地止损监测作为兜底;策略原有的进程保护仍依赖执行器运行、可用行情和允许执行的交易时段。 + +Alpaca、IBKR、Tiger、Webull 分别报告父单和保护子单的确认状态。Alpaca 查询嵌套子单,查询失败仍保留已受理的开仓结果;Tiger 查询一次子单;Webull 按组合响应中的子单标识和状态确认,仅返回父单时保持未确认。两端都会提示核查券商委托,不会把父单成功当作保护已挂好,也不会因此重发开仓单。股票券商订单通过券商委托视图核查,不使用加密货币闪电交易的保护提交记录。 + +股票附带移动止损不能同时设置固定止损或盈利激活比例,可以搭配固定止盈。两端股票平仓卖出不会附带新的开仓保护。Tiger、Webull 保护腿使用 DAY 有效期和正常交易时段,IBKR 子单使用 GTC,不能把到期订单当作永久保护。现有查询、撤单面板尚未统一覆盖所有新增条件单类型;本地未列出的订单须在交易所或券商端核实、修改或撤销。Alpaca/Webull 独立移动止损、Bybit 按价格距离设置的账户持仓追踪、现货 OCO 均属于独立接入,本次附带开仓入口未实现这些功能。方德原生策略单按要求暂缓。 + +本次不需要数据库迁移,提交记录使用现有 `qd_quick_trades.raw_result._quick_trade` 元数据。历史保护失败记录同样需要人工核对交易所状态。 + +部署时同步更新后端、交易 Worker 和两个客户端。离线适配及回执测试不等同于实盘账户、地区权限和交易所成交验证。 + +接口参考:[Gate futures](https://www.gate.com/docs/developers/apiv4/en/futures/)、[HTX USDT swaps](https://huobiapi.github.io/docs/usdt_swap/v1/en/)、[Tiger orders](https://docs-en.itigerup.com/docs/place-order)、[Webull stock orders](https://developer.webull.com/apis/docs/trade-api/stock/)、[Alpaca orders](https://docs.alpaca.markets/us/docs/orders-at-alpaca)、[IBKR trailing stops](https://www.interactivebrokers.com/docs/tws-api/order-types/trailing-stop)、[Bybit trading-stop](https://bybit-exchange.github.io/docs/v5/position/trading-stop)、[Binance algo orders](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order)。 diff --git a/mcp_server/README.md b/mcp_server/README.md index 9155ddc2a..6dbf53217 100644 --- a/mcp_server/README.md +++ b/mcp_server/README.md @@ -56,7 +56,7 @@ Never place an agent token in prompts, logs, screenshots, source control, or MCP | `list_portfolio_positions`, `list_paper_orders` | R | Portfolio and paper-order reads | | `emergency_stop_trading`, `cancel_open_paper_orders` | T | Emergency cancellation and T-token revocation | -Every mutating W/B/N/T tool requires a caller-generated `idempotency_key`; retries of the same request must reuse it. `stop_strategy` requires `confirm_stop=true`. `place_quick_order` requires `confirm_order=true`; a live-capable token also requires `confirm_live_trading=true`. Optional `tp_price` and `sl_price` protection are forwarded to the shared Quick Trade execution path. Server-side trading flags, allowlists, and per-order/per-day notional caps still apply. +Every mutating W/B/N/T tool requires a caller-generated `idempotency_key`; retries of the same request must reuse it. `stop_strategy` requires `confirm_stop=true`. `place_quick_order` requires `confirm_order=true`; a live-capable token also requires `confirm_live_trading=true`. Optional `tp_price`, `sl_price`, `trailing_stop_pct`, and `trailing_activation_pct` are forwarded to the shared Quick Trade execution path. Trailing fields are decimal ratios (`0.02` = 2%). Unsupported venue/market combinations and protection on paper orders are rejected before entry. `pending_fill` means protection is not active yet; `failed` requires checking exchange orders before any further action, not repeating the entry. Server-side trading flags, allowlists, and per-order/per-day notional caps still apply. ## Strategy API V2 workflow diff --git a/mcp_server/src/quantdinger_mcp/server.py b/mcp_server/src/quantdinger_mcp/server.py index 04932af07..a34864cf6 100644 --- a/mcp_server/src/quantdinger_mcp/server.py +++ b/mcp_server/src/quantdinger_mcp/server.py @@ -396,6 +396,8 @@ def place_quick_order( margin_mode: str | None = None, tp_price: float | None = None, sl_price: float | None = None, + trailing_stop_pct: float | None = None, + trailing_activation_pct: float | None = None, idempotency_key: str = "", confirm_order: bool = False, confirm_live_trading: bool = False, @@ -445,6 +447,10 @@ def place_quick_order( payload["tp_price"] = float(tp_price) if sl_price is not None: payload["sl_price"] = float(sl_price) + if trailing_stop_pct is not None: + payload["trailing_stop_pct"] = float(trailing_stop_pct) + if trailing_activation_pct is not None: + payload["trailing_activation_pct"] = float(trailing_activation_pct) headers = _idempotency_headers(idempotency_key) return _post("/api/agent/v1/quick-trade/orders", json=payload, headers=headers) diff --git a/mcp_server/tests/test_security_and_tools.py b/mcp_server/tests/test_security_and_tools.py index 6c2aef956..9613a52d8 100644 --- a/mcp_server/tests/test_security_and_tools.py +++ b/mcp_server/tests/test_security_and_tools.py @@ -234,6 +234,8 @@ def fake_post(path, json=None, headers=None): 0.01, tp_price=70000, sl_price=60000, + trailing_stop_pct=0.02, + trailing_activation_pct=0.05, idempotency_key="order-7", confirm_order=True, ) @@ -241,6 +243,8 @@ def fake_post(path, json=None, headers=None): assert out == {"status": "filled"} assert captured["json"]["tp_price"] == 70000.0 assert captured["json"]["sl_price"] == 60000.0 + assert captured["json"]["trailing_stop_pct"] == 0.02 + assert captured["json"]["trailing_activation_pct"] == 0.05 def test_stop_strategy_requires_confirmation(fresh_module):