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_PORTFOLIO, 80.0),
            OrderSpec(),
            DirectInstrumentSelection(),
        )
        return self.services.planAllocationOrders(AllocationPlan(updatedSecurities, execution))
TradingStrategy(config: Optional[Dict[str, Any]] = None)

Initialize strategy with optional configuration.

Args: 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.

config
state: Dict[str, Union[int, float, bool, str, List[Union[int, float, bool, str]], Dict[str, Any], NoneType]]
dataService: StrategyDataService
services: StrategyServices
def setDataService( self, dataService: StrategyDataService) -> None:

Set the data service for accessing market data and indicators.

This method is called by the execution engine to inject the data service into the strategy instance. The data service provides access to:

  • Indicator computation (SMA, RSI, MACD, etc.)
  • Market data (quotes, bars, financials, news)

Args: dataService: The strategy data service instance. This is a singleton service shared across all strategy executions.

Note: This method is typically called automatically by the execution engine. Strategies should not call this method directly.

def setContext( self, context: StrategyExecutionContext) -> None:

Set the execution context for the strategy instance.

This method is called by the execution engine to inject the execution context into the strategy instance. The context contains:

  • Portfolio: Current portfolio state with positions and balances
  • Universe securities: List of securities in the strategy's trading universe

Args: context: The execution context containing portfolio and universe data.

Note: This method is typically called automatically by the execution engine. Strategies should not call this method directly.

def setServices( self, services: StrategyServices) -> None:

Inject the runtime implementation of the public strategy helper contract.

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) -> Union[int, float, bool, str, List[Union[int, float, bool, str]], Dict[str, Any], NoneType]:

Get the state value for the given key.

Args: key: The key to get the state value for.

Returns: The state value for the given key.

def getState( self, key: str, default: Union[int, float, bool, str, List[Union[int, float, bool, str]], Dict[str, Any], NoneType] = None) -> Union[int, float, bool, str, List[Union[int, float, bool, str]], Dict[str, Any], NoneType]:
def setState( self, key: str, value: Union[int, float, bool, str, List[Union[int, float, bool, str]], Dict[str, Any], NoneType]) -> None:
def deleteState(self, key: str) -> None:
@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.

Args: 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 through getScheduledCallbacks() 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 getScheduledCallbacks( self) -> List[ScheduledCallback]:

Return all scheduled callbacks exposed by this strategy instance.

def getScheduledCallback( self, callbackName: str) -> ScheduledCallback:
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 injected into strategy instances via TradingStrategy.setDataService().

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
)
ALL_BARS: int = -1
DEFAULT_NUM_BARS: int = 100
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.

Args: 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.

Args: 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.

Args: 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.

Args: 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.

Args: 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.

Args: 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
)
strategy.setContext(context)
Strategies access context data via convenience methods:
portfolio = self.getPortfolio()
universe = self.getUniverseSecurities()
StrategyExecutionContext( portfolio: investfly.models.portfolio.Portfolio, universeSecurities: List[investfly.models.marketdata.Security], currentTime: datetime.datetime, openOptionGroups: List[investfly.models.portfolio.OptionPositionGroup] = <factory>)
universeSecurities: List[investfly.models.marketdata.Security]
currentTime: datetime.datetime
StrategyState = typing.Dict[str, typing.Union[int, float, bool, str, typing.List[typing.Union[int, float, bool, str]], typing.Dict[str, typing.Any], NoneType]]
StateValue = typing.Union[int, float, bool, str, typing.List[typing.Union[int, float, bool, str]], typing.Dict[str, typing.Any], NoneType]
PrimitiveStateValue = typing.Union[int, float, bool, str]
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]:
@abstractmethod
def rankSecurities( self, selection: RankedSecuritySelection) -> List[RankedSecurity]:
@abstractmethod
def evaluateCondition( self, condition: SecurityFilterExpression, security: investfly.models.marketdata.Security) -> bool:
@abstractmethod
def evaluateGuards( self, policy: GuardPolicy, scope: GuardScope = <GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>, targetKey: str | None = None) -> List[GuardDecision]:
@abstractmethod
def planOpenOrders( self, request: OpenOrderRequest) -> List[investfly.models.portfolio.TradeOrder]:
@abstractmethod
def planAllocationOrders( self, plan: AllocationPlan) -> List[investfly.models.portfolio.TradeOrder]:
@abstractmethod
def planCloseOrders( self, positions: List[investfly.models.portfolio.OpenPosition], closeSpec: ClosePositionSpec | None = None) -> List[investfly.models.portfolio.TradeOrder]:
@abstractmethod
def planRebalanceOrders( self, plan: RebalancePlan) -> List[investfly.models.portfolio.TradeOrder]:
@abstractmethod
def planScalingOrders( self, updatedSecurities: List[investfly.models.marketdata.Security]) -> List[investfly.models.portfolio.TradeOrder]:
@abstractmethod
def drainWarnings(self) -> List[str]:
@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.

CustomStrategyPolicy( assetType: investfly.models.marketdata.SecurityType, positionManagement: Optional[PositionManagementRules] = None, assetLifecycle: Optional[investfly.models.strategy.StrategyConfig.AssetLifecycleRules] = None, portfolioLimits: Optional[PortfolioLimits] = None)
positionManagement: Optional[PositionManagementRules] = None
portfolioLimits: Optional[PortfolioLimits] = None
def validate(self) -> None:
def protectiveExitPlan( self) -> ProtectiveExitPlan | None:
@dataclass(frozen=True)
class RankedSecurity:
RankedSecurity( security: investfly.models.marketdata.Security, score: float)
score: float
@dataclass
class OpenOrderRequest:

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

OpenOrderRequest( security: investfly.models.marketdata.Security, execution: OpenExecutionSettings, side: investfly.models.portfolio.PositionType = LONG, allowAddToExisting: bool = False, existingTargetPolicy: Optional[ExistingTargetPolicy] = None)
allowAddToExisting: bool = False
existingTargetPolicy: Optional[ExistingTargetPolicy] = None
@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.

AllocationPlan( securities: List[investfly.models.marketdata.Security], execution: OpenExecutionSettings, side: investfly.models.portfolio.PositionType = LONG, allowAddToExisting: bool = False)
allowAddToExisting: bool = False
@dataclass
class RebalancePlan:
RebalancePlan( targetSecurities: RankedSecuritySelection, allocationBudget: PositionSizeSpec, targetWeightMode: TargetWeightMode = <TargetWeightMode.EQUAL_WEIGHT: 'EQUAL_WEIGHT'>, replacementPolicy: ReplacementPolicy = <ReplacementPolicy.REPLACE_DROPPED: 'REPLACE_DROPPED'>, rebalanceTolerance: Optional[float] = 0.05, targetWeights: Optional[List[TargetWeightSpec]] = None)
targetSecurities: RankedSecuritySelection
allocationBudget: PositionSizeSpec
targetWeightMode: TargetWeightMode = <TargetWeightMode.EQUAL_WEIGHT: 'EQUAL_WEIGHT'>
replacementPolicy: ReplacementPolicy = <ReplacementPolicy.REPLACE_DROPPED: 'REPLACE_DROPPED'>
rebalanceTolerance: Optional[float] = 0.05
targetWeights: Optional[List[TargetWeightSpec]] = None
class TargetWeightMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

EQUAL_WEIGHT = <TargetWeightMode.EQUAL_WEIGHT: 'EQUAL_WEIGHT'>
SCORE_WEIGHTED = <TargetWeightMode.SCORE_WEIGHTED: 'SCORE_WEIGHTED'>
class ReplacementPolicy(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

REPLACE_DROPPED = <ReplacementPolicy.REPLACE_DROPPED: 'REPLACE_DROPPED'>
ADD_ONLY = <ReplacementPolicy.ADD_ONLY: 'ADD_ONLY'>
def buildProtectiveExitPlan( targetProfitPct: float | None = None, stopLossPct: float | None = None, trailingStopPct: float | None = None, maxHold: StrategyDuration | None = None) -> ProtectiveExitPlan:

Construct the common protective-exit DTO; the runtime owns its evaluation.

@dataclass
class StrategyConfig:
StrategyConfig( assetType: investfly.models.marketdata.SecurityType, assetLifecycle: Optional[investfly.models.strategy.StrategyConfig.AssetLifecycleRules] = None, entries: EntryRules = <factory>, positionManagement: Optional[PositionManagementRules] = <factory>, scheduledJobs: List[ScheduledJob] = <factory>, portfolioLimits: Optional[PortfolioLimits] = <factory>)
entries: EntryRules
positionManagement: Optional[PositionManagementRules]
scheduledJobs: List[ScheduledJob]
portfolioLimits: Optional[PortfolioLimits]
def entryUniverses( self) -> List[SecurityUniverseSelector]:
def firstEntryUniverse( self) -> Optional[SecurityUniverseSelector]:
def openPositions(self) -> List[OpenPositionSpec]:
def hasEnabledLogic(self) -> bool:
def firstEntryRule(self) -> Optional[EntryRule]:
def firstSignalExit(self) -> Optional[ExitRule]:
def firstOpenExpression( self) -> Optional[SecurityFilterExpression]:
def firstCloseExpression( self) -> Optional[SecurityFilterExpression]:
def firstOpenPosition( self) -> Optional[OpenPositionSpec]:
def securityExpressions( self) -> List[SecurityFilterExpression]:
def marketDataSecurityExpressions( self) -> List[SecurityFilterExpression]:
def optionOpenExecutions( self) -> List[OpenExecutionSettings]:
def validate(self) -> None:
def validateForTradedSecurityType( self, tradedSecurityType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> StrategyConfig:
class EdgeMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

RISING_EDGE = <EdgeMode.RISING_EDGE: 'RISING_EDGE'>
WHEN_TRUE = <EdgeMode.WHEN_TRUE: 'WHEN_TRUE'>
@dataclass
class EntryRule:
EntryRule( edgeMode: EdgeMode = <EdgeMode.RISING_EDGE: 'RISING_EDGE'>, condition: SecurityFilterExpression = None, runWhen: Optional[GuardPolicy] = None, existingPositionPolicy: Optional[EntryExistingPositionPolicy] = <factory>)
edgeMode: EdgeMode = <EdgeMode.RISING_EDGE: 'RISING_EDGE'>
condition: SecurityFilterExpression = None
runWhen: Optional[GuardPolicy] = None
existingPositionPolicy: Optional[EntryExistingPositionPolicy]
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> EntryRule:
@dataclass
class EntryRules:
EntryRules( universe: Optional[SecurityUniverseSelector] = None, execution: Optional[OpenExecutionSettings] = None, longEntry: Optional[EntryRule] = None, shortEntry: Optional[EntryRule] = None, optionEntry: Optional[EntryRule] = None)
universe: Optional[SecurityUniverseSelector] = None
execution: Optional[OpenExecutionSettings] = None
longEntry: Optional[EntryRule] = None
shortEntry: Optional[EntryRule] = None
optionEntry: Optional[EntryRule] = None
def positionEntries(self) -> List[EntryRule]:
def allEntries(self) -> List[EntryRule]:
def hasConfiguredEntry(self) -> bool:
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> EntryRules:
@dataclass
class OpenExecutionSettings:
OpenExecutionSettings( positionSize: Optional[PositionSizeSpec] = None, orderSpec: Optional[OrderSpec] = None, instrumentSelection: Optional[InstrumentSelectionSpec] = None)
positionSize: Optional[PositionSizeSpec] = None
orderSpec: Optional[OrderSpec] = None
instrumentSelection: Optional[InstrumentSelectionSpec] = None
futureContractSelector: Optional[FutureContractSelector]
optionStructure: Optional[OptionStructureSpec]
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[OpenExecutionSettings]:
@dataclass
class ExitRule:
ExitRule( edgeMode: EdgeMode = <EdgeMode.WHEN_TRUE: 'WHEN_TRUE'>, condition: SecurityFilterExpression = None, closePosition: Optional[ClosePositionSpec] = None)
edgeMode: EdgeMode = <EdgeMode.WHEN_TRUE: 'WHEN_TRUE'>
condition: SecurityFilterExpression = None
closePosition: Optional[ClosePositionSpec] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ExitRule:
@dataclass
class ExitRules:
ExitRules( signalExit: Optional[ExitRule] = None, protectiveExits: Optional[ProtectiveExitPlan] = None)
signalExit: Optional[ExitRule] = None
protectiveExits: Optional[ProtectiveExitPlan] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> ExitRules:
class ProfitThresholdType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT_GAIN = <ProfitThresholdType.PERCENT_GAIN: 'PERCENT_GAIN'>
ABSOLUTE_PNL = <ProfitThresholdType.ABSOLUTE_PNL: 'ABSOLUTE_PNL'>
PRICE = <ProfitThresholdType.PRICE: 'PRICE'>
TICKS = <ProfitThresholdType.TICKS: 'TICKS'>
POINTS = <ProfitThresholdType.POINTS: 'POINTS'>
PIPS = <ProfitThresholdType.PIPS: 'PIPS'>
R_MULTIPLE = <ProfitThresholdType.R_MULTIPLE: 'R_MULTIPLE'>
@dataclass
class StagedProfitTargets:
StagedProfitTargets( type: ProfitThresholdType, tiers: List[ProfitTargetTier] = <factory>)
tiers: List[ProfitTargetTier]
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def percentGain( threshold: float, closePercent: float) -> StagedProfitTargets:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> StagedProfitTargets:
@dataclass
class ProfitTargetTier:
ProfitTargetTier(threshold: float, closePercent: Optional[float] = None)
threshold: float
closePercent: Optional[float] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ProfitTargetTier:
class FixedStopThresholdType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT_FROM_ENTRY = <FixedStopThresholdType.PERCENT_FROM_ENTRY: 'PERCENT_FROM_ENTRY'>
ABSOLUTE_PNL = <FixedStopThresholdType.ABSOLUTE_PNL: 'ABSOLUTE_PNL'>
PRICE = <FixedStopThresholdType.PRICE: 'PRICE'>
TICKS_FROM_ENTRY = <FixedStopThresholdType.TICKS_FROM_ENTRY: 'TICKS_FROM_ENTRY'>
POINTS_FROM_ENTRY = <FixedStopThresholdType.POINTS_FROM_ENTRY: 'POINTS_FROM_ENTRY'>
PIPS_FROM_ENTRY = <FixedStopThresholdType.PIPS_FROM_ENTRY: 'PIPS_FROM_ENTRY'>
ATR_MULTIPLE_FROM_ENTRY = <FixedStopThresholdType.ATR_MULTIPLE_FROM_ENTRY: 'ATR_MULTIPLE_FROM_ENTRY'>
@dataclass
class FixedStopThreshold:
FixedStopThreshold( type: FixedStopThresholdType, value: float, atrParams: Optional[AtrParams] = None)
value: float
atrParams: Optional[AtrParams] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None, replacement: bool = False) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> FixedStopThreshold:
@dataclass
class FixedStopRule:
FixedStopRule( threshold: FixedStopThreshold)
threshold: FixedStopThreshold
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None, replacement: bool = False) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> FixedStopRule:
class TrailingStopDistanceType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT = <TrailingStopDistanceType.PERCENT: 'PERCENT'>
ATR_MULTIPLE = <TrailingStopDistanceType.ATR_MULTIPLE: 'ATR_MULTIPLE'>
PRICE = <TrailingStopDistanceType.PRICE: 'PRICE'>
TICKS = <TrailingStopDistanceType.TICKS: 'TICKS'>
POINTS = <TrailingStopDistanceType.POINTS: 'POINTS'>
@dataclass
class AtrParams:
AtrParams( period: int = 14, barInterval: investfly.models.marketdata.BarInterval = <BarInterval.ONE_DAY: 'ONE_DAY'>)
period: int = 14
barInterval: investfly.models.marketdata.BarInterval = <BarInterval.ONE_DAY: 'ONE_DAY'>
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> AtrParams:
@dataclass
class TrailingStopDistance:
TrailingStopDistance( type: TrailingStopDistanceType, value: float, atrParams: Optional[AtrParams] = None)
value: float
atrParams: Optional[AtrParams] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> TrailingStopDistance:
@dataclass
class TrailingStopRule:
TrailingStopRule( distance: TrailingStopDistance)
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> TrailingStopRule:
class SessionTimeTriggerType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

AT_TIME = <SessionTimeTriggerType.AT_TIME: 'AT_TIME'>
BEFORE_SESSION_CLOSE = <SessionTimeTriggerType.BEFORE_SESSION_CLOSE: 'BEFORE_SESSION_CLOSE'>
@dataclass
class SessionTimeTrigger:
SessionTimeTrigger( type: SessionTimeTriggerType = <SessionTimeTriggerType.BEFORE_SESSION_CLOSE: 'BEFORE_SESSION_CLOSE'>, time: Optional[str] = None, offsetBeforeClose: Optional[investfly.models.common.TimeDelta] = None, timeZonePolicy: Optional[str] = 'MARKET')
time: Optional[str] = None
offsetBeforeClose: Optional[investfly.models.common.TimeDelta] = None
timeZonePolicy: Optional[str] = 'MARKET'
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> SessionTimeTrigger:
class ProtectiveExecutionPolicy(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

BEST_AVAILABLE = <ProtectiveExecutionPolicy.BEST_AVAILABLE: 'BEST_AVAILABLE'>
BROKER_NATIVE_REQUIRED = <ProtectiveExecutionPolicy.BROKER_NATIVE_REQUIRED: 'BROKER_NATIVE_REQUIRED'>
INVESTFLY_MANAGED_ONLY = <ProtectiveExecutionPolicy.INVESTFLY_MANAGED_ONLY: 'INVESTFLY_MANAGED_ONLY'>
class StopSpecType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

FIXED = <StopSpecType.FIXED: 'FIXED'>
TRAILING = <StopSpecType.TRAILING: 'TRAILING'>
@dataclass
class StopSpec:
StopSpec( type: StopSpecType = <StopSpecType.FIXED: 'FIXED'>, fixed: Optional[FixedStopRule] = None, trailing: Optional[TrailingStopRule] = None)
type: StopSpecType = <StopSpecType.FIXED: 'FIXED'>
fixed: Optional[FixedStopRule] = None
trailing: Optional[TrailingStopRule] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def validateReplacement( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fixedStop( stopLoss: FixedStopRule) -> StopSpec:
@staticmethod
def trailingStop( trailingStop: TrailingStopRule) -> StopSpec:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> StopSpec:
@dataclass
class ProfitLevelCondition:
ProfitLevelCondition( type: ProfitThresholdType = <ProfitThresholdType.PERCENT_GAIN: 'PERCENT_GAIN'>, value: float = 0.0)
value: float = 0.0
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ProfitLevelCondition:
class ProtectionTriggerType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

TARGET_FILLED = <ProtectionTriggerType.TARGET_FILLED: 'TARGET_FILLED'>
PROFIT_REACHED = <ProtectionTriggerType.PROFIT_REACHED: 'PROFIT_REACHED'>
TIME_ELAPSED = <ProtectionTriggerType.TIME_ELAPSED: 'TIME_ELAPSED'>
@dataclass
class ProtectionTrigger:
ProtectionTrigger( type: ProtectionTriggerType, targetNumber: Optional[int] = None, profitLevel: Optional[ProfitLevelCondition] = None, timeElapsed: Optional[StrategyDuration] = None)
targetNumber: Optional[int] = None
profitLevel: Optional[ProfitLevelCondition] = None
timeElapsed: Optional[StrategyDuration] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None, profitTargets: Optional[StagedProfitTargets] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ProtectionTrigger:
@dataclass
class ProtectionAdjustment:
ProtectionAdjustment( id: str, trigger: ProtectionTrigger, replacementStop: StopSpec)
id: str
replacementStop: StopSpec
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None, profitTargets: Optional[StagedProfitTargets] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ProtectionAdjustment:
@dataclass
class ProtectiveExitPlan:
ProtectiveExitPlan( executionPolicy: ProtectiveExecutionPolicy = <ProtectiveExecutionPolicy.BEST_AVAILABLE: 'BEST_AVAILABLE'>, initialProtection: Optional[StopSpec] = None, profitTargets: Optional[StagedProfitTargets] = None, protectionAdjustments: List[ProtectionAdjustment] = <factory>, maxHold: Optional[StrategyDuration] = None, sessionClose: Optional[SessionTimeTrigger] = None)
initialProtection: Optional[StopSpec] = None
profitTargets: Optional[StagedProfitTargets] = None
protectionAdjustments: List[ProtectionAdjustment]
maxHold: Optional[StrategyDuration] = None
sessionClose: Optional[SessionTimeTrigger] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ProtectiveExitPlan:
class MonthlyScheduleAnchor(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

FIRST_TRADING = <MonthlyScheduleAnchor.FIRST_TRADING: 'first_trading'>
LAST_TRADING = <MonthlyScheduleAnchor.LAST_TRADING: 'last_trading'>
FIRST_CALENDAR = <MonthlyScheduleAnchor.FIRST_CALENDAR: 'first_calendar'>
NTH_CALENDAR_DAY = <MonthlyScheduleAnchor.NTH_CALENDAR_DAY: 'nth_calendar_day'>
NTH_WEEKDAY = <MonthlyScheduleAnchor.NTH_WEEKDAY: 'nth_weekday'>
class ScheduleDayMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

TRADING = <ScheduleDayMode.TRADING: 'trading'>
WEEKDAYS = <ScheduleDayMode.WEEKDAYS: 'weekdays'>
EVERYDAY = <ScheduleDayMode.EVERYDAY: 'everyday'>
@dataclass
class ScheduleEvent:
ScheduleEvent( callbackName: str, schedule: TriggerSchedule, scheduledTime: datetime.datetime, actualTime: datetime.datetime, isBacktest: bool = False)
callbackName: str
schedule: TriggerSchedule
scheduledTime: datetime.datetime
actualTime: datetime.datetime
isBacktest: bool = False
@dataclass
class ScheduledCallback:
ScheduledCallback( name: str, schedule: TriggerSchedule, callback: Callable[[ScheduleEvent], Any])
name: str
schedule: TriggerSchedule
callback: Callable[[ScheduleEvent], Any]
class ScheduleEventTiming(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

BEFORE = <ScheduleEventTiming.BEFORE: 'before'>
AFTER = <ScheduleEventTiming.AFTER: 'after'>
ON = <ScheduleEventTiming.ON: 'on'>
class ScheduleEventType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

EXPIRY = <ScheduleEventType.EXPIRY: 'expiry'>
EXDIV = <ScheduleEventType.EXDIV: 'exdiv'>
EARNINGS = <ScheduleEventType.EARNINGS: 'earnings'>
FIRSTNOTICE = <ScheduleEventType.FIRSTNOTICE: 'firstnotice'>
ROLLOVER = <ScheduleEventType.ROLLOVER: 'rollover'>
class SchedulePattern(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

INTERVAL = <SchedulePattern.INTERVAL: 'interval'>
HOURLY = <SchedulePattern.HOURLY: 'hourly'>
DAILY = <SchedulePattern.DAILY: 'daily'>
WEEKLY = <SchedulePattern.WEEKLY: 'weekly'>
MONTHLY = <SchedulePattern.MONTHLY: 'monthly'>
EVENT_RELATIVE = <SchedulePattern.EVENT_RELATIVE: 'event_relative'>
@dataclass
class ScheduleWindow:
ScheduleWindow(fromTime: str = '09:30', to: str = '16:00')
fromTime: str = '09:30'
to: str = '16:00'
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ScheduleWindow:
@dataclass
class TriggerSchedule:
TriggerSchedule( pattern: SchedulePattern = <SchedulePattern.DAILY: 'daily'>, days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[List[Weekday]] = None, intervalMinutes: Optional[int] = None, window: Optional[ScheduleWindow] = None, time: Optional[str] = '09:30', anchor: Optional[MonthlyScheduleAnchor] = None, day: Optional[int] = None, n: Optional[int] = None, dayOfWeek: Optional[Weekday] = None, event: Optional[ScheduleEventType] = None, timing: Optional[ScheduleEventTiming] = None, offsetTradingDays: Optional[int] = None)
pattern: SchedulePattern = <SchedulePattern.DAILY: 'daily'>
days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>
daysOfWeek: Optional[List[Weekday]] = None
intervalMinutes: Optional[int] = None
window: Optional[ScheduleWindow] = None
time: Optional[str] = '09:30'
anchor: Optional[MonthlyScheduleAnchor] = None
day: Optional[int] = None
n: Optional[int] = None
dayOfWeek: Optional[Weekday] = None
event: Optional[ScheduleEventType] = None
timing: Optional[ScheduleEventTiming] = None
offsetTradingDays: Optional[int] = None
@staticmethod
def everyMinute( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def everyFiveMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def everyFifteenMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def everyThirtyMinutes( days: ScheduleDayMode = <ScheduleDayMode.TRADING: 'trading'>, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def interval( intervalMinutes: int = 15, days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def hourly( days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None, window: Optional[ScheduleWindow] = None) -> TriggerSchedule:
@staticmethod
def daily( time: str = '09:30', days: Optional[ScheduleDayMode] = <ScheduleDayMode.TRADING: 'trading'>, daysOfWeek: Optional[Sequence[Weekday]] = None) -> TriggerSchedule:
@staticmethod
def weekly( daysOfWeek: Union[Weekday, Sequence[Weekday]] = <Weekday.MON: 'MON'>, time: str = '09:30') -> TriggerSchedule:
@staticmethod
def monthly( day: int = 1, time: str = '09:30') -> TriggerSchedule:
@staticmethod
def firstTradingDayOfMonth( time: str = '09:30') -> TriggerSchedule:
@staticmethod
def lastTradingDayOfMonth( time: str = '09:30') -> TriggerSchedule:
@staticmethod
def eventRelative( event: ScheduleEventType, timing: ScheduleEventTiming = <ScheduleEventTiming.BEFORE: 'before'>, offsetTradingDays: Optional[int] = 1, time: str = '09:30') -> TriggerSchedule:
def validate(self) -> None:
def minimumIntervalMinutes(self) -> int:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> TriggerSchedule:
class Weekday(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

MON = <Weekday.MON: 'MON'>
TUE = <Weekday.TUE: 'TUE'>
WED = <Weekday.WED: 'WED'>
THU = <Weekday.THU: 'THU'>
FRI = <Weekday.FRI: 'FRI'>
SAT = <Weekday.SAT: 'SAT'>
SUN = <Weekday.SUN: 'SUN'>
def toIndex(self) -> int:
@staticmethod
def fromIndex(index: int) -> Weekday:
def discoverScheduledCallbacks( strategy: TradingStrategy) -> List[ScheduledCallback]:
@dataclass
class ScheduledJob:
ScheduledJob( id: Optional[str] = None, name: Optional[str] = None, schedule: TriggerSchedule = <factory>, runWhen: Optional[GuardPolicy] = None, intent: Optional[ScheduledWorkflowIntent] = None)
id: Optional[str] = None
name: Optional[str] = None
schedule: TriggerSchedule
runWhen: Optional[GuardPolicy] = None
intent: Optional[ScheduledWorkflowIntent] = None
def validate(self) -> None:
def validateForAsset( self, assetType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ScheduledJob:
class ScheduledWorkflowIntentFamily(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

RANKED_PORTFOLIO_ROTATION = <ScheduledWorkflowIntentFamily.RANKED_PORTFOLIO_ROTATION: 'RANKED_PORTFOLIO_ROTATION'>
TARGET_BASKET_REBALANCE = <ScheduledWorkflowIntentFamily.TARGET_BASKET_REBALANCE: 'TARGET_BASKET_REBALANCE'>
RECURRING_SINGLE_ASSET_ENTRY = <ScheduledWorkflowIntentFamily.RECURRING_SINGLE_ASSET_ENTRY: 'RECURRING_SINGLE_ASSET_ENTRY'>
RECURRING_MULTI_ASSET_ENTRY = <ScheduledWorkflowIntentFamily.RECURRING_MULTI_ASSET_ENTRY: 'RECURRING_MULTI_ASSET_ENTRY'>
SCHEDULED_OPTION_ENTRY = <ScheduledWorkflowIntentFamily.SCHEDULED_OPTION_ENTRY: 'SCHEDULED_OPTION_ENTRY'>
@dataclass
class ScheduledWorkflowIntent:
ScheduledWorkflowIntent( family: Optional[ScheduledWorkflowIntentFamily] = None, securityType: Optional[investfly.models.marketdata.SecurityType] = None, portfolioRotation: Optional[PortfolioRotationConfig] = None, targetBasketRebalance: Optional[TargetBasketRebalanceConfig] = None, recurringMultiAssetEntry: Optional[RecurringMultiAssetEntryConfig] = None, recurringSingleAssetEntry: Optional[RecurringSingleAssetEntryConfig] = None, scheduledOptionEntry: Optional[OptionScheduledEntryConfig] = None)
family: Optional[ScheduledWorkflowIntentFamily] = None
securityType: Optional[investfly.models.marketdata.SecurityType] = None
portfolioRotation: Optional[PortfolioRotationConfig] = None
targetBasketRebalance: Optional[TargetBasketRebalanceConfig] = None
recurringMultiAssetEntry: Optional[RecurringMultiAssetEntryConfig] = None
recurringSingleAssetEntry: Optional[RecurringSingleAssetEntryConfig] = None
scheduledOptionEntry: Optional[OptionScheduledEntryConfig] = None
def validate(self) -> None:
def validateForAsset( self, assetType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[ScheduledWorkflowIntent]:
@dataclass
class PortfolioRotationConfig:
PortfolioRotationConfig( universe: SecurityUniverseSelector = <factory>, rankScore: Optional[SecurityScoreExpression] = None, targetCount: int = 10, allocationBudget: Optional[PositionSizeSpec] = None)
rankScore: Optional[SecurityScoreExpression] = None
targetCount: int = 10
allocationBudget: Optional[PositionSizeSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> PortfolioRotationConfig:
@dataclass
class TargetWeightSpec:
TargetWeightSpec(symbol: str, weightPct: float)
symbol: str
weightPct: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> TargetWeightSpec:
@dataclass
class TargetBasketRebalanceConfig:
TargetBasketRebalanceConfig( targetWeights: List[TargetWeightSpec] = <factory>, driftTolerancePct: Optional[float] = 5.0, allocationBudget: Optional[PositionSizeSpec] = None)
targetWeights: List[TargetWeightSpec]
driftTolerancePct: Optional[float] = 5.0
allocationBudget: Optional[PositionSizeSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> TargetBasketRebalanceConfig:
class ContributionMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

FIXED_CASH = <ContributionMode.FIXED_CASH: 'FIXED_CASH'>
BUYING_POWER_PERCENT = <ContributionMode.BUYING_POWER_PERCENT: 'BUYING_POWER_PERCENT'>
CASH_SWEEP = <ContributionMode.CASH_SWEEP: 'CASH_SWEEP'>
@dataclass
class ContributionSpec:
ContributionSpec( mode: ContributionMode = <ContributionMode.FIXED_CASH: 'FIXED_CASH'>, amount: Optional[float] = 100.0, percent: Optional[float] = None, minCashReservePct: Optional[float] = None)
amount: Optional[float] = 100.0
percent: Optional[float] = None
minCashReservePct: Optional[float] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> ContributionSpec:
@dataclass
class RecurringMultiAssetEntryConfig:
RecurringMultiAssetEntryConfig( targets: List[RecurringMultiAssetEntryTarget] = <factory>, contribution: Optional[ContributionSpec] = None)
contribution: Optional[ContributionSpec] = None
def validateForAsset( self, assetType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> RecurringMultiAssetEntryConfig:
@dataclass
class RecurringMultiAssetEntryTarget:
RecurringMultiAssetEntryTarget( symbol: Optional[str] = None, side: investfly.models.portfolio.PositionType = LONG, weightPct: Optional[float] = None, execution: Optional[OpenExecutionSettings] = None)
symbol: Optional[str] = None
weightPct: Optional[float] = None
execution: Optional[OpenExecutionSettings] = None
def validateForAsset( self, assetType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> RecurringMultiAssetEntryTarget:
@dataclass
class RecurringSingleAssetEntryConfig:
RecurringSingleAssetEntryConfig( symbol: Optional[str] = None, side: investfly.models.portfolio.PositionType = LONG, execution: OpenExecutionSettings = <factory>)
symbol: Optional[str] = None
def validate(self) -> None:
def validateForAsset( self, assetType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> RecurringSingleAssetEntryConfig:
@dataclass
class GuardPolicy:
GuardPolicy( guards: List[StrategyGuard] = <factory>)
guards: List[StrategyGuard]
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None, scope: Optional[GuardScope] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[GuardPolicy]:
class StrategyGuard:
type: ClassVar[StrategyGuardType]
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[StrategyGuard]:
class StrategyGuardType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

MARKET_REGIME = <StrategyGuardType.MARKET_REGIME: 'MARKET_REGIME'>
TIME = <StrategyGuardType.TIME: 'TIME'>
PORTFOLIO_MARGIN = <StrategyGuardType.PORTFOLIO_MARGIN: 'PORTFOLIO_MARGIN'>
CRYPTO_MARKET_REGIME = <StrategyGuardType.CRYPTO_MARKET_REGIME: 'CRYPTO_MARKET_REGIME'>
class GuardScope(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

SCHEDULED_JOB = <GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>
ENTRY_RULE = <GuardScope.ENTRY_RULE: 'ENTRY_RULE'>
@dataclass(frozen=True)
class StrategyGuardMetadata:
StrategyGuardMetadata( assetTypes: FrozenSet[investfly.models.marketdata.SecurityType], scopes: FrozenSet[GuardScope])
scopes: FrozenSet[GuardScope]
STRATEGY_GUARD_METADATA = {<StrategyGuardType.MARKET_REGIME: 'MARKET_REGIME'>: StrategyGuardMetadata(assetTypes=frozenset({OPTION, ETF, STOCK}), scopes=frozenset({<GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>})), <StrategyGuardType.TIME: 'TIME'>: StrategyGuardMetadata(assetTypes=frozenset({OPTION, CRYPTO, FUTURE, ETF, FOREX, STOCK}), scopes=frozenset({<GuardScope.ENTRY_RULE: 'ENTRY_RULE'>})), <StrategyGuardType.PORTFOLIO_MARGIN: 'PORTFOLIO_MARGIN'>: StrategyGuardMetadata(assetTypes=frozenset({OPTION, FOREX, FUTURE}), scopes=frozenset({<GuardScope.ENTRY_RULE: 'ENTRY_RULE'>, <GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>})), <StrategyGuardType.CRYPTO_MARKET_REGIME: 'CRYPTO_MARKET_REGIME'>: StrategyGuardMetadata(assetTypes=frozenset({CRYPTO}), scopes=frozenset({<GuardScope.SCHEDULED_JOB: 'SCHEDULED_JOB'>}))}
@dataclass
class MarketRegimeGuard(investfly.models.strategy.StrategyGuard):
MarketRegimeGuard( referenceSecurity: investfly.models.marketdata.Security = <factory>, rule: MarketRegimeRule = <MarketRegimeRule.PRICE_ABOVE_SMA: 'PRICE_ABOVE_SMA'>, timeFrame: MarketRegimeTimeFrame = <MarketRegimeTimeFrame.DAY: 'DAY'>, lookbackPeriods: int = 200)
type: ClassVar[StrategyGuardType] = <StrategyGuardType.MARKET_REGIME: 'MARKET_REGIME'>
rule: MarketRegimeRule = <MarketRegimeRule.PRICE_ABOVE_SMA: 'PRICE_ABOVE_SMA'>
lookbackPeriods: int = 200
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[MarketRegimeGuard]:
@dataclass
class TimeGuard(investfly.models.strategy.StrategyGuard):
TimeGuard( startTime: Optional[str] = None, endTime: Optional[str] = None, days: Optional[ScheduleDayMode] = None, windowMode: Optional[TimeWindowMode] = None)
type: ClassVar[StrategyGuardType] = <StrategyGuardType.TIME: 'TIME'>
startTime: Optional[str] = None
endTime: Optional[str] = None
days: Optional[ScheduleDayMode] = None
windowMode: Optional[TimeWindowMode] = None
@staticmethod
def between( startTime: Optional[str] = '09:30', endTime: Optional[str] = '16:00', days: Optional[ScheduleDayMode] = None, windowMode: Optional[TimeWindowMode] = None) -> TimeGuard:
def resolvedWindowMode(self) -> TimeWindowMode:
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[TimeGuard]:
class TimeWindowMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

CUSTOM = <TimeWindowMode.CUSTOM: 'CUSTOM'>
RTH_ONLY = <TimeWindowMode.RTH_ONLY: 'RTH_ONLY'>
WEEKDAY_SESSION = <TimeWindowMode.WEEKDAY_SESSION: 'WEEKDAY_SESSION'>
@dataclass
class PortfolioMarginGuard(investfly.models.strategy.StrategyGuard):
PortfolioMarginGuard( minBuyingPowerPct: Optional[float] = None, minMarginBufferPct: Optional[float] = None, maxLeverage: Optional[float] = None)
type: ClassVar[StrategyGuardType] = <StrategyGuardType.PORTFOLIO_MARGIN: 'PORTFOLIO_MARGIN'>
minBuyingPowerPct: Optional[float] = None
minMarginBufferPct: Optional[float] = None
maxLeverage: Optional[float] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[PortfolioMarginGuard]:
@dataclass
class CryptoMarketRegimeGuard(investfly.models.strategy.MarketRegimeGuard):
CryptoMarketRegimeGuard( referenceSecurity: investfly.models.marketdata.Security = <factory>, rule: MarketRegimeRule = <MarketRegimeRule.PRICE_ABOVE_SMA: 'PRICE_ABOVE_SMA'>, timeFrame: MarketRegimeTimeFrame = <MarketRegimeTimeFrame.DAY: 'DAY'>, lookbackPeriods: int = 200)
type: ClassVar[StrategyGuardType] = <StrategyGuardType.CRYPTO_MARKET_REGIME: 'CRYPTO_MARKET_REGIME'>
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[CryptoMarketRegimeGuard]:
@dataclass
class GuardDecision:
GuardDecision( passed: bool, guardType: StrategyGuardType, scope: Optional[GuardScope] = None, reasonCode: Optional[str] = None, message: Optional[str] = None, targetKey: Optional[str] = None)
passed: bool
guardType: StrategyGuardType
scope: Optional[GuardScope] = None
reasonCode: Optional[str] = None
message: Optional[str] = None
targetKey: Optional[str] = None
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> GuardDecision:
class MarketRegimeRule(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PRICE_ABOVE_SMA = <MarketRegimeRule.PRICE_ABOVE_SMA: 'PRICE_ABOVE_SMA'>
PRICE_BELOW_SMA = <MarketRegimeRule.PRICE_BELOW_SMA: 'PRICE_BELOW_SMA'>
class MarketRegimeTimeFrame(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

DAY = <MarketRegimeTimeFrame.DAY: 'DAY'>
@dataclass
class OpenPositionSpec:
OpenPositionSpec( side: investfly.models.portfolio.PositionType = LONG, orderSpec: Optional[OrderSpec] = None, positionSize: Optional[PositionSizeSpec] = None, contractSelector: Optional[FutureContractSelector] = None, allowAddToExisting: Optional[bool] = None)
orderSpec: Optional[OrderSpec] = None
positionSize: Optional[PositionSizeSpec] = None
contractSelector: Optional[FutureContractSelector] = None
allowAddToExisting: Optional[bool] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OpenPositionSpec:
@dataclass
class ClosePositionSpec:
ClosePositionSpec( closePercent: Optional[float] = None, orderSpec: Optional[OrderSpec] = None)
closePercent: Optional[float] = None
orderSpec: Optional[OrderSpec] = None
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> ClosePositionSpec:
class SecuritySelectionSource(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

STRATEGY_UNIVERSE = <SecuritySelectionSource.STRATEGY_UNIVERSE: 'STRATEGY_UNIVERSE'>
CUSTOM_LIST = <SecuritySelectionSource.CUSTOM_LIST: 'CUSTOM_LIST'>
@dataclass
class SecuritySelection:
SecuritySelection( source: SecuritySelectionSource = <SecuritySelectionSource.STRATEGY_UNIVERSE: 'STRATEGY_UNIVERSE'>, customSymbols: Optional[Set[str]] = None, candidateFilter: Optional[SecurityFilterExpression] = None)
customSymbols: Optional[Set[str]] = None
candidateFilter: Optional[SecurityFilterExpression] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
def collectSecurityExpressions( self, result: List[SecurityFilterExpression]) -> None:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> SecuritySelection:
@dataclass
class SecurityScoreExpression:
SecurityScoreExpression( dataParams: Optional[Dict[str, DataParam]] = None, formula: List[str] = <factory>)
dataParams: Optional[Dict[str, DataParam]] = None
formula: List[str]
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> SecurityScoreExpression:
@dataclass
class RankedSecuritySelection:
RankedSecuritySelection( universe: SecurityUniverseSelector = <factory>, scoreExpression: SecurityScoreExpression = <factory>, selectTopN: int = 10)
scoreExpression: SecurityScoreExpression
selectTopN: int = 10
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
def collectSecurityExpressions( self, result: List[SecurityFilterExpression]) -> None:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> RankedSecuritySelection:
def isScheduledIntentFamilyApplicableForAsset( family: ScheduledWorkflowIntentFamily, assetType: investfly.models.marketdata.SecurityType) -> bool:
def isStrategyGuardTypeApplicableForAssetAndScope( guardType: StrategyGuardType, assetType: investfly.models.marketdata.SecurityType, scope: GuardScope) -> bool:
def strategyGuardTypesForAssetAndScope( assetType: investfly.models.marketdata.SecurityType, scope: GuardScope) -> List[StrategyGuardType]:
@dataclass
class OptionGroupSelection:
OptionGroupSelection( template: Optional[Any] = None, underlyingSymbols: Optional[Set[str]] = None, hasShortPut: Optional[bool] = None, hasCoveredCall: Optional[bool] = None, hasAssignedShares: Optional[bool] = None, minDaysToExpiry: Optional[int] = None, maxDaysToExpiry: Optional[int] = None)
template: Optional[Any] = None
underlyingSymbols: Optional[Set[str]] = None
hasShortPut: Optional[bool] = None
hasCoveredCall: Optional[bool] = None
hasAssignedShares: Optional[bool] = None
minDaysToExpiry: Optional[int] = None
maxDaysToExpiry: Optional[int] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[OptionGroupSelection]:
@dataclass
class OptionLifecycleRules:
OptionLifecycleRules( structures: List[OptionLifecycleStructure] = <factory>, rules: List[OptionLifecycleRule] = <factory>)
structures: List[OptionLifecycleStructure]
rules: List[OptionLifecycleRule]
def validate(self) -> None:
def validateForPrimaryStructure( self, primaryStructure: Optional[OptionStructureSpec]) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[OptionLifecycleRules]:
@dataclass
class OptionLifecycleStructure:
OptionLifecycleStructure( id: str = '', structure: Optional[OptionStructureSpec] = None, orderSpec: Optional[OrderSpec] = None)
id: str = ''
structure: Optional[OptionStructureSpec] = None
orderSpec: Optional[OrderSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionLifecycleStructure:
@dataclass
class OptionLifecycleRule:
OptionLifecycleRule( id: str = '', structureRef: str = 'PRIMARY_ENTRY', trigger: Any = <factory>, actions: List[Any] = <factory>)
id: str = ''
structureRef: str = 'PRIMARY_ENTRY'
trigger: Any
actions: List[Any]
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionLifecycleRule:
@dataclass
class OptionDteTrigger:
OptionDteTrigger(type: str = 'DTE', atOrBelow: int = 1, legId: Optional[str] = None)
type: str = 'DTE'
atOrBelow: int = 1
legId: Optional[str] = None
def validate(self) -> None:
def referencedLegIds(self) -> Set[str]:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionDteTrigger:
@dataclass
class OptionMetricTrigger:
OptionMetricTrigger( type: str = 'METRIC', metric: OptionLifecycleMetric = <OptionLifecycleMetric.LOSS_PERCENT: 'LOSS_PERCENT'>, comparator: ComparisonOperator = <ComparisonOperator.GREATER_OR_EQUAL: '>='>, value: float = 0.0, legId: Optional[str] = None)
type: str = 'METRIC'
value: float = 0.0
legId: Optional[str] = None
def validate(self) -> None:
def referencedLegIds(self) -> Set[str]:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionMetricTrigger:
@dataclass
class OptionOutcomeTrigger:
OptionOutcomeTrigger( type: str = 'OUTCOME', outcome: OptionLifecycleOutcome = <OptionLifecycleOutcome.EXPIRED: 'EXPIRED'>, legId: Optional[str] = None, timing: Optional[OptionOutcomeTiming] = <OptionOutcomeTiming.ANY: 'ANY'>)
type: str = 'OUTCOME'
legId: Optional[str] = None
timing: Optional[OptionOutcomeTiming] = <OptionOutcomeTiming.ANY: 'ANY'>
def validate(self) -> None:
def referencedLegIds(self) -> Set[str]:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionOutcomeTrigger:
@dataclass
class OptionAllOfTrigger:
OptionAllOfTrigger(type: str = 'ALL_OF', triggers: List[Any] = <factory>)
type: str = 'ALL_OF'
triggers: List[Any]
def validate(self) -> None:
def referencedLegIds(self) -> Set[str]:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionAllOfTrigger:
@dataclass
class OptionCloseLegsAction:
OptionCloseLegsAction( type: str = 'CLOSE_LEGS', scope: OptionActionScope = <OptionActionScope.ALL_LEGS: 'ALL_LEGS'>, legIds: Optional[List[str]] = None, orderSpec: Optional[OrderSpec] = None)
type: str = 'CLOSE_LEGS'
legIds: Optional[List[str]] = None
orderSpec: Optional[OrderSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionCloseLegsAction:
@dataclass
class OptionRollAction:
OptionRollAction( type: str = 'ROLL', scope: OptionActionScope = <OptionActionScope.ALL_LEGS: 'ALL_LEGS'>, legIds: Optional[List[str]] = None, replacementStructureRef: str = 'CURRENT_STRUCTURE', creditRequirement: OptionRollCreditRequirement = <OptionRollCreditRequirement.MUST_BE_NET_CREDIT: 'MUST_BE_NET_CREDIT'>, orderSpec: Optional[OrderSpec] = None)
type: str = 'ROLL'
legIds: Optional[List[str]] = None
replacementStructureRef: str = 'CURRENT_STRUCTURE'
orderSpec: Optional[OrderSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionRollAction:
@dataclass
class OptionOpenStructureAction:
OptionOpenStructureAction(type: str = 'OPEN_STRUCTURE', structureId: str = '')
type: str = 'OPEN_STRUCTURE'
structureId: str = ''
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionOpenStructureAction:
@dataclass
class OptionLiquidateUnderlyingAction:
OptionLiquidateUnderlyingAction( type: str = 'LIQUIDATE_UNDERLYING', orderSpec: Optional[OrderSpec] = None)
type: str = 'LIQUIDATE_UNDERLYING'
orderSpec: Optional[OrderSpec] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionLiquidateUnderlyingAction:
@dataclass
class OptionCompleteAction:
OptionCompleteAction( type: str = 'COMPLETE', entryRearmPolicy: OptionEntryRearmPolicy = <OptionEntryRearmPolicy.RETURN_TO_ENTRY_RULE: 'RETURN_TO_ENTRY_RULE'>)
type: str = 'COMPLETE'
entryRearmPolicy: OptionEntryRearmPolicy = <OptionEntryRearmPolicy.RETURN_TO_ENTRY_RULE: 'RETURN_TO_ENTRY_RULE'>
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionCompleteAction:
class OptionLifecycleMetric(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

LOSS_PERCENT = <OptionLifecycleMetric.LOSS_PERCENT: 'LOSS_PERCENT'>
LEG_DELTA = <OptionLifecycleMetric.LEG_DELTA: 'LEG_DELTA'>
UNDERLYING_DISTANCE_TO_STRIKE_PERCENT = <OptionLifecycleMetric.UNDERLYING_DISTANCE_TO_STRIKE_PERCENT: 'UNDERLYING_DISTANCE_TO_STRIKE_PERCENT'>
def requiresLegId(self) -> bool:
class OptionLifecycleOutcome(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

EXPIRED = <OptionLifecycleOutcome.EXPIRED: 'EXPIRED'>
ASSIGNED = <OptionLifecycleOutcome.ASSIGNED: 'ASSIGNED'>
EXERCISED = <OptionLifecycleOutcome.EXERCISED: 'EXERCISED'>
CASH_SETTLED = <OptionLifecycleOutcome.CASH_SETTLED: 'CASH_SETTLED'>
class OptionOutcomeTiming(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

ANY = <OptionOutcomeTiming.ANY: 'ANY'>
EARLY = <OptionOutcomeTiming.EARLY: 'EARLY'>
EXPIRATION = <OptionOutcomeTiming.EXPIRATION: 'EXPIRATION'>
class OptionActionScope(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

ALL_LEGS = <OptionActionScope.ALL_LEGS: 'ALL_LEGS'>
TRIGGER_LEG = <OptionActionScope.TRIGGER_LEG: 'TRIGGER_LEG'>
LEG_IDS = <OptionActionScope.LEG_IDS: 'LEG_IDS'>
class OptionRollCreditRequirement(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

MUST_BE_NET_CREDIT = <OptionRollCreditRequirement.MUST_BE_NET_CREDIT: 'MUST_BE_NET_CREDIT'>
ALLOW_NET_DEBIT = <OptionRollCreditRequirement.ALLOW_NET_DEBIT: 'ALLOW_NET_DEBIT'>
class OptionEntryRearmPolicy(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

RETURN_TO_ENTRY_RULE = <OptionEntryRearmPolicy.RETURN_TO_ENTRY_RULE: 'RETURN_TO_ENTRY_RULE'>
WAIT_UNTIL_ORIGINAL_EXPIRATION = <OptionEntryRearmPolicy.WAIT_UNTIL_ORIGINAL_EXPIRATION: 'WAIT_UNTIL_ORIGINAL_EXPIRATION'>
DO_NOT_REENTER = <OptionEntryRearmPolicy.DO_NOT_REENTER: 'DO_NOT_REENTER'>
PRIMARY_OPTION_ENTRY_STRUCTURE = 'PRIMARY_ENTRY'
CURRENT_OPTION_STRUCTURE = 'CURRENT_STRUCTURE'
@dataclass
class OptionGroupRiskRules:
OptionGroupRiskRules( profitTarget: Optional[OptionGroupProfitRule] = None, stopLoss: Optional[OptionGroupLossRule] = None, orderSpec: Optional[OrderSpec] = None, exitTemplateId: Optional[str] = None)
profitTarget: Optional[OptionGroupProfitRule] = None
stopLoss: Optional[OptionGroupLossRule] = None
orderSpec: Optional[OrderSpec] = None
exitTemplateId: Optional[str] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[OptionGroupRiskRules]:
@dataclass
class OptionScheduledEntryConfig:
OptionScheduledEntryConfig( action: OptionScheduledEntryAction = <OptionScheduledEntryAction.OPEN_OPTION_STRUCTURE: 'OPEN_OPTION_STRUCTURE'>, existingTargetPolicy: Optional[ExistingTargetPolicy] = None, targetUnderlyings: Optional[SecuritySelection] = None, openExecution: Optional[OpenExecutionSettings] = None, templateType: Optional[OptionScheduledEntryTemplateType] = None)
existingTargetPolicy: Optional[ExistingTargetPolicy] = None
targetUnderlyings: Optional[SecuritySelection] = None
openExecution: Optional[OpenExecutionSettings] = None
templateType: Optional[OptionScheduledEntryTemplateType] = None
def validate(self) -> None:
def requiresUnderlyingSelection(self) -> bool:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionScheduledEntryConfig:
class OptionScheduledEntryAction(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

SELL_CASH_SECURED_PUT = <OptionScheduledEntryAction.SELL_CASH_SECURED_PUT: 'SELL_CASH_SECURED_PUT'>
SELL_COVERED_CALL = <OptionScheduledEntryAction.SELL_COVERED_CALL: 'SELL_COVERED_CALL'>
OPEN_OPTION_STRUCTURE = <OptionScheduledEntryAction.OPEN_OPTION_STRUCTURE: 'OPEN_OPTION_STRUCTURE'>
class OptionScheduledEntryTemplateType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

SELL_PREMIUM_ENTRY = <OptionScheduledEntryTemplateType.SELL_PREMIUM_ENTRY: 'SELL_PREMIUM_ENTRY'>
WHEEL_CASH_SECURED_PUT_ENTRY = <OptionScheduledEntryTemplateType.WHEEL_CASH_SECURED_PUT_ENTRY: 'WHEEL_CASH_SECURED_PUT_ENTRY'>
WHEEL_COVERED_CALL_ENTRY = <OptionScheduledEntryTemplateType.WHEEL_COVERED_CALL_ENTRY: 'WHEEL_COVERED_CALL_ENTRY'>
CONDOR_IRON_FLY_ENTRY = <OptionScheduledEntryTemplateType.CONDOR_IRON_FLY_ENTRY: 'CONDOR_IRON_FLY_ENTRY'>
CALENDAR_DIAGONAL_ENTRY = <OptionScheduledEntryTemplateType.CALENDAR_DIAGONAL_ENTRY: 'CALENDAR_DIAGONAL_ENTRY'>
CUSTOM_OPTION_ENTRY = <OptionScheduledEntryTemplateType.CUSTOM_OPTION_ENTRY: 'CUSTOM_OPTION_ENTRY'>
class OptionProfitThresholdType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

NET_PREMIUM_PCT = <OptionProfitThresholdType.NET_PREMIUM_PCT: 'NET_PREMIUM_PCT'>
NET_PNL_ABSOLUTE = <OptionProfitThresholdType.NET_PNL_ABSOLUTE: 'NET_PNL_ABSOLUTE'>
@dataclass
class OptionGroupProfitRule:
OptionGroupProfitRule( type: OptionProfitThresholdType, value: float)
value: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionGroupProfitRule:
class OptionLossThresholdType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

NET_PREMIUM_PCT = <OptionLossThresholdType.NET_PREMIUM_PCT: 'NET_PREMIUM_PCT'>
NET_PNL_ABSOLUTE = <OptionLossThresholdType.NET_PNL_ABSOLUTE: 'NET_PNL_ABSOLUTE'>
@dataclass
class OptionGroupLossRule:
OptionGroupLossRule( type: OptionLossThresholdType, value: float)
value: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionGroupLossRule:
class AllocationMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT_OF_PORTFOLIO = <AllocationMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>
FIXED_NOTIONAL = <AllocationMode.FIXED_NOTIONAL: 'FIXED_NOTIONAL'>
FIXED_QUANTITY = <AllocationMode.FIXED_QUANTITY: 'FIXED_QUANTITY'>
@dataclass
class AllocationModel:
AllocationModel( mode: AllocationMode = <AllocationMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>, percentOfPortfolio: Optional[float] = None, fixedNotional: Optional[float] = None, fixedQuantity: Optional[float] = None)
mode: AllocationMode = <AllocationMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>
percentOfPortfolio: Optional[float] = None
fixedNotional: Optional[float] = None
fixedQuantity: Optional[float] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> AllocationModel:
class PositionSizeMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT_OF_PORTFOLIO = <PositionSizeMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>
PERCENT_OF_PORTFOLIO_RISK = <PositionSizeMode.PERCENT_OF_PORTFOLIO_RISK: 'PERCENT_OF_PORTFOLIO_RISK'>
FIXED_RISK_BUDGET = <PositionSizeMode.FIXED_RISK_BUDGET: 'FIXED_RISK_BUDGET'>
FIXED_NOTIONAL = <PositionSizeMode.FIXED_NOTIONAL: 'FIXED_NOTIONAL'>
FIXED_QUANTITY = <PositionSizeMode.FIXED_QUANTITY: 'FIXED_QUANTITY'>
@dataclass
class PositionSizeSpec:
PositionSizeSpec( mode: Optional[PositionSizeMode] = <PositionSizeMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>, value: Optional[float] = None)
mode: Optional[PositionSizeMode] = <PositionSizeMode.PERCENT_OF_PORTFOLIO: 'PERCENT_OF_PORTFOLIO'>
value: Optional[float] = None
def validate(self, label: str = 'PositionSizeSpec') -> None:
def toAllocationModel(self) -> AllocationModel:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> PositionSizeSpec:
class EntryConflictAction(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

IGNORE = <EntryConflictAction.IGNORE: 'IGNORE'>
CLOSE_OPPOSITE_THEN_OPEN = <EntryConflictAction.CLOSE_OPPOSITE_THEN_OPEN: 'CLOSE_OPPOSITE_THEN_OPEN'>
OPEN_HEDGED_POSITION = <EntryConflictAction.OPEN_HEDGED_POSITION: 'OPEN_HEDGED_POSITION'>
@dataclass
class EntryConflictPolicy:
EntryConflictPolicy( action: Optional[EntryConflictAction] = <EntryConflictAction.IGNORE: 'IGNORE'>, allowHedging: Optional[bool] = False)
action: Optional[EntryConflictAction] = <EntryConflictAction.IGNORE: 'IGNORE'>
allowHedging: Optional[bool] = False
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType]) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[EntryConflictPolicy]:
@dataclass
class EntryExistingPositionPolicy:
EntryExistingPositionPolicy( sameTarget: Optional[ExistingTargetPolicy] = None, oppositeSide: Optional[EntryConflictPolicy] = None)
sameTarget: Optional[ExistingTargetPolicy] = None
oppositeSide: Optional[EntryConflictPolicy] = None
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType]) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[EntryExistingPositionPolicy]:
class ExistingTargetAction(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

IGNORE_NEW_ENTRY = <ExistingTargetAction.IGNORE_NEW_ENTRY: 'IGNORE_NEW_ENTRY'>
ADD_TO_EXISTING = <ExistingTargetAction.ADD_TO_EXISTING: 'ADD_TO_EXISTING'>
REPLACE_EXISTING = <ExistingTargetAction.REPLACE_EXISTING: 'REPLACE_EXISTING'>
@dataclass
class ExistingTargetPolicy:
ExistingTargetPolicy( action: ExistingTargetAction = <ExistingTargetAction.IGNORE_NEW_ENTRY: 'IGNORE_NEW_ENTRY'>, addRule: Optional[RepeatSignalAddRule] = None)
addRule: Optional[RepeatSignalAddRule] = None
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType]) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[ExistingTargetPolicy]:
@dataclass
class PositionExposureLimit:
PositionExposureLimit( maxNotional: Optional[float] = None, maxPositionPct: Optional[float] = None, maxQuantity: Optional[float] = None)
maxNotional: Optional[float] = None
maxPositionPct: Optional[float] = None
maxQuantity: Optional[float] = None
def validate(self, label: str = 'PositionExposureLimit') -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> PositionExposureLimit:
class MoveUnit(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT = <MoveUnit.PERCENT: 'PERCENT'>
TICKS = <MoveUnit.TICKS: 'TICKS'>
PIPS = <MoveUnit.PIPS: 'PIPS'>
class MoveBasis(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

AVERAGE_ENTRY_PRICE = <MoveBasis.AVERAGE_ENTRY_PRICE: 'AVERAGE_ENTRY_PRICE'>
@dataclass
class MoveCondition:
MoveCondition( unit: Optional[MoveUnit] = <MoveUnit.PERCENT: 'PERCENT'>, threshold: Optional[float] = None, levels: Optional[List[float]] = None, basis: Optional[MoveBasis] = <MoveBasis.AVERAGE_ENTRY_PRICE: 'AVERAGE_ENTRY_PRICE'>)
unit: Optional[MoveUnit] = <MoveUnit.PERCENT: 'PERCENT'>
threshold: Optional[float] = None
levels: Optional[List[float]] = None
basis: Optional[MoveBasis] = <MoveBasis.AVERAGE_ENTRY_PRICE: 'AVERAGE_ENTRY_PRICE'>
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType, label: str) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> MoveCondition:
@dataclass
class ScaleAddPlan:
ScaleAddPlan( maxSteps: Optional[int] = None, minIntervalBetweenAdds: Optional[StrategyDuration] = None, scalingSizeMode: Optional[investfly.models.strategy.StrategyConfig.ScalingSizeMode] = None, firstStepPctOfBase: Optional[float] = None, quantity: Optional[float] = None, quantities: Optional[List[float]] = None, stepSizeMultiplier: Optional[float] = None)
maxSteps: Optional[int] = None
minIntervalBetweenAdds: Optional[StrategyDuration] = None
firstStepPctOfBase: Optional[float] = None
quantity: Optional[float] = None
quantities: Optional[List[float]] = None
stepSizeMultiplier: Optional[float] = None
def validateForAsset( self, label: str, securityType: Optional[investfly.models.marketdata.SecurityType], allowUnlimitedSteps: bool) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ScaleAddPlan:
@dataclass
class RepeatSignalAddRule:
RepeatSignalAddRule( onlyIfWinning: Optional[bool] = False, addPlan: Optional[ScaleAddPlan] = None)
onlyIfWinning: Optional[bool] = False
addPlan: Optional[ScaleAddPlan] = None
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType]) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> RepeatSignalAddRule:
@dataclass
class WinnerScaleRule:
WinnerScaleRule( favorableMove: Optional[MoveCondition] = None, addPlan: Optional[ScaleAddPlan] = None)
favorableMove: Optional[MoveCondition] = None
addPlan: Optional[ScaleAddPlan] = None
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> WinnerScaleRule:
@dataclass
class LoserScaleLimits:
LoserScaleLimits( maxLossPctBeforeAdd: Optional[float] = None, maxTotalAddNotional: Optional[float] = None)
maxLossPctBeforeAdd: Optional[float] = None
maxTotalAddNotional: Optional[float] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> LoserScaleLimits:
@dataclass
class LoserScaleRule:
LoserScaleRule( adverseMove: Optional[MoveCondition] = None, addPlan: Optional[ScaleAddPlan] = None, limits: Optional[LoserScaleLimits] = None)
adverseMove: Optional[MoveCondition] = None
addPlan: Optional[ScaleAddPlan] = None
limits: Optional[LoserScaleLimits] = None
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> LoserScaleRule:
@dataclass
class ScalingPlan:
ScalingPlan( addToWinner: Optional[WinnerScaleRule] = None, addToLoser: Optional[LoserScaleRule] = None)
addToWinner: Optional[WinnerScaleRule] = None
addToLoser: Optional[LoserScaleRule] = None
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> ScalingPlan:
@dataclass
class PositionManagementRules:
PositionManagementRules( positionExits: Optional[ExitRules] = None, positionScaling: Optional[ScalingPlan] = None, optionGroupExits: Optional[investfly.models.strategy.OptionStrategyRules.OptionExitRules] = None)
positionExits: Optional[ExitRules] = None
positionScaling: Optional[ScalingPlan] = None
optionGroupExits: Optional[investfly.models.strategy.OptionStrategyRules.OptionExitRules] = None
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType) -> None:
def hasScheduledScaling(self) -> bool:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[PositionManagementRules]:
@dataclass
class PortfolioLimits:
PortfolioLimits( maxOpenPositions: Optional[int] = None, maxPositionExposure: Optional[PositionExposureLimit] = None, maxTotalMarginPct: Optional[float] = None, maxOpenPositionsPerSymbol: Optional[int] = None, optionGroupExposure: Optional[investfly.models.strategy.StrategyConfig.OptionGroupExposureLimits] = None)
maxOpenPositions: Optional[int] = None
maxPositionExposure: Optional[PositionExposureLimit] = None
maxTotalMarginPct: Optional[float] = None
maxOpenPositionsPerSymbol: Optional[int] = None
def validate(self) -> None:
def validateForAsset( self, securityType: investfly.models.marketdata.SecurityType) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> PortfolioLimits:
class OrderDuration(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

GTC = <OrderDuration.GTC: 'GTC'>
DAY = <OrderDuration.DAY: 'DAY'>
class StrategyOrderType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

MARKET_ORDER = <StrategyOrderType.MARKET_ORDER: 'MARKET_ORDER'>
LIMIT_ORDER = <StrategyOrderType.LIMIT_ORDER: 'LIMIT_ORDER'>
class LimitPriceOffsetUnit(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PERCENT = <LimitPriceOffsetUnit.PERCENT: 'PERCENT'>
PRICE = <LimitPriceOffsetUnit.PRICE: 'PRICE'>
TICKS = <LimitPriceOffsetUnit.TICKS: 'TICKS'>
POINTS = <LimitPriceOffsetUnit.POINTS: 'POINTS'>
PIPS = <LimitPriceOffsetUnit.PIPS: 'PIPS'>
@dataclass
class LimitPriceOffset:
LimitPriceOffset( unit: Optional[LimitPriceOffsetUnit] = None, value: Optional[float] = None)
unit: Optional[LimitPriceOffsetUnit] = None
value: Optional[float] = None
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType], label: str = 'LimitPriceOffset') -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> LimitPriceOffset:
@dataclass
class OrderSpec:
OrderSpec( orderType: Optional[StrategyOrderType] = <StrategyOrderType.MARKET_ORDER: 'MARKET_ORDER'>, orderDuration: Optional[OrderDuration] = <OrderDuration.DAY: 'DAY'>, limitPriceOffset: Optional[LimitPriceOffset] = None, unfilledTimeout: Optional[StrategyDuration] = None)
orderType: Optional[StrategyOrderType] = <StrategyOrderType.MARKET_ORDER: 'MARKET_ORDER'>
orderDuration: Optional[OrderDuration] = <OrderDuration.DAY: 'DAY'>
limitPriceOffset: Optional[LimitPriceOffset] = None
unfilledTimeout: Optional[StrategyDuration] = None
def validate( self, label: str = 'OrderSpec', securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def validateForAsset( self, securityType: Optional[investfly.models.marketdata.SecurityType], label: str = 'OrderSpec') -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OrderSpec:
@dataclass
class StrategyDuration:

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

StrategyDuration( value: int, unit: StrategyDurationUnit, barInterval: investfly.models.marketdata.BarInterval | None = None)
value: int
barInterval: investfly.models.marketdata.BarInterval | None = None
def validate(self, label: str = 'StrategyDuration') -> None:
def toPyTimeDelta(self) -> datetime.timedelta:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> StrategyDuration:
class StrategyDurationUnit(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

MINUTES = <StrategyDurationUnit.MINUTES: 'MINUTES'>
HOURS = <StrategyDurationUnit.HOURS: 'HOURS'>
DAYS = <StrategyDurationUnit.DAYS: 'DAYS'>
BARS = <StrategyDurationUnit.BARS: 'BARS'>
@dataclass
class FutureLifecycleRules:
FutureLifecycleRules( rollMode: FutureRollMode = <FutureRollMode.NONE: 'NONE'>, daysBeforeExpiry: Optional[int] = None)
rollMode: FutureRollMode = <FutureRollMode.NONE: 'NONE'>
daysBeforeExpiry: Optional[int] = None
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[FutureLifecycleRules]:
class FutureRollMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

NONE = <FutureRollMode.NONE: 'NONE'>
CLOSE_ONLY = <FutureRollMode.CLOSE_ONLY: 'CLOSE_ONLY'>
ROLL_TO_NEXT = <FutureRollMode.ROLL_TO_NEXT: 'ROLL_TO_NEXT'>
class DataTriggerInfo(typing.TypedDict):

Type definition for data trigger information

type: DataType
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).

Parameters: 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):
@dataclass
class TradingStrategyModel:
TradingStrategyModel( strategyName: str, strategyId: int | None = None, pythonCode: str | None = None, strategyConfig: StrategyConfig | None = None, strategyDesc: str | None = None, securityType: investfly.models.marketdata.SecurityType | None = None, visibility: investfly.models.common.Visibility = <Visibility.PUBLIC: 'PUBLIC'>)
strategyName: str
strategyId: int | None = None
pythonCode: str | None = None
strategyConfig: StrategyConfig | None = None
strategyDesc: str | None = None
securityType: investfly.models.marketdata.SecurityType | None = None
visibility: investfly.models.common.Visibility = <Visibility.PUBLIC: 'PUBLIC'>
type: ConfigOrScript | None
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> TradingStrategyModel:
def toDict(self) -> Dict[str, Any]:
class ConfigOrScript(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

CONFIG = <ConfigOrScript.CONFIG: 'CONFIG'>
SCRIPT = <ConfigOrScript.SCRIPT: 'SCRIPT'>
@dataclass
class DeploymentLog:
DeploymentLog( date: datetime.datetime, level: LogLevel, message: str)
date: datetime.datetime
level: LogLevel
message: str
@staticmethod
def info(message: str) -> DeploymentLog:
@staticmethod
def warn(message: str) -> DeploymentLog:
@staticmethod
def error(message: str) -> DeploymentLog:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> DeploymentLog:
class LogLevel(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

INFO = <LogLevel.INFO: 'INFO'>
WARN = <LogLevel.WARN: 'WARN'>
ERROR = <LogLevel.ERROR: 'ERROR'>
class BacktestStatus(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

NOT_STARTED = <BacktestStatus.NOT_STARTED: 'NOT_STARTED'>
QUEUED = <BacktestStatus.QUEUED: 'QUEUED'>
INITIALIZING = <BacktestStatus.INITIALIZING: 'INITIALIZING'>
RUNNING = <BacktestStatus.RUNNING: 'RUNNING'>
COMPLETE = <BacktestStatus.COMPLETE: 'COMPLETE'>
ERROR = <BacktestStatus.ERROR: 'ERROR'>
@dataclass
class BacktestResultStatus:
BacktestResultStatus( jobStatus: BacktestStatus, percentComplete: int)
jobStatus: BacktestStatus
percentComplete: int
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> BacktestResultStatus:
@dataclass
class BacktestResult:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> BacktestResult:
class StandardSymbolsList(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

SP_100 = SP_100
SP_500 = SP_500
NASDAQ_100 = NASDAQ_100
NASDAQ_COMPOSITE = NASDAQ_COMPOSITE
RUSSELL_1000 = RUSSELL_1000
RUSSELL_2000 = RUSSELL_2000
DOW_JONES_INDUSTRIALS = DOW_JONES_INDUSTRIALS
BIOTECH_ETF = BIOTECH_ETF
FINANCIAL_ETF = FINANCIAL_ETF
INDUSTRIAL_ETF = INDUSTRIAL_ETF
LARGECAP_GROWTH_ETF = LARGECAP_GROWTH_ETF
MATERIALS_ETF = MATERIALS_ETF
MIDCAP_GROWTH_ETF = MIDCAP_GROWTH_ETF
SMALLCAP_GROWTH_ETF = SMALLCAP_GROWTH_ETF
TECHNOLOGY_ETF = TECHNOLOGY_ETF
UTILITIES_ETF = UTILITIES_ETF
USD_CRYPTO = USD_CRYPTO
ALL_FOREX = ALL_FOREX
class CustomSecurityList:
symbols: List[str]
def addSymbol(self, symbol: str) -> None:
@staticmethod
def fromJson( json_dict: Dict[str, Any]) -> CustomSecurityList:
def toDict(self) -> Dict[str, Any]:
def validate(self) -> None:
class SecurityUniverseType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

STANDARD_LIST = <SecurityUniverseType.STANDARD_LIST: 'STANDARD_LIST'>
CUSTOM_LIST = <SecurityUniverseType.CUSTOM_LIST: 'CUSTOM_LIST'>
WATCH_LIST = <SecurityUniverseType.WATCH_LIST: 'WATCH_LIST'>
FUNDAMENTAL_QUERY = <SecurityUniverseType.FUNDAMENTAL_QUERY: 'FUNDAMENTAL_QUERY'>
DYNAMIC_QUERY = <SecurityUniverseType.DYNAMIC_QUERY: 'DYNAMIC_QUERY'>
@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.

SecurityUniverseSelector( securityType: investfly.models.marketdata.SecurityType, universeType: SecurityUniverseType, standardList: StandardSymbolsList | None = None, customList: CustomSecurityList | None = None, financialQuery: FinancialQuery | None = None, watchListId: int | None = None, query: SecurityFilterExpression | None = None)

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

customList: CustomSecurityList | None = None
financialQuery: FinancialQuery | None = None
watchListId: int | None = None
query: SecurityFilterExpression | None = None
@staticmethod
def getValidSymbolLists( securityType: investfly.models.marketdata.SecurityType) -> List[StandardSymbolsList]:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> SecurityUniverseSelector:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def singleStock( symbol: str) -> SecurityUniverseSelector:
@staticmethod
def fromSecurity( security: investfly.models.marketdata.Security) -> SecurityUniverseSelector:
@staticmethod
def fromSymbols( securityType: investfly.models.marketdata.SecurityType, symbols: List[str]) -> SecurityUniverseSelector:
@staticmethod
def fromStandardList( standardListName: StandardSymbolsList) -> SecurityUniverseSelector:
@staticmethod
def fromFinancialQuery( financialQuery: FinancialQuery) -> SecurityUniverseSelector:
@staticmethod
def fromDynamicQuery( query: SecurityFilterExpression, securityType: investfly.models.marketdata.SecurityType = STOCK) -> SecurityUniverseSelector:
@staticmethod
def fromWatchList( securityType: investfly.models.marketdata.SecurityType, watchListId: int) -> SecurityUniverseSelector:
@staticmethod
def fromFutureProduct( product: investfly.models.marketdata.FutureProduct) -> SecurityUniverseSelector:
def forScheduledUniverse( self) -> SecurityUniverseSelector:
def validate(self) -> None:
class FinancialQuery:
queryConditions: List[FinancialCondition]
sectors: Set[str]
def addCondition( self, condition: FinancialCondition) -> None:
def addSector(self, sector: str) -> None:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> FinancialQuery:
def toDict(self) -> Dict[str, Any]:
def validate(self) -> None:
def toSecurityFilterExpression( self) -> SecurityFilterExpression:
@dataclass
class FinancialCondition:
operator: ComparisonOperator
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> FinancialCondition:
def toDict(self) -> Dict[str, Any]:
def validate(self) -> None:
class ComparisonOperator(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

GREATER_THAN = <ComparisonOperator.GREATER_THAN: '>'>
LESS_THAN = <ComparisonOperator.LESS_THAN: '<'>
GREATER_OR_EQUAL = <ComparisonOperator.GREATER_OR_EQUAL: '>='>
LESS_OR_EQUAL = <ComparisonOperator.LESS_OR_EQUAL: '<='>
EQUAL_TO = <ComparisonOperator.EQUAL_TO: '=='>
class Sectors(builtins.str, enum.Enum):

Stock market sectors for fundamental queries.

INFORMATION_TECHNOLOGY = Information Technology
COMMUNICATION_SERVICES = Communication Services
UTILITIES = Utilities
ENERGY = Energy
CONSUMER_STAPLES = Consumer Staples
CONSUMER_DISCRETIONARY = Consumer Discretionary
MATERIALS = Materials
INDUSTRIALS = Industrials
FINANCIALS = Financials
REAL_ESTATE = Real Estate
HEALTH_CARE = Health Care
displayName: str

Get the display name of the sector.

class SecurityFilterExpression:
SecurityFilterExpression(expression: str = '')
dataParams: Dict[str, DataParam]
filterGroups: List[Dict[str, Any]]
def addDataParam( self, key: str, dataParam: DataParam) -> None:
@staticmethod
def createSimpleExpression( leftCondition: str, op: ComparisonOperator, rightCondition: str) -> SecurityFilterExpression:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> SecurityFilterExpression:
@staticmethod
def filterGroupToString(fg: Dict[str, Any]):
@staticmethod
def filterConditionToString(fc: Dict[str, Any]) -> str:
def toDict(self) -> Dict[str, Any]:
def validate(self) -> None:
def toExpressionString(self) -> str:
def toMySQLExpression(self) -> str:
def toEvalExpression(self) -> str:
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.

def addQuoteParam( self, quote_field: investfly.models.marketdata.QuoteField, alias: str | None = None) -> DataParam:
def addConstParam( self, value: int | float, unit: ConstUnit | None = None, alias: str | None = None) -> DataParam:
def addFinancialParam( self, financial_field: investfly.models.marketdata.FinancialField, alias: str | None = None) -> DataParam:
def addIndicatorParam( self, indicator_id: str, bar_interval: investfly.models.marketdata.BarInterval, alias: str | None = None, params: Optional[Dict[str, Any]] = None) -> DataParam:
def addBarPriceParam( self, bar_interval: investfly.models.marketdata.BarInterval, bar_price: str, lookback: int, alias: str | None = None) -> DataParam:
class DataSource(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

BARS = <DataSource.BARS: 'BARS'>
FINANCIAL = <DataSource.FINANCIAL: 'FINANCIAL'>
QUOTE = <DataSource.QUOTE: 'QUOTE'>
NEWS = <DataSource.NEWS: 'NEWS'>
class DataType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

BARS = BARS
FINANCIAL = FINANCIAL
QUOTE = QUOTE
NEWS = NEWS
INDICATOR = INDICATOR
CONST = CONST
class ConstUnit(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

K = <ConstUnit.K: 'K'>
M = <ConstUnit.M: 'M'>
B = <ConstUnit.B: 'B'>
class DataParam(typing.Dict[str, typing.Any]):
INDICATOR = 'indicator'
DATATYPE = 'datatype'
VALUE = 'value'
UNIT = 'unit'
def setDataType(self, dataType: DataType) -> None:
def getDataType(self) -> DataType:
def getIndicatorId(self) -> str:
def getBarInterval(self) -> investfly.models.marketdata.BarInterval | None:
def getQuoteField(self) -> investfly.models.marketdata.QuoteField | None:
def getFinancialField(self) -> investfly.models.marketdata.FinancialField | None:
def getCount(self) -> int | None:
def getLookback(self) -> int | None:
def getConstValue(self) -> int | float:
def getSecurity(self) -> str | None:
def validate(self) -> None:
@staticmethod
def fromDict( json_dict: Dict[str, Any]) -> DataParam:
def clone(self) -> DataParam:
class SortOrder(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

ASC = <SortOrder.ASC: 'ASC'>
DSC = <SortOrder.DSC: 'DSC'>
@dataclass
class SortBySpec:
SortBySpec( alias: str, dataParam: DataParam, order: SortOrder, limit: Optional[int] = None)
alias: str
dataParam: DataParam
order: SortOrder
limit: Optional[int] = None
@dataclass
class MarketQueryRequest:
MarketQueryRequest( securityFilterExpression: SecurityFilterExpression, sortBy: Optional[SortBySpec] = None)
securityFilterExpression: SecurityFilterExpression
sortBy: Optional[SortBySpec] = None
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.

LONG_CALL = <OptionStrategyTemplate.LONG_CALL: 'LONG_CALL'>
LONG_PUT = <OptionStrategyTemplate.LONG_PUT: 'LONG_PUT'>
COVERED_CALL = <OptionStrategyTemplate.COVERED_CALL: 'COVERED_CALL'>
CASH_SECURED_PUT = <OptionStrategyTemplate.CASH_SECURED_PUT: 'CASH_SECURED_PUT'>
BULL_PUT_CREDIT_SPREAD = <OptionStrategyTemplate.BULL_PUT_CREDIT_SPREAD: 'BULL_PUT_CREDIT_SPREAD'>
BEAR_CALL_CREDIT_SPREAD = <OptionStrategyTemplate.BEAR_CALL_CREDIT_SPREAD: 'BEAR_CALL_CREDIT_SPREAD'>
BULL_CALL_DEBIT_SPREAD = <OptionStrategyTemplate.BULL_CALL_DEBIT_SPREAD: 'BULL_CALL_DEBIT_SPREAD'>
BEAR_PUT_DEBIT_SPREAD = <OptionStrategyTemplate.BEAR_PUT_DEBIT_SPREAD: 'BEAR_PUT_DEBIT_SPREAD'>
IRON_CONDOR = <OptionStrategyTemplate.IRON_CONDOR: 'IRON_CONDOR'>
CALL_BUTTERFLY = <OptionStrategyTemplate.CALL_BUTTERFLY: 'CALL_BUTTERFLY'>
PUT_BUTTERFLY = <OptionStrategyTemplate.PUT_BUTTERFLY: 'PUT_BUTTERFLY'>
LONG_STRADDLE = <OptionStrategyTemplate.LONG_STRADDLE: 'LONG_STRADDLE'>
SHORT_STRADDLE = <OptionStrategyTemplate.SHORT_STRADDLE: 'SHORT_STRADDLE'>
LONG_STRANGLE = <OptionStrategyTemplate.LONG_STRANGLE: 'LONG_STRANGLE'>
SHORT_STRANGLE = <OptionStrategyTemplate.SHORT_STRANGLE: 'SHORT_STRANGLE'>
LONG_CALL_CALENDAR_SPREAD = <OptionStrategyTemplate.LONG_CALL_CALENDAR_SPREAD: 'LONG_CALL_CALENDAR_SPREAD'>
LONG_PUT_CALENDAR_SPREAD = <OptionStrategyTemplate.LONG_PUT_CALENDAR_SPREAD: 'LONG_PUT_CALENDAR_SPREAD'>
LONG_CALL_DIAGONAL_SPREAD = <OptionStrategyTemplate.LONG_CALL_DIAGONAL_SPREAD: 'LONG_CALL_DIAGONAL_SPREAD'>
LONG_PUT_DIAGONAL_SPREAD = <OptionStrategyTemplate.LONG_PUT_DIAGONAL_SPREAD: 'LONG_PUT_DIAGONAL_SPREAD'>
PROTECTIVE_PUT = <OptionStrategyTemplate.PROTECTIVE_PUT: 'PROTECTIVE_PUT'>
COLLAR = <OptionStrategyTemplate.COLLAR: 'COLLAR'>
IRON_BUTTERFLY = <OptionStrategyTemplate.IRON_BUTTERFLY: 'IRON_BUTTERFLY'>
LONG_CALL_CONDOR = <OptionStrategyTemplate.LONG_CALL_CONDOR: 'LONG_CALL_CONDOR'>
CUSTOM_COMBO = <OptionStrategyTemplate.CUSTOM_COMBO: 'CUSTOM_COMBO'>
def isMultiLeg(self) -> bool:
def legCount(self) -> int:
def requiresStockUnderlyingPosition(self) -> bool:
def requiresCashCollateral(self) -> bool:
def hasUndefinedRisk(self) -> bool:
class OptionLegAction(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

BUY_TO_OPEN = <OptionLegAction.BUY_TO_OPEN: 'BUY_TO_OPEN'>
SELL_TO_OPEN = <OptionLegAction.SELL_TO_OPEN: 'SELL_TO_OPEN'>
BUY_TO_CLOSE = <OptionLegAction.BUY_TO_CLOSE: 'BUY_TO_CLOSE'>
SELL_TO_CLOSE = <OptionLegAction.SELL_TO_CLOSE: 'SELL_TO_CLOSE'>
def isOpen(self) -> bool:
def isBuy(self) -> bool:
class OptionLegRole(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

PRIMARY = <OptionLegRole.PRIMARY: 'PRIMARY'>
UNDERLYING = <OptionLegRole.UNDERLYING: 'UNDERLYING'>
PROTECTIVE_PUT = <OptionLegRole.PROTECTIVE_PUT: 'PROTECTIVE_PUT'>
PROTECTIVE_CALL = <OptionLegRole.PROTECTIVE_CALL: 'PROTECTIVE_CALL'>
SHORT_PUT = <OptionLegRole.SHORT_PUT: 'SHORT_PUT'>
LONG_PUT = <OptionLegRole.LONG_PUT: 'LONG_PUT'>
SHORT_CALL = <OptionLegRole.SHORT_CALL: 'SHORT_CALL'>
LONG_CALL = <OptionLegRole.LONG_CALL: 'LONG_CALL'>
@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.

OptionLegSpec( legId: str, action: OptionLegAction, optionRight: investfly.models.marketdata.OptionType | None, quantityRatio: int = 1, linkedToLegId: str | None = None, widthFromLinked: float | None = None, securityType: investfly.models.marketdata.SecurityType = OPTION, contractSelector: OptionContractSelector | None = None, legRole: OptionLegRole | None = None)
legId: str
action: OptionLegAction
quantityRatio: int = 1
linkedToLegId: str | None = None
widthFromLinked: float | None = None
contractSelector: OptionContractSelector | None = None
legRole: OptionLegRole | None = None
def validate(self) -> None:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionLegSpec:
def toDict(self) -> Dict[str, Any]:
@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.

OptionContractSelector( targetDte: int, strikeSelectionMode: StrikeSelectionMode, targetDelta: float | None = None, strikeOffsetPct: float | None = None, strikeOffset: float | None = None, strike: float | None = None, minimumStrikeRule: MinimumStrikeRule = <MinimumStrikeRule.NONE: 'NONE'>)
targetDte: int
strikeSelectionMode: StrikeSelectionMode
targetDelta: float | None = None
strikeOffsetPct: float | None = None
strikeOffset: float | None = None
strike: float | None = None
minimumStrikeRule: MinimumStrikeRule = <MinimumStrikeRule.NONE: 'NONE'>
def validate(self) -> None:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> OptionContractSelector:
def toDict(self) -> Dict[str, Any]:
class StrikeSelectionMode(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

TARGET_DELTA = <StrikeSelectionMode.TARGET_DELTA: 'TARGET_DELTA'>
PERCENT_OFFSET = <StrikeSelectionMode.PERCENT_OFFSET: 'PERCENT_OFFSET'>
PRICE_OFFSET = <StrikeSelectionMode.PRICE_OFFSET: 'PRICE_OFFSET'>
EXACT_STRIKE = <StrikeSelectionMode.EXACT_STRIKE: 'EXACT_STRIKE'>
class MinimumStrikeRule(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

NONE = <MinimumStrikeRule.NONE: 'NONE'>
AT_OR_ABOVE_COST_BASIS = <MinimumStrikeRule.AT_OR_ABOVE_COST_BASIS: 'AT_OR_ABOVE_COST_BASIS'>
@dataclass
class OptionStructureSpec:
def isMultiLeg(self) -> bool:
def hasUnderlyingLeg(self) -> bool:
def lifecycleLegIds(self) -> List[str]:
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongCallSpec(investfly.models.strategy.OptionStructureSpec):
LongCallSpec( selector: OptionContractSelector)
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongPutSpec(investfly.models.strategy.OptionStructureSpec):
LongPutSpec( selector: OptionContractSelector)
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class CoveredCallSpec(investfly.models.strategy.OptionStructureSpec):
CoveredCallSpec( callSelector: OptionContractSelector, buyWrite: bool = False)
callSelector: OptionContractSelector
buyWrite: bool = False
def hasUnderlyingLeg(self) -> bool:
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class CashSecuredPutSpec(investfly.models.strategy.OptionStructureSpec):
CashSecuredPutSpec( putSelector: OptionContractSelector)
putSelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class BullPutCreditSpreadSpec(investfly.models.strategy.OptionStructureSpec):
BullPutCreditSpreadSpec( shortPutSelector: OptionContractSelector, spreadWidth: float)
shortPutSelector: OptionContractSelector
spreadWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class BearCallCreditSpreadSpec(investfly.models.strategy.OptionStructureSpec):
BearCallCreditSpreadSpec( shortCallSelector: OptionContractSelector, spreadWidth: float)
shortCallSelector: OptionContractSelector
spreadWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class BullCallDebitSpreadSpec(investfly.models.strategy.OptionStructureSpec):
BullCallDebitSpreadSpec( longCallSelector: OptionContractSelector, spreadWidth: float)
longCallSelector: OptionContractSelector
spreadWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class BearPutDebitSpreadSpec(investfly.models.strategy.OptionStructureSpec):
BearPutDebitSpreadSpec( longPutSelector: OptionContractSelector, spreadWidth: float)
longPutSelector: OptionContractSelector
spreadWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class IronCondorSpec(investfly.models.strategy.OptionStructureSpec):
IronCondorSpec( shortPutSelector: OptionContractSelector, shortCallSelector: OptionContractSelector, putWingWidth: float, callWingWidth: float)
shortPutSelector: OptionContractSelector
shortCallSelector: OptionContractSelector
putWingWidth: float
callWingWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class CallButterflySpec(investfly.models.strategy.OptionStructureSpec):
CallButterflySpec( bodySelector: OptionContractSelector, wingWidth: float)
bodySelector: OptionContractSelector
wingWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class PutButterflySpec(investfly.models.strategy.OptionStructureSpec):
PutButterflySpec( bodySelector: OptionContractSelector, wingWidth: float)
bodySelector: OptionContractSelector
wingWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongStraddleSpec(investfly.models.strategy.OptionStructureSpec):
LongStraddleSpec( bodySelector: OptionContractSelector)
bodySelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class ShortStraddleSpec(investfly.models.strategy.OptionStructureSpec):
ShortStraddleSpec( bodySelector: OptionContractSelector)
bodySelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongStrangleSpec(investfly.models.strategy.OptionStructureSpec):
LongStrangleSpec( putSelector: OptionContractSelector, callSelector: OptionContractSelector)
putSelector: OptionContractSelector
callSelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class ShortStrangleSpec(investfly.models.strategy.OptionStructureSpec):
ShortStrangleSpec( putSelector: OptionContractSelector, callSelector: OptionContractSelector)
putSelector: OptionContractSelector
callSelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongCallCalendarSpreadSpec(investfly.models.strategy.OptionStructureSpec):
LongCallCalendarSpreadSpec( shortCallSelector: OptionContractSelector, longCallTargetDte: int)
shortCallSelector: OptionContractSelector
longCallTargetDte: int
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongPutCalendarSpreadSpec(investfly.models.strategy.OptionStructureSpec):
LongPutCalendarSpreadSpec( shortPutSelector: OptionContractSelector, longPutTargetDte: int)
shortPutSelector: OptionContractSelector
longPutTargetDte: int
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongCallDiagonalSpreadSpec(investfly.models.strategy.OptionStructureSpec):
LongCallDiagonalSpreadSpec( shortCallSelector: OptionContractSelector, longCallSelector: OptionContractSelector)
shortCallSelector: OptionContractSelector
longCallSelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongPutDiagonalSpreadSpec(investfly.models.strategy.OptionStructureSpec):
LongPutDiagonalSpreadSpec( shortPutSelector: OptionContractSelector, longPutSelector: OptionContractSelector)
shortPutSelector: OptionContractSelector
longPutSelector: OptionContractSelector
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class ProtectivePutSpec(investfly.models.strategy.OptionStructureSpec):
ProtectivePutSpec( putSelector: OptionContractSelector, buyStock: bool = False)
putSelector: OptionContractSelector
buyStock: bool = False
def hasUnderlyingLeg(self) -> bool:
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class CollarSpec(investfly.models.strategy.OptionStructureSpec):
CollarSpec( putSelector: OptionContractSelector, callSelector: OptionContractSelector, buyStock: bool = False)
putSelector: OptionContractSelector
callSelector: OptionContractSelector
buyStock: bool = False
def hasUnderlyingLeg(self) -> bool:
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class IronButterflySpec(investfly.models.strategy.OptionStructureSpec):
IronButterflySpec( bodySelector: OptionContractSelector, wingWidth: float)
bodySelector: OptionContractSelector
wingWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class LongCallCondorSpec(investfly.models.strategy.OptionStructureSpec):
LongCallCondorSpec( lowerCallSelector: OptionContractSelector, wingWidth: float)
lowerCallSelector: OptionContractSelector
wingWidth: float
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class CustomComboSpec(investfly.models.strategy.OptionStructureSpec):
CustomComboSpec(legs: List[OptionLegSpec])
legs: List[OptionLegSpec]
def isMultiLeg(self) -> bool:
def hasUnderlyingLeg(self) -> bool:
def lifecycleLegIds(self) -> List[str]:
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@dataclass
class FutureContractSelector:

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

FutureContractSelector(contractOffset: int = 0)
contractOffset: int = 0
def validate(self) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Dict[str, Any]) -> FutureContractSelector:
class InstrumentSelectionSpec:
type: ClassVar[InstrumentSelectionType]
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def direct() -> DirectInstrumentSelection:
@staticmethod
def futureContract( selector: FutureContractSelector) -> FutureContractSelection:
@staticmethod
def optionStructure( structure: OptionStructureSpec) -> OptionStructureSelection:
@staticmethod
def forAsset( securityType: investfly.models.marketdata.SecurityType) -> InstrumentSelectionSpec:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[InstrumentSelectionSpec]:
class InstrumentSelectionType(builtins.str, enum.Enum):

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.

DIRECT = <InstrumentSelectionType.DIRECT: 'DIRECT'>
FUTURE_CONTRACT = <InstrumentSelectionType.FUTURE_CONTRACT: 'FUTURE_CONTRACT'>
OPTION_STRUCTURE = <InstrumentSelectionType.OPTION_STRUCTURE: 'OPTION_STRUCTURE'>
@dataclass
class DirectInstrumentSelection(investfly.models.strategy.InstrumentSelectionSpec):
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[DirectInstrumentSelection]:
@dataclass
class FutureContractSelection(investfly.models.strategy.InstrumentSelectionSpec):
FutureContractSelection( selector: FutureContractSelector)
type: ClassVar[InstrumentSelectionType] = <InstrumentSelectionType.FUTURE_CONTRACT: 'FUTURE_CONTRACT'>
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[FutureContractSelection]:
@dataclass
class OptionStructureSelection(investfly.models.strategy.InstrumentSelectionSpec):
OptionStructureSelection( structure: OptionStructureSpec)
type: ClassVar[InstrumentSelectionType] = <InstrumentSelectionType.OPTION_STRUCTURE: 'OPTION_STRUCTURE'>
structure: OptionStructureSpec
def validate( self, securityType: Optional[investfly.models.marketdata.SecurityType] = None) -> None:
def toDict(self) -> Dict[str, Any]:
@staticmethod
def fromDict( jsonDict: Optional[Dict[str, Any]]) -> Optional[OptionStructureSelection]: