m/market labResearch, with a record.
Source on GitHub ↗

policy_controller.py

1"""Human/rule research setup and compatibility controls over PolicyDecisionRunner."""23from __future__ import annotations45from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Sequence, Tuple, Union, cast67from sim_platform.domain.models import ContractError8from sim_platform.domain.json_values import copy_json9from sim_platform.decisions import DecisionConfig10from sim_platform.decisions.policy.models import DEFAULT_HOLD_NS, DEFAULT_RULE_QUANTITY11from sim_platform.execution import ExecutionConfig12from sim_platform.resources import cleanup_after_error13from .controller import ResearchController, policy_for14from .configuration import policy_settings1516if TYPE_CHECKING:  # Annotation only.17    from sim_platform.experiments.scheduling.clock import SharedExperimentClock18    from sim_platform.decisions.policy.handoffs import HandoffCondition19    from sim_platform.decisions.policy.contracts import Policy20    from sim_platform.decisions.policy.live.runner import LivePolicyDecisionRunner21    from sim_platform.decisions.policy.runner import PolicyDecisionRunner22    from sim_platform.market.native import PathInput23    from sim_platform.market.prepared.session import PreparedSession24    from .reports import ExportWriter25    from .views import SessionView2627    # Creates a runner from (profile, run_id, maker_id, market, policy).28    RunnerFactory = Callable[[str, str, str, PreparedSession, Policy], PolicyDecisionRunner]29    LiveRunnerFactory = Callable[[str, str, str, PreparedSession, Policy], LivePolicyDecisionRunner]303132class PolicyResearchController(ResearchController):33    """ResearchController for Human and Rule policies in controlled or live mode.3435    Created by Platform.open_research for 'human', 'rule', 'hold' or 'model'; it creates the36    run and picks the runner factory for the chosen execution mode. Ownership and37    closing are those of ResearchController.3839    Args:40        runner_factory: Creates the controlled-mode PolicyDecisionRunner.41        live_runner_factory: Creates the live-mode LivePolicyDecisionRunner.42        (The other arguments are those of ResearchController.)43    """4445    def __init__(46        self,47        operations: Any,48        *,49        market_factory: Callable[[str], PreparedSession],50        runner_factory: RunnerFactory,51        live_runner_factory: LiveRunnerFactory,52        files: Any,53        export_writer: ExportWriter,54    ) -> None:55        super().__init__(56            operations, market_factory=market_factory, files=files, export_writer=export_writer57        )58        self._runner_factories: Dict[str, Union[RunnerFactory, LiveRunnerFactory]] = dict(59            controlled=runner_factory, live=live_runner_factory60        )6162    def _policy(63        self,64        policy: str,65        quantity: int,66        hold_ns: int,67        model: Optional[Dict[str, Any]],68        execution_mode: str,69        allow_short: bool = False,70    ) -> Tuple[Policy, DecisionConfig]:71        """Build the selected policy and its decision settings."""72        if policy != 'model':73            if model is not None:74                raise ContractError('model settings need policy=model')75            selected = policy_for(policy, quantity, hold_ns)76            return selected, DecisionConfig(mode='manual' if policy == 'human' else 'automatic')77        if model is None:78            raise ContractError('the model method needs model settings')79        if execution_mode != 'controlled':80            raise ContractError('the model method runs in Controlled mode only')81        from sim_platform.decisions.policy.model_file import ModelFilePolicy8283        assert self.market is not None84        selected = ModelFilePolicy(85            model['model_file'],86            self.market.calendar,87            lookback=model['lookback_bars'],88            parameters=model['model_parameters'],89            python=model['model_python'],90            allow_short=allow_short,91        )92        timeout_ms = max(1, int(model['model_timeout_seconds'] * 1000))93        return selected, DecisionConfig(94            mode='automatic', triggers=('market',), timeout_ms=timeout_ms95        )9697    def start(98        self,99        profile: str,100        account: str,101        policy: str = 'human',102        quantity: int = DEFAULT_RULE_QUANTITY,103        hold_ns: int = DEFAULT_HOLD_NS,104        fee_per_share: int = 0,105        latency_ns: int = 0,106        execution_config: Optional[ExecutionConfig] = None,107        *,108        execution_mode: str,109        model: Optional[Dict[str, Any]] = None,110        allow_short: bool = False,111    ) -> SessionView:112        """Create a run on the prepared market and bind the runner for ``execution_mode``.113114        ``model`` holds the model method's settings (research.configuration.MODEL_DEFAULTS)115        and is required exactly when ``policy`` is 'model'. ``allow_short`` lets sales go116        beyond the shares held under the margin rule in docs/reference/orders.md.117        """118        self._check_open()119        if self._active():120            raise ContractError('a simulation is already active')121        if self.runner is not None:122            raise ContractError('load a fresh market before starting another experiment')123        prepared = bool(124            self.market125            and self._prepared_origin126            == dict(sequence=self.market.snapshot.sequence, time_ns=self.market.time_ns)127            and self.market.status in ('ready', 'paused')128        )129        if self.market is None or (130            not prepared and (self.market.status != 'ready' or self.market.time_ns != 0)131        ):132            raise ContractError('load fresh market data before starting a simulation')133        selected, config = self._policy(134            policy, quantity, hold_ns, model, execution_mode, allow_short135        )136        if execution_config is not None and (fee_per_share or latency_ns):137            raise ContractError('supply execution_config or legacy fee/latency arguments, not both')138        execution = execution_config139        if execution is None:140            execution = ExecutionConfig(fee_per_share=fee_per_share, latency_ns=latency_ns)141        if not isinstance(execution, ExecutionConfig):142            raise ContractError('expected ExecutionConfig')143        from sim_platform.domain.experiment import validate_execution_mode144145        mode = validate_execution_mode(execution_mode)146        self._current_source['execution_mode'] = mode147        maker, run = self.app.create_managed_decision_run(148            profile,149            account,150            list(getattr(self.market, 'universe', ())) or self.market.snapshot.symbol,151            selected,152            config,153            execution,154            source=self.source,155            allow_short=allow_short,156        )157        self._execution_mode = mode158        self.profile, self.run_id = profile, run159        try:160            self.runner = self._runner_factories[mode](profile, run, maker, self.market, selected)161        except Exception as exc:162163            def stop_failed_start() -> None:164                if self.app.run(profile, run, include_records=False)['status'] == 'running':165                    self.app.execution(166                        'finish', profile, run, 'stopped', 0, 'failed start', write=True167                    )168169            cleanup_after_error(exc, stop_failed_start)170            raise171        return self.view()172173    def start_from_beginning(self, *, execution_mode: str, **arguments: Any) -> SessionView:174        """Prepare the selected source again from its start point, then start()."""175        from sim_platform.domain.experiment import validate_execution_mode176177        validate_execution_mode(execution_mode)178        self._check_open()179        if self._active() or self.viewed_run or not self.source or not self.market:180            raise ContractError('load research data before starting a new simulation')181        source = copy_json(self.source)182        symbol = self.market.snapshot.symbol183        self.begin_prepare(184            source['path'],185            symbol,186            source['news_path'],187            source['allow_implicit_eof'],188            source.get('start_mode', 'beginning'),189            source.get('start_time_ns'),190            book=source.get('book'),191            start_date=source.get('start_date'),192        )193        self.wait_for_preparation()194        return self.start(execution_mode=execution_mode, **arguments)195196    def order(197        self,198        client_id: str,199        side: str,200        quantity: int,201        limit_price: Optional[int] = None,202        order_type: str = 'limit',203        symbol: Optional[str] = None,204    ) -> SessionView:205        """Desktop/CLI compatibility; order semantics belong to policy controls.206207        ``order_type`` 'market' sends a market order and takes no ``limit_price``.208        ``symbol`` chooses one symbol of an experiment on several symbols.209        """210        options = dict(symbol=symbol) if symbol else {}211        if order_type == 'market':212            self.policy_controls.market_order(client_id, side, quantity, **options)213        elif order_type == 'limit' and limit_price is not None:214            self.policy_controls.order(client_id, side, quantity, limit_price, **options)215        else:216            raise ContractError('a limit order needs limit_price; order_type is limit or market')217        return self.view()218219    def cancel(self, client_id: str) -> SessionView:220        self.policy_controls.cancel(client_id)221        return self.view()222223    def handoff(224        self,225        policy: str,226        quantity: int = DEFAULT_RULE_QUANTITY,227        hold_ns: int = DEFAULT_HOLD_NS,228        state_mode: str = 'reset',229        condition: Optional[HandoffCondition] = None,230    ) -> SessionView:231        # The rule and position-management methods trade one symbol; an experiment on232        # several symbols can only hand its decisions back to Manual trading.233        if len(getattr(self.market, 'universe', ())) > 1 and policy != 'human':234            raise ContractError('an experiment on several symbols can only switch to Manual')235        self.policy_controls.handoff(policy, quantity, hold_ns, state_mode, condition)236        return self.view()237238    def create_experiment(239        self,240        profile: str,241        account: str,242        *,243        source: Union[PathInput, Sequence[PathInput]],244        method: str = 'human',245        settings: Optional[Dict[str, Any]] = None,246        agent_id: Optional[str] = None,247        revision: Optional[int] = None,248        execution_config: Optional[ExecutionConfig] = None,249        log_path: Optional[PathInput] = None,250        clock: Optional[SharedExperimentClock] = None,251        execution_mode: str,252    ) -> SessionView:253        self._check_open()254        if self.runner is not None or self.viewed_run:255            raise ContractError('create the experiment in a fresh controller')256        if (257            agent_id is not None258            or revision is not None259            or log_path is not None260            or clock is not None261        ):262            raise ContractError('agent options require an AgentResearchController')263        from sim_platform.domain.experiment import validate_execution_mode264265        validate_execution_mode(execution_mode)266        options = policy_settings(method, settings)267        paths = list(source) if isinstance(source, (list, tuple)) else None268        self.begin_prepare(269            cast('PathInput', paths[0] if paths else source),270            options['symbol'],271            options['news'],272            options['allow_implicit_eof'],273            options['start_mode'],274            options['start_time_ns'],275            book=options['book'],276            start_date=options['start_date'],277            symbols=options['symbols'],278            paths=paths if paths and len(paths) > 1 else None,279        )280        self.wait_for_preparation()281        return self.start(282            profile,283            account,284            method,285            options['quantity'],286            options['hold_ns'],287            execution_config=execution_config,288            execution_mode=execution_mode,289            model=options.get('model'),290            allow_short=options['allow_short'],291        )