Skip to content

API Reference

github-actions[bot] edited this page Sep 26, 2026 · 22 revisions

REST API

Stonks API 0.1.0. Research + trading system: portfolio, strategies, market data, lab runs and background jobs.

flowchart LR
  C["Clients<br/>web UI, stonks mcp, scripts"] -->|"HTTP /api"| A["FastAPI app"]
  A --> S["Services"]
  S --> L[("lake.duckdb<br/>market data")]
  S --> T[("state.sqlite<br/>strategies, orders, ticks")]
Loading

Auth: reads (GET) are open to loopback clients by default ([api].open_reads_on_loopback). Every other method needs Authorization: Bearer $STONKS_API_TOKEN.

Tags: brokers · catalog · health · ingest · jobs · lab · market · orders · pnl · portfolio · risk · shadow · sources · strategies · studio · ticks

brokers endpoints

Method Path Summary Auth Request Response
GET /api/brokers Get Broker Info token, or open on loopback BrokerInfo
GET /api/brokers/alpaca/status Get Alpaca Status token, or open on loopback AlpacaStatus

catalog endpoints

Method Path Summary Auth Request Response
GET /api/catalog/asset-classes List Asset Classes token, or open on loopback list[string]
GET /api/catalog/intervals List Intervals token, or open on loopback list[IntervalInfo]
GET /api/catalog/strategies List Strategy Classes token, or open on loopback list[StrategyClassInfo]

health endpoints

Method Path Summary Auth Request Response
GET /api/health Liveness probe none Health
GET /api/health/report Health Report token, or open on loopback HealthReportView

ingest endpoints

Method Path Summary Auth Request Response
GET /api/ingest/jobs/{job_id}/result Get Ingest Result token, or open on loopback IngestResultView
GET /api/ingest/runs List Runs token, or open on loopback Page_IngestRunView_
POST /api/ingest/runs Start Ingest bearer token IngestRequest Job

jobs endpoints

Method Path Summary Auth Request Response
GET /api/jobs List Jobs token, or open on loopback Page_Job_
GET /api/jobs/{job_id} Get Job token, or open on loopback Job
POST /api/jobs/{job_id}/cancel Cancel Job bearer token Job
GET /api/jobs/{job_id}/events Stream Job Events token, or open on loopback SSE of JobEvent
POST /api/jobs/{job_id}/stream-token Create Stream Token bearer token StreamToken

lab endpoints

Method Path Summary Auth Request Response
POST /api/lab/backtests Start Backtest bearer token BacktestRequest Job
GET /api/lab/backtests/{job_id}/result Get Backtest Result token, or open on loopback BacktestResult
GET /api/lab/cost-models List Cost Models token, or open on loopback list[CostModelPreset]
POST /api/lab/runs Start Lab Run bearer token LabRunRequest Job
GET /api/lab/runs/{job_id}/result Get Lab Run Result token, or open on loopback LabRunView

market endpoints

Method Path Summary Auth Request Response
GET /api/market/bars Get Bars token, or open on loopback BarSeries
GET /api/market/coverage List Coverage token, or open on loopback Page_CoverageRow_
GET /api/market/instruments List Instruments token, or open on loopback Page_InstrumentView_

orders endpoints

Method Path Summary Auth Request Response
GET /api/orders List Orders token, or open on loopback Page_OrderView_
GET /api/orders/fills List Fills token, or open on loopback Page_FillView_

pnl endpoints

Method Path Summary Auth Request Response
GET /api/pnl Get Pnl token, or open on loopback PnlSeries

portfolio endpoints

Method Path Summary Auth Request Response
GET /api/portfolio Get Portfolio token, or open on loopback PortfolioView
GET /api/portfolio/snapshots List Snapshots token, or open on loopback Page_SnapshotView_

risk endpoints

Method Path Summary Auth Request Response
GET /api/risk/policy Get Risk Policy token, or open on loopback RiskPolicy

shadow endpoints

Method Path Summary Auth Request Response
GET /api/shadow/decisions List Shadow Decisions token, or open on loopback Page_ShadowDecisionView_
GET /api/shadow/pnl List Shadow Pnl token, or open on loopback Page_ShadowPnlSummary_
GET /api/shadow/strategies/{strategy_id}/pnl Get Shadow Pnl token, or open on loopback PnlSeries

sources endpoints

Method Path Summary Auth Request Response
GET /api/sources List Sources token, or open on loopback list[DataSourceInfo]

strategies endpoints

Method Path Summary Auth Request Response
GET /api/strategies List Strategies token, or open on loopback Page_StrategySummary_
GET /api/strategies/{strategy_id} Get Strategy token, or open on loopback StrategyDetail
POST /api/strategies/{strategy_id}/promote Promote bearer token StrategyDetail
POST /api/strategies/{strategy_id}/retire Retire bearer token StrategyDetail
POST /api/strategies/{strategy_id}/shadow Shadow bearer token StrategyDetail

studio endpoints

Method Path Summary Auth Request Response
GET /api/studio/drafts List Drafts token, or open on loopback Page_Draft_
POST /api/studio/drafts Create Draft bearer token DraftCreate Draft
GET /api/studio/drafts/{draft_id} Get Draft token, or open on loopback Draft
PATCH /api/studio/drafts/{draft_id} Update Draft bearer token DraftUpdate Draft
DELETE /api/studio/drafts/{draft_id} Delete Draft bearer token Draft
POST /api/studio/drafts/{draft_id}/backtests Start Backtest bearer token DraftBacktestRequest Job
POST /api/studio/drafts/{draft_id}/disable Disable Draft bearer token Draft
POST /api/studio/drafts/{draft_id}/enable Enable Draft bearer token Draft
POST /api/studio/drafts/{draft_id}/lab-runs Start Lab Run bearer token DraftLabRunRequest Job
POST /api/studio/drafts/{draft_id}/register Register Draft bearer token Draft
POST /api/studio/drafts/{draft_id}/validate Validate Draft bearer token ValidateRequest | null DraftValidation
GET /api/studio/schema Schema token, or open on loopback object
POST /api/studio/spec/validate Validate Spec bearer token SpecValidateRequest DraftValidation
GET /api/studio/templates Templates token, or open on loopback list[RuleTemplateView]

ticks endpoints

Method Path Summary Auth Request Response
GET /api/ticks List Ticks token, or open on loopback Page_TickRun_
POST /api/ticks Start Tick bearer token TickRequest Job
GET /api/ticks/jobs/{job_id}/result Get Tick Result token, or open on loopback TickResultView
GET /api/ticks/{tick_id} Get Tick token, or open on loopback TickRunWithOrders

Schemas

AlpacaStatus

Field Type Required Description
account BrokerAccountView | null no
clock MarketClockView | null no
connected boolean yes
error string | null no
paper boolean yes

AssetClassCosts

Fee and spread for one asset class.

Field Type Required Description
fee_bps number no
fee_flat number no
half_spread_bps number no

BacktestRequest

Field Type Required Description
cost_model "zero" | "realistic" | null no
end date yes
fee_per_trade number no
initial_cash number no
interval string no
rebalance_every_bars integer no
slippage_bps number no
start date yes
strategy StrategyRef yes
threshold number no
universe list[string] yes

BacktestResult

Field Type Required Description
cagr number | null yes
end date yes
equity list[EquityPoint] yes
final_return number | null yes
interval string yes
max_drawdown number | null yes
profit_factor number | null yes
sharpe number | null yes
start date yes
strategy_id string yes

BarSeries

Field Type Required Description
bars list[BarView] yes
interval string yes
ticker string yes
truncated boolean yes

BarView

Field Type Required Description
adj_close number | null yes
close number | null yes
high number | null yes
low number | null yes
open number | null yes
timestamp date-time yes
volume number | null yes

BrokerAccountView

Field Type Required Description
buying_power number yes
can_trade boolean yes
cash number yes
currency string yes
equity number yes
pattern_day_trader boolean yes
status string yes
trading_blocked boolean yes

BrokerInfo

Field Type Required Description
allow_live boolean yes
credentials_configured boolean yes
kind "simulated" | "alpaca" yes
paper boolean yes

CostModelPreset

Field Type Required Description
description string yes
name "zero" | "realistic" yes
settings CostModelSettings yes

CostModelSettings

Settings for AssetClassCostModel. Zero costs by default; CostModelSettings.realistic() is a sensible starting point.

Field Type Required Description
asset_classes dict[str, AssetClassCosts] no
default AssetClassCosts no
impact_bps number no
max_impact_bps number no

CoverageRow

Field Type Required Description
first_bar date-time yes
interval string yes
last_bar date-time yes
rows integer yes
ticker string yes

DataSourceInfo

Field Type Required Description
configured boolean yes
default boolean yes
detail string | null no
id "eodhd" | "yahoo" | "defillama" yes

Draft

Field Type Required Description
created_at string yes
id string yes
kind "rule" | "code" yes
name string yes
registered_strategy_id string | null yes
source_code string | null yes
spec object yes
status "draft" | "registered" yes
strategy_status "active" | "shadow" | "retired" | null yes
updated_at string yes

DraftBacktestRequest

A :class:~stonks.app.lab.BacktestRequest without the strategy (the draft is the strategy).

Field Type Required Description
end date yes
fee_per_trade number no
initial_cash number no
interval string no
rebalance_every_bars integer no
slippage_bps number no
start date yes
threshold number no
universe list[string] yes

DraftCreate

Field Type Required Description
kind "rule" | "code" no
name string yes
source_code string | null no
spec object no

DraftLabRunRequest

A :class:~stonks.app.lab.LabRunRequest without the strategy. A rule draft's spec is fixed (it has no tunable parameters); a code draft's class is tuned over its parameter space.

Field Type Required Description
budget integer no
end date yes
interval string no
objective "sharpe" | "cagr" | "final_return" no
register_strategy boolean no
seed integer no
start date yes
survival_tests list["oos" | "period_stability" | "perturbation" | "drift" | "runs_test" | "permutation" | "walk_forward"] no
train_ratio number no
tuner "grid" | "random" no
universe list[string] yes

DraftUpdate

Field Type Required Description
name string | null no
source_code string | null no
spec object | null no

DraftValidation

Field Type Required Description
issues list[ValidationIssue] yes
smoke SmokeCheck | null no
valid boolean yes

EquityPoint

Field Type Required Description
timestamp date-time yes
value number yes

FillView

Field Type Required Description
fee number yes
filled_at string yes
id integer yes
order_client_id string yes
price number yes
quantity number yes
tick_id string | null yes
ticker string yes

Health

Field Type Required Description
status string yes
version string yes

HealthCheckView

Field Type Required Description
detail string yes
name string yes
ok boolean yes

HealthReportView

Field Type Required Description
checked_at date-time yes
checks list[HealthCheckView] yes
healthy boolean yes

IngestRequest

Field Type Required Description
exchange string | null no
interval string | null no
kind "prices" | "intraday" | "fundamentals" | "metadata" yes
since date | null no
source "eodhd" | "yahoo" | "defillama" no
tickers list[string] no
until date | null no

IngestResultView

Field Type Required Description
kind string yes
run_id integer yes
status string yes
tickers_failed integer yes
tickers_ok integer yes

IngestRunView

Field Type Required Description
error string | null yes
finished_at date-time | null yes
id integer yes
kind string yes
source string yes
started_at date-time yes
status string | null yes
tickers_failed integer | null yes
tickers_ok integer | null yes

InstrumentView

Field Type Required Description
asset_class string | null yes
currency string | null yes
exchange string | null yes
id string yes
industry string | null yes
is_delisted boolean | null yes
name string | null yes
sector string | null yes

IntervalInfo

Field Type Required Description
code string yes
is_intraday boolean yes
seconds integer yes

Job

Field Type Required Description
created_at date-time yes
error string | null no
finished_at date-time | null no
id string yes
kind string yes
message string | null no
params object yes
progress number yes
result any no
started_at date-time | null no
status "queued" | "running" | "succeeded" | "failed" | "cancelled" yes

JobEvent

One data: payload of the job event stream.

Field Type Required Description
error string | null no
job_id string yes
message string | null no
progress number yes
reason "timeout" | "untracked" | null no
status "queued" | "running" | "succeeded" | "failed" | "cancelled" yes

LabRunRequest

Tunes the class the strategy ref points at (its params are ignored: the tuner searches the class's parameter space).

Field Type Required Description
budget integer no
end date yes
interval string no
mcpt McptOptions | null no
objective "sharpe" | "cagr" | "final_return" no
register_strategy boolean no
seed integer no
start date yes
strategy StrategyRef yes
survival_tests list["oos" | "period_stability" | "perturbation" | "drift" | "runs_test" | "permutation" | "walk_forward"] no
train_ratio number no
tuner "grid" | "random" no
universe list[string] yes
walk_forward WalkForwardConfig | null no

LabRunView

Field Type Required Description
best_params object yes
best_score number | null yes
class_path string yes
registered_strategy_id string | null yes
survival_reports list[SurvivalReportView] yes
verdict "pass" | "fail" yes

MarketClockView

Field Type Required Description
is_open boolean yes
next_close date-time yes
next_open date-time yes
timestamp date-time yes

McptOptions

Monte-Carlo permutation test settings (survival test permutation).

Field Type Required Description
max_p_value number no
metric "profit_factor" | "sharpe" | "final_return" | "cagr" no
n_permutations integer no
retune boolean no
seed integer | null no

OrderView

Field Type Required Description
broker_order_id string | null yes
client_id string yes
created_at string yes
limit_price number | null yes
order_type string yes
quantity number yes
side string yes
status string yes
strategy_id string | null yes
tick_id string | null yes
ticker string yes
updated_at string yes

Page_CoverageRow_

Field Type Required Description
items list[CoverageRow] yes
limit integer yes
offset integer yes
total integer yes

Page_Draft_

Field Type Required Description
items list[Draft] yes
limit integer yes
offset integer yes
total integer yes

Page_FillView_

Field Type Required Description
items list[FillView] yes
limit integer yes
offset integer yes
total integer yes

Page_IngestRunView_

Field Type Required Description
items list[IngestRunView] yes
limit integer yes
offset integer yes
total integer yes

Page_InstrumentView_

Field Type Required Description
items list[InstrumentView] yes
limit integer yes
offset integer yes
total integer yes

Page_Job_

Field Type Required Description
items list[Job] yes
limit integer yes
offset integer yes
total integer yes

Page_OrderView_

Field Type Required Description
items list[OrderView] yes
limit integer yes
offset integer yes
total integer yes

Page_ShadowDecisionView_

Field Type Required Description
items list[ShadowDecisionView] yes
limit integer yes
offset integer yes
total integer yes

Page_ShadowPnlSummary_

Field Type Required Description
items list[ShadowPnlSummary] yes
limit integer yes
offset integer yes
total integer yes

Page_SnapshotView_

Field Type Required Description
items list[SnapshotView] yes
limit integer yes
offset integer yes
total integer yes

Page_StrategySummary_

Field Type Required Description
items list[StrategySummary] yes
limit integer yes
offset integer yes
total integer yes

Page_TickRun_

Field Type Required Description
items list[TickRun] yes
limit integer yes
offset integer yes
total integer yes

ParameterInfo

Field Type Required Description
bounds list[any] | null no
default any no
description string yes
kind string yes
name string yes
tunable boolean yes

PnlRowView

Field Type Required Description
cumulative_return number | null yes
daily_change number | null yes
daily_return number | null yes
day date yes
days_elapsed integer | null no
drawdown number yes
total_value number yes

PnlSeries

One row per day. strategy_id is None for the real portfolio and a shadow strategy's id for its virtual portfolio.

Field Type Required Description
rows list[PnlRowView] yes
strategy_id string | null yes

PortfolioView

Field Type Required Description
cash number yes
positions list[PositionView] yes
positions_value number yes
snapshot_total_value number | null yes
taken_at date-time | null yes
tick_id string | null yes
total_value number yes

PositionView

Field Type Required Description
market_value number | null yes
price number | null yes
price_date date | null yes
quantity number yes
ticker string yes
weight number | null yes

ProblemDetails

Field Type Required Description
detail string | null no
errors list[object] | null no
instance string | null no
status integer yes
title string yes
type string no

RiskAdjustmentView

One order the risk policy clipped or dropped.

Field Type Required Description
adjusted_quantity number yes
original_quantity number yes
reason string yes
rule string yes
side string yes
ticker string yes

RiskPolicy

Portfolio construction limits applied between strategy.decide and the broker ([production.risk]). Defaults are permissive, so an unconfigured install trades exactly what the strategy asks for.

Field Type Required Description
cash_buffer_fraction number no
enabled boolean no
max_open_positions integer | null no
max_weight_per_asset_class dict[str, number] no
max_weight_per_ticker number no
min_order_notional number no

RuleTemplateView

Field Type Required Description
description string yes
id string yes
spec object yes
title string yes

ShadowDecisionView

Field Type Required Description
as_of date yes
created_at date-time yes
id integer yes
price number | null yes
quantity number yes
side string yes
status string yes
strategy_id string yes
tick_id string yes
ticker string yes

ShadowOutcomeView

How one shadow strategy was evaluated during the tick.

Field Type Required Description
decisions integer no
error string | null no
fills integer no
status string yes
strategy_id string yes
total_value number | null no

ShadowPnlSummary

Field Type Required Description
cumulative_return number | null yes
days integer yes
first_day date | null yes
latest_day date | null yes
max_drawdown number | null yes
status string | null yes
strategy_id string yes
total_value number | null yes

SmokeCheck

Field Type Required Description
data "lake" | "sample" yes
errors list[string] yes
evaluations integer yes
ok boolean yes
signals integer yes
tickers list[string] yes

SnapshotView

Field Type Required Description
cash number yes
id integer yes
positions dict[str, number] yes
taken_at date-time yes
tick_id string | null yes
total_value number yes

SpecValidateRequest

Field Type Required Description
spec object yes

StrategyClassInfo

Field Type Required Description
applicable_asset_classes list[string] yes
class_path string yes
description string yes
name string yes
parameters list[ParameterInfo] yes
source string yes

StrategyDetail

Field Type Required Description
applicable_asset_classes list[string] yes
class_path string yes
created_at string yes
id string yes
params object yes
status "active" | "shadow" | "retired" yes
survival_reports list[SurvivalReportView] yes
updated_at string yes

StrategyRef

Which strategy to run: a registered id, or a catalog class + params.

Field Type Required Description
class_path string | null no
params object no
strategy_id string | null no

StrategySummary

Field Type Required Description
applicable_asset_classes list[string] yes
class_path string yes
created_at string yes
id string yes
params object yes
status "active" | "shadow" | "retired" yes
updated_at string yes

StreamToken

Field Type Required Description
events_url string yes
expires_at date-time yes
token string yes

SurvivalReportView

Field Type Required Description
metrics dict[str, number | null] yes
notes string yes
passed boolean yes
test_id string yes

TickRequest

Field Type Required Description
as_of date | null no
asset_class "equity" | "crypto" | "commodity" | "bond" | null no
dry_run boolean no
tickers list[string] | null no

TickResultView

Field Type Required Description
dry_run boolean yes
fills integer yes
orders_placed integer yes
status string yes
tick_id string yes
winner_strategy_id string | null yes

TickRun

Field Type Required Description
finished_at string | null yes
id string yes
started_at string yes
status string yes
summary TickSummary | null yes

TickRunWithOrders

Field Type Required Description
finished_at string | null yes
id string yes
orders list[OrderView] yes
started_at string yes
status string yes
summary TickSummary | null yes

TickSummary

Field Type Required Description
error string | null no
error_type string | null no
fills integer | null no
orders_placed integer | null no
reason string | null no
risk_adjustments list[RiskAdjustmentView] no
shadow list[ShadowOutcomeView] no
shadow_error string | null no
winner_expected_return number | null no
winner_strategy_id string | null no

ValidateRequest

Smoke-run on these lake tickers (sample data when empty), over the last bars bars up to as_of (latest data when omitted).

Field Type Required Description
as_of date | null no
bars integer no
tickers list[string] no

ValidationIssue

Field Type Required Description
message string yes
path string yes

WalkForwardConfig

Walk-forward settings. test_days=None splits the dataset's validation window evenly over the folds; train_days=None means "everything before the first test window".

Field Type Required Description
anchored boolean no
metric "sharpe" | "cagr" | "final_return" no
min_mean_score number no
min_positive_share number no
n_splits integer no
test_days integer | null no
train_days integer | null no

Clone this wiki locally