openapi: 3.1.0
info:
  title: Chartnaut Partner API
  version: 1.0.0
  summary: Link your users' Chartnaut accounts, run backtest sessions and demo accounts for them, and embed Chartnaut in your site
  description: |
    The partner API is for companies that put Chartnaut inside their own product.
    Your server calls it with a secret partner key; your users link their own Chartnaut
    account to their account on your site, and you act for them within the scopes they granted.

    Design rules:
    - **Primitives, not products.** We have backtest **sessions** and **demo accounts**. You create
      them for your users, attach **labels**, list by label and run **bulk actions**. Competitions,
      groups, leaderboards and scheduling are yours.
    - **Reads are the truth; webhooks are hints.** Every fact has a GET. Webhooks carry an event
      type and ids only, at least once, in no guaranteed order. The frame's `postMessage` events
      are hints too.
    - **Ids carry a type prefix**, so one kind can never be passed where another is meant:
      `usr_42` (a Chartnaut user), `ses_42` (a backtest session), `acc_42` (a demo or linked
      account), `brk_42` (a rule breach), `alr_42` (an alert), `alf_42` (an alert fire). Positions
      and orders inside a session or account are plain integers. Wherever a user is named you may
      instead use your own ref: `ext:<external_user_ref>` (URL-encode it in a path).
    - **Every POST takes an `Idempotency-Key`** (required). A retry with the same key, path and
      body within 24 hours returns the first response with `Idempotent-Replayed: true`; the same
      key with a different path or body is `422 idempotency_key_reused`. PUT, PATCH and DELETE
      take no key.
    - **Lists are cursor-paged.** Pass `next_cursor` back as `cursor`; `null` means the last page.
      A full page always has a `next_cursor`, so the page after it can be empty. `limit` defaults
      to 50 (100 for trades, breaches and alert fires) and is capped at your `page_size` limit
      (200; never more than 500); a larger `limit` is cut to it, not refused. Cursors mark the last
      row you were given, not a position, so a page deep into a long history (a user with tens of
      thousands of trades) costs what the first does, and rows added while you page neither repeat
      nor go missing. A cursor belongs to the list that gave it: one from another list, or one you
      made up, is `400 invalid_request` with `details.field: "cursor"`. Lists never return more than
      a page; `GET /scripts` (an app holds at most 500 scripts) is answered whole.
    - **Rate-limit headers** (`RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`) are on
      every response to a request whose key checked out. A `401`, the `403 switched_off` when the
      whole API is off for you, and the `429` for too many bad keys from one IP carry none. A 429
      also carries `Retry-After`.
    - **Money is a decimal number in the account's currency (USD today)**, at most two decimal
      places. Rules are checked in whole cents.
    - **List order** differs by list; each one says which. `GET /sessions` and `GET /accounts` are
      newest first; `GET /users` and alert fires are oldest first.
    - **Unknown body fields are refused** (`400 invalid_request`, with the field named in
      `message`, not in `details`).
    - **Environments.** Every object belongs to `live` or `test`; a key only sees its own
      environment. Only `live` exists today (`cn_partner_live_…` keys).
    - **Users' plans apply to sessions.** A session you create for a user follows that user's
      Chartnaut plan (date window, history, futures access). A refusal is `422 plan_limit` with the
      reason. Demo accounts don't use the plan.

    ## Scopes

    | Scope | Shown to the user as |
    |---|---|
    | `frame:instant` | Open Chartnaut inside <partner> without signing in each time |
    | `sessions:write` | Create backtests for you, and end, lock or unlock them |
    | `sessions:read` | See those backtests: trades, profit and loss, and rule breaks |
    | `demo_accounts:write` | Create demo accounts for you; lock, unlock and close them |
    | `demo_accounts:read` | See those demo accounts: balance, positions, trades, breaches |
    | `accounts:read` | See your connected broker accounts: balances, positions and trades |
    | `alerts:read` | See when your Chartnaut alerts go off |
    | `terminal:read` | See what you do in <partner>'s Chartnaut: your charts, scripts, drawings, watchlists and backtest trades |
    | `terminal:write` | Change your charts, scripts, drawings and watchlists, and place orders in your own backtests |
    | `frame:live` | Show you live Chartnaut charts inside <partner> |

    A call that needs a scope the user did not grant is `403 scope_not_granted` with
    `details.scope` naming it. A user who isn't linked is `404 not_linked`.

    Sessions and demo accounts share most conventions: batch create answers per item, PATCH merges
    labels, trades use `instrument` and `realized_pnl`, breaches give `limit` and `value` in
    `money`, `units` or `count`. Known differences between the two (as built, 2026-11-18):

    | | Sessions | Demo accounts |
    |---|---|---|
    | Label keys | 1–64 of `A–Z a–z 0–9 _ . : -` | 1–40 of `a–z 0–9 _ . -`, starting with a letter or digit |
    | Label values | up to 200 characters | up to 100 bytes |
    | Trades and breaches lists | oldest first | newest first |
    | `side` | `long`, `short` | `Long`, `Short` |
    | Breach summary on a single read | `{count, last}` (the newest breach) | `{count, latest_at}` |
    | Bulk action results | `done`, `already`, `not_found`, `not_linked`, `conflict`, `error` | `locked`, `unlocked`, `closed`, `closing`, `already`, `not_found`, `error` |
    | A user who no longer grants the write scope, in a bulk action | `not_linked` | `not_found` (by labels: left out) |
    | `expected_count` with `ids` | `400` unless it equals the number of ids | `409 expected_count_mismatch` unless it equals the number found |
    | Bulk `200` body | `{action, matched, data}` | `{data}` |
    | Over the hourly ceiling (`202`) | `{pending_action_id, matched, message}` | `{pending_action_id}` |
    | Trades `since` filter | no | yes |

    ## The frame

    The frame is Chartnaut's own backtest screen in an iframe on your page. Two ways in:

    - **First time (or no frame token):** render `frame_url` from `POST /links`. The frame shows
      "Sign in with Chartnaut"; the user signs in in a new window on terminal.chartnaut.com, ticks
      the scopes and approves. The frame then opens on its own.
    - **Every later open:** get a frame token (`POST /users/{user}/frame-token`, needs
      `frame:instant`; valid 24 hours, the same token while it has over an hour left, so cache it)
      and render the `frame_url` it returns:
      `https://terminal.chartnaut.com/embed/<partner>?api=<api_host>[&session=ses_…]#ft=<frame_token>`.
      The token sits in the `#fragment`, so it never reaches a server log or a referrer. `api`
      points the frame at the user's own regional API host; render `frame_url` as given.

    The iframe needs `allow="clipboard-write; fullscreen"`. Only your registered frame origins may
    host it (`frame-ancestors`). Phones are not supported: the frame says so and posts
    `device_unsupported`. The script at `https://terminal.chartnaut.com/embed.js` does all of this:
    `Chartnaut.embed(el, { frameUrl })`, or `Chartnaut.embed(el, { frameToken, partner, session })`
    (that form builds the address without `api`, so the frame falls back to the API host it last
    signed in on, else the default).

    ### Events the frame posts to your page (hints)

    The frame posts to `window.parent` once per registered origin, never with `"*"`. Check
    `event.origin === "https://terminal.chartnaut.com"`, `event.source === iframe.contentWindow`
    and `event.data.source === "chartnaut"`. Every message has one shape
    (`components.schemas.FrameEvent`): `{ "source": "chartnaut", "type": "<event>", ...fields }`,
    e.g. `{ "source": "chartnaut", "type": "fill", "session_id": "ses_42", "position_id": 7,
    "order_id": 9 }`. They can be missed or repeated: read the session with `GET /sessions/{id}`.
    With embed.js: `frame.on('fill', fn)` calls `fn({ type, data })`, where `data` is the message
    without `source` and `type`.

    Two pages post events. The sign-in page (`/embed/<partner>`) posts `needs_link`, `signed_in`,
    `device_unsupported` and its own `error`, each with `session_id` when the address named one.
    Once the session is open, the backtest screen posts the rest.

    | `type` | When | Fields |
    |---|---|---|
    | `needs_link` | no usable frame token and no link (or the link can't be used): make a new link | `session_id`? |
    | `signed_in` | the user approved in the window and the frame signed in | `session_id`? |
    | `ready` | the session is open in the frame | `session_id` |
    | `fill` | an order filled (entry, stop, target) | `session_id`, `position_id`, `order_id` (each id an integer or `null`) |
    | `order` | an order was created, moved or cancelled | `session_id`, `position_id`, `order_id`, `change` (`created`, `price_changed`, `cancelled`) |
    | `close` | a position closed, all or part | `session_id`, `position_id`, `partial` |
    | `account` | balance or equity moved (at most once a second) | `session_id`, `at` (replay time, unix seconds) |
    | `breach` | a rule breach the server recorded | `session_id`, `breach_id` (`brk_…`, or `null`), `rule_type`, `action`, `at` (the bar's replay time, ISO 8601) |
    | `session_end` | the session ended | `session_id`, `status` (`ended`, `breached`, `completed_to_target`) |
    | `locked` / `unlocked` | you locked or unlocked it | `session_id` |
    | `continued_elsewhere` | another page (e.g. Chartnaut itself) took the session over | `session_id` |
    | `error` from the sign-in page | the frame can't sign in here | `session_id`?; `code` only when the browser can't hold the frame's sign-in: `partitioned_unsupported` (Safari before 26.2) or `cookie_not_stored`. Other sign-in-page errors (frames paused for you, another Chartnaut account already signed in to the frame, a refused token) carry no `code` |
    | `error` from the backtest screen | the frame stopped | `reason`: `signed_out` (get a new frame token), `wrong_mode`, `before_history`, `invalid_session`, `no_access` or `error` |
    | `device_unsupported` | opened on a phone | `session_id`? |

    ## Webhooks (hints)

    See `webhooks` below. Every delivery is `POST` JSON to your endpoint with
    `Chartnaut-Signature: t=<unix seconds>,v1=<hex>`, `Chartnaut-Event-Id: evt_…` and
    `Chartnaut-Event-Type: <type>`. `v1` is HMAC-SHA256 of `"<t>.<raw body>"` with the endpoint's
    signing secret, hex-encoded. While a secret is being rotated the header carries a second `v1=`
    signed with the previous secret; accept either. Reject a `t` more than 5 minutes from your
    clock. Answer 2xx within 10 seconds. Anything else is retried up to 24 attempts, waiting 30
    seconds and doubling to at most 12 hours between them (about a week in all), then marked dead
    (resend from the portal). Deduplicate on `id`.
  contact:
    email: partners@chartnaut.com
  termsOfService: https://docs.chartnaut.com/partners/terms

servers:
  - url: https://api.chartnaut.com/partner/v1
    description: |
      The partner API. The regional hosts (`eu-api.chartnaut.com`, `us-api.chartnaut.com`) answer
      every call too. Link and frame-token answers carry an `api_host`; it is already inside
      `frame_url`, so you don't need to use it.

security:
  - partnerKey: []

tags:
  - name: Users
    description: Linked users, their scopes, frame tokens and alert fires.
  - name: Managed users
    description: Business only. Chartnaut accounts you own, opened only in your frames, with no email, password or consent screen.
  - name: Links
    description: Start linking a user's Chartnaut account to your user.
  - name: Sessions
    description: Backtest sessions you create for your users.
  - name: Accounts
    description: Demo accounts you create for your users, and (with `accounts:read`) the user's own accounts.
  - name: Webhooks
    description: Test deliveries. Add endpoints and see their secrets on your project's **Webhooks** tab (Developers).
  - name: Scripts
    description: Your own scripts, published to your app for its users.

paths:
  # ───────────────────────────── Users ─────────────────────────────
  /users:
    get:
      tags: [Users]
      operationId: listUsers
      summary: List your linked users
      description: Active bindings only, oldest first (in the order they linked). Names and emails are never returned.
      parameters:
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of linked users.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/LinkedUser' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Managed users]
      operationId: createManagedUser
      summary: Create a managed user
      description: |
        Business only. A Chartnaut account you own: no email, no password, opened only in your
        frames (`frame:instant`, `terminal:read` and `terminal:write` are implicit, with no consent
        screen). `201` when made; `200` with the same user when that `external_ref` exists already.
        Free and Pro developers get `plan_limit`. Past your seats (with 10% grace) a new managed
        user gets `seat_limit`; users active this month carry on.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateManagedUser' }
      responses:
        '201':
          description: Created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ManagedUser' }
        '200':
          description: A managed user with that `external_ref` exists already.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ManagedUser' }
        default: { $ref: '#/components/responses/Error' }

  /users/{user}:
    get:
      tags: [Users]
      operationId: getUser
      summary: Read a linked user
      description: |
        The binding: your ref, the Chartnaut user id, the scopes granted and when
        they connected. `404 not_linked` when the user isn't (or is no longer) linked to you.
      parameters:
        - $ref: '#/components/parameters/User'
      responses:
        '200':
          description: The linked user.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/LinkedUser' }
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Managed users]
      operationId: updateManagedUser
      summary: Change a managed user's level or features
      description: Business only. Send only what changes. A linked (not managed) user is refused.
      parameters:
        - $ref: '#/components/parameters/User'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/UpdateManagedUser' }
      responses:
        '200':
          description: The managed user after the change.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/ManagedUser' }
        default: { $ref: '#/components/responses/Error' }
    delete:
      tags: [Managed users]
      operationId: deleteManagedUser
      summary: Delete a managed user
      description: |
        Business only; needs the key permission `users:delete`. The account is deleted and its
        frames stop. Export the user's data first if you need it.
      parameters:
        - $ref: '#/components/parameters/User'
      responses:
        '202':
          description: Deleting.
          content:
            application/json:
              schema:
                type: object
                required: [id, deleted]
                properties:
                  id: { type: string, pattern: '^usr_[0-9]+$' }
                  deleted: { const: true }
        default: { $ref: '#/components/responses/Error' }

  /users/{user}/export:
    post:
      tags: [Managed users]
      operationId: exportManagedUser
      summary: Export a managed user's data
      description: |
        Needs the key permission `users:export`. Starts an export and answers `202` at once;
        `export.ready` (with the download `url` and `expires_at`) follows, or poll
        `GET /exports/{export}`. Still works for 30 days after you've left, while your managed
        users are kept.
      parameters:
        - $ref: '#/components/parameters/User'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '202':
          description: The export has started.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UserExport' }
        default: { $ref: '#/components/responses/Error' }

  /exports/{export}:
    get:
      tags: [Managed users]
      operationId: getExport
      summary: Read an export
      description: The same answer as the `export.ready` webhook, for a server that polls. Needs `users:export`.
      parameters:
        - name: export
          in: path
          required: true
          description: The export id from `POST /users/{user}/export`.
          schema: { type: string }
      responses:
        '200':
          description: The export.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/UserExport' }
        default: { $ref: '#/components/responses/Error' }

  /users/{user}/connection:
    delete:
      tags: [Users]
      operationId: disconnectUser
      summary: Unlink a user
      description: |
        Ends the binding. Their frame token and frame sign-ins stop, demo accounts you created for
        them lock, and sessions stay the user's. Sends `user.disconnected`.
        The user can link again later through a new link. A user who isn't linked is `404 not_linked`.
      parameters:
        - $ref: '#/components/parameters/User'
      responses:
        '200':
          description: Unlinked.
          content:
            application/json:
              schema:
                type: object
                required: [disconnected]
                properties:
                  disconnected: { const: true }
        default: { $ref: '#/components/responses/Error' }

  /users/{user}/frame-token:
    post:
      tags: [Users]
      operationId: createFrameToken
      summary: Get a frame URL for a user
      description: |
        Needs `frame:instant` (`403 scope_not_granted` otherwise). Valid 24 hours. Asking again
        returns the same token while it has more than an hour left, so cache it; one live token per
        user. `frame_url` is ready to render:
        `https://terminal.chartnaut.com/embed/<partner>?api=<api_host>[&session=ses_…]#ft=<frame_token>`.
        `api_host` is the API origin the user linked through (their region), or the one you called
        if that isn't known. A token opens a backtest-only sign-in that ends when the token expires
        or the user is unlinked. Each token can be claimed 100 times a day. `403 switched_off` while
        frames are paused. An unknown field is `400 invalid_request`. One token per grant (app,
        mode, persist, session): the same grant gets the same token while it has over an hour
        left. Past 60 mints an hour for one user and app: `429 rate_limited` with `Retry-After`
        and `details.retry_after` (cache the URL until an hour before `expires_at`).

        **Backtests by key** (`backtest`, instead of `session`; needs `terminal:write` or
        `sessions:write`, else `403 scope_not_granted`): the first mint for a key creates a normal
        backtest owned by the user (their plan's window and history apply: `422 plan_limit`;
        every market; basic costs; per-asset-class margin at 1:100), tagged with the app so orders
        from your page may trade in it; every later mint with that key in that app returns the
        same session, whatever window it sends. The frame is bound to it. It is not a partner
        session: `GET /sessions` doesn't list it. A bad field is `400 invalid_request` with
        `details.field` (`backtest.key`, `backtest.start`, `backtest.end`,
        `backtest.starting_balance`). The window keeps its times of day (`start` 08:00 and `end`
        20:00 on one day is twelve hours). The backtest is made only once nothing else refuses the
        mint (the hourly ceiling, seats, your plan, switches): a refused mint makes nothing.
        Later mints may also name it by its id (`session`).
      parameters:
        - $ref: '#/components/parameters/User'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                app:
                  type: string
                  description: '`app_<id>` or the app''s slug. Default your default app (its slug is your partner slug).'
                mode:
                  type: string
                  enum: [backtest, live]
                  description: Left out is today's backtest frame. `live` needs `frame:live` on your account and from the user.
                persist:
                  type: string
                  enum: [device, account, none, host]
                  description: Where the layout is kept. Default the app's. `account` is refused for a managed user.
                session:
                  type: string
                  pattern: '^ses_[0-9]+$'
                  description: Open this session (one of yours for this user, or the user's backtest made in this app, e.g. by `backtest.key`; `404 not_found` with `details.session` otherwise). Not with `backtest`.
                backtest:
                  type: object
                  additionalProperties: false
                  required: [key, start]
                  properties:
                    key: { type: string, minLength: 1, maxLength: 200, description: 'Your name for this backtest: visible ASCII, no spaces. Unique per app and user.' }
                    start: { type: string, description: 'As `CreateSession.start`: a UTC date or an RFC 3339 time, in the past.' }
                    end: { type: string, description: 'As `CreateSession.end`. Left out: plays on to the latest data.' }
                    starting_balance: { type: number, exclusiveMinimum: 0, maximum: 1000000000, default: 100000, description: USD. }
      responses:
        '200':
          description: The live frame token.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/FrameToken' }
        default: { $ref: '#/components/responses/Error' }

  /users/{user}/alert-fires:
    get:
      tags: [Users]
      operationId: listAlertFires
      summary: List a user's alert fires
      description: |
        Needs `alerts:read`. Oldest first, in the order Chartnaut recorded them, after `since` (by
        default 24 hours ago). Paging follows when a fire was recorded, not when its event happened,
        so polling "since my last call" never misses a fire recorded late. With `cursor`, `since` is
        ignored. A `since` that isn't RFC 3339, or a cursor this API didn't give, is `400
        invalid_request`.
      parameters:
        - $ref: '#/components/parameters/User'
        - name: since
          in: query
          description: 'RFC 3339, e.g. `2026-11-17T09:00:00Z`. Fires recorded after it.'
          schema: { type: string, format: date-time }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/LimitDetail'
      responses:
        '200':
          description: A page of fires.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/AlertFire' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Links ─────────────────────────────
  /links:
    post:
      tags: [Links]
      operationId: createLink
      summary: Make a link for one of your users
      description: |
        Server to server only: if a browser could make links, anyone could attach their own
        Chartnaut account to someone else's account on your site. A link is single-use and
        expires in 30 minutes. Render `frame_url` in an iframe, or send the user to `connect_url`.

        On approval your `external_user_ref` is bound to the Chartnaut account that signed in,
        with the scopes the user ticked: every `required_scopes` entry is shown ticked and fixed;
        other scopes are ticked and can be unticked. One-to-one per partner: a ref already bound
        to another Chartnaut account, or a Chartnaut account already bound to another of your
        refs, is refused in the window ("This <partner> account is linked to a different
        Chartnaut account."). A user who is already linked and asked for new scopes is shown only
        the new ones.

        Send `account_label`, your own name for the person (their username or email on your
        site). The window shows it masked next to the Chartnaut account that is signed in: "Link
        <App> account j…@x.com to your Chartnaut account c…@gmail.com". Someone sent another
        person's link then sees the account isn't theirs before connecting. The full label never
        reaches the browser.

        20,000 links in any 24 hours per partner and 5 open (unused, unexpired) links per ref.
        Past either it is `422 partner_limit` with `details.limit` (`links_per_day` or
        `open_links_per_user`). An unknown scope, a scope not enabled for you, a required scope
        missing from `scopes`, an empty `scopes`, a bad `external_user_ref` or a `session_id` that
        isn't one of your sessions is `400 invalid_request`. `403 switched_off` while links are
        paused.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [external_user_ref, scopes]
              properties:
                external_user_ref:
                  type: string
                  minLength: 1
                  maxLength: 200
                  description: Your id for the user. Stable; never an email.
                scopes:
                  type: array
                  minItems: 1
                  items: { $ref: '#/components/schemas/Scope' }
                required_scopes:
                  type: array
                  description: A subset of `scopes` the user can't untick.
                  items: { $ref: '#/components/schemas/Scope' }
                session_id:
                  type: string
                  pattern: '^ses_[0-9]+$'
                  description: Open this session once linked. Must be one of your sessions (`400 invalid_request` otherwise) and belong to the user who signs in.
                account_label:
                  type: string
                  maxLength: 200
                  description: |
                    Your name for the person on your site (a username or email), shown masked on the
                    consent screen ("j…@x.com", "ja…th"). Strongly recommended. Up to 200 characters;
                    control, invisible and text-direction characters are `400 invalid_request`.
                  example: jane@example.com
      responses:
        '201':
          description: The link.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Link' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Scripts ─────────────────────────────
  /scripts:
    post:
      tags: [Scripts]
      operationId: publishScript
      summary: Publish one of your scripts to your app
      description: |
        Publishes an indicator (layers included), a definition or an insight your team owns (the
        account owner's or a team member's own Chartnaut scripts; private ones are the point) to
        one of your apps. Every user of the app runs it inside the app without installing anything;
        on chartnaut.com it doesn't run, and it is never listed in the community.

        No `version` follows the script's current version; a `version` pins it (a workspace
        pinned to a version you published before keeps it). `run_only`: the frame never receives
        the source, only a scrambled bundle. That hides the code from casual view; it is not
        cryptographic protection (anything a browser runs can be recovered). `listed: false`
        keeps it out of the script picker: add it by id from your page. Republishing changes only
        what you send. `201` the first time, `200` after.

        Someone else's script, or an id that doesn't exist: `404 not_found`. A version that
        doesn't exist, or a version on an insight: `400 invalid_request`. `run_only` on a script
        whose source is already shared in the community (public or unlisted, source shown):
        `409 conflict`. At most 500 scripts an app (`409 partner_limit`).
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [script]
              properties:
                script:
                  type: string
                  pattern: '^(ind|flw|ins)_[0-9]+$'
                  description: '`ind_<n>` an indicator or layer, `flw_<n>` a definition, `ins_<n>` an insight.'
                version: { type: integer, minimum: 1, description: A saved version number; leave it out to follow the current one. }
                run_only: { type: boolean, description: Never send the source to the frame. Default false. }
                listed: { type: boolean, description: In the script picker. Default true. }
                app: { type: string, description: '`app_<n>` or the app''s slug. Default your default app.' }
      responses:
        '200':
          description: Republished.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AppScript' }
        '201':
          description: Published.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AppScript' }
        default: { $ref: '#/components/responses/Error' }
    get:
      tags: [Scripts]
      operationId: listScripts
      summary: The scripts published to an app
      parameters:
        - name: app
          in: query
          description: '`app_<n>` or the app''s slug. Default your default app.'
          schema: { type: string }
      responses:
        '200':
          description: Every script published to the app, newest first.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    properties:
                      data: { type: array, items: { $ref: '#/components/schemas/AppScript' } }
        default: { $ref: '#/components/responses/Error' }
  /scripts/{script}:
    delete:
      tags: [Scripts]
      operationId: unpublishScript
      summary: Take a script off your app
      description: Frames stop running it on their next load (the chart keeps working without it). `404 not_found` when it isn't published to that app.
      parameters:
        - name: script
          in: path
          required: true
          schema: { type: string, pattern: '^(ind|flw|ins)_[0-9]+$' }
        - name: app
          in: query
          schema: { type: string }
      responses:
        '200':
          description: Unpublished.
          content:
            application/json:
              schema:
                type: object
                properties:
                  script: { type: string }
                  app: { type: string }
                  removed: { type: boolean, enum: [true] }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Sessions ─────────────────────────────
  /sessions:
    get:
      tags: [Sessions]
      operationId: listSessions
      summary: List your sessions, by user, label or status
      description: |
        Newest first (by when you created them). Only sessions you created, for users who are still
        linked and grant `sessions:read`. With `user`, needs that user's `sessions:read`. Labels
        filter with `label.<key>=<value>` (several are ANDed), e.g.
        `?label.event=nov-open&label.round=2`.

        List items are summaries (`SessionSummary`): `account` has only `currency`, `balance` and
        `realized_pnl` (no equity or open P&L), and `stats` counts `trades` only. There are no
        `open_positions`, `working_orders`, `rules` or `breaches`. Read `GET /sessions/{session}`
        for those.
      parameters:
        - $ref: '#/components/parameters/UserQuery'
        - $ref: '#/components/parameters/LabelFilter'
        - name: status
          in: query
          schema: { $ref: '#/components/schemas/SubjectStatus' }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of sessions.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/SessionSummary' }
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Sessions]
      operationId: createSession
      summary: Create a backtest session for a user
      description: |
        Needs `sessions:write`. The session follows the user's plan: a day outside the plan's window
        or history, or a market the user's account can't use (e.g. futures without futures access),
        is `422 plan_limit` with the reason in `message` and `details.reason`. 10 active (active or
        locked) sessions per user and 10,000 per partner (`422 partner_limit`, `details.limit`
        `active_sessions_per_user` or `active_sessions`). `rules` are copied onto the session and
        fixed after that. A reused `external_ref` is `409 conflict` with `details.existing_id`. A
        bad field is `400 invalid_request` with `details.field` (e.g. `instruments[1]`, `start`,
        `labels.cohort`); an unknown market is `400` on `instruments[i]`; a refusal by the
        session start itself (e.g. no data for the day) is `400` with no `details`. Answers `201`
        with the full session, as `GET /sessions/{session}` gives it.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateSession' }
            example:
              user: ext:user-8812
              name: Week 47 challenge
              instruments: [NAS100, EURUSD]
              start: '2026-09-01'
              end: '2026-09-30'
              starting_balance: 100000
              time_cap_minutes: 120
              rules:
                day_reset: { time: '17:00', tz: America/New_York }
                rules:
                  - { type: daily_loss, limit: { percent: 5 }, on_breach: close_and_end }
                  - { type: max_drawdown, limit: { percent: 10 }, mode: fixed, on_breach: close_and_end }
                  - { type: profit_target, target: { percent: 8 } }
              external_ref: challenge-981-user-8812
              labels: { event: week-47 }
              page_control: replay_and_orders
      responses:
        '201':
          description: Created.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Session' }
        default: { $ref: '#/components/responses/Error' }

  /sessions/batch:
    post:
      tags: [Sessions]
      operationId: createSessions
      summary: Create up to 500 sessions in one call
      description: |
        Each item is created or refused on its own, in order; `data[i]` answers `items[i]` with
        `index` (from 0) and the new `id`, or an `error` (`code`, `message`, `details`) as a single
        create would give it. The answer is `200` even when every item was refused. An empty
        `items`, more than your `batch_create` limit (500), or a body that doesn't parse (an
        unknown field in any item included) refuses the whole call with `400 invalid_request`. The
        whole call is one Idempotency-Key.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [items]
              properties:
                items:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items: { $ref: '#/components/schemas/CreateSession' }
      responses:
        '200':
          description: One result per item, in order.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      required: [index]
                      properties:
                        index: { type: integer }
                        id: { type: string, pattern: '^ses_[0-9]+$' }
                        error: { $ref: '#/components/schemas/ErrorBody' }
        default: { $ref: '#/components/responses/Error' }

  /sessions/actions:
    post:
      tags: [Sessions]
      operationId: sessionActions
      summary: End, lock or unlock many sessions
      description: |
        Name the sessions by `ids` (up to 1,000) or by `labels`, never both. A label-wide action
        needs `expected_count`, and is refused with `409 expected_count_mismatch` (nothing done;
        `details.expected` and `details.actual`) if the real count differs. With `ids`, an
        `expected_count` that isn't the number of ids is `400 invalid_request`; an id that isn't
        `ses_…` is `400` with `details.field` `ids[i]`. Each session answers on its own in `data`
        with a `result`: `done`, `already`, `not_found` (not one of yours), `not_linked` (its user
        is no longer linked or doesn't grant `sessions:write`), `conflict` (e.g. lock or unlock on
        a session that has ended) or `error`. `status` is set on an `end` that was `done`.
        `matched` counts the sessions found.

        - `lock`: frozen. No orders, edits, cancels, exits or fills (stops and targets included), and
          the replay can't move forward. An open frame freezes its controls.
        - `unlock`: resumes exactly where it stopped.
        - `end`: final. An open page closes at its price; with no page open the server closes open
          positions at the close of the bar at the replay time.

        `end` counts toward 2,000 items an hour per partner, shared with demo account `close_all`.
        Past that nothing is done and the whole request waits for Chartnaut's approval: `202` with
        `pending_action_id`, `matched` and `message`. `403 switched_off` while bulk actions are
        paused.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/BulkTarget'
                - type: object
                  required: [action]
                  properties:
                    action: { type: string, enum: [end, lock, unlock] }
      responses:
        '200':
          description: Done; one result per session.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema:
                type: object
                required: [action, matched, data]
                properties:
                  action: { type: string, enum: [end, lock, unlock] }
                  matched: { type: integer }
                  data:
                    type: array
                    items:
                      type: object
                      required: [id, result]
                      properties:
                        id: { type: string }
                        result: { type: string, enum: [done, already, not_found, not_linked, conflict, error] }
                        status: { $ref: '#/components/schemas/SubjectStatus' }
                        error: { type: string }
        '202':
          description: Over the hourly ceiling; nothing done, waiting for approval.
          content:
            application/json:
              schema:
                type: object
                required: [pending_action_id, matched]
                properties:
                  pending_action_id: { type: integer }
                  matched: { type: integer }
                  message: { type: string }
        default: { $ref: '#/components/responses/Error' }

  /sessions/{session}:
    get:
      tags: [Sessions]
      operationId: getSession
      summary: Read a session
      description: |
        Needs `sessions:read`. `account` is valued at `replay_time`: `balance` and `realized_pnl`
        from closed trades, `equity` and `unrealized_pnl` with open positions at the bar close at
        the replay time. The replay clock is saved every few seconds while the user plays, so it
        can trail the screen slightly. An id that isn't one of your sessions is `404 not_found`.
      parameters:
        - $ref: '#/components/parameters/SessionId'
      responses:
        '200':
          description: The session.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Session' }
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Sessions]
      operationId: updateSession
      summary: Change a session's labels or page control
      description: |
        Needs `sessions:write`. Labels and `page_control` only; everything else is fixed at create.
        Send at least one. `labels` is a JSON merge patch: a key with a string sets it, a key with
        `null` removes it, keys you leave out stay. The labels after the merge must still be valid
        (at most 20). Answers with the full session.
      parameters:
        - $ref: '#/components/parameters/SessionId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              properties:
                labels:
                  type: object
                  propertyNames: { pattern: '^[A-Za-z0-9_.:-]{1,64}$' }
                  additionalProperties: { type: [string, 'null'], maxLength: 200 }
                  example: { round: '2', cohort: null }
                page_control: { $ref: '#/components/schemas/PageControl' }
      responses:
        '200':
          description: The session.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Session' }
        default: { $ref: '#/components/responses/Error' }

  /sessions/{session}/trades:
    get:
      tags: [Sessions]
      operationId: listSessionTrades
      summary: A session's closed trades
      description: |
        Needs `sessions:read`. Oldest first, in the order they closed in replay time. Open positions
        are on the session itself (`open_positions`).
      parameters:
        - $ref: '#/components/parameters/SessionId'
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/LimitDetail'
      responses:
        '200':
          description: A page of closed trades.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/SessionTrade' }
        default: { $ref: '#/components/responses/Error' }

  /sessions/{session}/breaches:
    get:
      tags: [Sessions]
      operationId: listSessionBreaches
      summary: A session's rule breaches
      description: Needs `sessions:read`. Oldest first, by the breach's time (`at`).
      parameters:
        - $ref: '#/components/parameters/SessionId'
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/LimitDetail'
      responses:
        '200':
          description: A page of breaches.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/Breach' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Accounts ─────────────────────────────
  /accounts:
    get:
      tags: [Accounts]
      operationId: listAccounts
      summary: List demo accounts you created, or a user's own accounts
      description: |
        `origin=partner` (default): demo accounts you created, newest first, for users who are
        still linked and grant `demo_accounts:read` (with `user`, that user must). Filter by
        `user`, `label.<key>=<value>` and `status`. List items are `Account` without `valuation`
        (so no equity), `positions` or `breaches`: those are on `GET /accounts/{account}` only.
        `rules` is included.

        `origin=user`: the user's own accounts, not the ones you created: their own Chartnaut Demo
        account and every broker account they linked (MT4, MT5, cTrader and the rest). Needs `user`
        (`400 invalid_request` without it) and that user's `accounts:read`. Items are
        `UserAccount`, oldest first (by account id). `label.*` and `status` are ignored. Read-only:
        these ids are not yours to act on, and `GET /accounts/{account}` on one is `404
        not_found`. Only balances are returned: no positions or trades.

        Any other `origin` is `400 invalid_request`.
      parameters:
        - $ref: '#/components/parameters/UserQuery'
        - name: origin
          in: query
          schema: { type: string, enum: [partner, user], default: partner }
        - $ref: '#/components/parameters/LabelFilter'
        - name: status
          in: query
          schema: { $ref: '#/components/schemas/SubjectStatus' }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/Limit'
      responses:
        '200':
          description: A page of accounts.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items:
                          anyOf:
                            - $ref: '#/components/schemas/Account'
                            - $ref: '#/components/schemas/UserAccount'
        default: { $ref: '#/components/responses/Error' }
    post:
      tags: [Accounts]
      operationId: createAccount
      summary: Create a demo account for a user
      description: |
        Needs `demo_accounts:write`. A Chartnaut Demo account in USD under the user's own demo
        connection (made for them if they have none), filled at real prices on our server. Created
        `locked` unless you send `"locked": false`, so you can open a whole event at once with a
        bulk `unlock`. Demo accounts never use the user's plan slots or live-account credits.

        5 active (active or locked) per user and 2,000 per partner: `422 partner_limit` with
        `details.limit` (`demo_accounts_per_user` or `demo_accounts`) and `details.max`. A reused
        `external_ref` is `409 conflict` with `details.field: "external_ref"`. Invalid `rules` are
        `400 invalid_request` with `details.field` pointing into `rules`. Any other bad field
        (`display_name`, `starting_balance`, `leverage`, `external_ref`, `labels`) is `400
        invalid_request` naming it in `message`, with no `details`; so is an unknown field. A user
        who isn't linked is `404 not_linked`; one who didn't grant `demo_accounts:write` is `403
        scope_not_granted`. `403 switched_off` while demo account creation is paused.

        Answers `201` with the account as `GET /accounts/{account}` gives it.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateAccount' }
      responses:
        '201':
          description: Created.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Account' }
        default: { $ref: '#/components/responses/Error' }

  /accounts/batch:
    post:
      tags: [Accounts]
      operationId: createAccounts
      summary: Create up to 500 demo accounts in one call
      description: |
        Per item, like `POST /sessions/batch`: each item is created (in its own transaction) or
        refused on its own, and `data[i]` answers `items[i]` with `index` (from 0) and the new
        `id`, or an `error` (`code`, `message`, `details`) as a single create would give it. The
        answer is `200` even when every item was refused. An empty `items`, more than your
        `batch_create` limit (500), or a body that doesn't parse (an unknown field in any item
        included) refuses the whole call with `400 invalid_request`; `403 switched_off` while demo
        account creation is paused. The whole call is one Idempotency-Key.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [items]
              properties:
                items:
                  type: array
                  minItems: 1
                  maxItems: 500
                  items: { $ref: '#/components/schemas/CreateAccount' }
      responses:
        '200':
          description: One result per item, in order.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items:
                      type: object
                      required: [index]
                      properties:
                        index: { type: integer }
                        id: { type: string, pattern: '^acc_[0-9]+$' }
                        error: { $ref: '#/components/schemas/ErrorBody' }
        default: { $ref: '#/components/responses/Error' }

  /accounts/actions:
    post:
      tags: [Accounts]
      operationId: accountActions
      summary: Lock, unlock or close everything on many demo accounts
      description: |
        Your demo accounts only, for users who still grant `demo_accounts:write`. Named by `ids`
        (up to 1,000, each `acc_…`) or by `labels`, never both. `labels` needs `expected_count`.
        When `expected_count` is given (with `ids` or `labels`) and the number of accounts found
        differs, it is `409 expected_count_mismatch` with `details.expected` and `details.actual`,
        and nothing is done. Labels matching more than 1,000 accounts are `400 invalid_request`.

        Each account answers on its own in `data`: `{id, result, error?}`. `result` is:

        | `result` | Meaning |
        |---|---|
        | `locked` / `unlocked` | this call locked or unlocked it |
        | `closed` | `close_all`: locked, and nothing is left open |
        | `closing` | `close_all`: locked, positions still closing (a closed market, or past the call's 20 seconds); `error` may say why. Read the account for the result |
        | `already` | it was already in that state, or it has ended (lock, unlock) |
        | `not_found` | not one of yours, or its user no longer grants `demo_accounts:write` |
        | `error` | it failed; `error` says why. Retry |

        Ids not found come first, then the rest in account id order. Acting by labels, accounts
        whose user no longer grants the scope are left out rather than listed.

        - `lock`: frozen. The user can place, change, cancel or close nothing, and nothing fills:
          a resting entry, stop or target that is crossed stays armed and fills only after an
          unlock, if the price is still there. A margin stop-out still runs. The user sees
          "Locked by <partner>".
        - `unlock`: trading resumes.
        - `close_all`: locks, then cancels positions whose entry hasn't filled and closes the rest
          at market. It closes inline for up to 20 seconds; the rest are queued (`closing`). It
          works on locked accounts and is safe to repeat.

        `close_all` counts toward 2,000 items an hour per partner, shared with session `end`. Past
        that nothing is done and the whole call waits for Chartnaut's approval: `202` with
        `{"pending_action_id": n}` only. `403 switched_off` while bulk actions are paused.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/BulkTarget'
                - type: object
                  required: [action]
                  properties:
                    action: { type: string, enum: [lock, unlock, close_all] }
      responses:
        '200':
          description: Done; one result per account.
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AccountActionResult' }
        '202':
          description: '`close_all` over the hourly ceiling: nothing done, waiting for approval.'
          headers: { Idempotent-Replayed: { $ref: '#/components/headers/IdempotentReplayed' } }
          content:
            application/json:
              schema:
                type: object
                required: [pending_action_id]
                properties:
                  pending_action_id: { type: integer }
        default: { $ref: '#/components/responses/Error' }

  /accounts/{account}:
    get:
      tags: [Accounts]
      operationId: getAccount
      summary: Read an account
      description: |
        A demo account you created needs `demo_accounts:read`: balance, the live `valuation`
        (equity, floating P&L, margin), open `positions`, lock state, rules and a `breaches`
        summary. Only a single read has `valuation`, `positions` and `breaches`. `valuation` is
        left out when the account can't be valued now.

        One of the user's own accounts (an id from `origin=user`) needs `accounts:read` and answers
        a `UserAccount`; its open positions are at `/accounts/{account}/positions` and its closed
        trades at `/accounts/{account}/trades`. An account of a user who isn't linked to your app is
        `404 not_found`, as if it didn't exist; a linked user who didn't grant `accounts:read` is
        `403 scope_not_granted`.
      parameters:
        - $ref: '#/components/parameters/AccountId'
      responses:
        '200':
          description: The account.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/Account'
                  - $ref: '#/components/schemas/UserAccount'
        default: { $ref: '#/components/responses/Error' }
    patch:
      tags: [Accounts]
      operationId: updateAccount
      summary: Change a demo account's labels
      description: |
        Needs `demo_accounts:write`. `labels` is a JSON merge patch: a key with a string sets it, a
        key with `null` removes it, keys you leave out stay. Answers with the account as a list
        item gives it (no `valuation`, `positions` or `breaches`).
      parameters:
        - $ref: '#/components/parameters/AccountId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [labels]
              properties:
                labels:
                  type: object
                  propertyNames: { pattern: '^[a-z0-9][a-z0-9_.-]{0,39}$' }
                  additionalProperties: { type: [string, 'null'], maxLength: 100 }
                  example: { tier: pro, cohort: null }
      responses:
        '200':
          description: The account.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Account' }
        default: { $ref: '#/components/responses/Error' }

  /accounts/{account}/trades:
    get:
      tags: [Accounts]
      operationId: listAccountTrades
      summary: An account's closed trades
      description: |
        Newest first, by close time. A demo account you created needs `demo_accounts:read`; one of
        the user's own accounts (any broker) needs `accounts:read`.
      parameters:
        - $ref: '#/components/parameters/AccountId'
        - name: since
          in: query
          description: 'RFC 3339. Only trades closed at or after it.'
          schema: { type: string, format: date-time }
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/LimitDetail'
      responses:
        '200':
          description: A page of closed trades.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/AccountTrade' }
        default: { $ref: '#/components/responses/Error' }

  /accounts/{account}/positions:
    get:
      tags: [Accounts]
      operationId: listAccountPositions
      summary: A user's own account's open positions
      description: |
        Needs `accounts:read`. The open positions on one of the user's own accounts (an id from
        `origin=user`), oldest first, as Chartnaut last stored them. A demo account you created
        carries its positions in `GET /accounts/{account}` instead (`404` here).
      parameters:
        - $ref: '#/components/parameters/AccountId'
      responses:
        '200':
          description: The open positions.
          content:
            application/json:
              schema:
                type: object
                required: [data]
                properties:
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/UserPosition' }
        default: { $ref: '#/components/responses/Error' }

  /accounts/{account}/breaches:
    get:
      tags: [Accounts]
      operationId: listAccountBreaches
      summary: A demo account's rule breaches
      description: Needs `demo_accounts:read`. Newest first, by the breach's time (`at`).
      parameters:
        - $ref: '#/components/parameters/AccountId'
        - $ref: '#/components/parameters/Cursor'
        - $ref: '#/components/parameters/LimitDetail'
      responses:
        '200':
          description: A page of breaches.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Page'
                  - type: object
                    required: [data]
                    properties:
                      data:
                        type: array
                        items: { $ref: '#/components/schemas/Breach' }
        default: { $ref: '#/components/responses/Error' }

  # ───────────────────────────── Webhooks ─────────────────────────────
  /webhooks/test:
    get:
      tags: [Webhooks]
      operationId: sendTestWebhook
      summary: Send a `test.ping`
      description: |
        Queues one `test.ping` per active endpoint (or only `webhook`), delivered through the outbox
        like any event. Check the portal's webhook log, or your endpoint. `404 not_found` when no
        endpoint is set up; `400 invalid_request` when `webhook` isn't a positive integer.

        Paced: one `test.ping` per endpoint every 10 seconds. Endpoints pinged moments ago are left
        out; when every endpoint asked for was, `429 rate_limited` with `Retry-After` and
        `details.retry_after` (seconds). A `test.ping` is tried once (no retries), and reaches a
        paused endpoint too (paused for failing or over your plan's endpoint limit), so you can
        check a fix before resuming it.
      parameters:
        - name: webhook
          in: query
          description: One endpoint's id (from the portal).
          schema: { type: integer }
      responses:
        '202':
          description: Queued.
          content:
            application/json:
              schema:
                type: object
                required: [event_id]
                properties:
                  event_id: { type: string, pattern: '^evt_' }
        default: { $ref: '#/components/responses/Error' }

webhooks:
  partnerEvent:
    post:
      operationId: partnerEvent
      summary: Webhook event
      description: |
        Headers: `Chartnaut-Signature: t=<unix>,v1=<hex hmac_sha256(secret, t + "." + body)>[,v1=<previous secret's>]`,
        `Chartnaut-Event-Id: evt_…`, `Chartnaut-Event-Type: <type>`, `Content-Type:
        application/json`. At least once, in no guaranteed order. Answer 2xx within 10 s; anything
        else is retried up to 24 attempts (30 s doubling to 12 h between them).

        Each endpoint is delivered to on its own, at most 2 requests at a time, so a slow or
        flooded endpoint never holds up another. After 25 failed deliveries in a row over more
        than an hour, the endpoint is **paused**: only `test.ping` is sent to it until you press
        Resume (Webhooks, in the portal or the Developers page), and your account's owners and
        admins get an email. Its events wait 3 days and go out on resume.

        Live endpoints also count against your developer plan, across all your apps (Test ones
        count against nothing). After a downgrade that leaves you over the limit, every endpoint
        keeps delivering for 7 days (you get an email and a banner); then the oldest up to the
        limit carry on and the rest pause with the reason `over_plan_limit`, their events held
        3 days and `test.ping` still delivered. Choose which stay active on the Webhooks tab
        (your project's **Webhooks** tab on the Developers page) at any time; Resume
        on an endpoint paused over the limit is refused (409) unless there is room; an upgrade
        lifts the pauses by itself, oldest first.

        | `type` | `data` | Read |
        |---|---|---|
        | `user.connected` | `user`, `external_user_ref` | `GET /users/{user}` |
        | `user.disconnected` | `user`, `external_user_ref`, `by` (`user`, `partner` or `admin`) | `GET /users/{user}` (404 `not_linked`) |
        | `user.deleted` | `user`, `external_user_ref` | delete what you hold for them |
        | `session.ended` | `user`, `session`, `status` (`ended`, `breached`, `completed_to_target`), `external_ref` (the session's, when it has one) | `GET /sessions/{session}` |
        | `rule.breached` | `user`, `external_user_ref` (when linked), `session` or `account`, `breach`, `rule_id` | `GET /sessions/{session}/breaches` or `/accounts/{account}/breaches` |
        | `alert.fired` | `user`, `external_user_ref`, `alert`, `fire` (sent only while the user grants `alerts:read`) | `GET /users/{user}/alert-fires` |
        | `limits.warning` | `limit` (`free_linked`, `seats`, `pro_seats` or `data`), `used`, `cap`, `percent` (`80` or `100`). Once per threshold per UTC month, for your developer account (all your apps count together), sent to each of your apps' endpoints; your account's owner and billing email get the same by email | the Developers page's Plan and billing |
        | `test.ping` | (empty) | |
      parameters:
        - name: Chartnaut-Signature
          in: header
          required: true
          schema: { type: string, pattern: '^t=[0-9]+(,v1=[0-9a-f]{64})+$' }
        - name: Chartnaut-Event-Id
          in: header
          required: true
          schema: { type: string, pattern: '^evt_' }
        - name: Chartnaut-Event-Type
          in: header
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WebhookEvent' }
      responses:
        '2XX': { description: Received. Anything else is retried with backoff. }

components:
  securitySchemes:
    partnerKey:
      type: http
      scheme: bearer
      description: |
        A secret key: `cn_partner_test_…` (Test) or `cn_partner_live_…` (Live), made on your
        project's **Keys** tab (Developers). Shown once, stored hashed. Server-side only: never in a
        browser, an app or a frame URL. Rotate by creating a new key, switching, then revoking the
        old one (both work in between). `Authorization: Bearer cn_partner_live_…`.

  headers:
    IdempotentReplayed:
      description: '`true` when this is the stored response of an earlier request with the same Idempotency-Key.'
      schema: { type: string, enum: ['true'] }

  parameters:
    User:
      name: user
      in: path
      required: true
      description: '`usr_<id>`, or your own ref as `ext:<external_user_ref>` (URL-encoded).'
      schema: { type: string, pattern: '^(usr_[0-9]+|ext:.+)$', example: 'ext:user-8812' }
    UserQuery:
      name: user
      in: query
      description: '`usr_<id>` or `ext:<external_user_ref>`.'
      schema: { type: string, pattern: '^(usr_[0-9]+|ext:.+)$' }
    SessionId:
      name: session
      in: path
      required: true
      schema: { type: string, pattern: '^ses_[0-9]+$', example: ses_90211 }
    AccountId:
      name: account
      in: path
      required: true
      schema: { type: string, pattern: '^acc_[0-9]+$', example: acc_5521 }
    LabelFilter:
      name: label
      in: query
      style: deepObject
      explode: true
      description: |
        Written `label.<key>=<value>` (not `label[key]`), e.g. `?label.event=nov-open`. Several are
        ANDed; values match exactly. A key given twice, or one that breaks the label key rules, is
        `400 invalid_request`.
      schema:
        type: object
        additionalProperties: { type: string }
    Cursor:
      name: cursor
      in: query
      description: Opaque cursor from a previous page's `next_cursor` on the same list. Anything else is `400 invalid_request`.
      schema: { type: string }
    Limit:
      name: limit
      in: query
      description: Items a page. Above your `page_size` limit (200) it is cut to it; zero, negative or not a number means the default.
      schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
    LimitDetail:
      name: limit
      in: query
      description: Items a page. Above your `page_size` limit (200) it is cut to it; zero, negative or not a number means the default.
      schema: { type: integer, minimum: 1, maximum: 200, default: 100 }
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        Required on every POST (`400 invalid_request` without it): any unique string of 1–255
        visible ASCII characters (a UUID is ideal). Keys are per environment. A retry with the same
        key, path and body within 24 hours returns the first response with `Idempotent-Replayed:
        true` and runs nothing. The same key with a different path or body is `422
        idempotency_key_reused`; while the first request is still running, `409 conflict`. `5xx`
        and `429` answers are not stored, so a retry with the same key runs again.
      schema: { type: string, minLength: 1, maxLength: 255 }

  responses:
    Error:
      description: |
        Error. Every response to a request whose key checked out, errors included, carries
        `RateLimit-Limit` (requests a minute), `RateLimit-Remaining` and `RateLimit-Reset` (seconds
        until the minute resets). A `401`, the `403 switched_off` when the whole API is off for
        you, and the `429` for too many bad keys from one IP come before that check and carry
        none. A `429` also carries `Retry-After` (seconds).
      headers:
        RateLimit-Limit: { schema: { type: integer } }
        RateLimit-Remaining: { schema: { type: integer } }
        RateLimit-Reset: { schema: { type: integer } }
        Retry-After: { schema: { type: integer } }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

  schemas:
    # ── primitives ──
    Scope:
      type: string
      description: |
        What a user lets you do for them, granted on the consent screen.

        | Scope | Lets you |
        |---|---|
        | `frame:instant` | open Chartnaut inside your app without the user signing in each time (frame tokens) |
        | `sessions:write` | create backtests for the user, and end, lock or unlock them |
        | `sessions:read` | see those backtests: trades, profit and loss, rule breaks |
        | `terminal:read` | see what the user does in your app's Chartnaut: their charts, scripts, drawings, watchlists and backtest trades |
        | `terminal:write` | change their charts, scripts, drawings and watchlists, and place orders in their own backtests made in your app (a backtest by key) |
        | `frame:live` | show live Chartnaut charts inside your app (`mode: "live"`; live mode must also be enabled for your partner account) |
        | `demo_accounts:write` | create demo accounts for the user; lock, unlock and close them |
        | `demo_accounts:read` | see those demo accounts: balance, positions, trades, breaches |
        | `accounts:read` | see the user's connected broker accounts: balances, positions and trades |
        | `alerts:read` | see when the user's Chartnaut alerts go off |
      enum: [frame:instant, sessions:write, sessions:read, terminal:read, terminal:write, frame:live, demo_accounts:write, demo_accounts:read, accounts:read, alerts:read]
    Money:
      type: number
      description: A decimal amount in the account currency (USD), at most two decimal places.
      example: 10000
    Labels:
      type: object
      description: 'A session''s labels: up to 20; keys 1–64 letters, digits or `_ . : -`; string values up to 200 characters. Never interpreted; filter on them with `label.<key>=<value>`.'
      maxProperties: 20
      propertyNames: { pattern: '^[A-Za-z0-9_.:-]{1,64}$' }
      additionalProperties: { type: string, maxLength: 200 }
      example: { event: nov-open, round: '2' }
    AccountLabels:
      type: object
      description: 'A demo account''s labels: up to 20; keys 1–40 lower-case letters, digits or `_ . -`, starting with a letter or digit; string values up to 100 bytes. Never interpreted; filter on them with `label.<key>=<value>`.'
      maxProperties: 20
      propertyNames: { pattern: '^[a-z0-9][a-z0-9_.-]{0,39}$' }
      additionalProperties: { type: string, maxLength: 100 }
      example: { event: live-week, tier: pro }
    Page:
      type: object
      required: [data, next_cursor]
      properties:
        next_cursor: { type: [string, 'null'] }
    SubjectStatus:
      type: string
      enum: [active, locked, ended, breached, completed_to_target]
      description: |
        `active`; `locked` (by you or Chartnaut; a demo account also locks when its user unlinks);
        and the final ones: `ended` (you, the user, Chartnaut or a session's time cap ended it;
        `status_reason` says who), `breached` (a `close_and_end` rule fired),
        `completed_to_target` (the profit target was reached; everything was closed). A
        `block_order` breach refuses new orders but leaves the status `active`.

    # ── users ──
    ManagedUser:
      type: object
      required: [id, external_ref, managed, level, features, app, created_at]
      properties:
        id: { type: string, pattern: '^usr_[0-9]+$' }
        external_ref: { type: string, description: Your own id for the user. }
        name: { type: string }
        managed: { const: true }
        level: { type: string, description: '`free` or `pro`: which plan the account has.' }
        features:
          type: object
          additionalProperties: { type: boolean }
          description: 'Features you switched off, e.g. `{ "order_flow": false }`.'
        app: { type: [string, 'null'], description: The project the user was made for. }
        created_at: { type: string, format: date-time }
        purge_after: { type: string, format: date-time, description: "Set when you've left: the user's data is deleted after it." }
    CreateManagedUser:
      type: object
      required: [external_ref]
      properties:
        external_ref: { type: string, description: 'Your own id for the user; unique in your project.' }
        name: { type: string }
        app: { type: string, description: 'The project (`app_…` or its slug); default your default project.' }
    UpdateManagedUser:
      type: object
      properties:
        level: { type: string, enum: [free, pro] }
        features:
          type: object
          additionalProperties: { type: boolean }
          description: 'Switch features off: `{ "order_flow": false }`. Send only what changes.'
    UserExport:
      type: object
      required: [export, user, status]
      properties:
        export: { type: string }
        user: { type: string, pattern: '^usr_[0-9]+$' }
        status: { type: string, description: '`pending`, `running`, `ready` or `failed`.' }
        url: { type: string, format: uri, description: 'When ready, until `expires_at`.' }
        expires_at: { type: string, format: date-time }
    LinkedUser:
      type: object
      required: [id, external_user_ref, scopes, source, connected_at]
      properties:
        id: { type: string, pattern: '^usr_[0-9]+$' }
        external_user_ref: { type: string }
        scopes:
          type: array
          description: Exactly what the user granted.
          items: { $ref: '#/components/schemas/Scope' }
        source: { type: string, enum: [frame, connect], description: Where the user approved the link. }
        connected_at: { type: string, format: date-time }
    FrameToken:
      type: object
      required: [frame_token, expires_at, frame_url, api_host]
      properties:
        frame_token: { type: string, pattern: '^cnft_[0-9a-f]{64}$', description: 'A bearer credential for this user''s frame: keep it out of logs and other users'' pages.' }
        expires_at: { type: string, format: date-time }
        frame_url: { type: string, format: uri, description: '`https://terminal.chartnaut.com/embed/<partner>?api=<api_host>[&session=ses_…]#ft=<frame_token>`. Ready to render; the token is in the #fragment.' }
        api_host: { type: string, format: uri, description: 'The API origin the frame signs in on, e.g. `https://eu-api.chartnaut.com`: the one the user linked through, else the one you called. Already in `frame_url`.' }
        session: { type: string, pattern: '^ses_[0-9]+$', description: 'The session the frame is bound to (the one you named, or the backtest''s). Left out when none.' }
        backtest:
          type: object
          description: With `backtest` in the request.
          required: [key, session, created]
          properties:
            key: { type: string }
            session: { type: string, pattern: '^ses_[0-9]+$' }
            created: { type: boolean, description: True when this mint made the session. }
    AlertFire:
      type: object
      required: [id, alert, alert_name, symbol, timeframe, event, label, fired_at, recorded_at, bar_start, bar_end]
      properties:
        id: { type: string, pattern: '^alf_[0-9]+$', description: 'The fire''s id (as in `alert.fired`).' }
        alert: { type: string, pattern: '^alr_[0-9]+$', description: The alert's id. }
        alert_name: { type: string }
        symbol: { type: string, description: The market's display symbol. }
        timeframe: { type: string }
        event: { type: string, description: The definition event that fired. }
        label: { type: string }
        fired_at: { type: string, format: date-time, description: The event's time. }
        recorded_at: { type: string, format: date-time, description: When Chartnaut recorded it (the paging key). }
        bar_start: { type: string, format: date-time }
        bar_end: { type: string, format: date-time }

    # ── links ──
    Link:
      type: object
      required: [frame_url, connect_url, expires_at, api_host]
      properties:
        frame_url:
          type: string
          format: uri
          description: '`https://terminal.chartnaut.com/embed/<partner>?api=<api_host>&link=<token>[&session=ses_…]`. Render it in an iframe.'
        connect_url:
          type: string
          format: uri
          description: '`https://terminal.chartnaut.com/connect?link=<token>`, for a link from your own page instead of the frame.'
        expires_at: { type: string, format: date-time, description: 30 minutes after it was made. }
        api_host: { type: string, format: uri, description: 'The API origin that answered, e.g. `https://eu-api.chartnaut.com`. Already in `frame_url`.' }

    AppScript:
      type: object
      required: [script, app, kind, name, version, run_only, listed, published_at, updated_at]
      properties:
        script: { type: string, example: ind_61 }
        app: { type: string, example: app_3 }
        kind: { type: string, enum: [indicator, definition, insight] }
        name: { type: string }
        description: { type: string }
        version: { type: [integer, 'null'], description: The published version; null follows the current one. }
        run_only: { type: boolean }
        listed: { type: boolean }
        published_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }

    # ── rules ──
    RulesInput:
      description: |
        Inline rules, copied onto the session or account at create and fixed after that. Either a
        list of rules, or `{ "day_reset": {...}, "rules": [...] }` to move the trading day (one per
        rule set; default 17:00 America/New_York, the FX rollover, which follows US daylight saving).
        At most 50 rules. Checked in whole cents.

        `on_breach`:
        - `record` (default): store the breach and send `rule.breached`; nothing else.
        - `block_order`: also refuse new orders (exits stay allowed). A `daily_loss` block lasts
          until the next day reset; any other rule's lasts for good. The status stays `active`.
        - `close_and_end`: also close everything and end it; the status becomes `breached`.

        A profit target has no `on_breach`: reaching it closes everything and ends as
        `completed_to_target`. Every breach acts as its rule says. Only if Chartnaut pauses rule
        actions for you in an emergency are breaches stored with `action_applied: false`, and
        nothing is done.
      oneOf:
        - type: array
          maxItems: 50
          items: { $ref: '#/components/schemas/Rule' }
        - $ref: '#/components/schemas/RuleSet'
      example:
        - { type: daily_loss, limit: 500, on_breach: block_order }
        - { type: max_drawdown, limit: { percent: 10 }, mode: trailing, on_breach: close_and_end }
        - { type: profit_target, target: 1000 }
        - { type: slippage, ticks: 1 }
    RuleSet:
      type: object
      description: The canonical form, returned on read with every default filled in and every id present.
      additionalProperties: false
      properties:
        day_reset:
          type: object
          additionalProperties: false
          properties:
            time: { type: string, pattern: '^[0-2][0-9]:[0-5][0-9]$', default: '17:00' }
            tz: { type: string, default: America/New_York, description: An IANA time zone. }
        rules:
          type: array
          maxItems: 50
          items: { $ref: '#/components/schemas/Rule' }
    MoneyLimit:
      description: 'An amount (a bare number, or `{"amount": n}`), or `{"percent": n}` of the starting balance.'
      oneOf:
        - type: number
          exclusiveMinimum: 0
        - type: object
          additionalProperties: false
          required: [amount]
          properties: { amount: { type: number, exclusiveMinimum: 0 } }
        - type: object
          additionalProperties: false
          required: [percent]
          properties: { percent: { type: number, exclusiveMinimum: 0, maximum: 100 } }
    Rule:
      type: object
      required: [type]
      properties:
        id: { type: string, pattern: '^[A-Za-z0-9_.:-]{1,64}$', description: 'Your name for the rule; defaults to its type (then type_2, …). Breaches name it.' }
        type: { type: string, enum: [daily_loss, max_drawdown, max_position_size, max_open_positions, profit_target, slippage] }
      oneOf:
        - title: daily_loss
          type: object
          required: [type, limit]
          properties:
            type: { const: daily_loss }
            limit: { $ref: '#/components/schemas/MoneyLimit' }
            basis: { type: string, enum: [balance, equity], default: balance, description: Measured from the start-of-day balance or equity. }
            on_breach: { type: string, enum: [record, block_order, close_and_end], default: record }
        - title: max_drawdown
          type: object
          required: [type, limit]
          properties:
            type: { const: max_drawdown }
            limit: { $ref: '#/components/schemas/MoneyLimit' }
            mode: { type: string, enum: [fixed, trailing], default: fixed, description: '`fixed` from the starting balance; `trailing` from the peak.' }
            peak: { type: string, enum: [equity, balance], default: equity, description: 'Trailing only: what the peak follows (equity is updated on every price change).' }
            stop_at_starting_balance: { type: boolean, default: false, description: 'Trailing only: the floor stops rising once it reaches the starting balance.' }
            on_breach: { type: string, enum: [record, block_order, close_and_end], default: record }
        - title: max_position_size
          type: object
          required: [type, limit]
          properties:
            type: { const: max_position_size }
            limit:
              description: 'The largest position per market, in units as the platform shows them (lots, contracts, coins, shares), up to three decimals: a number or `{"units": n}`.'
              oneOf:
                - type: number
                  exclusiveMinimum: 0
                - type: object
                  required: [units]
                  properties: { units: { type: number, exclusiveMinimum: 0 } }
            on_breach: { type: string, enum: [record, block_order, close_and_end], default: record }
        - title: max_open_positions
          type: object
          required: [type, limit]
          properties:
            type: { const: max_open_positions }
            limit:
              oneOf:
                - type: integer
                  minimum: 1
                - type: object
                  required: [count]
                  properties: { count: { type: integer, minimum: 1 } }
            on_breach: { type: string, enum: [record, block_order, close_and_end], default: record }
        - title: profit_target
          type: object
          required: [type, target]
          properties:
            type: { const: profit_target }
            target: { $ref: '#/components/schemas/MoneyLimit' }
            basis: { type: string, enum: [equity, balance], default: equity, description: 'Reached when equity hits it, or when an exit brings the closed balance to it. The recorded result is the closed balance.' }
        - title: slippage
          type: object
          required: [type, ticks]
          properties:
            type: { const: slippage }
            ticks: { type: integer, minimum: 0, maximum: 10000, description: 'Every market and stop fill moves this many ticks against the trader. Limits never slip. A cost, never a breach.' }
    Breach:
      type: object
      required: [id, rule_id, rule_type, limit, value, unit, at, at_precision, prices, action, action_applied, detected_at, detected_by]
      properties:
        id: { type: string, pattern: '^brk_[0-9]+$' }
        rule_id: { type: string }
        rule_type: { type: string }
        period: { type: string, description: 'The trading day (YYYY-MM-DD) for daily rules.' }
        limit: { type: number, description: 'The rule''s limit, in `unit`.' }
        value: { type: number, description: 'What was observed, in `unit`.' }
        unit:
          type: string
          description: |
            The same for sessions and demo accounts: `money` (a decimal in the account currency)
            for money rules, `units` (lots, contracts, coins or shares, up to three decimals) for
            `max_position_size`, `count` (a whole number) for `max_open_positions`.
          enum: [money, units, count]
        at: { type: string, format: date-time, description: 'The crossing: replay time for backtests (the bar''s time), the exact price change for demo accounts.' }
        at_precision: { type: string, enum: [exact, between, bar], description: '`between`: across a gap in our price records, the crossing was between `window_start` and `window_end`.' }
        window_start: { type: string, format: date-time }
        window_end: { type: string, format: date-time }
        prices: { type: [object, 'null'], additionalProperties: true, description: 'Demo accounts: the bid/ask by market at the crossing. Sessions: `{}`.' }
        action: { type: string, enum: [record, block_order, close_and_end, complete] }
        action_applied: { type: boolean, description: '`false` when Chartnaut has paused rule actions for you (an emergency stop): the breach is stored and nothing is done.' }
        detected_at: { type: string, format: date-time }
        detected_by: { type: string, enum: [sweep, event, replay, client], description: 'Where it was found: `client` or `replay` for sessions; `sweep` (a price change) or `event` (a fill, close or adjustment) for demo accounts.' }

    # ── sessions ──
    Commission:
      type: object
      description: 'Charged per side on every market: `fixed` per unit (lot, contract, share; 0–1,000), or `percentage` of the side''s notional (0–100).'
      required: [type, value]
      properties:
        type: { type: string, enum: [fixed, percentage] }
        value: { type: number, minimum: 0 }
    CreateSession:
      type: object
      additionalProperties: false
      required: [user, instruments, starting_balance]
      properties:
        user: { type: string, description: '`usr_<id>` or `ext:<ref>`.' }
        name: { type: string, maxLength: 120, description: 'Shown to the user in Chartnaut. Defaults to "<your partner name> session".' }
        instruments:
          type: array
          minItems: 1
          maxItems: 10
          description: 'Markets by symbol as in the Chartnaut catalogue (e.g. `EURUSD`, `NAS100`); an alias or Chartnaut''s numeric instrument id also works. No market twice. Read back as display symbols. The session''s symbol picker is held to these.'
          items: { type: string }
        start: { type: string, description: 'Where the replay begins: a UTC date (`2026-09-01`, from 00:00 UTC) or an RFC 3339 time. In the past, and inside the user''s plan window. Required unless you give `day`.' }
        end: { type: string, description: 'Optional. Where the replay stops: a UTC date (through the end of that day) or an RFC 3339 time, after `start` and not in the future. Leave it out and the session plays on to the latest market data.' }
        day: { type: string, description: 'Shorthand for exactly one day: a UTC date (the whole UTC day) or an RFC 3339 time (the 24 hours from it). Give `start` (and `end`) or `day`, not both.' }
        starting_balance: { type: number, exclusiveMinimum: 0, maximum: 1000000000, description: Required; there is no default. }
        currency: { type: string, pattern: '^[A-Za-z]{3}$', default: USD, description: A three-letter code; read back in upper case. }
        leverage: { type: number, exclusiveMinimum: 0, maximum: 10000, default: 100 }
        commission: { $ref: '#/components/schemas/Commission' }
        time_cap_minutes: { type: integer, minimum: 0, maximum: 10080, default: 0, description: 'Minutes of play the user gets, from when a page first opens the session, before it ends on its own. 0: no cap.' }
        blind: { type: boolean, default: false, description: 'Hide the market, the date and prices: your setting; a display mode, not a security boundary.' }
        allow_skip: { type: boolean, default: true, description: Whether the user may skip forward (jump) in time. }
        rules: { $ref: '#/components/schemas/RulesInput' }
        external_ref: { type: string, minLength: 1, maxLength: 200, description: 'Your id for the session; unique per partner (`409 conflict` with `details.existing_id` on reuse).' }
        labels: { $ref: '#/components/schemas/Labels' }
        page_control: { $ref: '#/components/schemas/PageControl' }
    PageControl:
      type: string
      enum: [none, replay, replay_and_orders]
      default: none
      description: 'What the developer''s page may drive in this session through the terminal SDK: `none` (the default), `replay` (play, pause, step, speed, jump, hold) or `replay_and_orders` (also place orders).'
    SessionCommon:
      type: object
      required: [id, user, external_ref, labels, name, status, status_reason, created_at, replay_time, day, instruments, starting_balance, currency, leverage, blind, allow_skip, page_control]
      properties:
        id: { type: string, pattern: '^ses_[0-9]+$' }
        user: { type: string, pattern: '^usr_[0-9]+$' }
        external_user_ref: { type: string, description: Your ref for the user; left out when the user is no longer linked. }
        external_ref: { type: [string, 'null'] }
        labels: { $ref: '#/components/schemas/Labels' }
        name: { type: string }
        status: { $ref: '#/components/schemas/SubjectStatus' }
        status_reason: { type: string, description: 'Who set the status (e.g. `partner`, `admin`, `rule`, `time_cap`); empty when nobody has.' }
        created_at: { type: string, format: date-time }
        locked_at: { type: string, format: date-time, description: Left out when not locked. }
        ended_at: { type: string, format: date-time, description: Left out until it ends. }
        replay_time: { type: [string, 'null'], format: date-time, description: The replay clock as last saved. }
        locked_replay_time: { type: string, format: date-time, description: Where a lock or end froze the replay. Left out otherwise. }
        start: { type: string, format: date-time, description: Where the replay begins. }
        end: { type: [string, 'null'], format: date-time, description: Where the replay stops; null when the session plays on to the latest data. }
        day:
          type: object
          deprecated: true
          description: The same window as `start` and `end`, under its older name.
          required: [start, end]
          properties:
            start: { type: string, format: date-time }
            end: { type: [string, 'null'], format: date-time }
        instruments: { type: array, items: { type: string } }
        starting_balance: { $ref: '#/components/schemas/Money' }
        currency: { type: string }
        leverage: { type: number }
        commission: { $ref: '#/components/schemas/Commission' }
        time_cap_minutes: { type: integer, description: Left out when there is no cap. }
        opened_at: { type: string, format: date-time, description: When a page first opened it (the time cap runs from here). Left out until then. }
        time_cap_ends_at: { type: string, format: date-time, description: Left out without a cap or before the first open. }
        blind: { type: boolean }
        allow_skip: { type: boolean }
        page_control: { $ref: '#/components/schemas/PageControl' }
    Session:
      description: 'A session as `GET /sessions/{session}`, create and PATCH give it.'
      allOf:
        - $ref: '#/components/schemas/SessionCommon'
        - type: object
          required: [account, stats, breaches]
          properties:
            account:
              type: object
              description: The account at `replay_time`.
              required: [currency, balance, equity, realized_pnl, unrealized_pnl]
              properties:
                currency: { type: string }
                balance: { $ref: '#/components/schemas/Money' }
                equity: { $ref: '#/components/schemas/Money' }
                realized_pnl: { $ref: '#/components/schemas/Money' }
                unrealized_pnl: { $ref: '#/components/schemas/Money' }
                valued_at: { type: string, format: date-time, description: The replay time open positions were marked at. }
                unpriced: { type: integer, description: Open positions that could not be priced at the replay time (equity then leaves them out). Left out when 0. }
            open_positions:
              type: array
              description: Left out when there are none.
              items: { $ref: '#/components/schemas/SessionPosition' }
            working_orders: { type: integer, description: Left out when 0. }
            stats: { $ref: '#/components/schemas/Stats' }
            rules: { $ref: '#/components/schemas/RuleSet' }
            breaches:
              type: object
              required: [count]
              properties:
                count: { type: integer }
                last: { $ref: '#/components/schemas/Breach', description: The newest breach. Left out when there are none. }
    SessionSummary:
      description: |
        A session as `GET /sessions` lists it. `account` has `currency`, `balance` (starting
        balance plus realized P&L) and `realized_pnl` only. `stats` is the full `Stats` object, but
        only `trades` is counted: every other field is 0 (`profit_factor` null). No
        `open_positions`, `working_orders`, `rules` or `breaches`.
      allOf:
        - $ref: '#/components/schemas/SessionCommon'
        - type: object
          required: [account, stats]
          properties:
            account:
              type: object
              required: [currency, balance, realized_pnl]
              properties:
                currency: { type: string }
                balance: { $ref: '#/components/schemas/Money' }
                realized_pnl: { $ref: '#/components/schemas/Money' }
            stats: { $ref: '#/components/schemas/Stats' }
    Stats:
      type: object
      description: Closed trades only.
      required: [trades, wins, losses, win_rate, gross_profit, gross_loss, net_pnl, profit_factor, average_win, average_loss, largest_win, largest_loss, max_drawdown, max_drawdown_pct]
      properties:
        trades: { type: integer }
        wins: { type: integer }
        losses: { type: integer }
        win_rate: { type: number }
        gross_profit: { type: number }
        gross_loss: { type: number }
        net_pnl: { type: number }
        profit_factor: { type: [number, 'null'] }
        average_win: { type: number }
        average_loss: { type: number }
        largest_win: { type: number }
        largest_loss: { type: number }
        max_drawdown: { type: number }
        max_drawdown_pct: { type: number }
    SessionPosition:
      type: object
      required: [id, instrument, side, quantity, entry_price, opened_at]
      properties:
        id: { type: integer }
        instrument: { type: string }
        side: { type: string, enum: [long, short] }
        quantity: { type: number }
        entry_price: { type: number }
        opened_at: { type: string, format: date-time, description: Replay time. }
        mark: { type: number, description: Left out when it couldn't be priced. }
        unrealized_pnl: { type: number, description: Left out when it couldn't be priced. }
        unpriced: { type: string, description: Why it couldn't be priced. }
    SessionTrade:
      type: object
      required: [id, instrument, side, quantity, entry_price, exit_price, opened_at, closed_at, realized_pnl]
      properties:
        id: { type: integer }
        instrument: { type: string }
        side: { type: string, enum: [long, short] }
        quantity: { type: number }
        entry_price: { type: number }
        exit_price: { type: number }
        opened_at: { type: string, format: date-time, description: Replay time. }
        closed_at: { type: string, format: date-time, description: Replay time. }
        realized_pnl: { type: number }

    # ── accounts ──
    CreateAccount:
      type: object
      additionalProperties: false
      required: [user, display_name]
      properties:
        user: { type: string, description: '`usr_<id>` or `ext:<ref>`.' }
        display_name: { type: string, minLength: 1, maxLength: 64, description: Shown to the user in Chartnaut. Required. }
        starting_balance: { type: number, minimum: 100, maximum: 10000000, default: 100000, description: 'The starting balance in USD, rounded to whole cents. 0 or left out: 100,000.' }
        leverage: { type: number, minimum: 1, maximum: 500, default: 50, description: '0 or left out: 50.' }
        rules: { $ref: '#/components/schemas/RulesInput' }
        locked: { type: boolean, default: true, description: 'Created locked; open it with a bulk `unlock`.' }
        external_ref: { type: string, minLength: 1, maxLength: 200, description: 'Your id for the account; unique per partner (`409 conflict` on reuse).' }
        labels: { $ref: '#/components/schemas/AccountLabels' }
    Account:
      type: object
      description: |
        A demo account you created. `valuation`, `positions` and `breaches` are on
        `GET /accounts/{account}` and the create answer only; list items and the PATCH answer leave
        them out.
      required: [id, user, display_name, external_ref, labels, status, locked_at, ended_at, currency, starting_balance, leverage, balance, created_at, rules]
      properties:
        id: { type: string, pattern: '^acc_[0-9]+$' }
        user: { type: string, pattern: '^usr_[0-9]+$' }
        display_name: { type: string }
        external_ref: { type: [string, 'null'] }
        labels: { $ref: '#/components/schemas/AccountLabels' }
        status: { $ref: '#/components/schemas/SubjectStatus' }
        locked_at: { type: [string, 'null'], format: date-time }
        locked_by: { type: string, enum: [partner, rule, admin, system], description: 'Who locked it (`system`: the user unlinked). Left out when not locked.' }
        status_reason: { type: string, description: Left out when empty. }
        ended_at: { type: [string, 'null'], format: date-time }
        currency: { type: string, enum: [USD] }
        starting_balance: { $ref: '#/components/schemas/Money' }
        leverage: { type: number }
        balance: { $ref: '#/components/schemas/Money' }
        created_at: { type: string, format: date-time }
        rules: { $ref: '#/components/schemas/RuleSet', description: 'The rule set as stored; `{}` when there is none.' }
        valuation:
          type: object
          description: Valued now from the engines' last prices. Single read only, and left out when it can't be valued.
          required: [at, equity, floating_pnl, used_margin, free_margin, margin_level, stale]
          properties:
            at: { type: string, format: date-time }
            equity: { type: number }
            floating_pnl: { type: number }
            used_margin: { type: number }
            free_margin: { type: number }
            margin_level: { type: [number, 'null'] }
            stale: { type: boolean, description: 'A position could not be priced, or a quote is old.' }
        positions:
          type: array
          description: Open positions. Single read only, and left out when there are none.
          items:
            type: object
            required: [id, instrument, side, quantity, entry_price, opened_at, pending, floating_pnl]
            properties:
              id: { type: integer }
              instrument: { type: string }
              side: { type: string, enum: [Long, Short] }
              quantity: { type: number }
              entry_price: { type: number }
              opened_at: { type: string, format: date-time }
              pending: { type: boolean, description: The entry has not filled yet. }
              floating_pnl: { type: [number, 'null'] }
        breaches:
          type: object
          description: Single read only.
          required: [count, latest_at]
          properties:
            count: { type: integer }
            latest_at: { type: [string, 'null'], format: date-time }
    UserAccount:
      type: object
      description: |
        One of the user's own accounts (`origin=user`, read-only): their Chartnaut Demo account or
        a broker account they linked, never one you created. `balance` and `equity` are as
        Chartnaut last stored them. Its open positions and closed trades are read by id
        (`/accounts/{account}/positions`, `/accounts/{account}/trades`).
      required: [id, broker, display_name, currency, balance, equity, starting_balance, leverage, created_at]
      properties:
        id: { type: string, pattern: '^acc_[0-9]+$', description: 'For `GET /accounts/{account}`, `/positions` and `/trades` (`accounts:read`).' }
        broker: { type: string, description: 'The broker, e.g. `chartnaut_demo`, `mt4`, `mt5`, `ctrader`, `tradelocker`, `rithmic`.' }
        display_name: { type: string }
        currency: { type: string }
        balance: { type: number }
        equity: { type: number }
        starting_balance: { type: number }
        leverage: { type: number }
        created_at: { type: string, format: date-time }
    UserPosition:
      type: object
      description: An open position on one of the user's own accounts.
      required: [id, instrument, side, quantity, entry_price, opened_at]
      properties:
        id: { type: integer }
        instrument: { type: string }
        broker_symbol: { type: string, description: "The broker's own name for the market, when it has one." }
        side: { type: string, enum: [Long, Short] }
        quantity: { type: number }
        entry_price: { type: number }
        opened_at: { type: string, format: date-time }
    AccountTrade:
      type: object
      required: [id, instrument, side, quantity, entry_price, exit_price, realized_pnl, opened_at, closed_at]
      properties:
        id: { type: integer }
        instrument: { type: string }
        side: { type: string, enum: [Long, Short] }
        quantity: { type: number }
        entry_price: { type: number }
        exit_price: { type: number }
        realized_pnl: { type: number }
        opened_at: { type: string, format: date-time }
        closed_at: { type: string, format: date-time }
        stop_out: { type: boolean, description: 'True when a margin stop-out closed it; left out otherwise.' }
    AccountActionResult:
      type: object
      required: [data]
      properties:
        data:
          type: array
          items:
            type: object
            required: [id, result]
            properties:
              id: { type: string, pattern: '^acc_[0-9]+$' }
              result: { type: string, enum: [locked, unlocked, closed, closing, already, not_found, error] }
              error: { type: string, description: 'Why, for `error`; for `closing`, why a position is still open when known.' }

    # ── bulk ──
    BulkTarget:
      type: object
      description: 'Exactly one of `ids` or `labels`. `labels` needs `expected_count`. Each endpoint says how `expected_count` is checked with `ids`.'
      properties:
        ids:
          type: array
          minItems: 1
          maxItems: 1000
          items: { type: string, description: '`ses_…` for sessions, `acc_…` for accounts.' }
        labels:
          type: object
          description: The labels every target must hold (exact values, ANDed).
          additionalProperties: { type: string }
        expected_count: { type: integer, minimum: 0, description: 'Required with `labels`: how many you expect to match. Refused (`409 expected_count_mismatch`, nothing done) if different.' }

    # ── webhooks ──
    WebhookEvent:
      type: object
      required: [id, type, created_at, data]
      properties:
        id: { type: string, pattern: '^evt_', description: Deduplicate on this. }
        type: { type: string, enum: [user.connected, user.disconnected, user.deleted, session.ended, rule.breached, alert.fired, limits.warning, test.ping] }
        created_at: { type: string, format: date-time }
        data:
          type: object
          description: Ids and refs only (see the table in `webhooks.partnerEvent`). `{}` for `test.ping`.
          additionalProperties: true

    # ── the frame's page events ──
    FrameEvent:
      type: object
      description: 'A message the frame posts to your page (`window.parent.postMessage`, to your registered origins only). A hint: a type and ids, flat. See "Events the frame posts to your page" for which fields each type carries.'
      required: [source, type]
      additionalProperties: true
      properties:
        source: { const: chartnaut }
        type:
          type: string
          enum: [needs_link, signed_in, ready, fill, order, close, account, breach, session_end, locked, unlocked, continued_elsewhere, error, device_unsupported]
        session_id: { type: string, pattern: '^ses_[0-9]+$' }
        position_id: { type: [integer, 'null'] }
        order_id: { type: [integer, 'null'] }
        change: { type: string, enum: [created, price_changed, cancelled] }
        partial: { type: boolean }
        at: { type: [number, string], description: '`account`: replay time in unix seconds. `breach`: the bar''s replay time, ISO 8601.' }
        breach_id: { type: [string, 'null'], description: '`brk_…`' }
        rule_type: { type: string }
        action: { type: string, enum: [record, block_order, close_and_end, complete] }
        status: { type: string, enum: [ended, breached, completed_to_target] }
        code: { type: string, enum: [partitioned_unsupported, cookie_not_stored], description: '`error` from the sign-in page, when the browser can''t hold the frame''s sign-in. Other sign-in-page errors carry no `code`.' }
        reason: { type: string, enum: [signed_out, wrong_mode, before_history, invalid_session, no_access, error], description: '`error` from the backtest screen. `signed_out`: get a new frame token.' }

    # ── errors ──
    ErrorBody:
      type: object
      required: [code, message]
      properties:
        code:
          type: string
          description: |
            Stable. Branch on this, never on `message`.

            | Code | Status | Meaning |
            |---|---|---|
            | `unauthorized` | 401 | missing, unknown or revoked key (no RateLimit headers) |
            | `scope_not_granted` | 403 | the user didn't grant `details.scope` |
            | `forbidden` | 403 | your partner account isn't allowed this (`details.reason`, e.g. `no_access` for `frame:live` when live mode isn't enabled for you; `details.scope`) |
            | `permission_denied` | 403 | this key lacks the key permission the call needs (`details.permission`, e.g. `users:export`; `details.reason: "key_permission"`): use a key that has it, or add it in the partner portal |
            | `not_managed` | 409 | the call is for managed users only, and this user is linked (their own Chartnaut account and plan apply; `details.reason: "not_managed"`) |
            | `switched_off` | 403 | this part of the API is paused for you (everything, writes, frames, links, demo account creation, bulk actions); contact partners@chartnaut.com |
            | `not_linked` | 404 | the user isn't linked to you (`details.user` when the user was named in the request) |
            | `not_found` | 404 | no such object for you; an id of the wrong type or shape is this too |
            | `conflict` | 409 | `external_ref` already used (sessions: `details.existing_id`; accounts: `details.field`); the same Idempotency-Key still running; lock or unlock on an ended session |
            | `expected_count_mismatch` | 409 | a bulk action matched a different number (`details.expected`, `details.actual`) |
            | `invalid_request` | 400 | malformed body or unknown field (named in `message`, no `details`), a bad field (`details.field` where the endpoint names it), bad id, missing Idempotency-Key, invalid rules. Also `413` for a body over 2 MiB |
            | `idempotency_key_reused` | 422 | the Idempotency-Key was used with a different path or body |
            | `plan_limit` | 422 / 403 | the user's Chartnaut plan doesn't allow it (`details.reason`), or your developer plan's cap (`details.owner: "developer"`, `details.limit`: `apps` (an app past your plan's count after a downgrade takes no new users), `free_linked`, `managed_users`, `data`; with `used`, `cap`). No auto top-up: upgrade on the Developers page |
            | `seat_limit` | 403 | your Business seats are full this month (`details.limit` `seats` or `pro_seats`, `used`, `cap`): a new managed user can't start until you add seats; users active this month carry on |
            | `partner_limit` | 422 | one of your partner limits (`details.limit`, and for demo accounts `details.max`) |
            | `rate_limited` | 429 | your rate limit: `details.limit` is `rate_minute` or `rate_burst`. Also, with no `details` and `Retry-After: 60`, any call from an IP that sent 30 bad keys this minute, good keys included. See `Retry-After` |
            | `internal` | 500 | retry; if it persists contact partners@chartnaut.com |
          enum:
            - unauthorized
            - scope_not_granted
            - forbidden
            - permission_denied
            - not_managed
            - not_linked
            - plan_limit
            - seat_limit
            - partner_limit
            - not_found
            - conflict
            - expected_count_mismatch
            - rate_limited
            - idempotency_key_reused
            - switched_off
            - invalid_request
            - internal
        message: { type: string }
        details: { type: object, additionalProperties: true }
    Error:
      type: object
      required: [error]
      properties:
        error: { $ref: '#/components/schemas/ErrorBody' }
