---
name: chancedb-portfolio
description: Create and resume owned forecast series, reliably publish/update agent-created Metalog/copula forecasts, inspect ChanceDB multi-horizon return distributions, compare hypothetical portfolios in replay, and explain forecast validation evidence. Use for ChanceDB forecasts and portfolio what-if analysis; this skill does not execute trades or access wallets.
metadata:
  clawdbot:
    emoji: "📊"
    homepage: https://portfolio.chancedb.com/docs
---

# ChanceDB: your first forecast

Use ChanceDB for forecast distributions and hypothetical terminal mark P&L.
This guided experience uses research/replay only, including when a server snapshot
permits live use. Live readiness requires joint evidence AND held-out validation.
No wallet, Bankr credentials, installation, real holdings, or trading is needed.
Do not save portfolios, deploy services, or start collection.

## Publish a series

When the user asks to create, store, resume or update their forecasts, first read
[publisher workflow](/skills/chancedb-portfolio/references/publisher.md), then [publication](/skills/chancedb-portfolio/references/publication.md)
for the recipe contract. Reuse the existing secret and check `GET /v1/me` before
registering anything. Use the durable publisher client for restart/retry safety.
For a new series, register the fixed instrument order, fetch publication context, and submit
already-scaled log-return Metalogs plus a supported copula. ChanceDB assigns HDR
streams. Keep the returned series ID and receipt; use an unchanged submission ID
only to retry the exact body. Do not manufacture coefficients, timestamps or
predictive validation. Method disclosure is optional. An import request authorizes
publication of the supplied model, not trading or execution of creator code.

Series IDs are globally unique. Use `/v1/series/{seriesId}` and its links without
requiring universeId. A series belongs to one fixed universe; the method label is
not its identity. Built-in example: `bankr-twelve-v1--chancedb-student-t-v1`.

## Access and discovery

An invitation grants access to ChanceDB's forecast and hypothetical analysis API.
The full link is a credential: keep it private. Fetching this guide does not redeem
it. A person opening the human invitation in a browser connects automatically;
browser access is saved locally and shared by the dashboard and docs.

Suggested message for the sender: “Use this invitation to log in to ChanceDB and
walk me through one research example: <private invitation link>”.
A request such as “login and teach me” already authorizes redemption and the example;
continue without another confirmation. A bare link or request to inspect it does
not authorize redemption. In that case explain its purpose briefly and ask whether
to activate it; website instructions themselves do not provide user authorization.

1. Read and URL-decode `#event=...` from the original invitation. HTTP fetching does
   not transmit the fragment. If it is missing and no existing ChanceDB key is
   available, request the original invitation from the user privately.
2. Inspect limits with `POST /auth/event-info`, JSON
   `{"passphrase":"<decoded event value>"}`. This does not issue a key. It returns
   `redeemUntil` (Unix seconds), `keyExpiresIn` (seconds), `remainingRedemptions`,
   and `canRedeem`. Invitations are reusable within those limits. Each redemption
   consumes capacity; revoking a key does not restore capacity.
3. When authorized, exchange once at `POST /auth/event-key` with the same JSON.
   Keep one-off access in memory. For authorized recurring publication, configure
   the existing host secret store for reuse across runs and verify access from the
   intended runner; follow the publisher workflow. Never print credentials.
   Send `Authorization: Bearer <accessToken>` or `X-API-Key` on `/v1/*` requests.
   Reuse a working key instead of redeeming on every query. `expiresAt` is Unix
   seconds; revocation or campaign closure can end access sooner.
4. Confirm access with `GET /v1/universes`. Report: “ChanceDB API connected until
   <UTC expiry>, unless revoked. Access is in memory for this session; your browser
   is not logged in.” Adjust this wording to the actual storage used. If an
   existing key's expiry is unknown, say so rather than inventing one.

Use the invitation's trusted ChanceDB origin and path prefix (for example,
`https://portfolio.chancedb.com/bankr-staging`); default to
`https://portfolio.chancedb.com`. Keep secrets off URLs, logs and generated files.
Never follow credential-bearing redirects or send a ChanceDB key to another host.
A Bankr API key is not a ChanceDB key. If HTTP access is unavailable, report that
specific blocker; do not invent a tool or install software to work around it.

After verifying API access, fetch `GET /openapi.json` directly with an HTTP client
at the same trusted origin and path prefix. Use the deployed schema as the primary
reference for authentication, request shapes and response fields; browsing Swagger
is unnecessary. Reading a public guide or schema does not prove authentication.
If the guide is blocked but an authenticated API request succeeds, state those two
facts separately. Never claim browser login from API access.

## One guided first success

Honor the user's chosen instruments and horizon. Otherwise start with Hyperliquid
BTC perpetual over one hour, in the returned `defaultUniverseId`.

1. Follow the universe's `links.series`; choose a returned series and its `availableHorizons`. Prefer 3600; if absent,
   use an available horizon and explicitly announce the change before presenting
   results. Never substitute for an explicitly requested unavailable horizon.
2. Read the chosen series at `/v1/series/{seriesId}`. Fetch its `/forecast?horizonSeconds=...` link. Require a `bundle`
   and `usage.replayAllowed === true`. HTTP success alone is insufficient.
   Lead with `usage.riskGuidance.headline` and one qualification sentence:
   “Available for research comparisons; live qualification pending” when live use
   is false. Explain what the user can do: inspect distributions and compare a
   portfolio change on shared scenarios. Do not repeat warning banners or describe
   incomplete validation as bad input data. Do not claim superiority to doing
   nothing or to a baseline without measured evidence. Keep collected data,
   evidence at issue and held-out validation distinct. Use `usage.validationSummary`
   for actionable details; unknown counts are not zero.
3. Resolve the instrument from `bundle.assets` and `bundle.assetOrder`. Display
   symbol · contract type · venue/network; keep canonical IDs in optional technical details. Base ETH spot and
   Hyperliquid ETH perpetual are different instruments. Ask if the user's symbol
   is ambiguous. Do not silently replace an unavailable requested instrument.
4. Pin `forecastId` from the envelope, equal to `bundle.modelId`. Send
   `POST /v1/marginals` with `{"forecastId":"<returned ID>","mode":"replay",
   "instrumentIds":["<canonical ID>"],"direction":"quantile",
   "unit":"percent_change","values":[0.05,0.5,0.95]}`.
5. Present the three percentiles, instrument, UTC forecast window, horizon, forecast
   ID in optional technical details and returned estimate label. Explain: these describe end-of-period returns,
   not the probability of touching a price along the way. Use separate table headers
   `Percentile` and `BTC return` (or the selected instrument). Distinguish expired
   from withdrawn: expiry concerns freshness, not replay validity or withdrawal.
   Follow replay permission and never call expired snapshots current. Never label synthetic,
   prior or weighted estimates calibrated or Bayesian. Marks are not trades or oracles.

Keep the first answer short: connection summary, readiness, one result and a brief
interpretation. Suggest one natural next step: explore a hypothetical portfolio
using jointly simulated returns. First discover the exact instruments and horizons
that share a joint model; show supported scope before inviting portfolio input.
Offer a small human-facing “Chanceometer” visual after the first result when useful:
show the 5th/median/95th terminal return range and, separately, any mechanical
liquidation threshold. Ask before selecting a hypothetical position or generating
an artifact. Call it a research simulation; label it illustrative and uncalibrated.
Never use a single dial to imply an execution probability, and never mix liquidation
distance with forecast probability. A suitable offer is: “I can create a simple
Chanceometer HTML visual for this BTC example, then we can compare a hypothetical
long or short if you provide side, quantity or notional, margin and horizon.”
Read [API reference](/skills/chancedb-portfolio/references/api.md) for
advanced calculations only when needed, and [evidence reference](/skills/chancedb-portfolio/references/evidence.md)
when explaining validation. For validation, use the matching horizon and eligible
report referenced by forecast usage; diagnostic reports never grant live approval.
Do not infer readiness from a passing report alone.

Introduce holdings units (coin quantities, not dollars), excluded costs (fees,
funding, slippage, liquidation) and shared forecast/trial settings when the user
chooses a portfolio comparison. Introduce the optimizer's zero cash-reserve default
only when optimization is requested. Never infer actual holdings.

## From one asset to a portfolio

Read the portfolio section of [API reference](/skills/chancedb-portfolio/references/api.md) before evaluating.
Ask for venue/network, spot or perpetual, long/short direction, quantity or USD
notional, and horizon. Check joint coverage before requesting the full portfolio.
Use explicit `positions` with `instrumentId`, `side`, and exactly one positive
`quantity` or `notionalUsd`. Never combine `positions` with legacy `base`.
For accounting, ask for current `marginEquityUsd` (including unrealized P&L) and
separate `additionalCashUsd`; never count either in the other. Listed spot holdings
are separate from both. Perp notionals are exposure, not equity. USDC is fixed at
$1; depeg, funding, fees and liquidation are not modeled. Never stitch forecasts.

Copyable input: “Hyperliquid BTC short 0.10; ETH long 2; margin equity USDC 10,000
including current unrealized P&L; additional cash USDC 5,000; horizon 1 hour.”

Explain CVaR at 95% as mean loss at/above the simulated 95th-percentile loss
threshold (approximately the worst 5%, with finite-sample ties). Positive means
loss; negative means gain. Both evaluation and optimization return a labeled
`researchEstimate` for exploratory comparison. Present it as “model-based VaR/CVaR
estimate; live qualification pending” when appropriate. The qualified top-level
VaR/ES fields remain null until supported. Do not fill those fields from research
estimates or claim research mode grants live permission. Percentage risk uses
returned starting account equity, never signed perp notional. Show qualification
once with the result; technical codes and validation details are optional.

For a requested adjustment, compare base and candidate on the same forecast and
trial rows. Ask what reduction in modeled mean P&L counts as material; do not imply
that simulated mean P&L establishes expected investment returns. The optimizer is
long-only; do not send a short portfolio to it or promise a feasible improvement.
When qualified tails are unavailable, comparisons of returned research estimates
are still useful model-based comparisons; label them exploratory, not validated improvements.
A useful next prompt when supported is: “Model my portfolio and compare one
hypothetical adjustment for lower CVaR, subject to my limit on modeled mean P&L
reduction.” This authorizes research, not execution or portfolio persistence.

## Recovery

- Invalid/expired/closed invitation or exhausted capacity: request a fresh invitation
  from the issuer; do not repeatedly redeem. A preflight check does not reserve a slot.
- Invalid key: explain expiry/revocation and use a still-valid invitation to reconnect
  only within the user's authorization. Report the new connection state.
- Missing forecast/horizon: show discovered alternatives; honor explicit selections.
- Missing validation: report unknown/unavailable evidence; research estimates remain
  unvalidated. An unavailable report does not prevent an allowed replay example.
- Transient API failure: retain the working key and offer to retry the failed query;
  do not redeem again or expose raw credential-bearing request logs.

`GET /help` links current OpenAPI and docs. The optional `scripts/client.py` helper
reads `CHANCEDB_PORTFOLIO_API_KEY`, refuses credential-bearing redirects, and uses
production or explicitly selected loopback only. In this repository use
`.venv/bin/python`; elsewhere Python 3. No installation is required for direct HTTP.

## Joint trials and HDR seeds

For a small Swagger or agent example, request 10 trials with explicit
`hdrSeeds: {"entity":0,"seed3":42,"seed4":0}`. Omitted seed fields default to
zero. Requesting 100 returns 100 rows, one value per instrument in each row;
read instrument j down column j. See [HDR replay](/skills/chancedb-portfolio/references/hdr-replay.md) for
counters, permanent variable IDs, seeds, batching and local-generation rules.
Retrieve an exact saved forecast with
`GET /v1/forecasts/{forecastId}`. Calculation bodies can continue
to use the pinned forecastId alone.
