Options trading
Backtest multi-leg option spreads from the UI, Aurora, or the Python SDK: sizing, fills, fees, and reading results.
Options trading
NexusTrade supports algorithmic options strategies end-to-end: you define opening and closing rules in the same strategy / condition / action model as equities, run historical backtests on options data, and (depending on your brokerage) move toward paper or live deployment.
👉 Options overview (marketing) →
👉 Step-by-step guide: Backtest SPY options spreads in Python → (a $2,000 bull put and bear put example with the equity curve, every fill, and the results)
What you can do
| You want to… |
Supported |
How |
| Backtest multi-leg spreads (verticals, iron condors, straddles, calendars, custom) |
Yes |
OpenOption / CloseOption, from the UI, Aurora, or the Python / TypeScript SDK (example below) |
| Size each trade by risk |
Yes |
Contracts are sized from the spread's max loss: percent of portfolio: 5 risks about 5% of the book per new spread |
| Model commissions and fills |
Yes |
$0.65 per contract by default; fills from the historical bid/ask (midpoint to quote side, configurable) |
| Read return, Sharpe, Sortino, max drawdown, win rate, fees |
Yes |
result["statistics"] on the finished backtest |
| Read the equity curve |
Yes |
client.get_backtest_history(backtest_id) (retained 30 days) |
| Read each fill with its price |
Yes |
Run with generate_events=True, then client.list_backtest_events(...) (retained 3 days) |
| Simulate without placing trades |
Yes |
Backtests never touch a brokerage. Nothing trades unless you deploy and enable automation yourself |
| Query raw historical option quotes for your own pipeline |
No |
Option quotes are used inside the engine; there is no raw-quote export |
OpenOption and CloseOption
- OpenOption opens a new options position. You configure an options builder: underlying ticker (or a dynamic universe pipeline that picks underlyings), one or more legs (call/put, long/short), DTE windows, strike selection (percent, dollars, or delta from at-the-money), optional Greek filters per leg, optional spread type (vertical, iron condor, straddle, strangle, calendar, diagonal, custom), and allocation (percent of buying power, dollars, percent of portfolio, contracts, or percent of realized premium, which spends up to 100% of the Option Realized Premium balance and places no order while that balance is not positive).
- CloseOption closes existing option positions. Filters include underlyings, option type, direction, spread type, P/L percent (take profit / stop loss), DTE, days held, spread-level Greeks (delta, IV, theta), and quantity. Always use CloseOption to exit options—do not use Sell on option legs.
For how these fit into the strategy model, see Actions.
Strike selection
Each leg specifies how to find its strike price relative to the underlying:
| Method |
Description |
Example |
| Percent |
Distance as a % from ATM |
5 = 5% OTM |
| Dollars |
Distance in dollars from ATM |
10 = $10 OTM |
| Delta |
Target absolute delta |
0.30 = 30-delta option |
Positive distance always means OTM for both calls and puts. A distance of 0 means at-the-money.
Strike and expiration fallback ranges
If the target strike is unaffordable or no contract exists there, the system can search a fallback range. You specify a start distance and an end distance. The search walks the range from the strike nearest the money outward and takes the nearest affordable one. The iteration direction (OTMToITM or ITMToOTM) is stored with the range and does not change that order.
Similarly, an expiration fallback range lets the system search a wider DTE window when the primary DTE window has no available contracts. Candidates are tried shortest DTE first. Structures whose legs share one expiration (verticals, iron condors, straddles and strangles) follow the range's direction instead: ShortestFirst or LongestFirst.
Greek filters (entry)
Each leg can include optional Greek constraints that filter candidate contracts during resolution. Only contracts passing all specified bounds are considered.
| Filter |
Use case |
minDelta / maxDelta |
Target a specific delta range (e.g. sell 25–35 delta puts) |
minIv / maxIv |
Only trade when IV is in a desired range |
minGamma / maxGamma |
Filter by gamma exposure |
minTheta / maxTheta |
Filter by time decay |
minVega / maxVega |
Filter by volatility sensitivity |
minRho / maxRho |
Filter by interest rate sensitivity |
All fields are optional — omit any to skip that constraint.
Greek-based exits (CloseOption)
CloseOption supports spread-level Greek filters for dynamic exit rules beyond simple P/L thresholds:
| Filter |
Description |
minSpreadDelta / maxSpreadDelta |
Close when the net spread delta drifts outside a range |
minIv / maxIv |
Close when implied volatility crosses a threshold (e.g. IV crush) |
minSpreadTheta / maxSpreadTheta |
Close when daily theta decay is too small to justify holding |
These filters are applied at the spread level (aggregated across all legs). Spreads where Greeks are unavailable are skipped conservatively.
Ratio spreads
Each leg has an optional ratio field (default: 1). For a 1:2 ratio put spread, set the long leg to ratio: 1 and the short leg to ratio: 2. The system calculates contract quantities accordingly.
Supported spread types
Vertical, iron condor, straddle, strangle, calendar, diagonal, and custom. The spread type is auto-detected from the leg configuration if not specified.
Options indicators for conditions
NexusTrade includes seven option-specific indicators you can use in strategy conditions. All accept optional filters (underlying, option type, direction, spread type):
| Indicator |
Description |
| Option Spread Count |
Number of open spreads (use to gate entries, e.g. < 3) |
| Option Position Value |
Total market value of matching spreads |
| Option Position P&L% |
Weighted average P&L % across spreads |
| Option Days to Expiration |
Min or max DTE across spreads |
| Option Days Held |
Min or max days since entry |
| Option Collateral |
Total collateral locked |
| Option Unrealized P&L |
Total unrealized P&L in dollars |
For full parameter details, see Advanced Indicators.
Options order cooldowns
Two dedicated indicators measure time since your most recent option order:
- Days Since Option Order — with optional filters for underlying, option type, direction, spread type, position effect (open/close), and DTE range at order time.
- Minutes Since Option Order — same filters, for intraday cooldowns.
These let you build cooldowns like “don’t open another SPY spread for 30 minutes after the last one.”
Backtest options from the Python SDK
For a walkthrough with recorded charts, a winning and a losing trade, and an Aurora version, see Backtest SPY options spreads in Python. The reference version follows.
pip install nexustrade (5.4 or later), create an API key at nexustrade.io/developers, and export it as NEXUSTRADE_API_KEY. The example below backtests a SPY bull put credit spread and a SPY bear put debit spread on a $2,000 book, risking about 5% per trade, from March 2022 through 2025. It ran end to end against production while this page was written.
import nexustrade as nt
client = nt.NexusTradeClient.from_environment()
def put_leg(direction, dollars_otm):
return nt.leg(
option_type="put",
direction=direction, # "long" or "short"
min_days_to_expiration=30,
max_days_to_expiration=45,
distance=dollars_otm, # dollars below spot
distance_type="dollars",
)
def open_vertical(direction, legs):
# Open a new spread only when none is held.
return nt.strategy(
f"Open SPY {direction} put vertical",
nt.OptionSpreadCount("SPY", "put", direction, "vertical") < nt.Value(1),
nt.open_option(
builder=nt.options_builder(underlying_symbol="SPY", spread_type="vertical", legs=legs),
# Contracts are sized from max loss, so this risks ~5% of the book.
allocation={"type": "percent of portfolio", "amount": 5},
),
)
def close_vertical(direction, take_profit, stop_loss):
return nt.strategy(
f"Close SPY {direction} put verticals",
nt.always(),
nt.close_option(
underlyings=["SPY"], option_type="put", direction=direction, spread_type="vertical",
triggers=[
nt.pnl_trigger(min_pnl_percent=take_profit),
nt.pnl_trigger(max_pnl_percent=stop_loss),
nt.dte_trigger(max_dte=7),
],
),
)
# Bull put credit spread: sell the put $5 below spot, buy the put $6 below.
bull_put = nt.portfolio("SPY bull put credit spread", [
open_vertical("short", [put_leg("short", 5), put_leg("long", 6)]),
close_vertical("short", take_profit=50, stop_loss=-100),
], initial_value=2_000)
# Bear put debit spread: buy the put $1 below spot, sell the put $3 below.
bear_put = nt.portfolio("SPY bear put debit spread", [
open_vertical("long", [put_leg("long", 1), put_leg("short", 3)]),
close_vertical("long", take_profit=50, stop_loss=-50),
], initial_value=2_000)
operations = client.create_backtests(
[
nt.backtest(book, start_date="2022-03-07", end_date="2025-12-31", generate_events=True)
for book in (bull_put, bear_put)
],
idempotency_key="spy-put-spreads-v1",
)
for finished in client.wait_for_backtests(operations, timeout_seconds=1800):
result = finished["result"]
stats = result["statistics"]
print(result["backtestId"], stats["percentChange"], stats["sharpeRatio"],
stats["maxDrawdown"], stats["totalFees"], stats["closedTradeCount"])
A credit vertical is direction="short" and a debit vertical is direction="long" in the spread filters. Swap "put" for "call" to get the call-side versions.
Reading results
Each finished operation's result["statistics"] carries percentChange, sharpeRatio, sortinoRatio, maxDrawdown, avgDrawdown, winRate, profitFactor, closedTradeCount (closed option legs, so a two-leg spread counts twice), totalFees, peakReservedCollateral (the most capital at risk at once) and optionOpenDays. result["baselineStatistics"] is the same block for buy-and-hold of the benchmark (the underlying, here SPY).
The equity curve and the individual fills are separate reads:
backtest_id = result["backtestId"]
# Equity curve: time, value, cash, positionValue, comparisonValue, reservedCollateral
curve, page = [], 1
while page is not None:
batch = client.get_backtest_history(backtest_id, page=page, page_size=5000)
curve += batch["points"]
page = batch["nextPage"]
# Every executed order with its fill price and contracts
fills, page = [], 1
while True:
batch = client.list_backtest_events(
backtest_id, event_types=["Order"], order_statuses=["Filled"], page=page, page_size=50,
)
fills += batch["events"]
if not batch["hasMore"]:
break
page += 1
Each fill's event carries asset (contract symbol, strikePrice, expirationDate, optionType), side, quantity, filledAtPrice (per share; multiply by 100 for dollars), filledAtTime, fees, and positionEffect (open or close). Legs of one spread share a multiLegGroupId; a closing order's targetSpreadId names the opening group it closes, so you can pair each entry with its exit. Events come 50 per page; follow hasMore.
Per-tick history is kept for 30 days after the run. Event traces exist only when the backtest was submitted with generate_events=True (it costs 5x the research tokens) and are kept for 3 days, so export them soon after the run. Both reads raise backtest_not_ready while the run is still going; list_backtest_events raises events_unavailable when the run kept no traces. The same calls exist in the TypeScript SDK as getBacktestHistory and listBacktestEvents.
What this example returned
From the production run of the code above (no tuning; these are illustrative structures, not recommendations):
|
Bull put credit spread |
Bear put debit spread |
SPY buy-and-hold |
| Return |
−35.2% |
−48.3% |
+66.4% |
| Sharpe |
−1.28 |
−1.35 |
0.81 |
| Max drawdown |
36.5% |
48.5% |
23.8% |
| Spreads opened and closed |
71 (142 legs) |
63 (126 legs) |
— |
| Total commissions |
$192.40 |
$163.80 |
— |
| Peak capital at risk |
$88 |
$99 |
— |
Two things a small account should take from this. First, at 5% risk on $2,000 each trade can lose about $100, which only fits $1–2 wide SPY spreads; a wider spread resolves to zero contracts and simply never trades. Second, commissions are large relative to the book: about $190 over four years is nearly 10% of starting capital before any P&L.
Data coverage, fills and fees
- Data range. Daily option backtests start in March 2022 (the earliest supported start for a SPY book was 2022-03-07). If you ask for an earlier date the API rejects the request and names the earliest date it supports for that portfolio.
- Fills. Orders fill against the historical bid/ask.
fee_config={"OptionSlippageFraction": 0} fills at the midpoint, 1 at the ask for buys and bid for sells; the default is 0.5. A leg with no executable quote waits instead of filling at a stale print.
- Commissions. $0.65 per contract by default. Override it with
fee_config={"Option": {"type": "dollars", "amount": 0.5}} on nt.backtest(...). The run reports the total as statistics["totalFees"].
- Liquidity. Entries are capped by a share of each contract's recent volume;
statistics["optionLiquidity"] reports how many entries were limited.
- Timing. A daily backtest decides and fills on daily snapshots. Use
interval="Minute" (up to 730 days per run) when intraday timing matters.
Describing strategies to Aurora
In Aurora, describe concrete option structures (underlying, spread type, DTE, strikes, allocation)—not open-ended “research then trade options” tasks. Aurora maps your request to OpenOption / CloseOption via portfolio generation.
Example prompts:
”Create an SPY bull put spread when price is above the 200-day SMA: short 2% OTM put, long 5% OTM put, 30–45 DTE, 10% of buying power”
”Close all SPY options at +50% profit or −30% loss”
”Buy ATM calls on the top 3 S&P 500 stocks by 30-day momentum each Monday, 30–45 DTE”
”Sell 30-delta puts on SPY, 20–30 DTE, close at 50% profit or when delta exceeds −0.50”
Portfolio starting capital (important)
Standard equity portfolios often use $25,000 as a default initial portfolio value when you do not specify a size. Options consume much more buying power than the same dollar allocation in stock: each contract represents 100 shares of the underlying, and strategies like LEAPS or short premium on index ETFs can require very large notional or margin.
When you do not state an account size, NexusTrade’s assistants and generators assume:
- $25,000 for stock/ETF-only portfolios.
- $500,000 as a baseline initial value for options portfolios.
- $1,000,000 for LEAPS, multi-underlying selection (e.g. momentum-ranked names), or short premium on broad indices (e.g. SPY, QQQ), unless you specify otherwise.
If your backtest uses too small an initial value, you may see few or no fills. If you do use a small account, narrow the strategy: fewer underlyings, defined-risk spreads instead of naked short premium, shorter DTE, or smaller allocation per trade.
Backtesting options
Options backtesting is a premium feature available to paid subscribers. Options backtests use historical daily options data from March 2022 onward; see Data coverage, fills and fees above. Treat results like any backtest: watch for overfitting, test multiple date ranges, then paper trade before live capital. See Backtesting for general methodology.
Live trading and brokerages
Not every brokerage enables every option order type in automation. Supported multi-leg and options capabilities depend on the connected broker—see Live Trading & Deployment and your broker’s integration. Paper trading is the right first step for new options automations.
Related