Skip to main content

Public contracts, models, samples, and API clients for Investfly Python strategies and indicators

Project description

Investfly Python SDK

investfly-sdk is the public Python contract for building custom trading strategies and custom indicators on Investfly. It contains typed models, abstract service contracts, API clients, and runnable authoring examples. Live and backtest execution algorithms remain in the Investfly runtime.

Install

python3 -m venv venv
source venv/bin/activate
pip install investfly-sdk

Python 3.11 or later is required.

Custom strategies

Subclass TradingStrategy, choose a universe, and implement a market-data callback and/or one or more @scheduled callbacks. The runtime injects:

  • self.dataService for market data and indicators
  • self.context for the current portfolio, universe, time, and option groups
  • self.services for runtime-owned selection, ranking, guard evaluation, allocation, instrument selection, order planning, rebalancing, and scaling

Use getStrategyPolicy() for continuous behavior the runtime should enforce around your callbacks, including protective exits, position scaling, option-group exits and lifecycle, futures lifecycle, and portfolio limits.

from typing import List, Optional
from investfly.models import *


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

    def getStrategyPolicy(self) -> CustomStrategyPolicy:
        return CustomStrategyPolicy(
            assetType=SecurityType.STOCK,
            positionManagement=PositionManagementRules(
                positionExits=ExitRules(
                    protectiveExits=buildProtectiveExitPlan(
                        targetProfitPct=10.0,
                        stopLossPct=5.0,
                        trailingStopPct=2.0,
                    )
                )
            ),
            portfolioLimits=PortfolioLimits(maxOpenPositions=5),
        )

    @data_trigger(type=DataType.BARS, barInterval=BarInterval.FIFTEEN_MINUTE)
    def onMarketData(self, updatedSecurities: List[Security]) -> Optional[List[TradeOrder]]:
        execution = OpenExecutionSettings(
            positionSize=PositionSizeSpec(PositionSizeMode.PERCENT_OF_PORTFOLIO, 15.0),
            orderSpec=OrderSpec(),
            instrumentSelection=DirectInstrumentSelection(),
        )
        return self.services.planAllocationOrders(AllocationPlan(updatedSecurities, execution)) or None

The authoritative investfly.samples.strategies catalog contains 37 runnable examples: 8 stock, 5 forex, 5 crypto, 5 futures, and 14 option strategies. The option examples cover all 24 OptionStrategyTemplate structures, including the Wheel lifecycle, calendars, diagonals, condors, butterflies, volatility structures, protective hedges, and custom multi-leg combinations. Catalog metadata describes each strategy's intervals, capabilities, why Python is required, and real-data audit profile.

Custom indicators

Subclass Indicator, implement getIndicatorSpec(), computeSeries(), and calculateRequiredBars(). Indicator authors receive an injected IndicatorDataService; the SDK also ships NumPy/pandas helpers, TA-Lib type stubs, and indicator samples.

CLI and REST clients

Installing the package also installs investfly-cli. Run investfly-cli, then use login, copysamples, strategy.*, and indicator.* commands.

For direct API access:

from investfly.api.InvestflyApiClient import InvestflyApiClient

api = InvestflyApiClient()
session = api.login("username", "password")
strategies = api.strategyApi.listStrategies()
api.logout()

TLS certificate verification is enabled by default. API calls use a finite timeout and raise InvestflyApiError for non-2xx responses.

Version 3.1

Version 3.1 expands the typed service boundary and publishes the comprehensive sample catalog. Version 3.0 was an intentional breaking boundary cleanup. Runtime algorithms and runtime-state encoding are no longer published as SDK utilities. Custom strategies call self.services and describe continuous behavior with getStrategyPolicy() instead. See CHANGELOG.md for the removed 2.x surface and replacements.

API documentation is published at investfly.com/apidocs/investfly.html. For help, contact support@investfly.com.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

investfly_sdk-3.1.0.tar.gz (188.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

investfly_sdk-3.1.0-py3-none-any.whl (262.4 kB view details)

Uploaded Python 3

File details

Details for the file investfly_sdk-3.1.0.tar.gz.

File metadata

  • Download URL: investfly_sdk-3.1.0.tar.gz
  • Upload date:
  • Size: 188.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for investfly_sdk-3.1.0.tar.gz
Algorithm Hash digest
SHA256 5ec5a9ba6c3e9012c08f3070087e2ac9661ae58ac5089084a3e3f766a362c8c5
MD5 0820fe31cb2b3f3dfeb2d42f1cec9f67
BLAKE2b-256 54beea0cf8ddddc4f618473beea78c191c97cef3d6967a822d12845be8d64561

See more details on using hashes here.

File details

Details for the file investfly_sdk-3.1.0-py3-none-any.whl.

File metadata

  • Download URL: investfly_sdk-3.1.0-py3-none-any.whl
  • Upload date:
  • Size: 262.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for investfly_sdk-3.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b9795afa33f2caed327161089b2a4e24b6058d4edf4ade32da407c9461a4aa80
MD5 a140126f9a7c5f1c8d8d05f0fc468fd2
BLAKE2b-256 197acbb608267c3b85623ce19875a8f5b74d64c91cea948fa0815ab2abb84e99

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page