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

> ## Agent Instructions
> SecId API: use the sandbox base URL https://partners-api.sandbox.securitize.io/investors/v1/onboarding-reliance unless the user explicitly provides production access. Authenticate with OAuth 2.0 client credentials: POST https://partners-api.sandbox.securitize.io/oauth2/token (form fields grant_type=client_credentials, client_id, client_secret, read from environment variables), cache the bearer token for its expires_in (7200 s) and send it as Authorization: Bearer on every call; never print or log the secret or the token.
> Nothing is verified until POST /investors/{investorId}/verification/submit. An individual: create, upload one identity document, submit. A company: create, add its people as key parties (at least one with isBeneficialOwner: true), upload their documents, submit.
> Branch on the HTTP status and the error `code`, never on `message`. A body without `code` comes from the gateway: on a 401 get a new token and send the request again; a 403 means the account is not enabled for this API.
> SecId API addresses: send address.state only when that address's countryCode is US, as the 2-letter state code (NY); omit it for any other country, also when the user has a province or region. Otherwise the call answers 400 validation_error on address.state.
> SecId API individuals in the US: taxId is the person's Social Security number, and it is checked against the name and residential address sent; send them as registered. A mismatch can move the investor to manual-review instead of verified. Sandbox does not run the check.
> Creates are safe to repeat with the same body: after a timeout or a 502, send the identical create again. Document uploads are not: each call stores a new document, so only re-send a document after a 502.
> Poll GET /investors/{investorId} about every 30 seconds, then back off; treat any status you do not recognise as not verified. In sandbox, the webhook investor.kyc.updated also announces every status change, and investor.suitability.updated / investor.dlt_test.updated every change of the suitability and DLT test verificationStatus: verify the signature, deduplicate on sourceEventId and confirm with the matching GET before acting. Token whitelisting is asynchronous too: poll GET /investors/{investorId}/wallets/whitelist until the status leaves processing.
> SecId API tax forms: POST /investors/{investorId}/tax-forms takes multipart/form-data (parts file, formType, signatureDate); never base64 or JSON. Let the HTTP client set content-type with the boundary. At any point of the verification, before or after the investor is verified, only for investors you created (201), one PDF up to 10 MB per call; each upload replaces the form on file, so after a 502 send the same request again. A W-9 can instead go as JSON fields to POST /investors/{investorId}/tax-forms/w9 (TIN as 9 digits, SSN or EIN): it does not replace a form on file (409 tax_form_already_active, details.activeTaxForm), and it requires a certification object (certifiedAt, signatureName, subjectToBackupWithholding false, isUSPerson true, certificationTextVersion w9-sm-2026-10): the investor certifies in your flow on the text published at /secid-api/tax-forms#the-certification, shown without changes; subjectToBackupWithholding true answers 422 business_rule_violation (details.reason backup_withholding_not_supported). Unlike creates, a repeat after success answers 409 tax_form_already_active, not 201: when details.activeTaxForm.formType is W-9, treat it as on file.
> Use synthetic test data in sandbox (@test.invalid emails, fresh ids each run). Never send more than one DLT test attempt per test investor unless the user asks: three failed attempts lock the test permanently.
> The complete contract, with every field, response and error, is the OpenAPI file of the API reference; the Errors page says what to do for each code.
> CET Underlying API: a WebSocket at wss://partners-rt-gw.sandbox.securitize.io/v1/market-maker/stream (TLS only; ws:// hangs with no answer). Sign hello, place_order, cancel_order and submit_crypto_funding with the user's Ed25519 key, read from an environment variable or secrets store; never print or log it. Sign timestamp + "." + type + "." + the exact payload string you send: serialise the payload once and embed that same string in the frame.
> CET Underlying API: send a unique requestId of at most 32 characters (a UUID without hyphens) on every message and match replies on it; frames without a requestId are pushes. Every amount is a decimal string, never a JSON number; compare amounts as decimals. Branch on the error code, never on message.
> CET Underlying API: an ack to place_order means taken, not filled. externalRef is the idempotency key; after an ack with status UNKNOWN or an UPSTREAM_UNAVAILABLE error, call get_order by externalRef before resending. Updates are delivered at most once: after any reconnect, read working orders back with get_order. Every order is placed by quantity. A buy must be a LIMIT order: quantity × limitPrice plus fees is held against your own available cash (get_cash_balance_v2), and a buy it does not cover, a MARKET buy or a notional order is refused (INVALID_ORDER). A sell must be placed by quantity, after its CETs reach the redemption wallet, or it is refused. mint_updated and burn_updated push mints and burns once they are on chain; after a gap, read them with get_mints and get_burns. The complete contract is the AsyncAPI file of the API reference.
> Stocks API (Beta): documented ahead of its release through the partner gateway; paths, fields and errors can change. Base URL https://partners-api.sandbox.securitize.io/stocks/v1. Send x-api-key on every call and investorId on every call about an investor. Read the key from an environment variable; never print or log it, and never call the API from frontend code.
> Stocks API: an investor can trade only once the SecId API shows them verified, with verified suitability (and a passed DLT test in the EEA), and once their wallet on the stock's chain is linked with their signature of the agreement message, signed verbatim. There is no whitelisting call: the first trade whitelists the wallet.
> Stocks API: orders are fill or kill. GET /stocks/realtime-price, prepare within about 20 seconds (signedPrice), have the investor's wallet sign the returned transaction unchanged and sign-only (never send it), then submit it once with POST /stocks/execute-signed-transaction within 120 seconds. Amounts are raw base units as strings; USDC has 6 decimals. The outcome is on chain: follow transactionHash.
> Stocks API: production access requires a UI audit by Securitize Compliance of the live screens: the disclosures and the market data shown, the NBBO included.
> Corporate Actions API (Beta, 0.x): in development and subject to change; paths, fields, enumerations and event names can change before 1.0.0. Base URL https://partners-api.sandbox.securitize.io/corporate-actions/v1. Get a bearer token with OAuth 2.0 client credentials at POST https://partners-api.sandbox.securitize.io/oauth2/token (no scope, 2 hours), cache it, and send Authorization: Bearer on every call. Read the client id, secret and the webhook signing secret from environment variables; never print or log them, and never call the API from frontend code.
> Corporate Actions API: webhooks arrive signed with the Standard Webhooks scheme under the svix-id, svix-timestamp and svix-signature headers (HMAC-SHA256 over id.timestamp.raw body, base64, v1 prefix; the secret is base64 after whsec_). Verify before parsing, reject a timestamp more than 5 minutes off, answer 2xx within 10 seconds. Delivery is at least once and can be out of order: deduplicate on sourceEventId, keep the highest version per object (objectId), order by sequence per stream.id, and replace the object with data (never merge).
> Corporate Actions API: treat an unknown caType, reasonCode, eventType or enum value as informational, never as an error. A restriction ends only with ca.restriction.removed; expectedEnd is informational. marketStatus UNAVAILABLE means do not trade; the reason field carries a restriction reasonCode or a market reason such as PRE_MARKET. GET /tokens?status= filters by marketStatus (OPEN, CLOSED, UNAVAILABLE), not by the token's ACTIVE status.
> Corporate Actions API: the event routes are at https://partners-api.sandbox.securitize.io/webhooks/v1 (not under /corporate-actions/v1) and cover every webhook family sent to the partner; filter with eventTypes=ca.* for corporate actions only. After an outage call POST /events/recover with since at the start of the outage (resends failed deliveries only), or page GET /events?since= (newest first, iterator paging, 90 days), then read state with GET /tokens/{tokenId}/status and GET /corporate-actions/{sourceCaId}. In sandbox, POST /sandbox/events with a scenario and one of your tokenIds publishes a scripted sequence at once; order the events by sequence, not by arrival.
> Investor Activity API: base URL https://partners-api.sandbox.securitize.io/v1. Authentication is OAuth 2.0 client credentials only (no API key): POST https://partners-api.sandbox.securitize.io/oauth2/token (no scope, 2 hours), cache the token, and send Authorization: Bearer on every call. The token identifies the investor account; there is no investor id to pass. Read the client id, secret and the webhook signing secret from environment variables; never print or log them, and never call the API from frontend code.
> Investor Activity API: every amount is an integer string in base units with a sibling decimals (human = amount / 10^decimals); parse with BigInt or a decimal type, never a float. Cash amounts (deposits, confirmations, payouts) are in the minor units of currencyId (1 = USD, decimals 2); token amounts (transactions, mintings, holdings) in the token's base units. Never add cash to tokens.
> Investor Activity API: reconcile a subscription by grouping GET /deposits?tokenId= on tokenIssuanceId and matching the transaction in GET /transactions?tokenId= with the same tokenIssuanceId (null on a deposit means not issued yet; null on a transaction means not an issuance). Each issuance has a deposit movement (cash in) and a liquidation movement (that cash applied to the tokens) for the same amount: count the cash once, by direction=deposit, never by adding every movement. Page with offset and limit (max 100) until offset + meta.length reaches meta.total; there is no tokenIssuanceId filter. Reconcile a redemption by txHash (transfer, investor.redemption.pending, payout sourceTransaction) and by the redemption's data.id across pending, confirmed, payout.initiated and payout.completed.
> Investor Activity API: webhooks arrive signed with the Standard Webhooks scheme under the svix-id, svix-timestamp and svix-signature headers (HMAC-SHA256 over id.timestamp.raw body, base64, v1 prefix; the secret is base64 after whsec_). Verify before parsing, reject a timestamp more than 5 minutes off, answer 2xx within 15 seconds. The body is {eventType, eventId, timestamp, data}: deduplicate on eventId (not svix-id), upsert by data.id, never move a record back to an earlier step, and treat an unknown eventType, processType or paymentMethod as informational. In webhooks a field with no value is absent; in endpoint answers it is null. After an outage page GET /webhook-events (newest first, iterator paging, optional eventType) back to the start of the outage.
> SecId hosted onboarding: instead of the API, a partner can send an investor to https://stocks.securitize.io/partners?tokenId=<stock token id>&partnerUrl=<return URL> (tokenAddress may replace tokenId; partnerUrl must be an absolute https URL, URL-encoded). Securitize runs identity verification, the investment profile and the wallet there. Nothing is appended to partnerUrl on return: check the wallet on chain before trading (Beta on Solana).

# Sandbox and authentication

> Where to connect, how to sign, how to open a session, and how sandbox behaves.

## Endpoint

| Environment | URL |
| - | - |
| Sandbox | `wss://partners-rt-gw.sandbox.securitize.io/v1/market-maker/stream` |

> [!WARNING]
>
> **TLS only.** A plain `ws://` connection is never answered: it hangs until your client gives up, with no error to read. Check the scheme before you debug anything else.

Production uses the same messages at a production URL, arranged with Securitize once your integration passes the [go-live checklist](https://developers.securitize.io/cet-underlying-api/go-live-checklist.md).

## Keys

You sign with an **Ed25519 keypair**. You register its public key with Securitize; the private key never leaves your systems, and nothing secret crosses the wire in either direction. Any Ed25519 keypair works, whatever chain your CETs are minted on; a Solana keypair is one. Prefer a dedicated keypair over one that also holds assets.

### Generate a keypair

With OpenSSL, and Python's `base58` package (`pip install base58`) to print the keys the way the API uses them:

```bash theme={null}
openssl genpkey -algorithm ed25519 -out private.pem

# Public key, base58: the one you register with Securitize
openssl pkey -in private.pem -pubout -outform DER | tail -c 32 | python3 -c 'import sys,base58;print(base58.b58encode(sys.stdin.buffer.read()).decode())'

# Private key, base58: what your client signs with. Keep it secret
openssl pkey -in private.pem -outform DER | tail -c 32 | python3 -c 'import sys,base58;print(base58.b58encode(sys.stdin.buffer.read()).decode())'
```

Send Securitize the base58 public key, the wallet that should receive your CETs, and whether the key trades or is read-only. To fund your cash with crypto, also send the wallets you will send USDC from. Never send the private key. Once the key is registered, the examples in [Open a session](#open-a-session) connect with the private key in `CET_SIGNING_KEY`.

To rotate, register another public key. Several can be active at once, so you can move to the new key and then ask Securitize to retire the old one, with no coordinated cutover.

A key can be registered **read-only**: its session gets every read and every push, and `place_order` and `cancel_order` answer `NOT_PERMITTED`. Use one for monitoring and reconciliation, so the systems that only read never hold a key that can trade.

## Signing

`hello`, `place_order` and `cancel_order` carry a `timestamp` and a `signature`:

```
signature = base58( Ed25519-Sign( privateKey,
                                  timestamp + "." + type + "." + payloadBytes ) )
```

* **`payloadBytes` are the exact bytes of `payload` as they go on the wire.** The server verifies the payload it received, never a re-serialisation of it. Key order and whitespace are yours to choose, as long as what you sign is what you send: serialise the payload once, sign that string, and put the same string in the frame. This is the most common way a signed integration fails.
* **`timestamp` is Unix seconds, within 30 seconds of the server clock.** Keep NTP running: a drifted clock has every signed message refused with `TIMESTAMP_OUT_OF_WINDOW`. `welcome` and `pong` carry `serverTime` to check yours against.
* `type` is part of the signed text, so a signature made for one message cannot be lifted onto another.

| Signed | Unsigned |
| - | - |
| `hello`, `place_order`, `cancel_order`, `submit_crypto_funding` | `get_symbols`, `get_redemption_address`, `get_redemption_balance`, `get_redemption_balances`, `get_order`, `get_mints`, `get_burns`, `get_cash_balance_v2`, `get_cash_movements`, `get_crypto_funding`, `ping` |

Reads and the heartbeat ride on the session `hello` opens; everything that moves shares, CETs or cash is signed. Most reads are also served over HTTP without a session, each request signed with the same key: see [Reads over HTTP](https://developers.securitize.io/cet-underlying-api/reference/http-reads.md). The [sandbox-only](https://developers.securitize.io/cet-underlying-api/sandbox-funding.md) `sandbox_deposit` and `sandbox_withdraw` are signed the same way.

## Open a session

Connect, send a signed `hello` within 10 seconds, wait for `welcome`, then send `ping` every `heartbeatSeconds`. Both examples read the private key, base58, from an environment variable; a 64-byte Solana secret key works too, since its first 32 bytes are the Ed25519 seed.

```javascript JavaScript theme={null}
// npm install ws @noble/ed25519 bs58
import WebSocket from 'ws';
import * as ed from '@noble/ed25519';
import bs58 from 'bs58';
import { randomUUID } from 'node:crypto';

const URL = 'wss://partners-rt-gw.sandbox.securitize.io/v1/market-maker/stream';
const privateKey = bs58.decode(process.env.CET_SIGNING_KEY).slice(0, 32);
const publicKey = bs58.encode(await ed.getPublicKeyAsync(privateKey));

// A requestId of at most 32 characters is echoed intact: a UUID without its hyphens.
const requestId = () => randomUUID().replaceAll('-', '');

// The payload is serialised once: the same string is signed and sent.
async function signedFrame(type, payload) {
  const payloadJson = JSON.stringify(payload);
  const timestamp = Math.floor(Date.now() / 1000);
  const signed = new TextEncoder().encode(`${timestamp}.${type}.${payloadJson}`);
  const signature = bs58.encode(await ed.signAsync(signed, privateKey));
  return `{"type":${JSON.stringify(type)},"requestId":"${requestId()}","timestamp":${timestamp},"payload":${payloadJson},"signature":"${signature}"}`;
}

const ws = new WebSocket(URL);
ws.on('open', async () => ws.send(await signedFrame('hello', { publicKey, nonce: randomUUID() })));
ws.on('message', (data) => {
  const frame = JSON.parse(data);
  if (frame.type === 'welcome') {
    setInterval(() => ws.send(JSON.stringify({ type: 'ping', requestId: requestId() })), frame.payload.heartbeatSeconds * 1000);
  }
  console.log(frame.type, frame.requestId ?? '', JSON.stringify(frame.payload));
});
ws.on('close', (code) => console.log('closed', code));
```

```python Python theme={null}
# pip install websockets pynacl base58
import asyncio, json, os, time, uuid

import base58
import websockets
from nacl.signing import SigningKey

URL = "wss://partners-rt-gw.sandbox.securitize.io/v1/market-maker/stream"
signing_key = SigningKey(base58.b58decode(os.environ["CET_SIGNING_KEY"])[:32])
public_key = base58.b58encode(bytes(signing_key.verify_key)).decode()


def signed_frame(type_, payload):
    payload_json = json.dumps(payload, separators=(",", ":"))  # serialised once: signed and sent as is
    timestamp = int(time.time())
    signed = f"{timestamp}.{type_}.{payload_json}".encode()
    signature = base58.b58encode(signing_key.sign(signed).signature).decode()
    return (f'{{"type":{json.dumps(type_)},"requestId":"{uuid.uuid4().hex}","timestamp":{timestamp},'
            f'"payload":{payload_json},"signature":"{signature}"}}')


async def heartbeat(ws, seconds):
    while True:
        await asyncio.sleep(seconds)
        await ws.send(json.dumps({"type": "ping", "requestId": uuid.uuid4().hex}))


async def main():
    async with websockets.connect(URL) as ws:
        await ws.send(signed_frame("hello", {"publicKey": public_key, "nonce": str(uuid.uuid4())}))
        welcome = json.loads(await ws.recv())
        if welcome["type"] != "welcome":
            raise RuntimeError(welcome)
        asyncio.create_task(heartbeat(ws, welcome["payload"]["heartbeatSeconds"]))
        async for raw in ws:
            frame = json.loads(raw)
            print(frame["type"], frame.get("requestId", ""), frame.get("payload"))


asyncio.run(main())
```

`welcome` means you are connected. An `error` with `SIGNATURE_INVALID` means the signature or the key ([below](#when-the-session-does-not-open)).

## Limits

| What | Limit | Past it |
| - | - | - |
| Time from connecting to `hello` | 10 seconds | The socket is closed (`4001`) |
| Clock difference on a signed message | 30 seconds | `TIMESTAMP_OUT_OF_WINDOW`; the socket stays open |
| Heartbeat | `ping` every 10 seconds | A socket quiet for 3 minutes is closed (`4008`) |
| Frame size | 64 KB | The socket is closed (`1009`), without an `error` first |
| Sessions per socket | One | A second `hello` answers `MALFORMED`; the first session stands |

One socket is one session. A second connection opens a second session, not a second channel on the first.

## Reconnecting

Reconnect on any close or dropped connection, including `1006` (closed without a close frame), with backoff, never in a tight loop, and open a new session. A release restarts the service and closes every socket with `1001`. Updates sent while you were disconnected are not replayed: read back every order you still hold as working with `get_order`. See [Track, cancel and reconcile orders](https://developers.securitize.io/cet-underlying-api/track-orders.md#after-a-disconnect).

## When the session does not open

| What you see | Meaning |
| - | - |
| The connection hangs, with nothing to read | `ws://` instead of `wss://` |
| `error` `SIGNATURE_INVALID`, then the socket closes | The signature does not verify, or the public key is not registered; the two are not distinguished. Check that you sign the exact payload string you send |
| `error` `TIMESTAMP_OUT_OF_WINDOW`, the socket stays open | Your clock is more than 30 seconds off. Fix NTP; reconnecting does not help |
| `error` `UPSTREAM_UNAVAILABLE`, the socket stays open | The key could not be checked at that moment. Send a new `hello`, with a new `nonce`, on the same socket |
| `error` `UNAUTHENTICATED`, then the socket closes | A message other than `hello` was sent before `welcome` |
| The socket closes about 10 seconds after connecting | No `hello` arrived |

## How sandbox behaves

Sandbox sends orders to the broker's simulator, which **executes every order at once, at whatever limit price you name**, even one far from the market. That makes the whole lifecycle testable without a live market. Calibrate nothing on it:

* **A `LIMIT` order never rests.** It fills at your price at once. In production it rests until the market reaches it.
* **Cancelling never succeeds.** Every order has filled before the cancellation arrives, so every `cancel_order` answers `ORDER_NOT_CANCELLABLE`. In production, `PENDING_CANCEL` and `CANCELLED` are ordinary.
* **Before the market opens, an order priced more than 2% from the last price is refused.** During market hours the simulator fills it regardless.
* **Fills come 100 shares at a time.** A 250-share order arrives as three executions and three `trade_updated` frames, and usually mints more than once.
* **References must change between runs.** An `externalRef` you already used is refused as a duplicate, including the ones in these docs.
* **You fund your own cash.** The sandbox-only `sandbox_deposit` and `sandbox_withdraw` move USD into and out of it. See [Sandbox funding](https://developers.securitize.io/cet-underlying-api/sandbox-funding.md).


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