> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trdrs.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Save a hedging policy's script

> Compiles `source` and saves it as the next version of the policy's script, which the policy runs from now in the mode it has: `off` for a first save, so a new script trades nothing until you set its mode. A source that doesn't compile is refused, and nothing is saved. Send `expectedRevision` null for a policy with no script yet, and the `revision` you read after. Where the script is `on` and the policy is active, saving also needs `hedge:execute`, as changing an active policy's terms does. `resultsDays` are the windows of whole UTC days whose results the script reads for each account, at most 4, each from 1 to 365; `[30]` where you send none. Required scope: `hedge:manage`. Preview: served on the sandbox to every venue, and production availability is arranged when a venue qualifies. Trading API keys and pre-registration keys do not authorize these routes.



## OpenAPI

````yaml /api/openapi.json post /api/venues/{venueId}/hedging-policies/{hedgingPolicyId}/script
openapi: 3.1.0
info:
  title: trdrs Engine API
  version: 1.1.0
  description: >-
    ## API Reference


    Every route the trdrs engine serves, with what to send and what comes back.
    It covers market

    data and news, trading and account state for a trader's own software, the
    Connect API a Connect

    app's backend calls and the Connect dashboard's routes, Connect
    pre-registration, the statements

    that carry a Connect account between environments, the venue routes a prop
    firm or brokerage runs its

    accounts through, and a trader's own challenges.


    Start with the Quickstart for your first call. The API standards hold the
    rules every route

    shares: keys, errors, rate limits, idempotency, paging and streaming.
servers:
  - url: https://app.trdrs.co
    description: Production
  - url: /
    description: This engine
security: []
tags:
  - name: Venue platform preview
    description: >-
      Run your venue: its providers, instruments, conditions, groups, routes,
      stages, venue rules, keys, accounts, usage, balance receipts and webhooks.
      These routes are in preview. They are served on the sandbox to every
      venue, and production access is arranged when a venue qualifies. Every
      route here under `/api/venues/` takes a Venue key. The back office reaches
      the same routes under `/api/back-office/` with a verified owner’s session,
      because the Venue key stays on your server, and both run the same checks.
      The team’s routes under `/api/organizations` serve the back office and the
      Connect dashboard alike, since one organization can run venues and Connect
      apps with one team.
  - name: Market data
    description: >-
      Search and look up symbols, read price history and quotes, check the
      server clock, and stream live bars. Crypto prices come from each
      provider’s public feed. Futures prices are licensed to each user and
      stream only from that trader’s own futures source: a login on their
      venue’s production Rithmic system, under their own market data
      subscription. A Rithmic Test login carries no market data. Futures reach
      the trader’s own signed-in session, and a venue’s or Connect app’s backend
      acting for its trader. A Trading API key reads crypto market data only.
      Without a source, a futures request answers 503 `feed_requires_connection`
      and the symbol search lists no futures.
  - name: News
    description: >-
      Market news and the economic calendar, from licensed and open sources,
      tagged with futures roots as they arrive. The content is the same for
      everyone, and these routes admit the same callers as market data: a
      licensed origin, a session or a Trading API key. Page headlines by publish
      time, filter them by instrument root, and stream them live over
      server-sent events. Thumbnails come through the image route.
  - name: Trading
    description: >-
      Place, change and cancel orders, protect a position with a bracket and
      change or withdraw it, and close or flatten positions. Every call that
      places an order takes a `clientOrderId` as its idempotency key.
  - name: Account
    description: >-
      Read an account a trader can trade: its balance, positions, working
      orders, fills, profit and loss history, and the live account stream. You
      don’t create accounts here. A trader connects their own account at a
      provider, or opens their own Demo on the paper book, in the trdrs app. A
      venue issues accounts on the paper book with Issue an account into a
      group, and a venue pre-registers accounts at a provider through Connect
      with Pre-register a trader’s account.
  - name: Connect
    description: >-
      Connect is the account picker a trader opens: in the trdrs app, where it
      lists the built-in providers and every listed venue, and in hosted Connect
      on a Connect app’s website, where it lists the tiles the app chose. The
      pre-registration routes let a venue fill Connect in the trdrs app ahead of
      time, for a trader who signs in to trdrs. You tell trdrs that a trader has
      an account at a built-in provider: their sign-in email, and optionally the
      account number and login name. When that trader signs in, Connect shows
      the account ready to link, and they sign in to the provider themselves,
      once. The trader types their own password, and access starts when their
      own login succeeds. You can list who you pre-registered and who has
      linked, and cancel a pre-registration that hasn’t been used. A
      pre-registration expires after 30 days, and sending it again refreshes it.
      These routes take the pre-registration key. [Register an
      account](/guides/register-an-account) walks through the whole flow.
  - name: Connect apps preview
    description: >-
      Run a Connect app: your own trading interface, whose traders connect their
      accounts in hosted Connect on your website and trade them on your screens.
      The Connect API is what your backend calls with your app’s API key: Create
      a Connect link, read and close it, and the account, market and trading
      routes with your trader named in `x-trdrs-trader`. Hosted Connect calls
      its own routes with the frame session a Connect link opens. The Connect
      dashboard calls the rest with your Connect sign-in session: your apps,
      each app’s name and logo, API keys, websites, tiles, white-label paper and
      Demos, traders and active traders, invoices, conformance runs and its
      Connect pass. These routes are in preview, served on the sandbox, where
      they are free. An app’s production opens when production records the app’s
      Connect pass, which the sandbox signs once the app passes its Connect
      conformance run.
  - name: Connect accounts
    description: >-
      A Connect client's team signs in to the Connect dashboard with a Connect
      account of its own, never a trader's, and one login reaches both
      environments. Production answers a short statement for the signed-in
      account, naming its verified email and the Connect apps it owns, and
      sandbox exchanges it for a sandbox session and the counterpart app of
      each: the sandbox app that stands for the production one. The environments
      share no credential: production signs the statement with its own key, and
      sandbox checks it with production's public key alone. These routes take
      the Connect dashboard's own session, from the dashboard's origin; a
      trader's session and every key are refused, and a Connect account's
      session reaches no trading, account, market or AI route.
  - name: Trading platform session
    description: >-
      The routes the trdrs trading platform calls for a trader signed in to it:
      the trader's own Hyperliquid wallet, their Demo on the paper book, the
      exchanges they connect, their sign-in sessions, and payout requests from
      their accounts. Each takes the trader's own session from trdrs's own
      origin, and an API key or a Venue key can't call them. They are listed so
      you can see what the trading platform does for your traders. A venue's own
      app does the same things from its backend with its Venue key and
      `x-trdrs-trader`, and a Connect app opens hosted Connect with a Connect
      link; [Build a trader app](/guides/build-a-trader-app) maps each one.
  - name: Challenges
    description: >-
      List evaluation programs, enroll in one, and read a trader’s own
      enrollments and their history. **Preview: outside the additive-only
      promise**, so these shapes can change; see Versioning and stability.
      **They take a signed-in session, not a key**, and exist only on an engine
      that runs with `CHALLENGES_ENABLED`. Anywhere else every one answers
      `404`.
paths:
  /api/venues/{venueId}/hedging-policies/{hedgingPolicyId}/script:
    post:
      tags:
        - Venue platform preview
      summary: Save a hedging policy's script
      description: >-
        Compiles `source` and saves it as the next version of the policy's
        script, which the policy runs from now in the mode it has: `off` for a
        first save, so a new script trades nothing until you set its mode. A
        source that doesn't compile is refused, and nothing is saved. Send
        `expectedRevision` null for a policy with no script yet, and the
        `revision` you read after. Where the script is `on` and the policy is
        active, saving also needs `hedge:execute`, as changing an active
        policy's terms does. `resultsDays` are the windows of whole UTC days
        whose results the script reads for each account, at most 4, each from 1
        to 365; `[30]` where you send none. Required scope: `hedge:manage`.
        Preview: served on the sandbox to every venue, and production
        availability is arranged when a venue qualifies. Trading API keys and
        pre-registration keys do not authorize these routes.
      parameters:
        - name: venueId
          in: path
          required: true
          schema:
            type: string
            format: uuid
        - name: hedgingPolicyId
          in: path
          required: true
          schema:
            type: string
            format: uuid
          description: The hedging policy's `id`.
        - name: Idempotency-Key
          in: header
          required: true
          schema:
            type: string
            minLength: 1
            maxLength: 128
          description: >-
            A key you choose, 1 to 128 characters, that identifies this write.
            Send the same key when you retry it, so the write is never applied
            twice.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VenueHedgeScriptSaveRequest'
      responses:
        '200':
          description: >-
            Success. The response is sent with `Cache-Control: no-store`, so
            don't cache it.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VenueHedgeScriptResponse'
        '400':
          description: >-
            `script_compile_failed`: the source doesn't compile. `diagnostics`
            lists each error as `{ line, col, message }`, counted from 1, such
            as an import from anything but `@trdrs/script-sdk`.
            `invalid_request` with `field` `source` or `resultsDays` for one
            that isn't one.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: >-
            The Venue key or the session is missing, malformed, revoked or
            expired.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: >-
            The credential is valid but can't do this: the key lacks the scope
            or its creator is no longer an owner, the email isn't verified, a
            reader tried to write, or the request came from an origin that isn't
            trusted.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: >-
            The venue, account or resource doesn't exist in this environment, or
            isn't yours to see.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: >-
            `version_conflict`: the revision you sent is stale, or null where
            the policy already has a script.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '413':
          description: The body is larger than this route accepts.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '415':
          description: 'Send the body as JSON, with `Content-Type: application/json`.'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '503':
          description: >-
            trdrs can't complete the request right now, because a part of the
            venue platform or its credential store is unavailable. Don't assume
            a write happened: retry it with the same `Idempotency-Key`.
            `engine_draining` with a `Retry-After` header: the engine you
            reached is restarting for a release and did nothing. Wait for
            `Retry-After`, then send the same request again, with the same
            `clientOrderId` or `Idempotency-Key` where the route takes one:
            another engine takes it. A write refused before any route takes it
            says `server draining` as its `error`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
          headers:
            Retry-After:
              $ref: '#/components/headers/RetryAfter'
      security:
        - venueKey: []
      x-codeSamples:
        - lang: javascript
          label: TypeScript
          source: >-
            const res = await
            fetch('https://app.trdrs.co/api/venues/{venueId}/hedging-policies/{hedgingPolicyId}/script',
            {
              method: 'POST',
              headers: {
                'content-type': 'application/json',
                Authorization: `Bearer ${process.env.TRDRS_VENUE_KEY}`,
                "Idempotency-Key": "example-request-1",
              },
              body: JSON.stringify({
                "source": "import type { HedgeAnswer, HedgeInput } from '@trdrs/script-sdk'\n\n// Hold each hedge until it is off by more than START dollars, then bring it to within TARGET dollars.\nconst START = 1_000_000\nconst TARGET = 400_000\n\nexport default function hedge(input: HedgeInput): HedgeAnswer {\n  const hedges: Record<string, number> = {}\n  for (const market of input.instruments) {\n    if (!market.hedgeable) continue\n    const has = market.held + market.pending\n    // Where the policy can't size it now, keep what the hedge holds.\n    hedges[market.instrumentId] = has\n    if (market.price === null || market.policyTarget === null) continue\n    const target = market.policyTarget\n    const off = target - has\n    // A net that calls for no hedge closes it at once.\n    if (target === 0 || off === 0) { hedges[market.instrumentId] = target; continue }\n    const perUnit = Math.abs(market.price) * market.contractMultiplier\n    if (Math.abs(off) * perUnit <= START) continue\n    // What is left off once the order goes: TARGET dollars, in whole steps.\n    const left = Math.floor(TARGET / perUnit / market.step) * market.step\n    if (left >= Math.abs(off)) continue\n    hedges[market.instrumentId] = off > 0 ? target - left : target + left\n  }\n  return { hedges }\n}\n",
                "resultsDays": [
                  30
                ],
                "expectedRevision": null
              }),
            })

            const data = await res.json()
        - lang: shell
          label: cURL
          source: >-
            curl -X POST
            'https://app.trdrs.co/api/venues/{venueId}/hedging-policies/{hedgingPolicyId}/script'
            \
              -H "Authorization: Bearer $TRDRS_VENUE_KEY" \
              -H 'Idempotency-Key: example-request-1' \
              -H 'content-type: application/json' \
              -d '{"source":"import type { HedgeAnswer, HedgeInput } from '@trdrs/script-sdk'\n\n// Hold each hedge until it is off by more than START dollars, then bring it to within TARGET dollars.\nconst START = 1_000_000\nconst TARGET = 400_000\n\nexport default function hedge(input: HedgeInput): HedgeAnswer {\n  const hedges: Record<string, number> = {}\n  for (const market of input.instruments) {\n    if (!market.hedgeable) continue\n    const has = market.held + market.pending\n    // Where the policy can't size it now, keep what the hedge holds.\n    hedges[market.instrumentId] = has\n    if (market.price === null || market.policyTarget === null) continue\n    const target = market.policyTarget\n    const off = target - has\n    // A net that calls for no hedge closes it at once.\n    if (target === 0 || off === 0) { hedges[market.instrumentId] = target; continue }\n    const perUnit = Math.abs(market.price) * market.contractMultiplier\n    if (Math.abs(off) * perUnit <= START) continue\n    // What is left off once the order goes: TARGET dollars, in whole steps.\n    const left = Math.floor(TARGET / perUnit / market.step) * market.step\n    if (left >= Math.abs(off)) continue\n    hedges[market.instrumentId] = off > 0 ? target - left : target + left\n  }\n  return { hedges }\n}\n","resultsDays":[30],"expectedRevision":null}'
components:
  schemas:
    VenueHedgeScriptSaveRequest:
      type: object
      additionalProperties: false
      properties:
        source:
          type: string
          minLength: 1
          maxLength: 65536
          description: >-
            The script's TypeScript source, at most 65,536 characters. It may
            import from `@trdrs/script-sdk` alone.
        resultsDays:
          type: array
          items:
            type: integer
            minimum: 1
            maximum: 365
          maxItems: 4
        expectedRevision:
          type:
            - integer
            - 'null'
          minimum: 1
      required:
        - source
        - expectedRevision
      example:
        source: >
          import type { HedgeAnswer, HedgeInput } from '@trdrs/script-sdk'


          // Hold each hedge until it is off by more than START dollars, then
          bring it to within TARGET dollars.

          const START = 1_000_000

          const TARGET = 400_000


          export default function hedge(input: HedgeInput): HedgeAnswer {
            const hedges: Record<string, number> = {}
            for (const market of input.instruments) {
              if (!market.hedgeable) continue
              const has = market.held + market.pending
              // Where the policy can't size it now, keep what the hedge holds.
              hedges[market.instrumentId] = has
              if (market.price === null || market.policyTarget === null) continue
              const target = market.policyTarget
              const off = target - has
              // A net that calls for no hedge closes it at once.
              if (target === 0 || off === 0) { hedges[market.instrumentId] = target; continue }
              const perUnit = Math.abs(market.price) * market.contractMultiplier
              if (Math.abs(off) * perUnit <= START) continue
              // What is left off once the order goes: TARGET dollars, in whole steps.
              const left = Math.floor(TARGET / perUnit / market.step) * market.step
              if (left >= Math.abs(off)) continue
              hedges[market.instrumentId] = off > 0 ? target - left : target + left
            }
            return { hedges }
          }
        resultsDays:
          - 30
        expectedRevision: null
    VenueHedgeScriptResponse:
      type: object
      additionalProperties: false
      properties:
        script:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/VenueHedgeScript'
      required:
        - script
      example:
        script:
          hedgingPolicyId: 00000000-0000-0000-0000-000000000001
          mode: watch
          revision: 3
          version:
            id: 00000000-0000-0000-0000-000000000005
            version: 2
            sdkVersion: 0.1.0
            resultsDays:
              - 30
            createdBy: user-owner
            createdAt: '2026-11-13T09:00:00.000Z'
            running: true
            source: >
              import type { HedgeAnswer, HedgeInput } from '@trdrs/script-sdk'


              // Hold each hedge until it is off by more than START dollars,
              then bring it to within TARGET dollars.

              const START = 1_000_000

              const TARGET = 400_000


              export default function hedge(input: HedgeInput): HedgeAnswer {
                const hedges: Record<string, number> = {}
                for (const market of input.instruments) {
                  if (!market.hedgeable) continue
                  const has = market.held + market.pending
                  // Where the policy can't size it now, keep what the hedge holds.
                  hedges[market.instrumentId] = has
                  if (market.price === null || market.policyTarget === null) continue
                  const target = market.policyTarget
                  const off = target - has
                  // A net that calls for no hedge closes it at once.
                  if (target === 0 || off === 0) { hedges[market.instrumentId] = target; continue }
                  const perUnit = Math.abs(market.price) * market.contractMultiplier
                  if (Math.abs(off) * perUnit <= START) continue
                  // What is left off once the order goes: TARGET dollars, in whole steps.
                  const left = Math.floor(TARGET / perUnit / market.step) * market.step
                  if (left >= Math.abs(off)) continue
                  hedges[market.instrumentId] = off > 0 ? target - left : target + left
                }
                return { hedges }
              }
          changedBy: user-owner
          changedAt: '2026-11-13T09:05:00.000Z'
          failuresInARow: 0
          lastFailureAt: null
          lastFailureReason: null
    ErrorResponse:
      type: object
      description: >-
        The body of every error response. It always carries `error`, an English
        sentence you can show. A refused trading request also carries `code`,
        one of the refusal codes, and `params`, the details of that refusal.
        Translate by `code` and `params`, and show a generic message for a code
        you don't recognize. Other errors may carry a `code` of their own.
      properties:
        error:
          type: string
          description: What went wrong, as an English sentence.
        code:
          type: string
          description: >-
            A stable machine code. On a refused trading request, it is one of
            the refusal codes.
        params:
          type: object
          description: >-
            The details of the refusal named by `code`, on a refused trading
            request.
      required:
        - error
      example:
        error: invalid_instrument
    VenueHedgeScript:
      type: object
      additionalProperties: false
      properties:
        hedgingPolicyId:
          type: string
          format: uuid
        mode:
          type: string
          enum:
            - 'off'
            - watch
            - 'on'
          description: >-
            `off`: the script doesn't run. `watch`: it runs on each sizing of
            the net and its runs record what it would hedge, while the policy's
            own terms trade. `on`: its answer is what the net hedges.
        revision:
          type: integer
          minimum: 1
          description: >-
            The script's revision, which each save and each change of mode or
            version moves on. Send it back as `expectedRevision`.
        version:
          $ref: '#/components/schemas/VenueHedgeScriptVersion'
        changedBy:
          type: string
        changedAt:
          type: string
          format: date-time
        failuresInARow:
          type: integer
          minimum: 0
          description: >-
            The runs in a row that failed, each falling back to the policy's own
            terms; 0 once a run answers. A run on the same book as the last
            counts once.
        lastFailureAt:
          type:
            - string
            - 'null'
          format: date-time
        lastFailureReason:
          type:
            - string
            - 'null'
          enum:
            - script_error
            - script_timeout
            - script_memory
            - script_answer_invalid
            - null
          description: Why the last run in a row failed, or null where none did.
      required:
        - hedgingPolicyId
        - mode
        - revision
        - version
        - changedBy
        - changedAt
        - failuresInARow
        - lastFailureAt
        - lastFailureReason
      description: >-
        A hedging policy's script: its mode, the version it runs and its
        failures in a row.
    VenueHedgeScriptVersion:
      type: object
      additionalProperties: false
      properties:
        id:
          type: string
          format: uuid
        version:
          type: integer
          minimum: 1
          description: >-
            The version's number: 1 for the first save, one more for each save
            after.
        sdkVersion:
          type: string
          description: The script SDK version the source compiled against.
        resultsDays:
          type: array
          items:
            type: integer
            minimum: 1
            maximum: 365
          maxItems: 4
          description: >-
            The windows of whole UTC days whose results the script reads for
            each account, under `accounts[].results` keyed by the days.
        createdBy:
          type: string
          description: Who saved it.
        createdAt:
          type: string
          format: date-time
        running:
          type: boolean
          description: Whether the policy runs this version.
        source:
          type: string
          description: >-
            The script's TypeScript source, on a read of one version and of the
            script; left out of the list of versions.
      required:
        - id
        - version
        - sdkVersion
        - resultsDays
        - createdBy
        - createdAt
        - running
      description: >-
        One save of a hedging policy's script. A version is never changed: a new
        save is a new version, and the policy can be set back to any earlier
        one.
  headers:
    RetryAfter:
      description: >-
        How many seconds to wait before sending the same request again. A `503`
        carries it only when the engine did nothing, so the request may be sent
        again as it is.
      schema:
        type: integer
        minimum: 1
  securitySchemes:
    venueKey:
      type: http
      scheme: bearer
      description: >-
        The Venue key (`trdrs_vk_sandbox_…` or `trdrs_vk_production_…`), in
        preview. It belongs to one venue in one environment and carries the
        scopes it was created with. The venue's verified owner creates it while
        signed in. It works on the `/api/venues/{venueId}` routes and, with
        `trader:read` or `trader:trade`, on the account, market and trading
        routes, reading the venue's own traders' accounts and routing their
        orders, each request naming its trader in `x-trdrs-trader`. A
        `trdrs_sk_…` key can't be used in its place. It reaches its venue's
        routes and its venue's own traders, and the owner manages keys from a
        signed-in session. Keep it on your server.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.