> For the complete documentation index, see [llms.txt](https://docs.forepaas.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.forepaas.org/api-reference/api-reference/cycle.md). Agents can also search and read this documentation through its [MCP server](https://docs.forepaas.org/~gitbook/mcp).

# Cycle Markets

Cycle-market windows, pricing, trading, positions, settlement, and claims

The cycle module exposes 17 operations: 14 queries and 3 order, cancellation, or claim operations. All requests use `https://openapi.foregate.com` and the [gateway signing headers](https://docs.forepaas.org/getting-started/authentication.md). User-scoped operations also require the `Authorization=<session-token>` cookie returned by `POST /user/register`; identity comes from that cookie, never a caller-supplied `userId`.

The request and response examples below are illustrative structures, not live production calls. IDs such as `10001`, `20001`, `30001`, and `40001` are placeholders: discover a real series/window and use the authenticated user's own orders and positions. cURL signature placeholders and fixed example dates are not valid authentication. Generated GitBook HTTP snippets also require a fresh UTC date, the complete signed headers, a real session cookie where required, and the Content-MD5 of the exact POST body. Do not substitute an API key for a signature or cookie. Use the JavaScript or Python `ForeGateClient` from [Code Examples](https://docs.forepaas.org/advanced/code-examples.md) to calculate the signature and body digest.

The upstream reference includes development observations from October 2026. Those observations, including current order restrictions, have not been independently verified against production. Production signing-date tolerance and separate WebSocket routing were not established by that audit. No live trading guarantees follow from the examples.

## IDs and request conventions

| Value                                             | Meaning and use                                                                                                                                                              |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initialMarketId`                                 | Series ID; use as `marketId` for order creation, cancellation, and claims.                                                                                                   |
| `windowId`                                        | Window ID; use as `outcomeId` for orders. Always pair it with its own series.                                                                                                |
| Snapshot `orderSubmitLocator`                     | Contains the series `marketId` and window `outcomeId` to use for order creation.                                                                                             |
| Snapshot `orderbookLocator.marketId`              | Equals the window ID. It supports the order-book compatibility request with `outcomeId` omitted; it is not an order-creation series ID.                                      |
| Probability-history `marketId` / `outcomeId`      | Both are window IDs for compatibility. Do not reuse that `marketId` as an order-creation series ID.                                                                          |
| `optionId`                                        | `"0"` = UP; `"1"` = DOWN. These are cycle option identifiers, not ordinary market option database IDs.                                                                       |
| Order-creation `orderId` / open-order detail `id` | Exact open-order ID for cancellation `orderOpenIds[]`; distinct from a position ID.                                                                                          |
| `positionId`                                      | The authenticated user's position ID from either position query; required for SELL and single-position claims. Only claims accept `"-1"` as a series-wide position selector. |

JSON IDs are strings containing positive signed 64-bit Long values (`1` through `9223372036854775807`), except the documented `optionId` values and claim `positionId: "-1"` sentinel. Positive decimal inputs accept strings or JSON numbers. The gateway expands exponent notation using exact decimal arithmetic, without an intermediate binary floating-point conversion, and allows at most 256 digits after normalization. For example, `"1e-3"` denotes `0.001`; limit-price tick and range checks apply to that expanded value. Use decimal strings to preserve precision when serializing a request. Returned numeric amount fields are strings; preserve returned null values intact.

`Accept-Language` is optional and is forwarded upstream, for example `en-US` or `zh-CN`. Save renewed `Set-Cookie` values as well as the initial register cookie; the proxy removes the upstream Domain attribute before forwarding them. Supply `X-NONCE` when required by the deployment. `X-TIMESTAMP` is Unix seconds and cannot replace the HMAC-required UTC `date` header. The source's ±900-second signing window was verified for development HTTP only.

GET parameters belong in the query string, with URL encoding and no repeated keys. POST requests contain a JSON object and no query parameters. Only the listed fields are accepted. The gateway fixes `marketType` to `3` on order-book, open-order, position, and personal-activity queries; it fixes `coinId` to `"2"` (USDT) on asset positions and personal activity and `modelType` to `orderbook` on personal activity. These fields may be omitted; supplied alternatives are overridden rather than used as filters.

## Time, states, and pagination

The gateway signing `date` is UTC in `YYYY-MM-DD HH:mm:ss` format. Window, server, and settlement timestamps use ISO 8601 UTC with `Z`. Curve timestamps are millisecond strings. Upstream LocalDateTime fields (`createdAt`, `updatedAt`, `expirationAt`, `marketStartTime`, `marketEndTime`, and activity `date`) retain their format without a timezone suffix and are interpreted as UTC. Custom activity `startTime` and `endTime` likewise use UTC ISO date-times without a timezone suffix. Activity `date` is a record field, not the signing request header.

| Field                 | Values                                                                                                                                                       |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Window `publicStatus` | `UPCOMING_TRADABLE`, `ACTIVE`, `QUIET`, `PRICE_PENDING`, `TRADING_SUSPENDED`, `RESOLVING`, `DISPUTE`, `PAYOUT_PROCESSING`, `CORRECTING`, `SETTLED`, `VOIDED` |
| Result                | `UP`, `DOWN`, `VOID`, or null                                                                                                                                |
| Settlement type       | `NORMAL`, `VOID`, `CORRECTION`                                                                                                                               |
| Settlement status     | `RESOLVING`, `DISPUTE`, `PAYOUT_PROCESSING`, `CORRECTING`, `SETTLED`, `VOIDED`                                                                               |
| Settlement readiness  | `READY`, `BLOCKED`, `UNKNOWN`                                                                                                                                |
| Order status          | `NEW`, `PENDING_ORDER`, `REJECTED`, `ACCEPTED`, `OPEN`, `MATCHING`, `PARTIAL_FILLED`, `FILLED`, `CANCELED`                                                   |
| Position status       | `NORMAL`, `TRADING`, `SETTLED`, `CLAIMING`, `CLAIMED`, `CLAIMFAIL`; the shared model may also expose `FILLED`                                                |
| Activity `sortBy`     | `Newest`, `Oldest`, `Amount`, `AmountAsc`, `Shares`, `SharesAsc`                                                                                             |
| Activity `timeFilter` | `all`, `max_days`, `today`, `last_3_days`, `last_7_days`, `last_30_days`, `custom`                                                                           |
| Activity `type`       | `ALL` or an exact event type such as `BUY`, `SELL`, `CLAIM`, `MARKET_CLAIM`, `NO_RESULT_CLAIM`, `MODIFY`, `RESOLVE`                                          |

A lifecycle status is not permission to trade. Use snapshot `tradingEnabled`, `tradeLockTime`, and readiness; order submission checks the gates again before matching. `isCurrent` only identifies the current time window. Book and maker readiness use `READY`. Disabled reasons include `WINDOW_OFFLINE`, `TRADING_STATUS_UNKNOWN`, `TRADING_SUSPENDED`, `BOOK_NOT_READY`, `MAKER_INITIALIZING`, `TRADE_LOCKED`, and `TRADE_STATUS_*`. Preserve unknown reasons rather than deriving permission from a status label.

Paginated query records are in `data.records`. Preserve upstream pagination metadata only when supplied; do not invent `total` or `pages`. The window list uses `pageNum=1` and `pageSize=20`; values below 1 are normalized to those defaults, and size is capped at 100. Other paginated queries use `page=1` and `pageSize=10`, capped at 100; nonpositive inputs return HTTP 400. Open orders have additional grouping and missing-statistics rules described below.

## Query endpoints

### List open cycle windows

Returns published, non-deleted windows whose raw trade status is `OPEN_FOR_ORDERS` or `ACTIVE`, including eligible future windows.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/windows" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `GET`                         |
| **Path**           | `/cycle/windows`              |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Query Parameters:**

| Parameter   | Type    | Required | Default | Description                                                              |
| ----------- | ------- | -------- | ------- | ------------------------------------------------------------------------ |
| `symbol`    | string  | No       | —       | Underlying symbol; trimmed and normalized to uppercase.                  |
| `cycleType` | string  | No       | —       | Cycle such as `5m`, `15m`, `4h`, or `1d`; trimmed, then matched exactly. |
| `pageNum`   | integer | No       | `1`     | Values below 1 become 1.                                                 |
| `pageSize`  | integer | No       | `20`    | Values below 1 become 20; capped at 100.                                 |

Records are sorted by window start time and then window ID, ascending. Omitted or blank filters select all eligible windows; request `symbol` corresponds to response `coinSymbol`. This operation does not return `tradingEnabled` or `tradeLockTime`: fetch the snapshot before trading. `isCurrent` only tests windowStartTime ≤ serverTime < windowEndTime, and different assets/cycles may have current windows simultaneously. Save the window ID to locate existing orders after the window leaves this list. Missing prices remain null rather than becoming zero. lockPrice/endPrice are underlying asset prices; upPrice/downPrice are share-price summaries and do not guarantee execution. Never use the underlying asset price as limitPrice.

**Request Example:**

```http
GET /cycle/windows?symbol=ETH&cycleType=5m&pageNum=1&pageSize=20
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/windows?symbol=ETH&cycleType=5m&pageNum=1&pageSize=20" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/windows', {
  query: {"symbol": "ETH", "cycleType": "5m", "pageNum": 1, "pageSize": 20},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/windows", query={'symbol': 'ETH', 'cycleType': '5m', 'pageNum': 1, 'pageSize': 20})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "pageNum": 1,
    "pageSize": 20,
    "total": 1,
    "serverTime": "2026-11-02T00:00:00Z",
    "records": [
      {
        "initialMarketId": "10001",
        "windowId": "20001",
        "coinSymbol": "ETH",
        "cycleType": "5m",
        "publicStatus": "ACTIVE",
        "isCurrent": true
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                       | Type            | Description                                                                                                                 |
| ----------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `data.pageNum / pageSize / total`                           | integer         | Window-list pagination.                                                                                                     |
| `data.serverTime`                                           | UTC date-time   | Server time with Z.                                                                                                         |
| `data.records[]`                                            | array           | Series/window IDs, symbol, cycle, lifecycle status, times and price summaries; consult the generated schema for all fields. |
| `data.records[].isCurrent`                                  | boolean         | Time-window membership only.                                                                                                |
| `data.stateVersion`                                         | integer or null | Highest state version on this page; null without a version/record, and not a global cursor.                                 |
| `data.records[].lockPrice / endPrice / upPrice / downPrice` | string or null  | Underlying prices and share-price summaries; future/unfinished/untrusted prices can be null.                                |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Malformed query fields or pagination return HTTP 400/code `1001`. An empty records array, including one with no exact cycle match, is a normal result. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get a cycle window snapshot

Returns the window lifecycle, trading gates, prices, options, and the locators needed for order-book and trading calls.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/windows/{windowId}" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `GET`                         |
| **Path**           | `/cycle/windows/{windowId}`   |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Path and Query Parameters:**

| Parameter  | Type          | Required | Default | Description         |
| ---------- | ------------- | -------- | ------- | ------------------- |
| `windowId` | string (path) | Yes      | —       | Positive window ID. |

Use `tradeLockTime`, not `windowEndTime`, as the trade cutoff. `tradingEnabled` is a snapshot and is rechecked for actual submission. `bestBid`/`bestAsk` are the best quotes; `lastPrice` is a summary and does not guarantee an execution price. Option keys are lowercase `up`/`down`; result values are uppercase. Keep series/window IDs from the same snapshot.

**Request Example:**

```http
GET /cycle/windows/20001
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/windows/20001" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/windows/20001', {
  query: {},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/windows/20001", query={})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "windowId": "20001",
    "initialMarketId": "10001",
    "coinSymbol": "ETH",
    "cycleType": "5m",
    "publicStatus": "ACTIVE",
    "tradingEnabled": true,
    "options": [
      {
        "optionId": "0",
        "key": "up",
        "bestBid": "0.49",
        "bestAsk": "0.51"
      },
      {
        "optionId": "1",
        "key": "down",
        "bestBid": "0.49",
        "bestAsk": "0.51"
      }
    ],
    "tradeStatus": "ACTIVE",
    "isOnline": true,
    "suspendTrading": false,
    "clobBookStatus": "READY",
    "makerSeedStatus": "READY",
    "windowStartTime": "2026-11-02T00:00:00Z",
    "windowEndTime": "2026-11-02T00:05:00Z",
    "tradeLockTime": "2026-11-02T00:04:30Z",
    "serverTime": "2026-11-02T00:00:00Z",
    "orderbookLocator": {
      "marketId": "20001",
      "optionIds": [
        "0",
        "1"
      ]
    },
    "orderSubmitLocator": {
      "marketId": "10001",
      "outcomeId": "20001"
    }
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                               | Type                     | Description                                                                                            |
| ------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------ |
| `data.windowId / initialMarketId`                                   | string                   | Window and series IDs.                                                                                 |
| `data.publicStatus / tradeStatus`                                   | string                   | Public lifecycle and raw upstream trade state are distinct.                                            |
| `data.tradingEnabled`                                               | boolean                  | Current permission snapshot; not an execution guarantee.                                               |
| `data.tradingDisabledReason`                                        | string                   | Upstream trading-disabled reason; the source does not specify its nullability when trading is enabled. |
| `data.isOnline / suspendTrading`                                    | boolean or null          | Listing and suspension signals.                                                                        |
| `data.clobBookStatus / makerSeedStatus`                             | string                   | Readiness signals; READY means ready.                                                                  |
| `data.windowStartTime / windowEndTime / tradeLockTime / serverTime` | UTC date-time            | Times with Z.                                                                                          |
| `data.options[]`                                                    | array                    | optionId, lowercase key, name, bestBid, bestAsk, lastPrice; absent prices may be null.                 |
| `data.orderbookLocator`                                             | object                   | Compatibility marketId is the window ID; optionIds are cycle option IDs.                               |
| `data.orderSubmitLocator`                                           | object                   | Actual series marketId plus window outcomeId for order creation.                                       |
| `data.fee`                                                          | object                   | makerFeeRate, takerFeeRate, claimFeeRate, winPayoutPerShare.                                           |
| `data.lockPrice / endPrice / difference / totalVolume`              | string or null           | Price and volume summaries.                                                                            |
| `data.result / stateVersion`                                        | string or null / integer | Result enum and state version; do not submit stateVersion as an order field.                           |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid window ID returns HTTP 400/code `1001`; missing resources preserve upstream HTTP 404/code `182001`, `182002`, or `182003` as applicable. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get cycle probability history

Returns UP/DOWN probability history for a window.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/chance/history" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `GET`                         |
| **Path**           | `/cycle/chance/history`       |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Query Parameters:**

| Parameter  | Type   | Required | Default | Description                                                                                                  |
| ---------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------------ |
| `windowId` | string | Yes      | —       | Positive window ID.                                                                                          |
| `optionId` | string | No       | —       | `"0"` = UP; `"1"` = DOWN.                                                                                    |
| `interval` | string | No       | `1m`    | Unfinished window: 1m is the last minute, ALL is the entire round to date; other values use the last minute. |

Omit `optionId` for both sides. Ended windows ignore `interval` and return the full history, with at most one nonzero point per five seconds. `chance` is a percentage: share price = chance / 100. Both returned `marketId` and `outcomeId` are window IDs for compatibility, not trading series IDs. An empty curve is valid.

**Request Example:**

```http
GET /cycle/chance/history?windowId=20001&optionId=0&interval=1m
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/chance/history?windowId=20001&optionId=0&interval=1m" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/chance/history', {
  query: {"windowId": "20001", "optionId": "0", "interval": "1m"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/chance/history", query={'windowId': '20001', 'optionId': '0', 'interval': '1m'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": [
    {
      "marketId": "20001",
      "outcomeId": "20001",
      "optionChanceHistoryVos": [
        {
          "optionId": "0",
          "optionName": "UP",
          "chanceHistory": [
            {
              "chance": "51.00",
              "timestamp": "1793577600000",
              "optionTvl": "0"
            }
          ]
        }
      ]
    }
  ]
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                             | Type   | Description                                                                      |
| --------------------------------- | ------ | -------------------------------------------------------------------------------- |
| `data[]`                          | array  | Non-paginated records: marketId, outcomeId, outcomeName, optionChanceHistoryVos. |
| `data[].optionChanceHistoryVos[]` | array  | optionId, optionName, chanceHistory.                                             |
| `chanceHistory[].chance`          | string | Percentage probability.                                                          |
| `chanceHistory[].timestamp`       | string | Milliseconds since Unix epoch.                                                   |
| `chanceHistory[].optionTvl`       | string | Cycle history TVL, currently zero.                                               |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid window/option IDs return HTTP 400/code `1001`; preserve upstream missing-resource and history errors. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get underlying-asset price history

Returns the BTC/ETH or other underlying asset price curve for the requested UTC interval.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/prices/history" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `GET`                         |
| **Path**           | `/cycle/prices/history`       |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Query Parameters:**

| Parameter       | Type   | Required            | Default | Description                                                                     |
| --------------- | ------ | ------------------- | ------- | ------------------------------------------------------------------------------- |
| `token`         | string | One of token/symbol | —       | Underlying asset symbol, not a login token; takes precedence and is uppercased. |
| `symbol`        | string | One of token/symbol | —       | Compatibility alias for token.                                                  |
| `startTs`       | string | Yes                 | —       | Unix seconds or milliseconds; response uses milliseconds.                       |
| `endTs`         | string | Yes                 | —       | Unix seconds or milliseconds; future end is clamped to now.                     |
| `primarySource` | string | No                  | —       | Prefer the price source returned by the window snapshot.                        |

The maximum range is three days. Ranges of at most five minutes use five-second points; longer ranges are downsampled to about 600 points. Preserve string-valued flags and counts. An empty curve is valid and does not imply a zero asset price.

**Request Example:**

```http
GET /cycle/prices/history?token=ETH&startTs=1793577600000&endTs=1793577900000
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/prices/history?token=ETH&startTs=1793577600000&endTs=1793577900000" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/prices/history', {
  query: {"token": "ETH", "startTs": "1793577600000", "endTs": "1793577900000"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/prices/history", query={'token': 'ETH', 'startTs': '1793577600000', 'endTs': '1793577900000'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "token": "ETH",
    "requestedStartTs": "1793577600000",
    "requestedEndTs": "1793577900000",
    "pointCount": "1",
    "points": [
      {
        "ts": "1793577600000",
        "price": "2500.12",
        "eventTs": "1793577600000",
        "filled": "0"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                      | Type   | Description                                                                                                             |
| ---------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- |
| `data.token`                                               | string | Normalized underlying symbol.                                                                                           |
| `data.requestedStartTs / requestedEndTs / startTs / endTs` | string | Requested and actual bounds in milliseconds.                                                                            |
| `data.stepSeconds / rawIntervalSeconds / maxRangeSeconds`  | string | Sampling step, raw five-second interval, and maximum range of 259200 seconds.                                           |
| `data.truncated`                                           | string | The string true or false, not a JSON boolean.                                                                           |
| `data.pointCount`                                          | string | Number of returned points; the illustrative sample contains one.                                                        |
| `data.points[]`                                            | array  | ts, price, eventTs, filled; timestamps are millisecond strings and filled is "0" for observed or "1" for filled points. |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Missing token/symbol or malformed timestamps return HTTP 400/code `1001`. A start after the end or actual clamped end returns an upstream business error, including HTTP 400/code `182013` or `182014` as returned. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get cycle order-book depth

Returns cycle bid and ask depth for a window and side.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/orderbook" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `POST`                        |
| **Path**           | `/cycle/orderbook`            |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |

**Request Body:**

| Parameter    | Type    | Required              | Default   | Description                                                                                                            |
| ------------ | ------- | --------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------- |
| `marketId`   | string  | marketId or outcomeId | —         | Prefer series ID together with outcomeId; compatibility requests may use the window ID only when outcomeId is omitted. |
| `outcomeId`  | string  | marketId or outcomeId | —         | Window ID; prefer the complete series/window pair.                                                                     |
| `optionId`   | string  | Yes                   | —         | "0" = UP; "1" = DOWN.                                                                                                  |
| `marketType` | integer | No                    | Fixed `3` | Gateway overrides supplied values to cycle type `3`.                                                                   |

Both `asks` and `bids` are sorted by price descending. Do not assume `asks[0]` is the lowest ask; use the snapshot bestAsk or compute the minimum. Depth below 0.01 shares is removed and displayed sizes are rounded down to two decimal places. Compatibility body: `{"marketId":"20001","optionId":"0"}`; never use that window ID as an order-creation series ID.

**Request Example:**

```json
{
  "marketId": "10001",
  "outcomeId": "20001",
  "optionId": "0",
  "marketType": 3
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/orderbook" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"marketId":"10001","outcomeId":"20001","optionId":"0","marketType":3}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('POST', '/cycle/orderbook', {
  body: {"marketId": "10001", "outcomeId": "20001", "optionId": "0", "marketType": 3},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("POST", "/cycle/orderbook", body={'marketId': '10001', 'outcomeId': '20001', 'optionId': '0', 'marketType': 3})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "outcomeId": "20001",
    "optionId": "0",
    "asks": [
      {
        "price": "0.51",
        "size": "10.00"
      }
    ],
    "bids": [
      {
        "price": "0.49",
        "size": "8.00"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                       | Type   | Description                                                                |
| --------------------------- | ------ | -------------------------------------------------------------------------- |
| `data.outcomeId / optionId` | string | Window and selected option.                                                |
| `data.asks / bids`          | array  | Depth levels with decimal-string price and size, both descending by price. |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Missing option ID, missing both locator IDs, or an invalid locator/option returns HTTP 400/code `1001`; unmatched series/window errors preserve upstream code `3009` when returned. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List the current user's open cycle orders

Returns the current user's grouped LIMIT orders in OPEN or PARTIAL\_FILLED state.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/orders/open" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/orders/open`                           |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter    | Type    | Required | Default   | Description                                                                 |
| ------------ | ------- | -------- | --------- | --------------------------------------------------------------------------- |
| `page`       | integer | No       | `1`       | Page number, starting at 1; nonpositive values are rejected.                |
| `pageSize`   | integer | No       | `10`      | Page size; nonpositive values are rejected and values above 100 are capped. |
| `marketId`   | string  | No       | —         | Filter by series ID (`initialMarketId`).                                    |
| `outcomeId`  | string  | No       | —         | Filter by window ID belonging to the selected series.                       |
| `optionId`   | string  | No       | —         | `"0"` = UP; `"1"` = DOWN.                                                   |
| `marketType` | integer | No       | Fixed `3` | Gateway overrides supplied values to cycle type `3`.                        |
| `title`      | string  | No       | —         | Title or window-code search.                                                |

This query excludes ACCEPTED, MATCHING, and market orders. `records` contains grouped rows, not individual orders. Cancel using `ordersOpenDetailVOList[].id`, never a position ID. Upstream zero placeholders for `total`, `pages`, or count statistics are omitted; actual nonzero statistics are preserved when supplied. Missing totals do not mean there are no orders, and group counts do not equal the nested detail count. Continue paging until an empty records page when totals are unavailable.

**Request Example:**

```json
{
  "page": 1,
  "pageSize": 20,
  "marketId": "10001",
  "outcomeId": "20001",
  "marketType": 3
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/orders/open" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"page":1,"pageSize":20,"marketId":"10001","outcomeId":"20001","marketType":3}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/orders/open', {
  cookieRequired: true,
  body: {"page": 1, "pageSize": 20, "marketId": "10001", "outcomeId": "20001", "marketType": 3},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/orders/open", cookie_required=True, body={'page': 1, 'pageSize': 20, 'marketId': '10001', 'outcomeId': '20001', 'marketType': 3})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "current": 1,
    "size": 20,
    "records": [
      {
        "marketId": "10001",
        "outcomeId": "20001",
        "optionId": "0",
        "ordersOpenDetailVOList": [
          {
            "id": "30001",
            "side": "BUY",
            "price": "0.40",
            "share": "10"
          }
        ]
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                                          | Type                      | Description                                                                                                                                      |
| ------------------------------------------------------------------------------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data.records[]`                                                               | array                     | Grouped series/window/option rows.                                                                                                               |
| `data.records[].ordersOpenDetailVOList[]`                                      | array                     | Individual open orders; id is the cancellation ID, with side, price, share and other upstream detail fields.                                     |
| `data.current / size / total / pages / count`                                  | integer, when supplied    | Upstream metadata; zero placeholder statistics are omitted, and missing statistics are not synthesized.                                          |
| `data.records[].ordersOpenDetailVOList[].expirationAt / createdAt / updatedAt` | UTC LocalDateTime or null | Retained upstream timezone-free timestamps. An expirationAt response field does not promise support for custom expiry or automatic cancellation. |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid pagination, IDs, or unsupported fields return HTTP 400/code `1001`. Missing/invalid sessions return HTTP 401 with gateway `1401` or upstream `401`. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List cycle positions

Returns the current user's cycle positions, including claimed records when present.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/positions" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/positions`                             |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter     | Type    | Required | Default   | Description                                                                 |
| ------------- | ------- | -------- | --------- | --------------------------------------------------------------------------- |
| `page`        | integer | No       | `1`       | Page number, starting at 1; nonpositive values are rejected.                |
| `pageSize`    | integer | No       | `10`      | Page size; nonpositive values are rejected and values above 100 are capped. |
| `marketId`    | string  | No       | —         | Filter by series ID (`initialMarketId`).                                    |
| `outcomeId`   | string  | No       | —         | Filter by window ID belonging to the selected series.                       |
| `marketType`  | integer | No       | Fixed `3` | Gateway overrides supplied values to cycle type `3`.                        |
| `positionId`  | string  | No       | —         | Filter by the current user's position ID.                                   |
| `orderStatus` | string  | No       | —         | Position-state filter; see the position-status values above.                |
| `filter`      | string  | No       | —         | Title or window-code search.                                                |

This query includes CLAIMED records, excludes FILLED, and retains positions with shares at least 0.01. `availableShare` is the sellable amount. Asset-page `status`, `coinId`, and `network` are not cycle filters on this operation; use the asset-position endpoint for its distinct scope. Compatibility fields may be null. When reconciling a claim, query by positionId without a SETTLED-only filter so that CLAIMING and CLAIMED remain visible.

**Request Example:**

```json
{
  "page": 1,
  "pageSize": 20,
  "marketId": "10001",
  "outcomeId": "20001",
  "marketType": 3
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/positions" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"page":1,"pageSize":20,"marketId":"10001","outcomeId":"20001","marketType":3}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/positions', {
  cookieRequired: true,
  body: {"page": 1, "pageSize": 20, "marketId": "10001", "outcomeId": "20001", "marketType": 3},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/positions", cookie_required=True, body={'page': 1, 'pageSize': 20, 'marketId': '10001', 'outcomeId': '20001', 'marketType': 3})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "records": [
      {
        "marketId": "10001",
        "outcomeId": "20001",
        "optionId": "0",
        "positionId": "40001",
        "shares": "10",
        "availableShare": "10",
        "averagePrice": "0.40",
        "orderStatus": "CLAIMED"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                    | Type                   | Description                                               |
| ---------------------------------------- | ---------------------- | --------------------------------------------------------- |
| `data.records[]`                         | array                  | Current-user position rows with series/window/option IDs. |
| `data.records[].positionId`              | string                 | Position ID for SELL or claim.                            |
| `data.records[].shares / availableShare` | string                 | Total and currently sellable shares.                      |
| `data.records[].averagePrice`            | string or null         | Average position price when supplied.                     |
| `data.records[].orderStatus`             | string                 | Position status; separate from order status.              |
| `data.current / size / total / pages`    | integer, when supplied | Upstream pagination metadata.                             |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid fields, IDs, or pagination return HTTP 400/code `1001`; missing/expired sessions return HTTP 401/code `1401` or upstream `401`. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List asset-page positions for cycle markets

Returns the current user's asset-page cycle positions with asset-page status and network filters.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/positions/assets" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/positions/assets`                      |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter      | Type    | Required | Default     | Description                                                                 |
| -------------- | ------- | -------- | ----------- | --------------------------------------------------------------------------- |
| `page`         | integer | No       | `1`         | Page number, starting at 1; nonpositive values are rejected.                |
| `pageSize`     | integer | No       | `10`        | Page size; nonpositive values are rejected and values above 100 are capped. |
| `marketId`     | string  | No       | —           | Filter by series ID (`initialMarketId`).                                    |
| `outcomeId`    | string  | No       | —           | Filter by window ID belonging to the selected series.                       |
| `marketType`   | integer | No       | Fixed `3`   | Gateway overrides supplied values to cycle type `3`.                        |
| `positionId`   | string  | No       | —           | Filter by the current user's position ID.                                   |
| `filter`       | string  | No       | —           | Title or description search.                                                |
| `status`       | string  | No       | —           | Asset-page status: Live, Ended, or Resolved.                                |
| `orderStatus`  | string  | No       | —           | Position-state filter; see the position-status values above.                |
| `coinId`       | string  | No       | Fixed `"2"` | USDT; gateway overrides any supplied currency ID.                           |
| `network`      | string  | No       | —           | `mainnet` or `testnet`.                                                     |
| `languageCode` | string  | No       | —           | Optional localization; prefer the Accept-Language request header.           |

The gateway fixes USDT `coinId` to "2". This query has a different scope from the general position list; do not assume the same filters select the same rows. Use its positionId and availableShare for the current user, and preserve nullable compatibility fields.

**Request Example:**

```json
{
  "page": 1,
  "pageSize": 20,
  "marketId": "10001",
  "outcomeId": "20001",
  "marketType": 3
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/positions/assets" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"page":1,"pageSize":20,"marketId":"10001","outcomeId":"20001","marketType":3}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/positions/assets', {
  cookieRequired: true,
  body: {"page": 1, "pageSize": 20, "marketId": "10001", "outcomeId": "20001", "marketType": 3},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/positions/assets", cookie_required=True, body={'page': 1, 'pageSize': 20, 'marketId': '10001', 'outcomeId': '20001', 'marketType': 3})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "records": [
      {
        "marketId": "10001",
        "outcomeId": "20001",
        "optionId": "0",
        "positionId": "40001",
        "shares": "10",
        "availableShare": "10"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                         | Type                   | Description                                  |
| ------------------------------------------------------------- | ---------------------- | -------------------------------------------- |
| `data.records[]`                                              | array                  | Asset-page position rows.                    |
| `data.records[].positionId / marketId / outcomeId / optionId` | string                 | User position, series, window, and side IDs. |
| `data.records[].shares / availableShare`                      | string                 | Position shares and sellable shares.         |
| `data.current / size / total / pages`                         | integer, when supplied | Upstream pagination metadata.                |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Malformed JSON, IDs, or pagination return HTTP 400/code `1001`; preserve actual upstream status/network errors. Invalid sessions preserve HTTP 401/code `1401` or upstream `401`. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List the current user's cycle activity

Returns the current user's cycle activity, optionally filtered by series, window, order, and event type.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/activity/user" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `GET`                                          |
| **Path**           | `/cycle/activity/user`                         |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                           |
| ------------------------ | ------------------- | --------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                      |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                     |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                      |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.     |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.              |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                          |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.           |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user. |

**Query Parameters:**

| Parameter     | Type      | Required                 | Default           | Description                                                                  |
| ------------- | --------- | ------------------------ | ----------------- | ---------------------------------------------------------------------------- |
| `page`        | integer   | No                       | `1`               | Page number, starting at 1; nonpositive values are rejected.                 |
| `pageSize`    | integer   | No                       | `10`              | Page size; nonpositive values are rejected and values above 100 are capped.  |
| `marketId`    | string    | No                       | —                 | Filter by series ID (`initialMarketId`).                                     |
| `outcomeId`   | string    | No                       | —                 | Filter by window ID belonging to the selected series.                        |
| `marketType`  | integer   | No                       | Fixed `3`         | Gateway overrides supplied values to cycle type `3`.                         |
| `marketTitle` | string    | No                       | —                 | Title filter.                                                                |
| `orderId`     | string    | No                       | —                 | Exact order ID filter.                                                       |
| `sortBy`      | string    | No                       | `Newest`          | Sort enum above; the Amount expression and tie stability remain unconfirmed. |
| `type`        | string    | No                       | `ALL`             | Exact activity-event type, or ALL for every type.                            |
| `filter`      | string    | No                       | —                 | Upstream filter condition; no additional interpretation is defined here.     |
| `search`      | string    | No                       | Empty string      | Keyword search.                                                              |
| `coinId`      | string    | No                       | Fixed `"2"`       | USDT; gateway overrides any supplied currency ID.                            |
| `timeFilter`  | string    | No                       | `all`             | Time-filter enum above.                                                      |
| `network`     | string    | No                       | —                 | `mainnet` or `testnet`.                                                      |
| `modelType`   | string    | No                       | Fixed `orderbook` | Gateway overrides any supplied trading model.                                |
| `startTime`   | date-time | When `timeFilter=custom` | —                 | Custom UTC start, without a timezone suffix, e.g. `2026-11-02T00:00:00`.     |
| `endTime`     | date-time | No                       | Now for `custom`  | Custom UTC end without a timezone suffix; omitted end uses the current time. |

Do not supply userId. `type=ALL` does not restrict the event type; other values match the exact type. Custom times are UTC without a timezone suffix. `price`, `value`, and `fees` have event-dependent semantics that remain to be confirmed; do not apply one balance formula to BUY, SELL, and CLAIM or subtract fees again from a potentially net value. Amount/AmountAsc expression, mixed-event ordering, and stable ties are not established.

**Request Example:**

```http
GET /cycle/activity/user?marketId=10001&outcomeId=20001&marketType=3&page=1&pageSize=20&type=ALL
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/activity/user?marketId=10001&outcomeId=20001&marketType=3&page=1&pageSize=20&type=ALL" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('GET', '/cycle/activity/user', {
  cookieRequired: true,
  query: {"marketId": "10001", "outcomeId": "20001", "marketType": 3, "page": 1, "pageSize": 20, "type": "ALL"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("GET", "/cycle/activity/user", cookie_required=True, query={'marketId': '10001', 'outcomeId': '20001', 'marketType': 3, 'page': 1, 'pageSize': 20, 'type': 'ALL'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "records": [
      {
        "marketId": "10001",
        "outcomeId": "20001",
        "optionId": "0",
        "type": "BUY",
        "shares": "10",
        "price": "0.40",
        "date": "2026-11-02T00:00:00"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                   | Type                      | Description                                                                                  |
| ------------------------------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------- |
| `data.records[]`                                        | array                     | Activity records with id, user display data, series/window/option and order-related context. |
| `data.records[].type / shares / price`                  | string                    | Event type, shares, and event-specific price or amount.                                      |
| `data.records[].value / fees`                           | string                    | Event-dependent amount and fee; gross/net inclusion is unconfirmed per event type.           |
| `data.records[].marketType / modelType / coinId`        | integer / string / string | Cycle 3, orderbook, USDT "2".                                                                |
| `data.records[].date / marketStartTime / marketEndTime` | UTC LocalDateTime         | Upstream timezone-free text, interpreted as UTC.                                             |
| `data.current / size / total / pages`                   | integer, when supplied    | Upstream pagination metadata, never fabricated.                                              |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid query, pagination, or custom time range returns HTTP 400/code `1001` or an upstream time-parameter code as returned. Missing/invalid sessions return HTTP 401/code `1401` or upstream `401`. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List cycle activity for a series and window

Returns public cycle activity for the selected series and window.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/activity/market" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                         |
| ------------------ | ----------------------------- |
| **Method**         | `GET`                         |
| **Path**           | `/cycle/activity/market`      |
| **Authentication** | `Gateway signature + API key` |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Query Parameters:**

| Parameter    | Type      | Required                 | Default          | Description                                                                  |
| ------------ | --------- | ------------------------ | ---------------- | ---------------------------------------------------------------------------- |
| `marketId`   | string    | Yes                      | —                | Series ID (`initialMarketId`).                                               |
| `outcomeId`  | string    | Yes                      | —                | Window ID belonging to that series.                                          |
| `page`       | integer   | No                       | `1`              | Page number, starting at 1; nonpositive values are rejected.                 |
| `pageSize`   | integer   | No                       | `10`             | Page size; nonpositive values are rejected and values above 100 are capped.  |
| `sortBy`     | string    | No                       | `Newest`         | Sort enum above; the Amount expression and tie stability remain unconfirmed. |
| `type`       | string    | No                       | `ALL`            | Exact activity-event type, or ALL for every type.                            |
| `filter`     | string    | No                       | —                | Upstream filter condition; no additional interpretation is defined here.     |
| `search`     | string    | No                       | Empty string     | Keyword search.                                                              |
| `timeFilter` | string    | No                       | `max_days`       | Time-filter enum above.                                                      |
| `startTime`  | date-time | When `timeFilter=custom` | —                | Custom UTC start, without a timezone suffix, e.g. `2026-11-02T00:00:00`.     |
| `endTime`    | date-time | No                       | Now for `custom` | Custom UTC end without a timezone suffix; omitted end uses the current time. |

This operation does not accept marketType, userId, or orderId. Custom start/end use UTC LocalDateTime without a timezone suffix; omitted custom end uses now. As with personal activity, price/value/fees semantics vary by event and remain unconfirmed. The Amount sorting expression, mixed-event comparison, and tie stability must not be inferred from sample ordering.

**Request Example:**

```http
GET /cycle/activity/market?marketId=10001&outcomeId=20001&page=1&pageSize=20
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/activity/market?marketId=10001&outcomeId=20001&page=1&pageSize=20" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/activity/market', {
  query: {"marketId": "10001", "outcomeId": "20001", "page": 1, "pageSize": 20},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/activity/market", query={'marketId': '10001', 'outcomeId': '20001', 'page': 1, 'pageSize': 20})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "records": [
      {
        "marketId": "10001",
        "outcomeId": "20001",
        "optionId": "0",
        "type": "BUY",
        "shares": "10",
        "price": "0.40"
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                 | Type                   | Description                                                        |
| ----------------------------------------------------- | ---------------------- | ------------------------------------------------------------------ |
| `data.records[]`                                      | array                  | Public series/window activity rows.                                |
| `data.records[].marketId / outcomeId / optionId`      | string                 | Series, window, and side IDs.                                      |
| `data.records[].type / shares / price / value / fees` | string                 | Event data; amount and fee interpretations remain event-dependent. |
| `data.records[].date`                                 | UTC LocalDateTime      | Activity time retains the upstream timezone-free format.           |
| `data.current / size / total / pages`                 | integer, when supplied | Upstream pagination metadata.                                      |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Missing/mismatched series or window, unsupported query fields, invalid pagination, or invalid custom times return HTTP 400/code `1001` or the actual upstream business error. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### List cycle window top holders

Returns the top holders for each side of a cycle window.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/windows/{windowId}/top-holders" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                   |
| ------------------ | --------------------------------------- |
| **Method**         | `GET`                                   |
| **Path**           | `/cycle/windows/{windowId}/top-holders` |
| **Authentication** | `Gateway signature + API key`           |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Path and Query Parameters:**

| Parameter  | Type                   | Required | Default | Description                                                        |
| ---------- | ---------------------- | -------- | ------- | ------------------------------------------------------------------ |
| `windowId` | string (path)          | Yes      | —       | Positive window ID.                                                |
| `limit`    | string (numeric query) | No       | `15`    | Numeric limit clamped to 1–50; malformed numeric text is rejected. |

Holder user IDs are display identifiers, not request identity selectors. Preserve returned share strings.

**Request Example:**

```http
GET /cycle/windows/20001/top-holders?limit=15
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/windows/20001/top-holders?limit=15" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/windows/20001/top-holders', {
  query: {"limit": 15},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/windows/20001/top-holders", query={'limit': 15})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "windowId": "20001",
    "optionHolderVoList": [
      {
        "optionId": "0",
        "holderVoList": [
          {
            "userId": "70001",
            "userName": "trader",
            "share": "10"
          }
        ]
      }
    ]
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                | Type   | Description                                          |
| ------------------------------------ | ------ | ---------------------------------------------------- |
| `data.windowId`                      | string | Window ID.                                           |
| `data.optionHolderVoList[]`          | array  | Per-option holder lists.                             |
| `data.optionHolderVoList[].optionId` | string | Cycle side 0 or 1.                                   |
| `holderVoList[]`                     | array  | User display fields and decimal-string share values. |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Malformed window ID or numeric limit returns HTTP 400/code `1001`; unavailable windows preserve the upstream missing-resource error. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get cycle window settlement

Returns the settlement card, result, readiness evidence, and settlement progress for a window.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/windows/{windowId}/settlement" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                  |
| ------------------ | -------------------------------------- |
| **Method**         | `GET`                                  |
| **Path**           | `/cycle/windows/{windowId}/settlement` |
| **Authentication** | `Gateway signature + API key`          |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Path and Query Parameters:**

| Parameter  | Type          | Required | Default | Description         |
| ---------- | ------------- | -------- | ------- | ------------------- |
| `windowId` | string (path) | Yes      | —       | Positive window ID. |

`available=false` is a normal response; other card fields may be null. Result proposal, confirmation, payout completion, position claim, and wallet credit are separate stages. completedTime is not a user claim time. The conditions for PAYOUT\_PROCESSING → SETTLED, sufficiency of READY plus zero pending counts, allowed null completedTime states, and permitted lag behind CLAIMED/wallet credit remain unconfirmed. Do not infer completion, normality of a stale card, or an SLA from those signals.

**Request Example:**

```http
GET /cycle/windows/20001/settlement
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/windows/20001/settlement" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/windows/20001/settlement', {
  query: {},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/windows/20001/settlement", query={})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "available": true,
    "settlementId": "50001",
    "status": "SETTLED",
    "result": "UP",
    "lockPrice": "2500.00",
    "settlementPrice": "2501.20",
    "readiness": {
      "status": "READY",
      "snapshotMatched": true
    }
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                                                                                                   | Type                                                | Description                                                                             |
| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `data.available`                                                                                                        | boolean                                             | Whether a displayable settlement card exists.                                           |
| `data.settlementId / settlementVersion / settlementType`                                                                | string / integer / string, nullable                 | Settlement identity, revision, and NORMAL/VOID/CORRECTION type.                         |
| `data.status / result`                                                                                                  | string or null                                      | Settlement status and UP/DOWN/VOID result.                                              |
| `data.lockPrice / settlementPrice / difference`                                                                         | string or null                                      | Underlying price evidence and difference.                                               |
| `data.proposalTime / disputeEndTime / completedTime`                                                                    | UTC date-time or null                               | Settlement timestamps; completedTime timing and allowed null states remain unconfirmed. |
| `data.externalDescription / stateVersion / serverTime`                                                                  | string / integer / UTC date-time, nullable          | Description, state revision, and server time.                                           |
| `data.readiness.status`                                                                                                 | string or null                                      | READY, BLOCKED, or UNKNOWN.                                                             |
| `data.readiness.windowOpenTradeSeq / tradeWatermark / processedContiguousTradeSeq`                                      | string or null                                      | Trade-sequence/watermark evidence.                                                      |
| `data.readiness.postTradePendingCount / walletTradePendingCount / openOrderUnresolvedCount / cancelReleasePendingCount` | integer or null                                     | Pending work counters; zero is not an established sufficient completion test.           |
| `data.readiness.positionSnapshotId / positionSnapshotHash / positionSnapshotReadyAt / snapshotMatched`                  | string / string / UTC date-time / boolean, nullable | Snapshot identity, integrity, readiness time, and match evidence.                       |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid window IDs return HTTP 400/code `1001`; missing settlement resources preserve HTTP 404/upstream `182001`, `182002`, or `182003` when returned. available=false is not an error. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get recent cycle results and streaks

Returns recent window results and streak counts for one series.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/series/{initialMarketId}/roadmap" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                     |
| ------------------ | ----------------------------------------- |
| **Method**         | `GET`                                     |
| **Path**           | `/cycle/series/{initialMarketId}/roadmap` |
| **Authentication** | `Gateway signature + API key`             |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Path and Query Parameters:**

| Parameter         | Type            | Required | Default | Description         |
| ----------------- | --------------- | -------- | ------- | ------------------- |
| `initialMarketId` | string (path)   | Yes      | —       | Positive series ID. |
| `limit`           | integer (query) | No       | `20`    | Clamped to 1–100.   |

upCount, downCount, and voidCount summarize the returned items, not all windows in the series. Preserve void and correction settlement types instead of treating every completed item as a normal UP/DOWN result.

**Request Example:**

```http
GET /cycle/series/10001/roadmap?limit=20
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/series/10001/roadmap?limit=20" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/series/10001/roadmap', {
  query: {"limit": 20},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/series/10001/roadmap", query={'limit': 20})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "initialMarketId": "10001",
    "items": [
      {
        "windowId": "20001",
        "result": "UP",
        "settlementType": "NORMAL",
        "settlementPrice": "2501.20"
      }
    ],
    "upCount": 1,
    "downCount": 0,
    "voidCount": 0,
    "currentStreak": {
      "result": "UP",
      "count": 1
    }
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                  | Type    | Description                                                      |
| -------------------------------------- | ------- | ---------------------------------------------------------------- |
| `data.initialMarketId`                 | string  | Series ID.                                                       |
| `data.items[]`                         | array   | Recent window results, settlement types, prices, and timestamps. |
| `data.upCount / downCount / voidCount` | integer | Counts over returned items only.                                 |
| `data.currentStreak`                   | object  | Current result and consecutive count.                            |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid series ID or limit returns HTTP 400/code `1001`; missing series preserve the upstream missing-resource code. See [shared cycle errors](#shared-errors) for authentication and transport failures.

### Get effective cycle rules

Returns the effective series configuration, optionally for a particular window.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/series/{initialMarketId}/rules" method="get" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                   |
| ------------------ | --------------------------------------- |
| **Method**         | `GET`                                   |
| **Path**           | `/cycle/series/{initialMarketId}/rules` |
| **Authentication** | `Gateway signature + API key`           |

**Request Headers:**

| Header                   | Required            | Description                                                       |
| ------------------------ | ------------------- | ----------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                  |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                 |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                  |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret. |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.          |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                      |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.       |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.            |

**Path and Query Parameters:**

| Parameter         | Type           | Required | Default | Description                                         |
| ----------------- | -------------- | -------- | ------- | --------------------------------------------------- |
| `initialMarketId` | string (path)  | Yes      | —       | Positive series ID.                                 |
| `windowId`        | string (query) | No       | —       | Select the configuration effective for this window. |

Read the configured fee rates, price sources, locking lead time, precision, rounding, equal-price result, and payout rules. The illustrative values below are not universal business defaults; do not derive fees, tie handling, or settlement timing from the example.

**Request Example:**

```http
GET /cycle/series/10001/rules?windowId=20001
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X GET "https://openapi.foregate.com/cycle/series/10001/rules?windowId=20001" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>"
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const res = await client.request('GET', '/cycle/series/10001/rules', {
  query: {"windowId": "20001"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
res = client.request("GET", "/cycle/series/10001/rules", query={'windowId': '20001'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "initialMarketId": "10001",
    "configVersion": 1,
    "lockingTimeSeconds": 30,
    "priceScale": 3,
    "roundingMode": "HALF_UP",
    "winPayoutPerShare": "1.00"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                                              | Type                    | Description                                                        |
| -------------------------------------------------- | ----------------------- | ------------------------------------------------------------------ |
| `data.initialMarketId / configVersion`             | string / integer        | Series and effective configuration revision.                       |
| `data.lockingTimeSeconds`                          | integer                 | Configured lead time for trade locking.                            |
| `data.priceScale / roundingMode`                   | integer / string        | Configured precision and rounding.                                 |
| `data.winPayoutPerShare`                           | string                  | Configured winning payout.                                         |
| `data.summary / lockingTimeDescription / rules`    | string                  | Summary, locking explanation, and localized rule text.             |
| `data.disputeDurationSeconds`                      | integer                 | Configured dispute duration.                                       |
| `data.equalResult / sourceDisclosure / voidPolicy` | string                  | Configured equal-price result, source disclosure, and void policy. |
| `data.makerFeeRate / takerFeeRate / claimFeeRate`  | string                  | Effective configured fee rates.                                    |
| `data.serverTime / stateVersion`                   | UTC date-time / integer | Server timestamp and state version.                                |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid series/window IDs or mismatched configuration selectors return HTTP 400/code `1001` or the upstream resource/business error. See [shared cycle errors](#shared-errors) for authentication and transport failures.

## Trading and claim endpoints

### Create a cycle order

Submits a cycle LIMIT or MARKET order for the authenticated user.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/orders" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/orders`                                |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter      | Type                     | Required             | Default                        | Description                                                                                                              |
| -------------- | ------------------------ | -------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `direction`    | string                   | Yes                  | —                              | BUY or SELL.                                                                                                             |
| `orderType`    | string                   | Yes                  | —                              | LIMIT or MARKET.                                                                                                         |
| `marketId`     | string                   | Yes                  | —                              | Series ID from initialMarketId / orderSubmitLocator.marketId.                                                            |
| `outcomeId`    | string                   | Yes                  | —                              | Window ID belonging to that series.                                                                                      |
| `optionId`     | string                   | Yes                  | —                              | "0" = UP; "1" = DOWN.                                                                                                    |
| `positionId`   | string                   | Every SELL           | —                              | Current user position for the same window and option; required for both LIMIT SELL and MARKET SELL.                      |
| `limitPrice`   | decimal string or number | Every LIMIT          | —                              | Unit price. Proxy validation: >0 and ≤1, multiple of fixed tick 0.001. Actual acceptance at 1 is unconfirmed; see below. |
| `share`        | decimal string or number | LIMIT or MARKET SELL | —                              | Positive number of shares.                                                                                               |
| `price`        | decimal string or number | MARKET BUY           | —                              | Positive total buy amount, not unit price.                                                                               |
| `timeInForce`  | string                   | No                   | Omission semantics unconfirmed | Current documented development restriction: explicit GTC only; prefer explicit GTC for LIMIT.                            |
| `expirationAt` | Unsupported              | Must be omitted      | —                              | Any presence, including null, is rejected with HTTP 400/code 1001; no automatic expiry promise.                          |

SELL always requires positionId, including LIMIT SELL. Do not pass user identity, coinId, marketType, or state-version fields: these are server-controlled. ACCEPTED only acknowledges processing; it is not OPEN, a fill, or a completed trade. Gates are checked again before matching. Save fgRequestId and orderId, then reconcile open orders, positions, activity, and account assets. Absence from open orders alone cannot distinguish pending, filled, canceled, or rejected states. There is no documented public final-status lookup by fgRequestId. An uncertain or timed-out result does not authorize a duplicate write; writes are not automatically retried.

The proxy validates `0 < limitPrice ≤ 1` at tick `0.001`. Development evidence records a rejected price of 1 (HTTP 400/code 5003, "amount not in range") and an executed 0.99 request. Neither proves a formal maximum of 0.99 or 0.999 or that price alone triggers the error. Exact amount/price/direction constraints remain unconfirmed. Current development behavior rejects FOK, IOC, and POST\_ONLY; omission of timeInForce does not have a confirmed execution default. expirationAt is rejected even when null or in the past/future; explicitly cancel remaining orders at the desired cutoff.

**Other order combinations** (supply the same series/window pair):

| Scenario        | Required scenario-specific fields                                                                                              |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| MARKET BUY DOWN | `direction=BUY`, `orderType=MARKET`, `optionId="1"`, `price="5"`                                                               |
| LIMIT SELL UP   | `direction=SELL`, `orderType=LIMIT`, `timeInForce=GTC`, `optionId="0"`, `positionId="40001"`, `limitPrice="0.60"`, `share="2"` |
| MARKET SELL UP  | `direction=SELL`, `orderType=MARKET`, `optionId="0"`, `positionId="40001"`, `share="2"`                                        |

**Request Example:**

```json
{
  "direction": "BUY",
  "orderType": "LIMIT",
  "timeInForce": "GTC",
  "marketId": "10001",
  "outcomeId": "20001",
  "optionId": "0",
  "limitPrice": "0.40",
  "share": "10"
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/orders" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"direction":"BUY","orderType":"LIMIT","timeInForce":"GTC","marketId":"10001","outcomeId":"20001","optionId":"0","limitPrice":"0.40","share":"10"}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/orders', {
  cookieRequired: true,
  body: {"direction": "BUY", "orderType": "LIMIT", "timeInForce": "GTC", "marketId": "10001", "outcomeId": "20001", "optionId": "0", "limitPrice": "0.40", "share": "10"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/orders", cookie_required=True, body={'direction': 'BUY', 'orderType': 'LIMIT', 'timeInForce': 'GTC', 'marketId': '10001', 'outcomeId': '20001', 'optionId': '0', 'limitPrice': '0.40', 'share': '10'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "fgRequestId": "REQ202611020001",
    "orderId": "30001",
    "orderStatus": "ACCEPTED",
    "createdAt": "2026-11-02T00:00:00"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field              | Type              | Description                                                                          |
| ------------------ | ----------------- | ------------------------------------------------------------------------------------ |
| `data.fgRequestId` | string            | Processing correlation ID; no public final-status endpoint by this ID is documented. |
| `data.orderId`     | string            | Exact order ID for cancellation; not positionId.                                     |
| `data.orderStatus` | string            | Order acknowledgement state; ACCEPTED is not final.                                  |
| `data.createdAt`   | UTC LocalDateTime | Creation time retains the timezone-free upstream format.                             |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid field combinations, missing SELL positionId, tick misalignment, unsupported timeInForce, or any expirationAt return HTTP 400/code `1001`. Upstream price/amount rejection can return HTTP 400/code `5003`. On HTTP 504/code `2001` or transport uncertainty, reconcile before considering another write. See [shared cycle errors](#shared-errors) for authentication and transport failures.

```json
{
  "code": 1001,
  "message": "bad request: expirationAt is not supported for cycle orders; omit it and explicitly cancel remaining orders",
  "data": null
}
```

### Cancel specific cycle orders

Cancels an exact list of the authenticated user's cycle open orders within one series.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/orders/cancel" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/orders/cancel`                         |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter       | Type   | Required | Default | Description                                                                                              |
| --------------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------- |
| `marketId`      | string | Yes      | —       | Positive series ID, not a window ID; must match the orders.                                              |
| `orderOpenIds`  | array  | Yes      | —       | Nonempty exact order-ID list from create-order orderId or open-order nested detail id; never positionId. |
| `outcomeId`     | string | No       | —       | Optional window locator; does not expand the cancellation scope.                                         |
| `optionId`      | string | No       | —       | `"0"` = UP; `"1"` = DOWN.                                                                                |
| `processRemark` | string | No       | —       | Processing remark.                                                                                       |

Range cancellation using only marketId/outcomeId/optionId is unsupported. For bulk cancellation, query all pages of open orders, verify series/window/side, collect nested order IDs, and submit exact IDs per series. Orders can fill between query and cancellation. Check each per-order success when present, then re-query open orders, positions, balance, and sellable shares for partial fills and released remainders. Top-level success does not guarantee every cancellation succeeded. `data` varies by upstream branch and may be a boolean, object, or per-order array; the sample below illustrates only the array branch and is not a fixed response-shape guarantee.

**Request Example:**

```json
{
  "marketId": "10001",
  "orderOpenIds": [
    "30001"
  ]
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/orders/cancel" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"marketId":"10001","orderOpenIds":["30001"]}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/orders/cancel', {
  cookieRequired: true,
  body: {"marketId": "10001", "orderOpenIds": ["30001"]},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/orders/cancel", cookie_required=True, body={'marketId': '10001', 'orderOpenIds': ['30001']})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": [
    {
      "orderId": "30001",
      "success": true,
      "message": null
    }
  ]
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                          | Type                      | Description                                                                  |
| ------------------------------ | ------------------------- | ---------------------------------------------------------------------------- |
| `code / message`               | integer / string          | Overall request processing result; does not guarantee every order succeeded. |
| `data`                         | boolean, object, or array | Upstream branch-dependent result; no fixed per-order shape is promised.      |
| `data[].success, when present` | boolean                   | Inspect every returned per-order outcome and preserve its actual message.    |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Missing series ID, empty/missing exact order IDs, or a range-only request returns HTTP 400/code `1001`. Preserve per-order ownership/state errors; a fill/cancel race can produce mixed results. See [shared cycle errors](#shared-errors) for authentication and transport failures.

```json
{
  "code": 1001,
  "message": "bad request: Range cancellation is not supported for cycle orders; provide marketId and a non-empty orderOpenIds array",
  "data": null
}
```

### Claim cycle positions

Submits a claim for the current user's settled positions in one series.

{% openapi src="/files/RRgdmIfYudFzNUU7IfYI" path="/cycle/claim" method="post" %}
[openapi.yaml](https://1848912399-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F4Jfq6o1ZJ9TcdPcIBHBM%2Fuploads%2Fgit-blob-9c36a92a8548739c286ccdd627995e665e08b1ca%2Fopenapi.yaml?alt=media)
{% endopenapi %}

| Property           | Value                                          |
| ------------------ | ---------------------------------------------- |
| **Method**         | `POST`                                         |
| **Path**           | `/cycle/claim`                                 |
| **Authentication** | `Gateway signature + API key + session cookie` |

**Request Headers:**

| Header                   | Required            | Description                                                            |
| ------------------------ | ------------------- | ---------------------------------------------------------------------- |
| `accept`                 | Yes                 | application/json; participates in the signature.                       |
| `date`                   | Yes                 | Fresh UTC signing timestamp: YYYY-MM-DD HH:mm:ss.                      |
| `x-ca-key`               | Yes                 | Gateway APP Key.                                                       |
| `x-ca-signature`         | Yes                 | Base64 HMAC-SHA256 of the canonical request using the APP Secret.      |
| `x-ca-signature-headers` | Yes                 | Signed custom-header names; the examples sign x-api-key.               |
| `x-api-key`              | Yes                 | ForeGate API key; included in the signature.                           |
| `Accept-Language`        | No                  | Optional locale forwarded upstream, such as en-US or zh-CN.            |
| `X-NONCE`                | Deployment-specific | Supply a unique nonce when required by the deployment.                 |
| `content-type`           | Yes                 | application/json.                                                      |
| `content-md5`            | Yes                 | Base64 MD5 of the exact serialized JSON body; signed with the request. |
| `Cookie`                 | Yes                 | Authorization= from POST /user/register; identifies the current user.  |

**Request Body:**

| Parameter    | Type   | Required | Default | Description                                                                              |
| ------------ | ------ | -------- | ------- | ---------------------------------------------------------------------------------------- |
| `marketId`   | string | Yes      | —       | Positive series ID; "-1" is not accepted.                                                |
| `positionId` | string | Yes      | —       | Positive position ID, or "-1" for all claimable positions across windows in that series. |

Only the current user's SETTLED records are eligible. positionId="-1" selects across windows of the supplied series; marketId="-1" does not allow cross-series claims. A five-minute duplicate-claim protection is documented by the upstream development reference, not a payout SLA. fgRequestId acknowledges processing, not payment. Query positions by ID without a SETTLED-only filter to see CLAIMING/CLAIMED, and confirm activity plus wallet credit. No public final-status lookup by fgRequestId is documented. On uncertain outcomes, reconcile instead of blindly submitting another claim.

**Request Example:**

```json
{
  "marketId": "10001",
  "positionId": "40001"
}
```

The cURL block uses signing placeholders. The client tabs require the [signing helper setup](https://docs.forepaas.org/advanced/code-examples.md); replace illustrative IDs before use.

{% tabs %}
{% tab title="cURL" %}

```bash
curl -X POST "https://openapi.foregate.com/cycle/claim" \
  -H "accept: application/json" \
  -H "date: <current UTC YYYY-MM-DD HH:mm:ss>" \
  -H "x-ca-key: <APP Key>" \
  -H "x-ca-signature: <base64 HMAC-SHA256>" \
  -H "x-ca-signature-headers: x-api-key" \
  -H "x-api-key: <X-API-KEY>" \
  -H "cookie: Authorization=<session-token>" \
  -H "content-type: application/json" \
  -H "content-md5: <base64 MD5 of exact body>" \
  --data-raw '{"marketId":"10001","positionId":"40001"}'
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const client = new ForeGateClient({
  appKey: process.env.FOREGATE_APP_KEY,
  appSecret: process.env.FOREGATE_APP_SECRET,
  apiKey: process.env.FOREGATE_API_KEY,
});
const cookie = process.env.FOREGATE_SESSION_COOKIE; // Authorization=<session-token>
if (!cookie) throw new Error("Set FOREGATE_SESSION_COOKIE before running this example");
client.setSessionCookie(cookie);
const res = await client.request('POST', '/cycle/claim', {
  cookieRequired: true,
  body: {"marketId": "10001", "positionId": "40001"},
});
```

{% endtab %}

{% tab title="Python" %}

```python
client = ForeGateClient(
    app_key=os.environ["FOREGATE_APP_KEY"],
    app_secret=os.environ["FOREGATE_APP_SECRET"],
    api_key=os.environ["FOREGATE_API_KEY"],
)
cookie = os.environ["FOREGATE_SESSION_COOKIE"]  # Authorization=<session-token>
client.set_session_cookie(cookie)
res = client.request("POST", "/cycle/claim", cookie_required=True, body={'marketId': '10001', 'positionId': '40001'})
```

{% endtab %}

{% tab title="Response" %}
**Response Sample:**

Illustrative populated response; IDs and values are not production fixtures.

```json
{
  "code": 0,
  "message": "ok",
  "data": {
    "fgRequestId": "REQ202611020002"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field              | Type   | Description                                                                         |
| ------------------ | ------ | ----------------------------------------------------------------------------------- |
| `data.fgRequestId` | string | Processing receipt/correlation ID; does not itself prove CLAIMED or credited funds. |

The generated OpenAPI panel contains the complete endpoint-specific response schema. Preserve a top-level `requestId` when the upstream returns one.

**Error Responses:**

Invalid marketId/positionId input returns HTTP 400/code `1001`. No claimable position can return HTTP 400/code `3008`; a missing market or mismatched cycle locator can return HTTP 404/code `3009`. Preserve the actual upstream status for ownership or series/position mismatches rather than assuming one validation code. Upstream `3037`, `4010`, or `4017` can signal retry-later, duplicate, or disallowed-state behavior; preserve the actual message and reconcile before another write. See [shared cycle errors](#shared-errors) for authentication and transport failures.

## Contract details awaiting confirmation

The development audit recorded two 1-USDT buy orders reducing available balance by 2.04 USDT while frozenAmount remained zero, followed by available-balance restoration on cancellation. This does not prove missing reservation or lost funds. The coverage of frozenAmount, the place to query cycle principal/fee reservations, and the meanings of availableAmount/currentAmount during these stages remain unconfirmed. Do not treat `currentAmount = availableAmount + frozenAmount + positionValue` as a complete funds ledger or derive an undocumented reservation amount.

Development activity samples showed a BUY expense reconciled using value plus fees, a SELL sample with value already net of fees, and a zero-fee CLAIM. For that SELL sample, `1.178303 + 0.024547 = 0.495 × 2.43`; deducting fees from its value again would charge twice. These observations do not establish a general formula. Formal price/value/fees definitions must be confirmed separately for BUY, SELL, and each claim event, along with Amount/AmountAsc expressions, mixed-event comparison, and ordering stability for equal amounts.

A development record showed PAYOUT\_PROCESSING, null completedTime, READY and zero pending counters despite a historical position already claimed and credited. That is an unresolved settlement-card observation, not proof that such a card is correct or complete. Transition conditions, readiness/counter sufficiency, timestamp filling, permitted asynchronous differences, and any formal processing/query rules still need confirmation. No seconds/minutes SLA is asserted. The price-1 rejection and order-restriction limitations are recorded at [Create a cycle order](#create-a-cycle-order).

## Shared errors

Check both HTTP status and business `code`; preserve the actual upstream message. Empty pages, empty curves, and settlement available=false are normal business results. They do not imply zero prices, permission to trade, or permission to claim.

| HTTP / code                    | Meaning                                                                                                                               |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `400 / 1001`                   | Invalid fields, JSON shape, IDs, option, decimal, tick, range, or unsupported order/cancellation feature; rejected before forwarding. |
| `401 / 1401`                   | Missing key, timestamp, required cookie, or invalid gateway authentication.                                                           |
| `415 / 1415`                   | An explicitly supplied POST Content-Type is not JSON.                                                                                 |
| `404 / 182001, 182002, 182003` | Missing series, window, or settlement resource; preserve the returned code.                                                           |
| `401 / 401`                    | Upstream session invalid.                                                                                                             |
| `400 / 182013, 182014`         | Upstream time or numeric parameter error.                                                                                             |
| `400 / 3008`                   | No claimable position.                                                                                                                |
| `404 / 3009`                   | Market missing or cycle locator mismatch.                                                                                             |
| `400 / 3037, 4010, 4017`       | Upstream retry-later, duplicate-request, or disallowed-state behavior; inspect the actual message.                                    |
| `400 / 5003`                   | Development price/amount rejection observed at price 1; exact triggering constraints remain unconfirmed.                              |
| `504 / 2001`                   | Upstream timeout. Writes are not automatically retried; reconcile the outcome.                                                        |
| `502 / 2002, 2003`             | Connection failure, invalid upstream JSON, or invalid response structure.                                                             |

Existing upstream HTTP errors take precedence when supplied. An illustrative validation response is:

```json
{
  "code": 1001,
  "message": "bad request: limitPrice must be a multiple of tick size 0.001",
  "data": null
}
```

For any accepted or uncertain write, retain its correlation/order IDs and reconcile open orders, positions, activity, and wallet balances. Neither a missing query row nor an acknowledgement establishes a final result. No public final-status endpoint keyed by fgRequestId is documented, and blind retries can duplicate an order or claim.
