investfly.models.strategy

Strategy execution models and related utilities.

class TradingStrategy(abc.ABC):

Base class for all trading strategies.

TradingStrategy is an abstract base class that defines the interface and common functionality for all trading strategies. Strategies can be triggered by market data events (bars/ticks) or scheduled time intervals.

Key Features

  • Configuration: Strategies can accept configuration parameters via the config dictionary in the constructor.
  • State Management: Strategies can maintain persistent state across executions by using self.state directly. The execution engine automatically persists and restores self.state between executions.
  • Stateless Execution: Each callback is executed on a fresh instance, ensuring thread-safety and isolation.
  • Data Access: Access to market data and indicators via dataService.
  • Context Access: Access to portfolio and universe securities via context.

Required Implementation

Subclasses must implement:

Optional Implementation

Subclasses may override:

  • onMarketData(): Handle market data updates (requires @data_trigger decorator).
  • Scheduled methods: Handle wall-clock events. Decorate one or more methods with @scheduled(TriggerSchedule...).
  • getStrategyPolicy(): Define runtime-managed exits, scaling, lifecycle, and limits.

    Attributes

  • config (Dict[str, Any] | None): Strategy-specific configuration parameters.

  • state (StrategyState): Persistent state dictionary for the strategy. Initialized as an empty dictionary. Child classes can use this directly to store state values. The execution engine automatically persists and restores this dictionary between executions, so child classes just need to read/write to self.state directly.
  • dataService (StrategyDataService): Service for accessing market data and indicators.
  • services (StrategyServices): Runtime-managed planning, selection, and evaluation helpers.
  • context (StrategyExecutionContext): Execution context containing portfolio and universe.

Example

A minimal runtime-planned allocation:

class AllocationStrategy(TradingStrategy):
    def getSecurityUniverseSelector(self):
        return SecurityUniverseSelector.fromSymbols(SecurityType.STOCK, ["AAPL", "MSFT"])

    @data_trigger(type=DataType.BARS, barInterval=BarInterval.ONE_DAY)
    def onMarketData(self, updatedSecurities):
        execution = OpenExecutionSettings(
            PositionSizeSpec(PositionSizeMode.PERCENT_OF_EQUITY, 80.0),
            OrderSpec(),
            DirectInstrumentSelection(),
        )
        return self.services.planAllocationOrders(AllocationPlan(updatedSecurities, execution))
TradingStrategy(config: Optional[Dict[str, Any]] = None)

Initialize strategy with optional configuration.

Arguments:
  • config: Dictionary of strategy-specific parameters. Can contain any structure (numeric, list, string, nested dictionaries, etc.). Defaults to None if no configuration is provided.
Note:

The dataService and context attributes are set by the execution engine before strategy methods are called. They should not be set manually in the constructor.

def getPortfolio(self) -> investfly.models.portfolio.Portfolio:

Get the portfolio from the execution context.

Returns:

The current portfolio state containing:

  • Open positions
  • Account balances
  • Portfolio performance metrics
Example:
portfolio = self.getPortfolio()
portfolio_value = portfolio.balances.currentValue
for position in portfolio.openPositions:
    print(f"{position.security.symbol}: {position.quantity} shares")
def getUniverseSecurities(self) -> List[investfly.models.marketdata.Security]:

Get the universe securities from the execution context.

Returns:

List of Security objects representing all securities in the strategy's trading universe. This is the resolved list based on the security universe selector returned by getSecurityUniverseSelector().

Example:
universe = self.getUniverseSecurities()
for security in universe:
    quote = self.dataService.getQuote(security)
    if quote:
        print(f"{security.symbol}: {quote.lastPrice}")
def getStateValue(self, key: str) -> typing.Any | None:

Get the state value for the given key.

Arguments:
  • key: The key to get the state value for.
Returns:

The state value for the given key.

def getState(self, key: str, default: typing.Any | None = None) -> typing.Any | None:

Return a persisted strategy value, or default when the key is absent.

def setState(self, key: str, value: Any) -> None:

Store a value that Investfly persists between strategy callbacks.

def deleteState(self, key: str) -> None:

Remove a persisted strategy value when it exists.

@abstractmethod
def getSecurityUniverseSelector( self) -> SecurityUniverseSelector:

Return the security universe selector for this strategy.

This method must be implemented by all strategy subclasses. It defines which securities the strategy will evaluate and trade.

Returns:

A SecurityUniverseSelector object that defines the strategy's trading universe. The selector can specify:

  • A single security
  • A standard predefined list (e.g., S&P 500, NASDAQ 100)
  • A custom list of symbols
  • A fundamental query-based selection
Example:
# Single stock
return SecurityUniverseSelector.singleStock("AAPL")

# Standard list
return SecurityUniverseSelector.fromStandardList(StandardSymbolsList.SP_500)

# Custom list
return SecurityUniverseSelector.fromSymbols(
    SecurityType.STOCK, ["AAPL", "MSFT", "GOOGL"]
)

# Fundamental query
query = FinancialQuery(
    SecurityType.STOCK,
    FinancialCondition(FinancialField.MARKET_CAP, ComparisonOperator.GREATER_THAN, 1000000000)
)
return SecurityUniverseSelector.fromFinancialQuery(query)
def onMarketData( self, updatedSecurities: List[investfly.models.marketdata.Security]) -> Optional[List[investfly.models.portfolio.TradeOrder]]:

Handle market data updates (bars/ticks).

This optional method is called whenever market data is updated for securities in the strategy's universe. To enable this callback, override this method and decorate it with @data_trigger.

The @data_trigger decorator specifies when this method should be called:

  • type (DataType): The type of market data to trigger on. Currently supported: DataType.BARS (bar/candlestick data).
  • barInterval (BarInterval, optional): Required for BARS type. Options: ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, SIXTY_MINUTE, ONE_DAY.
Arguments:
  • updatedSecurities: List of Security objects that received market data updates triggering this callback. Strategies should iterate over this list instead of the full universe to process only securities with new data.
Returns:

Optional list of TradeOrder objects to execute. Return None or an empty list if no trades should be placed.

Note:
  • If your logic requires Quote data (e.g., LastPrice), use @data_trigger(type=DataType.BARS, barInterval=BarInterval.ONE_MINUTE) to trigger on every 1-minute bar update, then access quotes using self.dataService.getQuote(security).
  • The method is called only for securities that have received updates, not for the entire universe.
Example:
@data_trigger(type=DataType.BARS, barInterval=BarInterval.ONE_DAY)
def onMarketData(self, updatedSecurities):
    orders = []
    for security in updatedSecurities:
        # Compute indicators
        sma = self.dataService.computeIndicatorSeries(
            "SMA", security, {"period": 20, "barInterval": BarInterval.ONE_DAY}
        )
        # Generate trade orders based on indicator values
        if sma.last.value > threshold:
            orders.append(TradeOrder(security, TradeType.BUY, OrderType.MARKET_ORDER))
    return orders if orders else None
def onSchedule( self, event: ScheduleEvent) -> Optional[List[investfly.models.portfolio.TradeOrder]]:

Handle scheduled time-based events.

Custom strategies may decorate any number of scheduled methods with @scheduled(TriggerSchedule...). The execution engine discovers all decorated callbacks automatically and passes a ScheduleEvent to each callback.

Returns:

Optional list of TradeOrder objects to execute. Return None or an empty list if no trades should be placed.

Note:
  • Multiple methods can be decorated with @scheduled to run distinct jobs at distinct schedule patterns.
  • The event argument includes the callback name, the schedule, the scheduled time, the actual evaluation time, and whether the callback is executing inside a backtest.
Example:
@scheduled(TriggerSchedule.daily("10:00"))
def rebalanceDaily(self, event: ScheduleEvent):
    orders = []
    portfolio = self.getPortfolio()
    return orders

@scheduled(TriggerSchedule.interval(5, days=ScheduleDayMode.EVERYDAY, window=ScheduleWindow("09:00", "13:00")))
def checkPositions(self, event: ScheduleEvent):
    return None
def getStrategyPolicy( self) -> CustomStrategyPolicy | None:

Return runtime-managed position, lifecycle, and portfolio behavior.

The same contract models used by configuration-driven strategies are accepted here. The runtime evaluates the policy in live trading and backtests; user strategy code supplies inputs and consumes planned orders without owning the algorithms.

class StrategyDataService(abc.ABC):

Interface for accessing market data and indicators from strategies.

StrategyDataService provides indicator computation and market query capabilities specifically for trading strategies, as well as market data access.

This service provides access to:

  • Technical indicators (SMA, RSI, MACD, etc.)
  • Market data (quotes, bars, financials)
  • News and fundamental data
  • Market queries (screeners)

The service is implemented by the execution engine and exposed to strategy instances through self.dataService.

Example:

Strategies access the data service via self.dataService:

# Compute indicators
sma = self.dataService.computeIndicatorSeries(
    "SMA", security, {"period": 20, "barInterval": BarInterval.ONE_DAY}
)

# Get current quote
quote = self.dataService.getQuote(security)
if quote:
    current_price = quote.lastPrice

# Get historical bars
bars = self.dataService.getBars(
    security, BarInterval.ONE_DAY, numBars=50
)
DEFAULT_INDICATOR_COUNT: int = 2

Constant for retrieving all available bars.

@abstractmethod
def getBars( self, security: investfly.models.marketdata.Security, barInterval: investfly.models.marketdata.BarInterval, numBars: int = 100) -> List[investfly.models.marketdata.Bar]:

Retrieve historical bars for a security.

For futures products, pass the product-level Security such as Security("MNQ", SecurityType.FUTURE). This returns the continuous back-adjusted series formed by stitching bars across successive contracts. Individual contract-level historical bars are not available through this method.

Arguments:
  • security: The Security object for which to fetch bars.
  • barInterval: The interval of bars to retrieve (e.g., ONE_MINUTE, ONE_DAY).
  • numBars: Number of bars to return. Use StrategyDataService.ALL_BARS to retrieve all available bars.
Returns:

List of Bar objects containing OHLC data in chronological order (oldest first).

Raises:
  • NoDataException: If the requested data is not available.
@abstractmethod
def getFinancials( self, symbol: str) -> Dict[investfly.models.marketdata.FinancialField, numbers.Number]:

Retrieve fundamental financial metrics for the given symbol.

Arguments:
  • symbol: The stock symbol (e.g., "AAPL", "MSFT").
Returns:

Dictionary mapping FinancialField enums to their corresponding values.

@abstractmethod
def getQuote( self, security: investfly.models.marketdata.Security) -> investfly.models.marketdata.Quote:

Retrieve the latest quote for the given security.

For futures, security can be a product-level Security (returns the expiry-safe active-contract quote from the product-keyed live cache) or a specific Future contract. Live execution can also resolve a contract-symbol Security such as Security("MNQM26", SecurityType.FUTURE) to a direct contract quote for any active contract returned by listFutures(). Backtests intentionally reject concrete contract quotes because the available futures history is product-level and back-adjusted.

Arguments:
  • security: The Security (or Future) for which to retrieve the quote.
Returns:

Quote object containing the latest market data.

@abstractmethod
def listFutures( self, product: investfly.models.marketdata.FutureProduct) -> List[investfly.models.marketdata.Future]:

List active futures contracts for a product, sorted by ascending expiry.

def listOptionExpiries( self, underlyingSymbol: str) -> List[investfly.models.marketdata.OptionExpiry]:

List broker/vendor-listed expirations for live option contract selection.

def getOptionChain( self, underlyingSymbol: str, expiry: investfly.models.marketdata.OptionExpiry) -> investfly.models.marketdata.OptionChain:

Return the listed option chain for one underlying and expiration.

@abstractmethod
def getNews( self, security: investfly.models.marketdata.Security) -> List[investfly.models.marketdata.StockNews]:

Retrieve latest news articles for the given security.

Arguments:
  • security: The Security object for which to retrieve news.
Returns:

List of StockNews objects containing news articles.

@abstractmethod
def computeIndicatorSeries( self, indicatorId: str, security: investfly.models.marketdata.Security, params: Dict[str, Any]) -> investfly.models.indicator.IndicatorSeries:

Compute a technical indicator series for a given security.

This method computes a technical indicator (e.g., SMA, RSI, MACD) and returns a series of indicator values over time. The series can be used for analysis, signal generation, and crossover detection.

The indicatorId parameter is declared as a string (not an enum) to support both standard indicators provided by Investfly and custom indicators defined by users. For standard indicators, the string value must match one of the values from the StandardIndicatorId enum.

Arguments:
  • indicatorId: The identifier of the indicator to compute. Must be a string value. For standard indicators supported by Investfly, use one of the values from StandardIndicatorId enum:

    Moving Averages:

    • "SMA": Simple Moving Average
    • "EMA": Exponential Moving Average

    Momentum Indicators:

    • "RSI": Relative Strength Index
    • "ROC": Rate of Change
    • "CMO": Chande Momentum Oscillator
    • "CMO_SMOOTHED": Smoothed CMO
    • "PPO": Percentage Price Oscillator
    • "ULTIMATE_OSC": Ultimate Oscillator

    Trend Indicators:

    • "MACD": Moving Average Convergence Divergence
    • "MACDS": MACD Signal Line
    • "ADX": Average Directional Index
    • "PLUS_DI": Plus Directional Indicator
    • "MINUS_DI": Minus Directional Indicator
    • "PSAR": Parabolic SAR

    Volatility Indicators:

    • "ATR": Average True Range
    • "STD_DEV": Standard Deviation
    • "UPPER_BBAND": Upper Bollinger Band
    • "LOWER_BBAND": Lower Bollinger Band
    • "BBAND": Bollinger Bands (composite, for charts only)

    Oscillators:

    • "CCI": Commodity Channel Index
    • "WILLIAM_R": Williams' %R
    • "FAST_STOCHASTIC_OSC": Fast Stochastic Oscillator
    • "SLOW_STOCHASTIC_OSC": Slow Stochastic Oscillator
    • "STOCHASTICS": Stochastic (composite, for charts only)

    Price Indicators:

    • "MEDIAN_PRICE": Median Price
    • "TYPICAL_PRICE": Typical Price
    • "MAX": Maximum value over period
    • "MIN": Minimum value over period

    Candlestick Patterns:

    • "DOJI": Doji pattern
    • "HAMMER": Hammer pattern
    • "INVERTED_HAMMER": Inverted Hammer pattern
    • "DRAGONFLY_DOJI": Dragonfly Doji pattern
    • "GRAVESTONE_DOJI": Gravestone Doji pattern
    • "HANGING_MAN": Hanging Man pattern
    • "BULLISH": Bullish pattern
    • "BEARISH": Bearish pattern

    Support/Resistance:

    • "SUPPORT": Support level
    • "RESISTANCE": Resistance level

    Other:

    • "AVGVOLUME": Average Volume
    • "HIGH52WEEK": 52-Week High
    • "LOW52WEEK": 52-Week Low
    • "DRAWDOWN": Drawdown
    • "PRICECHANGEPCT": Price Change Percentage

    For custom indicators, use the custom indicator ID string as defined when the indicator was created.

  • security: The security for which to compute the indicator.
  • params: Dictionary of parameters for the indicator computation. Common parameters include:
    • "period" (int): Period for the indicator (e.g., 20 for SMA(20)).
    • "barInterval" (BarInterval): Bar interval for the data source.
    • Indicator-specific parameters (e.g., "fast_period", "slow_period" for MACD).
Returns:

IndicatorSeries object containing the computed indicator values. The series provides methods for:

  • Accessing the latest value: series.last.value
  • Converting to list: series.toList()
  • Crossover detection: series.cross_over(other), series.cross_under(other)
Note:
  • The indicatorId parameter is a string type (not StandardIndicatorId enum) to support both standard and custom indicators.
  • When using standard indicators, the string value must exactly match one of the StandardIndicatorId enum values (see investfly.models.indicator.IndicatorEnums.StandardIndicatorId).
  • Custom indicators can be referenced by their custom ID string.
Example:
# Compute 20-period SMA on daily bars (standard indicator)
sma20 = self.dataService.computeIndicatorSeries(
    "SMA",  # Must match StandardIndicatorId.SMA.value
    security,
    {"period": 20, "barInterval": BarInterval.ONE_DAY}
)

# Compute 14-period RSI (standard indicator)
rsi = self.dataService.computeIndicatorSeries(
    "RSI",  # Must match StandardIndicatorId.RSI.value
    security,
    {"period": 14, "barInterval": BarInterval.ONE_DAY}
)

# Compute custom indicator
custom_indicator = self.dataService.computeIndicatorSeries(
    "MY_CUSTOM_INDICATOR",  # Custom indicator ID
    security,
    {"param1": 10, "barInterval": BarInterval.ONE_DAY}
)

# Check for crossover
if sma20.cross_over(rsi):
    # SMA crossed above RSI - bullish signal
    pass

# Access latest value
current_rsi = rsi.last.value
@abstractmethod
def runMarketQuery( self, request: MarketQueryRequest) -> List[investfly.models.marketdata.Security]:

Run a market query using a market query request.

This method executes a screener query to find securities that match the given filter expression. The query is executed against the universe of securities available to this strategy.

Arguments:
  • request: MarketQueryRequest containing:
    • securityFilterExpression: SecurityFilterExpression with filter criteria. The expression can include filters on:
      • Quote fields (price, volume, etc.)
      • Financial data (market cap, P/E ratio, etc.)
      • Technical indicators (SMA, RSI, etc.)
    • sortBy: Optional SortBySpec for sorting and limiting results.
Returns:

List of Security objects that match the filter criteria. Returns an empty list if no securities match.

Example:
from investfly.models.strategy.SecurityFilterExpression import SecurityFilterExpression
from investfly.models.strategy.MarketQueryRequest import MarketQueryRequest
from investfly.models.strategy.DataParams import DataParam, DataType
from investfly.models.marketdata.QuoteField import QuoteField

# Create a filter expression: price > 100
filter_expr = SecurityFilterExpression("price > 100")
price_param = DataParam(DataType.QUOTE, quoteField=QuoteField.LAST_PRICE)
filter_expr.addDataParam("price", price_param)

# Create market query request
query_request = MarketQueryRequest(securityFilterExpression=filter_expr)

# Run the query
matching_securities = self.dataService.runMarketQuery(query_request)
for security in matching_securities:
    print(f"Found: {security.symbol}")
@dataclass
class StrategyExecutionContext:

Execution context for a strategy instance.

The execution context contains per-execution data that is specific to a strategy deployment. This context is created by the execution engine and injected into strategy instances before their methods are called.

The context provides deployment-agnostic access to:

  • Portfolio state (positions, balances, performance)
  • Universe securities (resolved list of securities to evaluate)
Attributes:
  • portfolio: The current portfolio state containing open/closed positions, balances, and performance as returned by the portfolio API (virtual or broker-backed). This is broker-derived account state only — it does not include application-defined groupings of option legs (brokers do not expose multi-leg structure after fill).
  • openOptionGroups: Engine-supplemented view of multi-leg option structures for this tick. Populated in backtest by reconstructing groups from open option positions; live execution hydrates Java's reconciled open-position-group endpoint. Used for group-level exit logic (e.g. DTE cutoff) that requires knowing which legs belong together, including underlying stock/ETF legs for buy-write structures.
  • universeSecurities: List of Security objects representing all securities in the strategy's trading universe. This is the resolved list based on the security universe selector returned by TradingStrategy.getSecurityUniverseSelector().
Example:

The execution engine creates and injects the context:

context = StrategyExecutionContext(
    portfolio=current_portfolio,
    universeSecurities=resolved_securities
)
# Investfly makes this context available before invoking the strategy.

Strategies access context data via convenience methods:

portfolio = self.getPortfolio()
universe = self.getUniverseSecurities()
class StrategyServices(abc.ABC):

Runtime-injected operations shared with configuration-driven strategies.

This class is a public contract only. Strategy authors call self.services; Investfly injects the live/backtest implementation before any strategy callback is evaluated.

@abstractmethod
def selectSecurities( self, selection: SecuritySelection | RankedSecuritySelection) -> List[investfly.models.marketdata.Security]:

Resolve a selection specification to ordered securities.

@abstractmethod
def rankSecurities( self, selection: RankedSecuritySelection) -> List[RankedSecurity]:

Resolve and score securities using a ranked selection specification.

@abstractmethod
def evaluateCondition( self, condition: SecurityFilterExpression, security: investfly.models.marketdata.Security) -> bool:

Evaluate a filter expression for one security.

@abstractmethod
def evaluateGuards( self, policy: GuardPolicy, scope: GuardScope = <GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>, targetKey: str | None = None) -> List[GuardDecision]:

Evaluate strategy guards and return their decisions for the requested scope.

@abstractmethod
def planOpenOrders( self, request: OpenOrderRequest) -> List[investfly.models.portfolio.TradeOrder]:

Plan entry orders with runtime-managed selection, sizing, and execution.

@abstractmethod
def planAllocationOrders( self, plan: AllocationPlan) -> List[investfly.models.portfolio.TradeOrder]:

Plan orders that allocate a budget across a group of securities.

@abstractmethod
def planCloseOrders( self, positions: List[investfly.models.portfolio.OpenPosition], closeSpec: ClosePositionSpec | None = None) -> List[investfly.models.portfolio.TradeOrder]:

Plan closing orders for the supplied open positions.

@abstractmethod
def planRebalanceOrders( self, plan: RebalancePlan) -> List[investfly.models.portfolio.TradeOrder]:

Plan orders that move the portfolio toward a target basket.

@abstractmethod
def planScalingOrders( self, updatedSecurities: List[investfly.models.marketdata.Security]) -> List[investfly.models.portfolio.TradeOrder]:

Plan scale-in orders for positions affected by the latest market update.

@abstractmethod
def drainWarnings(self) -> List[str]:

Return and clear non-fatal warnings produced by previous service calls.

@dataclass
class CustomStrategyPolicy:

Continuous behavior that the runtime manages around custom strategy callbacks.

A custom strategy remains responsible for deciding when to request an entry or rebalance. The runtime owns the configured position management, asset lifecycle, and portfolio-limit algorithms before and after those callbacks.

@dataclass(frozen=True)
class RankedSecurity:

A selected security and its ranking score.

@dataclass
class OpenOrderRequest:

Request runtime-managed instrument selection, sizing, and order construction.

@dataclass
class AllocationPlan:

Allocate one total execution budget equally across the supplied securities.

For percentage and notional sizing, execution.positionSize is the total pool and the runtime divides it by the number of securities. For fixed quantity sizing, the quantity is applied to each security.

@dataclass
class RebalancePlan:

Describe target selection, weighting, and replacement for a rebalance.

class TargetWeightMode(builtins.str, enum.Enum):

How a rebalance budget is distributed among selected securities.

class ReplacementPolicy(builtins.str, enum.Enum):

How a rebalance handles securities that leave the target set.

def buildProtectiveExitPlan( targetProfitPct: float | None = None, stopLossPct: float | None = None, trailingStopPct: float | None = None, maxHold: StrategyDuration | None = None) -> ProtectiveExitPlan:

Build a protective-exit plan from common percentage-based settings.

The returned plan may combine a profit target, fixed stop, trailing stop, and maximum holding period. The Investfly runtime evaluates the plan.

@dataclass
class StrategyConfig:

Complete declarative trading-strategy configuration.

Combines the security universe, entry and exit rules, scheduled jobs, position management, asset lifecycle, and portfolio limits evaluated by Investfly in live trading and backtests.

class EdgeMode(builtins.str, enum.Enum):

How a condition treats transitions at its threshold.

@dataclass
class EntryRule:

One entry condition paired with execution settings.

@dataclass
class EntryRules:

Collection of entry rules and their conflict policy.

@dataclass
class OpenExecutionSettings:

Instrument selection, sizing, and order settings for opening a position.

@dataclass
class ExitRule:

One exit condition and the position-closing behavior it activates.

@dataclass
class ExitRules:

Collection of exit rules evaluated for open positions.

class ProfitThresholdType(builtins.str, enum.Enum):

Measurement used to define a profit target.

@dataclass
class StagedProfitTargets:

Ordered profit-taking tiers for progressively closing a position.

@dataclass
class ProfitTargetTier:

One profit threshold and the percentage of a position to close.

class FixedStopThresholdType(builtins.str, enum.Enum):

Measurement used to locate a fixed protective stop.

@dataclass
class FixedStopThreshold:

Threshold value for a fixed stop rule.

@dataclass
class FixedStopRule:

Protective stop fixed at a price or distance from entry.

class TrailingStopDistanceType(builtins.str, enum.Enum):

Measurement used for a trailing-stop distance.

@dataclass
class AtrParams:

Average True Range settings used by volatility-based distances.

@dataclass
class TrailingStopDistance:

Distance maintained by a trailing protective stop.

@dataclass
class TrailingStopRule:

Protective stop that follows favorable price movement.

class SessionTimeTriggerType(builtins.str, enum.Enum):

Reference point used by a session-time trigger.

@dataclass
class SessionTimeTrigger:

Trigger at a time relative to market-session open or close.

class ProtectiveExecutionPolicy(builtins.str, enum.Enum):

Execution policy for runtime-managed protective orders.

class StopSpecType(builtins.str, enum.Enum):

Available fixed and trailing stop specifications.

@dataclass
class StopSpec:

Fixed or trailing protective stop definition.

@dataclass
class ProfitLevelCondition:

Condition that becomes true after a profit tier is reached.

class ProtectionTriggerType(builtins.str, enum.Enum):

Events that can activate a protection adjustment.

@dataclass
class ProtectionTrigger:

Event condition that activates a protection adjustment.

@dataclass
class ProtectionAdjustment:

Replacement protective stop activated by a later trigger.

@dataclass
class ProtectiveExitPlan:

Profit targets, stops, adjustments, and maximum holding period for a position.

class MonthlyScheduleAnchor(builtins.str, enum.Enum):

Ways to anchor a monthly schedule within the month.

class ScheduleDayMode(builtins.str, enum.Enum):

Calendar used to decide which days a schedule may run.

@dataclass
class ScheduleEvent:

Invocation details passed to a scheduled strategy callback.

@dataclass
class ScheduledCallback:

A discovered callback together with its validated schedule.

class ScheduleEventTiming(builtins.str, enum.Enum):

Whether a callback runs before, after, or on its reference event.

class ScheduleEventType(builtins.str, enum.Enum):

Market or instrument events usable by event-relative schedules.

class SchedulePattern(builtins.str, enum.Enum):

Supported recurrence patterns for a scheduled callback.

@dataclass
class ScheduleWindow:

Intraday time window, expressed as HH:MM local market times.

@dataclass
class TriggerSchedule:

Recurrence definition used by scheduled().

Prefer the named factory methods such as daily(), weekly(), or eventRelative(); they populate the fields required by each pattern.

@staticmethod
def everyMinute( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create a one-minute schedule within an optional intraday window.

@staticmethod
def everyFiveMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create a five-minute schedule within an optional intraday window.

@staticmethod
def everyFifteenMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create a fifteen-minute schedule within an optional intraday window.

@staticmethod
def everyThirtyMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create a thirty-minute schedule within an optional intraday window.

@staticmethod
def interval( intervalMinutes: int = 15, days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create a repeating minute interval on the selected days and time window.

@staticmethod
def hourly( days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:

Create an hourly schedule on the selected days and time window.

@staticmethod
def daily( time: str = '09:30', days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None) -> TriggerSchedule:

Create a once-per-day schedule at time in HH:MM format.

@staticmethod
def weekly( daysOfWeek: Union[Weekday, Sequence[Weekday]] = <Weekday.MON: 'MON'>, time: str = '09:30') -> TriggerSchedule:

Create a weekly schedule on one or more weekdays.

@staticmethod
def monthly( day: int = 1, time: str = '09:30') -> TriggerSchedule:

Create a monthly schedule on a calendar day from 1 through 31.

@staticmethod
def firstTradingDayOfMonth( time: str = '09:30') -> TriggerSchedule:

Create a schedule for the first trading day of every month.

@staticmethod
def lastTradingDayOfMonth( time: str = '09:30') -> TriggerSchedule:

Create a schedule for the last trading day of every month.

@staticmethod
def eventRelative( event: ScheduleEventType, timing: ScheduleEventTiming = <ScheduleEventTiming.BEFORE: 'before'>, offsetTradingDays: Optional[int] = 1, time: str = '09:30') -> TriggerSchedule:

Create a schedule relative to a market or instrument event.

class Weekday(builtins.str, enum.Enum):

Weekday values accepted by weekly and custom-day schedules.

def toIndex(self) -> int:

Return the zero-based Monday-to-Sunday index.

@staticmethod
def fromIndex(index: int) -> Weekday:

Create a weekday from a zero-based Monday-to-Sunday index.

@dataclass
class ScheduledJob:

A validated schedule paired with a workflow intent and guard policy.

class ScheduledWorkflowIntentFamily(builtins.str, enum.Enum):

High-level behavior performed by a scheduled workflow.

@dataclass
class ScheduledWorkflowIntent:

Typed intent executed by a scheduled strategy job.

@dataclass
class PortfolioRotationConfig:

Selection and execution settings for a scheduled portfolio rotation.

@dataclass
class TargetWeightSpec:

Target portfolio weight for one security.

@dataclass
class TargetBasketRebalanceConfig:

Target basket, weights, and tolerance for scheduled rebalancing.

class ContributionMode(builtins.str, enum.Enum):

How recurring contributions are expressed.

@dataclass
class ContributionSpec:

Cash or percentage budget contributed by a recurring entry.

@dataclass
class RecurringMultiAssetEntryConfig:

Targets and contribution settings for recurring multi-asset entries.

@dataclass
class RecurringMultiAssetEntryTarget:

One target and allocation in a recurring multi-asset entry.

@dataclass
class RecurringSingleAssetEntryConfig:

Contribution and execution settings for a recurring single-asset entry.

@dataclass
class GuardPolicy:

Ordered strategy guards and their combination behavior.

class StrategyGuard:

Base contract for a pre-execution strategy guard.

class StrategyGuardType(builtins.str, enum.Enum):

Kinds of pre-execution strategy guards.

class GuardScope(builtins.str, enum.Enum):

Execution scopes in which a strategy guard may be evaluated.

@dataclass(frozen=True)
class StrategyGuardMetadata:

Identifier, scope, and behavior shared by all strategy guards.

@dataclass
class MarketRegimeGuard(investfly.models.strategy.StrategyGuard):

Guard that allows execution only in a configured market regime.

@dataclass
class TimeGuard(investfly.models.strategy.StrategyGuard):

Guard that allows or blocks execution within a configured time window.

class TimeWindowMode(builtins.str, enum.Enum):

How a time guard interprets its configured window.

@dataclass
class PortfolioMarginGuard(investfly.models.strategy.StrategyGuard):

Guard that enforces a portfolio margin threshold.

@dataclass
class CryptoMarketRegimeGuard(investfly.models.strategy.MarketRegimeGuard):

Market-regime guard tailored to continuously traded crypto markets.

@dataclass
class GuardDecision:

Result of evaluating one strategy guard.

class MarketRegimeRule(builtins.str, enum.Enum):

Supported interpretations of a market-regime condition.

class MarketRegimeTimeFrame(builtins.str, enum.Enum):

Time horizon used to evaluate market regime.

@dataclass
class OpenPositionSpec:

Selection criteria for currently open portfolio positions.

@dataclass
class ClosePositionSpec:

Quantity and order settings for closing selected positions.

class SecuritySelectionSource(builtins.str, enum.Enum):

Source from which a security selection obtains candidates.

@dataclass
class SecuritySelection:

Candidate universe and filter used to select securities.

@dataclass
class SecurityScoreExpression:

Expression used to score a security for ranking.

@dataclass
class RankedSecuritySelection:

Security selection with scoring, ordering, and result limits.

@dataclass
class OptionGroupSelection:

Criteria for selecting an existing option group.

@dataclass
class OptionLifecycleRules:

Ordered lifecycle rules evaluated for an option strategy.

@dataclass
class OptionLifecycleStructure:

Named option structure available to lifecycle rules.

@dataclass
class OptionLifecycleRule:

A trigger and ordered actions for one option lifecycle transition.

@dataclass
class OptionDteTrigger:

Trigger based on days remaining until option expiration.

@dataclass
class OptionMetricTrigger:

Trigger based on a measured option-group metric.

@dataclass
class OptionOutcomeTrigger:

Trigger based on a previously recorded lifecycle outcome.

@dataclass
class OptionAllOfTrigger:

Composite trigger that requires every child condition to match.

@dataclass
class OptionCloseLegsAction:

Lifecycle action that closes selected option legs.

@dataclass
class OptionRollAction:

Lifecycle action that rolls selected legs to new contracts.

@dataclass
class OptionOpenStructureAction:

Lifecycle action that opens an additional option structure.

@dataclass
class OptionLiquidateUnderlyingAction:

Lifecycle action that liquidates the associated underlying position.

@dataclass
class OptionCompleteAction:

Lifecycle action that marks the option structure complete.

class OptionLifecycleMetric(builtins.str, enum.Enum):

Option-group metric available to lifecycle triggers.

class OptionLifecycleOutcome(builtins.str, enum.Enum):

Lifecycle outcome recorded for a completed option structure.

class OptionOutcomeTiming(builtins.str, enum.Enum):

Timing used when matching a lifecycle outcome.

class OptionActionScope(builtins.str, enum.Enum):

Subset of an option group affected by a lifecycle action.

class OptionRollCreditRequirement(builtins.str, enum.Enum):

Credit or debit constraint applied to a roll action.

class OptionEntryRearmPolicy(builtins.str, enum.Enum):

When a scheduled entry becomes eligible again after execution.

@dataclass
class OptionGroupRiskRules:

Profit, loss, and holding-period risk controls for an option group.

@dataclass
class OptionScheduledEntryConfig:

Schedule, structure, and rearming behavior for option entries.

class OptionScheduledEntryAction(builtins.str, enum.Enum):

Action taken when a scheduled option entry is evaluated.

class OptionScheduledEntryTemplateType(builtins.str, enum.Enum):

Source used to construct a scheduled option entry.

class OptionProfitThresholdType(builtins.str, enum.Enum):

Measurement used by an option-group profit threshold.

@dataclass
class OptionGroupProfitRule:

Profit threshold that can close an option group.

class OptionLossThresholdType(builtins.str, enum.Enum):

Measurement used by an option-group loss threshold.

@dataclass
class OptionGroupLossRule:

Loss threshold that can close an option group.

class AllocationMode(builtins.str, enum.Enum):

Method used to distribute capital among selected securities.

@dataclass
class AllocationModel:

Allocation mode and optional explicit target weights.

class PositionSizeMode(builtins.str, enum.Enum):

Units used to express an entry position size.

@dataclass
class PositionSizeSpec:

Requested position size and its measurement mode.

class EntryConflictAction(builtins.str, enum.Enum):

Action taken when a new entry conflicts with an existing position.

@dataclass
class EntryConflictPolicy:

Policy for resolving simultaneous or conflicting entry signals.

@dataclass
class EntryExistingPositionPolicy:

Behavior when an entry targets a security already represented in the portfolio.

class ExistingTargetAction(builtins.str, enum.Enum):

Action applied to an existing target position.

@dataclass
class ExistingTargetPolicy:

Policy for entries that resolve to an existing target instrument.

@dataclass
class PositionExposureLimit:

Maximum exposure allowed for one position.

class MoveUnit(builtins.str, enum.Enum):

Unit used to measure a price move for scaling rules.

class MoveBasis(builtins.str, enum.Enum):

Reference price used to measure a scaling move.

@dataclass
class MoveCondition:

Required favorable or adverse move before a scaling action.

class ScalingSizeMode(builtins.str, enum.Enum):

How a scale-in order derives its quantity.

@dataclass
class ScaleAddPlan:

Sizing and execution settings for one scale-in action.

@dataclass
class RepeatSignalAddRule:

Scale-in rule activated by repeated entry signals.

@dataclass
class WinnerScaleRule:

Scale-in rule for positions moving favorably.

@dataclass
class LoserScaleLimits:

Safety limits for averaging into a losing position.

@dataclass
class LoserScaleRule:

Scale-in rule for positions moving adversely.

@dataclass
class ScalingPlan:

Combined repeat-signal, winner, and loser scale-in behavior.

@dataclass
class PositionManagementRules:

Runtime-managed exits and scaling behavior for open positions.

@dataclass
class PortfolioLimits:

Portfolio-wide position count, exposure, and buying-power limits.

@dataclass
class OptionGroupExposureLimits:

Portfolio exposure limits for grouped option positions.

class OrderDuration(builtins.str, enum.Enum):

Time-in-force choices for strategy orders.

class StrategyOrderType(builtins.str, enum.Enum):

Order types available to declarative strategy execution.

class LimitPriceOffsetUnit(builtins.str, enum.Enum):

Unit used to offset a generated limit price.

@dataclass
class LimitPriceOffset:

Adjustment applied when deriving a strategy limit price.

@dataclass
class OrderSpec:

Order type, duration, and limit-price behavior for strategy execution.

@dataclass
class StrategyDuration:

Elapsed strategy time; BARS means count multiplied by an explicit fixed interval.

class StrategyDurationUnit(builtins.str, enum.Enum):

Units supported by strategy duration values.

@dataclass
class FutureLifecycleRules:

Expiration and roll behavior for futures positions.

class FutureRollMode(builtins.str, enum.Enum):

Policy used to roll a futures position before expiration.

@dataclass
class AssetLifecycleRules:

Asset-specific lifecycle behavior for runtime-managed positions.

class DataTriggerInfo(typing.TypedDict):

Type definition for data trigger information

def data_trigger( type: DataType, barInterval: Optional[investfly.models.marketdata.BarInterval] = None):

Decorator to mark a method to run on market data events.

Returns a tuple (wrapper_func, trigger_info).

Arguments:
  • type (DataType): BARS, or other DataType
  • barInterval (BarInterval, optional): Interval for BARS events
Usage:

@data_trigger(type=DataType.BARS, barInterval=BarInterval.ONE_MINUTE) def onMarketData(self): ...

def scheduled(schedule: TriggerSchedule):

Decorate a strategy method so Investfly invokes it on schedule.

The decorated method receives one ScheduleEvent and may return a list of trade orders, matching the scheduled callback contract on TradingStrategy.

@dataclass
class TradingStrategyModel:

Stored strategy identity, configuration, source, and deployment metadata.

class ConfigOrScript(builtins.str, enum.Enum):

Whether a stored strategy is declarative or implemented by Python code.

@dataclass
class DeploymentLog:

Timestamped message emitted by a deployed strategy.

class LogLevel(builtins.str, enum.Enum):

Severity of a strategy deployment log message.

class BacktestStatus(builtins.str, enum.Enum):

Lifecycle state of a submitted backtest.

@dataclass
class BacktestResultStatus:

Outcome status reported by a completed backtest.

@dataclass
class BacktestResult:

Summary and output references for a strategy backtest.

class StandardSymbolsList(builtins.str, enum.Enum):

Investfly-maintained security lists available as strategy universes.

class CustomSecurityList:

User-supplied symbols grouped by security type.

class SecurityUniverseType(builtins.str, enum.Enum):

Supported sources for a strategy security universe.

@dataclass
class SecurityUniverseSelector:

This class is used to specify the set of stocks to use in trading strategy. You can pick one of the standard list (e.g SP100) that we provide, provide your own list with comma separated symbols list, or provide a query based on fundamental metrics like MarketCap, PE Ratio etc.

The security type for the universe selector

universeType: SecurityUniverseType

The approach used to specify the stocks. Depending on the universeType, one of the attribute below must be specified

standardList: StandardSymbolsList | None = None

Standard Symbol List (i.e SP500, SP100). Required if universeType is set to STANDARD_LIST

class FinancialQuery:

Fundamental conditions used to select a security universe.

@dataclass
class FinancialCondition:

One fundamental field comparison in a financial query.

class ComparisonOperator(builtins.str, enum.Enum):

Comparison operators used by financial screening conditions.

class Sectors(builtins.str, enum.Enum):

Stock market sectors for fundamental queries.

displayName: str

Get the display name of the sector.

class SecurityFilterExpression:

Composable boolean expression evaluated for a security.

def breakByDataType( self) -> tuple[SecurityFilterExpression | None, SecurityFilterExpression | None, SecurityFilterExpression | None]:

Break the expression by data type. Returns: (quoteExpression, financialExpression, indicatorExpression) FilterGroups containing only financial fields and constants go to financialExpression. FilterGroups containing only quote fields and constants go to quoteExpression. All other FilterGroups (containing indicators) go to indicatorExpression.

def replaceVarInWithField(self) -> None:

Replace variable names with field names in the expression for financial and quote queries. This allows direct computation without variable resolution.

class DataSource(builtins.str, enum.Enum):

Market-data source used by a strategy expression.

class DataType(builtins.str, enum.Enum):

Kinds of data available to strategy triggers and expressions.

class ConstUnit(builtins.str, enum.Enum):

Unit attached to a constant in a strategy expression.

class DataParam(typing.Dict[str, typing.Any]):

Reference to a market-data field or constant value.

class SortOrder(builtins.str, enum.Enum):

Ascending or descending query result ordering.

@dataclass
class SortBySpec:

Expression and direction used to sort market-query results.

@dataclass
class MarketQueryRequest:

Filter, sort, and result limit for a market-data query.

class OptionStrategyTemplate(builtins.str, enum.Enum):

Templated option structures supported by the Phase-1 MVP automated options engine.

Naked short calls/puts and undefined-risk structures outside this list are rejected by validation. Each template prescribes a fixed leg count and action shape except CUSTOM_COMBO, where conservative validation reads the explicit leg specs.

class OptionLegAction(builtins.str, enum.Enum):

Whether an option leg opens or closes a long or short position.

class OptionLegRole(builtins.str, enum.Enum):

Semantic role of a leg within a multi-leg option structure.

@dataclass
class OptionLegSpec:

Specification for a single leg of an option strategy. See Java OptionLegSpec for the canonical contract; both languages share the same JSON shape.

@dataclass
class OptionContractSelector:

Bounded contract selector applied after the underlying signal triggers.

The option template already supplies CALL/PUT and the leg structure. This selector keeps the user-facing contract choice to target DTE plus one primary strike rule. targetDelta is a positive delta magnitude; PUT selection applies the negative sign at runtime.

class StrikeSelectionMode(builtins.str, enum.Enum):

How an option strike is selected relative to the underlying market.

class MinimumStrikeRule(builtins.str, enum.Enum):

Lower strike bound applied during option contract selection.

@dataclass
class OptionStructureSpec:

Base contract for a runtime-selected option structure.

@dataclass
class LongCallSpec(investfly.models.strategy.OptionStructureSpec):

One long call selected by expiration and strike rules.

@dataclass
class LongPutSpec(investfly.models.strategy.OptionStructureSpec):

One long put selected by expiration and strike rules.

@dataclass
class CoveredCallSpec(investfly.models.strategy.OptionStructureSpec):

Covered call composed of underlying shares and a short call.

@dataclass
class CashSecuredPutSpec(investfly.models.strategy.OptionStructureSpec):

Cash-secured short put structure.

@dataclass
class BullPutCreditSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Bullish put credit spread with short and protective long puts.

@dataclass
class BearCallCreditSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Bearish call credit spread with short and protective long calls.

@dataclass
class BullCallDebitSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Bullish call debit spread with long and short calls.

@dataclass
class BearPutDebitSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Bearish put debit spread with long and short puts.

@dataclass
class IronCondorSpec(investfly.models.strategy.OptionStructureSpec):

Four-leg iron condor with call and put credit spreads.

@dataclass
class CallButterflySpec(investfly.models.strategy.OptionStructureSpec):

Three-strike call butterfly structure.

@dataclass
class PutButterflySpec(investfly.models.strategy.OptionStructureSpec):

Three-strike put butterfly structure.

@dataclass
class LongStraddleSpec(investfly.models.strategy.OptionStructureSpec):

Long call and put at the same strike and expiration.

@dataclass
class ShortStraddleSpec(investfly.models.strategy.OptionStructureSpec):

Short call and put at the same strike and expiration.

@dataclass
class LongStrangleSpec(investfly.models.strategy.OptionStructureSpec):

Long out-of-the-money call and put structure.

@dataclass
class ShortStrangleSpec(investfly.models.strategy.OptionStructureSpec):

Short out-of-the-money call and put structure.

@dataclass
class LongCallCalendarSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Call calendar spread using near and far expirations.

@dataclass
class LongPutCalendarSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Put calendar spread using near and far expirations.

@dataclass
class LongCallDiagonalSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Call diagonal spread using different strikes and expirations.

@dataclass
class LongPutDiagonalSpreadSpec(investfly.models.strategy.OptionStructureSpec):

Put diagonal spread using different strikes and expirations.

@dataclass
class ProtectivePutSpec(investfly.models.strategy.OptionStructureSpec):

Underlying shares protected by a long put.

@dataclass
class CollarSpec(investfly.models.strategy.OptionStructureSpec):

Underlying shares protected by a put and financed by a short call.

@dataclass
class IronButterflySpec(investfly.models.strategy.OptionStructureSpec):

Four-leg iron butterfly centered on a shared short strike.

@dataclass
class LongCallCondorSpec(investfly.models.strategy.OptionStructureSpec):

Four-strike long call condor structure.

@dataclass
class CustomComboSpec(investfly.models.strategy.OptionStructureSpec):

Custom multi-leg option structure assembled from explicit leg specifications.

@dataclass
class FutureContractSelector:

Selects a listed futures contract after a product-level signal triggers.

class InstrumentSelectionSpec:

Base contract for selecting the instrument opened by a strategy.

class InstrumentSelectionType(builtins.str, enum.Enum):

Available runtime instrument-selection modes.

@dataclass
class DirectInstrumentSelection(investfly.models.strategy.InstrumentSelectionSpec):

Open the selected security without a derivative transformation.

@dataclass
class FutureContractSelection(investfly.models.strategy.InstrumentSelectionSpec):

Select a futures contract from the target product at execution time.

@dataclass
class OptionStructureSelection(investfly.models.strategy.InstrumentSelectionSpec):

Select the contracts needed for an option structure at execution time.