investfly.models.strategy
Strategy execution models and related utilities.
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
configdictionary in the constructor. - State Management: Strategies can maintain persistent state across executions
by using
self.statedirectly. The execution engine automatically persists and restoresself.statebetween 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:
getSecurityUniverseSelector(): Define which securities the strategy evaluates.
Optional Implementation
Subclasses may override:
onMarketData(): Handle market data updates (requires@data_triggerdecorator).- 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 toself.statedirectly. - 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))
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
dataServiceandcontextattributes are set by the execution engine before strategy methods are called. They should not be set manually in the constructor.
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")
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}")
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.
Return a persisted strategy value, or default when the key is absent.
Store a value that Investfly persists between strategy callbacks.
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)
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 usingself.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
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
@scheduledto run distinct jobs at distinct schedule patterns.- The
eventargument 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
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.
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 )
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.
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.
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.
List active futures contracts for a product, sorted by ascending expiry.
List broker/vendor-listed expirations for live option contract selection.
Return the listed option chain for one underlying and expiration.
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.
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
StandardIndicatorIdenum: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
indicatorIdparameter is a string type (notStandardIndicatorIdenum) to support both standard and custom indicators.- When using standard indicators, the string value must exactly match one of the
StandardIndicatorIdenum values (seeinvestfly.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
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.
- securityFilterExpression: SecurityFilterExpression with filter criteria.
The expression can include filters on:
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}")
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()
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.
Resolve a selection specification to ordered securities.
Resolve and score securities using a ranked selection specification.
Evaluate a filter expression for one security.
Evaluate strategy guards and return their decisions for the requested scope.
Plan entry orders with runtime-managed selection, sizing, and execution.
Plan orders that allocate a budget across a group of securities.
Plan closing orders for the supplied open positions.
Plan orders that move the portfolio toward a target basket.
Plan scale-in orders for positions affected by the latest market update.
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.
A selected security and its ranking score.
Request runtime-managed instrument selection, sizing, and order construction.
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.
Describe target selection, weighting, and replacement for a rebalance.
How a rebalance budget is distributed among selected securities.
How a rebalance handles securities that leave the target set.
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.
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.
How a condition treats transitions at its threshold.
One entry condition paired with execution settings.
Collection of entry rules and their conflict policy.
Instrument selection, sizing, and order settings for opening a position.
One exit condition and the position-closing behavior it activates.
Collection of exit rules evaluated for open positions.
Measurement used to define a profit target.
Ordered profit-taking tiers for progressively closing a position.
One profit threshold and the percentage of a position to close.
Measurement used to locate a fixed protective stop.
Threshold value for a fixed stop rule.
Protective stop fixed at a price or distance from entry.
Measurement used for a trailing-stop distance.
Average True Range settings used by volatility-based distances.
Distance maintained by a trailing protective stop.
Protective stop that follows favorable price movement.
Reference point used by a session-time trigger.
Trigger at a time relative to market-session open or close.
Execution policy for runtime-managed protective orders.
Available fixed and trailing stop specifications.
Fixed or trailing protective stop definition.
Condition that becomes true after a profit tier is reached.
Events that can activate a protection adjustment.
Event condition that activates a protection adjustment.
Replacement protective stop activated by a later trigger.
Profit targets, stops, adjustments, and maximum holding period for a position.
Ways to anchor a monthly schedule within the month.
Calendar used to decide which days a schedule may run.
Invocation details passed to a scheduled strategy callback.
A discovered callback together with its validated schedule.
Whether a callback runs before, after, or on its reference event.
Market or instrument events usable by event-relative schedules.
Supported recurrence patterns for a scheduled callback.
Intraday time window, expressed as HH:MM local market times.
Recurrence definition used by scheduled().
Prefer the named factory methods such as daily(), weekly(), or
eventRelative(); they populate the fields required by each pattern.
Create a one-minute schedule within an optional intraday window.
Create a five-minute schedule within an optional intraday window.
Create a fifteen-minute schedule within an optional intraday window.
Create a thirty-minute schedule within an optional intraday window.
Create a repeating minute interval on the selected days and time window.
Create an hourly schedule on the selected days and time window.
Create a once-per-day schedule at time in HH:MM format.
Create a weekly schedule on one or more weekdays.
Create a schedule relative to a market or instrument event.
Weekday values accepted by weekly and custom-day schedules.
A validated schedule paired with a workflow intent and guard policy.
High-level behavior performed by a scheduled workflow.
Typed intent executed by a scheduled strategy job.
Selection and execution settings for a scheduled portfolio rotation.
Target portfolio weight for one security.
Target basket, weights, and tolerance for scheduled rebalancing.
How recurring contributions are expressed.
Cash or percentage budget contributed by a recurring entry.
Targets and contribution settings for recurring multi-asset entries.
One target and allocation in a recurring multi-asset entry.
Contribution and execution settings for a recurring single-asset entry.
Ordered strategy guards and their combination behavior.
Base contract for a pre-execution strategy guard.
Kinds of pre-execution strategy guards.
Execution scopes in which a strategy guard may be evaluated.
Identifier, scope, and behavior shared by all strategy guards.
Guard that allows execution only in a configured market regime.
Guard that allows or blocks execution within a configured time window.
How a time guard interprets its configured window.
Guard that enforces a portfolio margin threshold.
Market-regime guard tailored to continuously traded crypto markets.
Result of evaluating one strategy guard.
Supported interpretations of a market-regime condition.
Time horizon used to evaluate market regime.
Selection criteria for currently open portfolio positions.
Quantity and order settings for closing selected positions.
Source from which a security selection obtains candidates.
Candidate universe and filter used to select securities.
Expression used to score a security for ranking.
Security selection with scoring, ordering, and result limits.
Criteria for selecting an existing option group.
Ordered lifecycle rules evaluated for an option strategy.
Named option structure available to lifecycle rules.
A trigger and ordered actions for one option lifecycle transition.
Trigger based on days remaining until option expiration.
Trigger based on a measured option-group metric.
Trigger based on a previously recorded lifecycle outcome.
Composite trigger that requires every child condition to match.
Lifecycle action that closes selected option legs.
Lifecycle action that rolls selected legs to new contracts.
Lifecycle action that opens an additional option structure.
Lifecycle action that liquidates the associated underlying position.
Lifecycle action that marks the option structure complete.
Option-group metric available to lifecycle triggers.
Lifecycle outcome recorded for a completed option structure.
Timing used when matching a lifecycle outcome.
Subset of an option group affected by a lifecycle action.
Credit or debit constraint applied to a roll action.
When a scheduled entry becomes eligible again after execution.
Profit, loss, and holding-period risk controls for an option group.
Schedule, structure, and rearming behavior for option entries.
Action taken when a scheduled option entry is evaluated.
Source used to construct a scheduled option entry.
Measurement used by an option-group profit threshold.
Profit threshold that can close an option group.
Measurement used by an option-group loss threshold.
Loss threshold that can close an option group.
Method used to distribute capital among selected securities.
Allocation mode and optional explicit target weights.
Units used to express an entry position size.
Requested position size and its measurement mode.
Action taken when a new entry conflicts with an existing position.
Policy for resolving simultaneous or conflicting entry signals.
Behavior when an entry targets a security already represented in the portfolio.
Action applied to an existing target position.
Policy for entries that resolve to an existing target instrument.
Maximum exposure allowed for one position.
Unit used to measure a price move for scaling rules.
Reference price used to measure a scaling move.
Required favorable or adverse move before a scaling action.
How a scale-in order derives its quantity.
Sizing and execution settings for one scale-in action.
Scale-in rule activated by repeated entry signals.
Scale-in rule for positions moving favorably.
Safety limits for averaging into a losing position.
Scale-in rule for positions moving adversely.
Combined repeat-signal, winner, and loser scale-in behavior.
Runtime-managed exits and scaling behavior for open positions.
Portfolio-wide position count, exposure, and buying-power limits.
Portfolio exposure limits for grouped option positions.
Time-in-force choices for strategy orders.
Order types available to declarative strategy execution.
Unit used to offset a generated limit price.
Adjustment applied when deriving a strategy limit price.
Order type, duration, and limit-price behavior for strategy execution.
Elapsed strategy time; BARS means count multiplied by an explicit fixed interval.
Units supported by strategy duration values.
Expiration and roll behavior for futures positions.
Policy used to roll a futures position before expiration.
Asset-specific lifecycle behavior for runtime-managed positions.
Type definition for data trigger information
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): ...
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.
Stored strategy identity, configuration, source, and deployment metadata.
Whether a stored strategy is declarative or implemented by Python code.
Timestamped message emitted by a deployed strategy.
Severity of a strategy deployment log message.
Lifecycle state of a submitted backtest.
Outcome status reported by a completed backtest.
Summary and output references for a strategy backtest.
Investfly-maintained security lists available as strategy universes.
User-supplied symbols grouped by security type.
Supported sources for a strategy security universe.
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 approach used to specify the stocks. Depending on the universeType, one of the attribute below must be specified
Standard Symbol List (i.e SP500, SP100). Required if universeType is set to STANDARD_LIST
Fundamental conditions used to select a security universe.
One fundamental field comparison in a financial query.
Comparison operators used by financial screening conditions.
Stock market sectors for fundamental queries.
Composable boolean expression evaluated for a security.
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.
Market-data source used by a strategy expression.
Kinds of data available to strategy triggers and expressions.
Unit attached to a constant in a strategy expression.
Reference to a market-data field or constant value.
Ascending or descending query result ordering.
Expression and direction used to sort market-query results.
Filter, sort, and result limit for a market-data query.
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.
Whether an option leg opens or closes a long or short position.
Semantic role of a leg within a multi-leg option structure.
Specification for a single leg of an option strategy. See Java OptionLegSpec for the canonical contract; both languages share the same JSON shape.
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.
How an option strike is selected relative to the underlying market.
Lower strike bound applied during option contract selection.
Base contract for a runtime-selected option structure.
One long call selected by expiration and strike rules.
One long put selected by expiration and strike rules.
Covered call composed of underlying shares and a short call.
Cash-secured short put structure.
Bullish put credit spread with short and protective long puts.
Bearish call credit spread with short and protective long calls.
Bullish call debit spread with long and short calls.
Bearish put debit spread with long and short puts.
Four-leg iron condor with call and put credit spreads.
Three-strike call butterfly structure.
Three-strike put butterfly structure.
Long call and put at the same strike and expiration.
Short call and put at the same strike and expiration.
Long out-of-the-money call and put structure.
Short out-of-the-money call and put structure.
Call calendar spread using near and far expirations.
Put calendar spread using near and far expirations.
Call diagonal spread using different strikes and expirations.
Put diagonal spread using different strikes and expirations.
Underlying shares protected by a long put.
Underlying shares protected by a put and financed by a short call.
Four-leg iron butterfly centered on a shared short strike.
Four-strike long call condor structure.
Custom multi-leg option structure assembled from explicit leg specifications.
Selects a listed futures contract after a product-level signal triggers.
Base contract for selecting the instrument opened by a strategy.
Available runtime instrument-selection modes.
Open the selected security without a derivative transformation.
Select a futures contract from the target product at execution time.
Select the contracts needed for an option structure at execution time.