# Copyright (c) 2026 fxtradingguide.com
# SPDX-License-Identifier: MIT

"""Adapter from a causal signal column to backtesting.py.

The library fills a market order on the next bar's open unless
``trade_on_close`` is set. These studies leave it false. ``spread`` is a
fraction of price, applied by the library on the fill. See the Backtest
constructor docs in backtesting.py 0.6.
"""

from __future__ import annotations

import warnings

from backtesting import Strategy

# An open position at the last row is expected: the fill model does not invent
# a closing trade on the final observation, and the study does not read the
# return. The library warns about that open trade. The warning is not a result.
warnings.filterwarnings(
    "ignore",
    message=r"Some trades remain open at the end of backtest",
)


class SignalStrategy(Strategy):
    """Hold the position the signal column already decided at this close.

    The column is built only from data up to and including that observation.
    ``size`` below 1 is a fraction of equity. 0.10 is 10 percent of cash as
    notional, not 10 percent of cash at risk.
    """

    notional_fraction = 0.10

    def init(self) -> None:
        self.rule = self.I(lambda values: values, self.data.Signal, name="Rule")

    def next(self) -> None:
        target = self.rule[-1]
        if target != target:  # NaN during warmup.
            return
        target = int(target)
        if target == 1 and not self.position.is_long:
            self.buy(size=self.notional_fraction)
        elif target == -1 and not self.position.is_short:
            self.sell(size=self.notional_fraction)
        elif target == 0 and self.position:
            self.position.close()
