Metadata-Version: 2.2
Name: investfly-sdk
Version: 3.1.0
Summary: Public contracts, models, samples, and API clients for Investfly Python strategies and indicators
Author-email: "Investfly.com" <admin@investfly.com>
License: MIT
Project-URL: Homepage, https://www.investfly.com
Project-URL: Documentation, https://www.investfly.com/apidocs/investfly.html
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Typing :: Typed
Classifier: Operating System :: OS Independent
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: numpy>=1.26.0
Requires-Dist: pandas>=2.2.0
Requires-Dist: requests>=2.32.3
Provides-Extra: dev
Requires-Dist: build>=1.2.2; extra == "dev"
Requires-Dist: mypy>=1.15.0; extra == "dev"
Requires-Dist: pandas-stubs>=2.2.0.240218; extra == "dev"
Requires-Dist: pytest>=8.3.0; extra == "dev"
Requires-Dist: types-requests>=2.32.0.20250602; extra == "dev"

# Investfly Python SDK

`investfly-sdk` is the public Python contract for building custom trading strategies and
custom indicators on [Investfly](https://www.investfly.com). It contains typed models,
abstract service contracts, API clients, and runnable authoring examples. Live and backtest
execution algorithms remain in the Investfly runtime.

## Install

```bash
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.

```python
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:

```python
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](CHANGELOG.md)
for the removed 2.x surface and replacements.

API documentation is published at
[investfly.com/apidocs/investfly.html](https://www.investfly.com/apidocs/investfly.html).
For help, contact support@investfly.com.
