""" Action menu builder — reduces impossible action space to compact meaningful set. Menu size target: our actions: 8-24 each counterparty role: 3-12 depth: 2-4 Order type mapping (common-sensical): QUOTE/REQUOTE/CHASE: LIMIT (passive, post_only) CROSS_SPREAD (low urgency): LIMIT + IOC (taker, partial fill OK) CROSS_SPREAD (high urgency): MARKET (immediate fill) STOP_LOSS: STOP_MARKET (trigger → market exit) TAKE_PROFIT: TRIGGER_MARKET (trigger → market exit) TRAILING_STOP: TRAILING_STOP (trailing stop exit) """ from __future__ import annotations from typing import List, Optional, Tuple from malkhut.state import ( ActionKind, FulfilmentPolicyParams, IntentKind, MarketWorldState, OpenOrderState, OrderType, Side, TradePathState, ) from malkhut.actions import FulfilmentAction CHASE_MIN_OFFSET = 0 # minimum offset ticks for chase CHASE_MAX_OFFSET = 5 # maximum offset ticks for chase def _side_for_intent(intent_kind: IntentKind) -> Side: if intent_kind in (IntentKind.ENTER_LONG, IntentKind.ADD_LONG, IntentKind.REDUCE_SHORT, IntentKind.EXIT_SHORT): return Side.BUY return Side.SELL def _exit_side_for_position(state: MarketWorldState) -> Optional[Side]: path = state.trade_path if path is None: return None return Side.SELL if path.side == Side.BUY else Side.BUY def _path_risk_says_exit(state: MarketWorldState, params: FulfilmentPolicyParams) -> bool: path = state.trade_path if path is None: return False if abs(path.mae_bps) >= params.mae_tail_cut_bps: if path.recovery_velocity_bps_per_s < params.recovery_velocity_min_bps_per_s: return True if path.time_in_loss_s > params.max_time_in_loss_s: return True if path.failed_recovery_count >= params.failed_recovery_cut_count: return True if path.mfe_bps > 0: giveback = path.distance_from_mfe_bps / max(path.mfe_bps, 1e-12) if giveback >= params.mfe_giveback_cut_fraction: return True return False def build_our_actions( state: MarketWorldState, params: FulfilmentPolicyParams, ) -> Tuple[FulfilmentAction, ...]: intent = state.intent if intent is None: return (FulfilmentAction(ActionKind.NOOP, None, None, 0, 0.0, 0),) side = _side_for_intent(intent) actions: List[FulfilmentAction] = [] # Always allow no-op actions.append(FulfilmentAction( kind=ActionKind.NOOP, side=None, order_type=None, price_ticks_from_best=0, qty_fraction=0.0, ttl_ms=100, )) # Existing order management for oo in state.open_orders: if oo.symbol != intent.symbol: continue actions.append(FulfilmentAction( kind=ActionKind.CANCEL, side=oo.side, order_type=None, price_ticks_from_best=0, qty_fraction=0.0, ttl_ms=0, cancel_order_id=oo.client_order_id, )) for offset in params.quote_offsets_ticks: actions.append(FulfilmentAction( kind=ActionKind.CANCEL_REPLACE, side=side, order_type=OrderType.LIMIT, price_ticks_from_best=offset, qty_fraction=0.25, ttl_ms=params.passive_ttl_ms, cancel_order_id=oo.client_order_id, post_only=intent.prefer_maker, reduce_only=intent.reduce_only, metadata={"requote": True, "requote_offset": offset}, )) # Passive quote placements for offset in params.quote_offsets_ticks: for frac in params.quote_size_fractions: actions.append(FulfilmentAction( kind=ActionKind.PLACE, side=side, order_type=OrderType.LIMIT, price_ticks_from_best=offset, qty_fraction=frac, ttl_ms=params.passive_ttl_ms, post_only=intent.prefer_maker, reduce_only=intent.reduce_only, )) # Aggressive crossing — urgency + fee+slippage threshold driven maker/taker decision # The system learns: if (fee + slippage) < threshold → execute (pay the friction) # Threshold is movable (CMA-ES optimizable), tested at 2-3 bps per leg. estimated_fee_bps = state.venue.taker_fee_bps # what taker would pay estimated_slippage_bps = 0.5 # rough estimate; calibrated model refines in CWM estimated_friction = estimated_fee_bps + estimated_slippage_bps if intent.urgency > params.urgency_taker_threshold: # High urgency: full taker if friction is acceptable if estimated_friction <= params.execution_friction_threshold_bps or intent.urgency > 0.9: for frac in (0.05, 0.10, 0.25): actions.append(FulfilmentAction( kind=ActionKind.CROSS_SPREAD, side=side, order_type=OrderType.MARKET, price_ticks_from_best=0, qty_fraction=frac, ttl_ms=params.aggressive_ttl_ms, reduce_only=intent.reduce_only, metadata={"urgency": intent.urgency, "mode": "taker_market", "friction_bps": estimated_friction}, )) else: # Friction too high even at high urgency → IOC partial for frac in (0.03, 0.06): actions.append(FulfilmentAction( kind=ActionKind.CROSS_SPREAD, side=side, order_type=OrderType.LIMIT, price_ticks_from_best=0, qty_fraction=frac, ttl_ms=params.aggressive_ttl_ms, time_in_force="IOC", reduce_only=intent.reduce_only, metadata={"urgency": intent.urgency, "mode": "taker_ioc", "friction_bps": estimated_friction}, )) elif intent.urgency > params.urgency_taker_threshold * 0.5: # Medium urgency: IOC partial if friction is low if estimated_friction <= params.execution_friction_threshold_bps * 1.5: for frac in (0.03, 0.06): actions.append(FulfilmentAction( kind=ActionKind.CROSS_SPREAD, side=side, order_type=OrderType.LIMIT, price_ticks_from_best=0, qty_fraction=frac, ttl_ms=params.aggressive_ttl_ms, time_in_force="IOC", reduce_only=intent.reduce_only, metadata={"urgency": intent.urgency, "mode": "taker_ioc", "friction_bps": estimated_friction}, )) # Low urgency: passive only (maker) — no taker actions added # Path-risk exits if _path_risk_says_exit(state, params): # STOP_MARKET for stop-loss exits (trigger → market) actions.append(FulfilmentAction( kind=ActionKind.FULL_EXIT, side=_exit_side_for_position(state), order_type=OrderType.STOP_MARKET, price_ticks_from_best=0, qty_fraction=1.0, ttl_ms=0, reduce_only=True, metadata={"reason": "path_risk_exit", "exit_type": "stop_market"}, )) # Chase actions (cancel → wait → retry with configurable wait_to_retry_ms) if params.chase_enabled and params.wait_to_retry_ms > 0: chase_ttl = params.wait_to_retry_ms for offset in range(CHASE_MIN_OFFSET, min(CHASE_MAX_OFFSET + 1, params.chase_offset_ticks + 1)): for frac in params.quote_size_fractions: actions.append(FulfilmentAction( kind=ActionKind.PLACE, side=side, order_type=OrderType.LIMIT, price_ticks_from_best=offset, qty_fraction=frac, ttl_ms=chase_ttl, post_only=True, metadata={"chase": True, "chase_offset": offset, "chase_max_retries": params.chase_max_retries, "order_type_combo": "LIMIT+post_only+chase"}, )) return tuple(actions)