# Order

### Submit Order

{% openapi src="/files/5MOm3p5RkCwChISqy4Ij" path="/api/order/openapi/order/submit" method="post" %}
[openapi.yaml](https://3978567741-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlpNKReYzAUPT4VYMRTyV%2Fuploads%2Fgit-blob-69cf0ae81af4e580d980aec75811124b0ee0575e%2Fopenapi.yaml?alt=media)
{% endopenapi %}

This endpoint allows a user to submit a buy or sell order for a specific market outcome.

**Use Case:** This is the core trading endpoint. Use it to allow users to buy and sell shares in a market.

{% hint style="warning" %}
**Asynchronous Processing:** This endpoint returns a `fgRequestId` for tracking. The order is processed asynchronously. Use the [Query Transaction Result](#query-transaction-result) endpoint to check the final status. **Do not retry** order submissions blindly - always check the transaction result first to avoid duplicate orders.
{% endhint %}

> **Performance Tip:** Always fetch the latest market details before submitting an order to ensure you have current prices and avoid order rejections.

| Property           | Value                             |
| ------------------ | --------------------------------- |
| **Method**         | `POST`                            |
| **Path**           | `/api/order/openapi/order/submit` |
| **Authentication** | Required (JWT)                    |

**Request Body:**

| Field       | Type   | Required   | Description                                                                                                          |
| ----------- | ------ | ---------- | -------------------------------------------------------------------------------------------------------------------- |
| `marketId`  | number | Yes        | The unique ID of the market.                                                                                         |
| `outcomeId` | number | Yes        | The unique ID of the outcome.                                                                                        |
| `optionId`  | number | Yes        | The unique ID of the option.                                                                                         |
| `direction` | string | Yes        | The order direction: `BUY` (purchase shares) or `SELL` (sell shares).                                                |
| `orderType` | string | Yes        | The order type. For PARIMUTUEL markets, use `PARIMUTUEL`.                                                            |
| `amount`    | number | Yes (BUY)  | **For BUY orders:** The amount to spend (in the market's currency). **For SELL orders:** Use `shares` field instead. |
| `shares`    | number | Yes (SELL) | **For SELL orders:** The number of shares to sell. Not used for BUY orders.                                          |

**Order Type Clarification:**

* **BUY orders:** Specify `amount` (how much currency to spend). The system calculates shares based on current price.
* **SELL orders:** Specify `shares` (how many shares to sell). The system calculates proceeds based on current price.
* **Currency:** Determined by the market's `coinId` and your authorization settings.

**Precision & Validation Rules:**

| Field    | Max Decimal Places | Min Value  | Max Value | Rounding   |
| -------- | ------------------ | ---------- | --------- | ---------- |
| `amount` | 8                  | 0.01       | 1,000,000 | Round down |
| `shares` | 8                  | 0.00000001 | No limit  | Round down |
| `price`  | 8                  | 0.00000001 | 1.0       | Round down |

{% hint style="warning" %}
**Precision Errors:** Submitting values with more than 8 decimal places may result in error code `5005` (amount precision error) or `5006` (share precision error). Always round to 8 decimals before submission.
{% endhint %}

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

```bash
curl -X POST "https://apidev.forepass.org/api/order/openapi/order/submit" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-jwt-token" \
  -d '{
    "marketId": 1841,
    "outcomeId": 1986,
    "optionId": 5213,
    "direction": "BUY",
    "orderType": "PARIMUTUEL",
    "amount": 101
  }'
```

{% endtab %}

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

```javascript
// First get market details to find IDs
const details = await client.getMarketDetails(1841);
const option = details.data.outcomes[0].options[0];

// Submit order
const order = await client.submitOrder({
  marketId: 1841,
  outcomeId: details.data.outcomes[0].outcomeId,
  optionId: option.optionId,
  direction: 'BUY',
  orderType: 'PARIMUTUEL',
  amount: 101
});

console.log(`Order request ID: ${order.data.fgRequestId}`);
```

{% endtab %}

{% tab title="Python" %}

```python
# First get market details to find IDs
details = client.get_market_details(1841)
option = details['data']['outcomes'][0]['options'][0]

# Submit order
order = client.submit_order({
    'marketId': 1841,
    'outcomeId': details['data']['outcomes'][0]['outcomeId'],
    'optionId': option['optionId'],
    'direction': 'BUY',
    'orderType': 'PARIMUTUEL',
    'amount': 101
})

print(f"Order request ID: {order['data']['fgRequestId']}")
```

{% endtab %}

{% tab title="Response" %}

```json
{
  "code": 200,
  "msg": "success",
  "data": {
    "fgRequestId": "d7c19300-e90d-4fc0-acbc-5b070c77677b"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field         | Type   | Description                                                                                                               |
| ------------- | ------ | ------------------------------------------------------------------------------------------------------------------------- |
| `fgRequestId` | string | Unique request identifier. Use this to query the transaction result via `/api/user/openapi/request/result/{fgRequestId}`. |

{% hint style="info" %}
**Async Pattern:** This endpoint uses asynchronous processing. The response does not indicate whether the order succeeded or failed - you must poll the transaction result endpoint using the `fgRequestId` to get the final status (`SUCCESS`, `FAILED`, or `PENDING`).
{% endhint %}

**HTTP Status Codes:**

| Code  | Description                                                       |
| ----- | ----------------------------------------------------------------- |
| `200` | Order submitted successfully.                                     |
| `401` | Invalid or expired JWT token.                                     |
| `404` | Market, outcome, or option not found.                             |
| `422` | Business logic error (e.g., insufficient balance, market closed). |
| `500` | Internal server error.                                            |

**Possible Errors:**

| Error Message          | Cause                                     | Solution                                  |
| ---------------------- | ----------------------------------------- | ----------------------------------------- |
| `Invalid token`        | JWT token is invalid or expired.          | Re-authenticate the user.                 |
| `Insufficient balance` | User doesn't have enough funds.           | Check user balance before placing orders. |
| `Market closed`        | The market is no longer accepting trades. | Verify market status is `ACTIVE`.         |
| `Invalid price`        | Price is outside acceptable range.        | Check current market prices and adjust.   |
| `Market not found`     | The specified market ID doesn't exist.    | Verify all IDs are correct.               |

***

### Claim Reward

This endpoint allows a user to claim their rewards from a settled market.

**Use Case:** After a market has been settled, users who held winning shares can use this endpoint to claim their winnings.

| Property           | Value                            |
| ------------------ | -------------------------------- |
| **Method**         | `POST`                           |
| **Path**           | `/api/order/openapi/order/claim` |
| **Authentication** | Required (JWT)                   |

**Request Body:**

| Field      | Type   | Required | Description                   |
| ---------- | ------ | -------- | ----------------------------- |
| `marketId` | number | Yes      | The ID of the settled market. |

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

```bash
curl -X POST "https://apidev.forepass.org/api/order/openapi/order/claim" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-jwt-token" \
  -d '{"marketId": 1744}'
```

{% endtab %}

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

```javascript
const claim = await client.claimRewards(1744);

console.log(`Successfully claimed $${claim.data.claimedAmount}`);
console.log(`Transaction ID: ${claim.data.transactionId}`);
```

{% endtab %}

{% tab title="Python" %}

```python
claim = client.claim_rewards(1744)

print(f"Successfully claimed ${claim['data']['claimedAmount']}")
print(f"Transaction ID: {claim['data']['transactionId']}")
```

{% endtab %}

{% tab title="Response" %}

```json
{
  "code": 200,
  "msg": "success",
  "data": {
    "claimedAmount": 150.0,
    "transactionId": "txn_123456"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field           | Type   | Description                                   |
| --------------- | ------ | --------------------------------------------- |
| `claimedAmount` | number | The amount of rewards claimed in USD.         |
| `transactionId` | string | Unique transaction identifier for this claim. |

**HTTP Status Codes:**

| Code  | Description                                    |
| ----- | ---------------------------------------------- |
| `200` | Rewards claimed successfully.                  |
| `401` | Invalid or expired JWT token.                  |
| `404` | Market not found or no claimable rewards.      |
| `422` | Market not settled or rewards already claimed. |
| `500` | Internal server error.                         |

**Possible Errors:**

| Error Message          | Cause                                              | Solution                                    |
| ---------------------- | -------------------------------------------------- | ------------------------------------------- |
| `Invalid token`        | JWT token is invalid or expired.                   | Re-authenticate the user.                   |
| `Market not found`     | The specified market ID doesn't exist.             | Verify the market ID.                       |
| `Market not settled`   | The market hasn't been settled yet.                | Wait for market settlement before claiming. |
| `No claimable rewards` | User has no winning positions in this market.      | Check user positions before claiming.       |
| `Already claimed`      | Rewards have already been claimed for this market. | Each market can only be claimed once.       |

***

### Query Transaction Result

This endpoint allows you to query the result of an asynchronous transaction (market creation, order placement, etc.) using the `fgRequestId`.

| Property           | Value                                            |
| ------------------ | ------------------------------------------------ |
| **Method**         | `GET`                                            |
| **Path**           | `/api/user/openapi/request/result/{fgRequestId}` |
| **Authentication** | Required (JWT)                                   |

**Path Parameters:**

| Parameter     | Type   | Description                                                      |
| ------------- | ------ | ---------------------------------------------------------------- |
| `fgRequestId` | string | The request ID returned from submit order or market application. |

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

```bash
curl -X GET "https://apidev.forepass.org/api/user/openapi/request/result/7e6b0db7-f11b-4e31-bb40-cebaad52e382" \
  -H "Authorization: Bearer your-jwt-token"
```

{% endtab %}

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

```javascript
const response = await fetch(
  `${baseUrl}/api/user/openapi/request/result/7e6b0db7-f11b-4e31-bb40-cebaad52e382`,
  {
    headers: {
      'Authorization': `Bearer ${jwtToken}`
    }
  }
);

const result = await response.json();
console.log(`Transaction status: ${result.data.status}`);
if (result.data.status === 'SUCCESS') {
  console.log('Transaction completed successfully');
} else if (result.data.errorMsg) {
  console.error(`Error: ${result.data.errorMsg}`);
}
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.get(
    f'{base_url}/api/user/openapi/request/result/7e6b0db7-f11b-4e31-bb40-cebaad52e382',
    headers={'Authorization': f'Bearer {jwt_token}'}
)

result = response.json()
print(f"Transaction status: {result['data']['status']}")
if result['data']['status'] == 'SUCCESS':
    print('Transaction completed successfully')
elif result['data'].get('errorMsg'):
    print(f"Error: {result['data']['errorMsg']}")
```

{% endtab %}

{% tab title="Response" %}

```json
{
  "code": 200,
  "msg": "success",
  "data": {
    "id": "7e6b0db7-f11b-4e31-bb40-cebaad52e382",
    "merchantId": 102001001,
    "userId": 39689,
    "status": "SUCCESS",
    "errorMsg": null,
    "notifyContent": "{\"amount\":0.00,\"marketId\":10017,\"tranType\":\"MARKET_CREATION\",\"userId\":39689}",
    "notifyStatus": 0,
    "notifyRetryTimes": 0,
    "notifyUpdateTime": null,
    "createTime": "2026-01-21T10:54:46",
    "updateTime": "2026-01-21T10:56:00"
  }
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field           | Type           | Description                                          |
| --------------- | -------------- | ---------------------------------------------------- |
| `id`            | string         | The request ID.                                      |
| `merchantId`    | number         | Your merchant ID.                                    |
| `userId`        | number         | The user ID who initiated the request.               |
| `status`        | string         | Transaction status (`SUCCESS`, `FAILED`, `PENDING`). |
| `errorMsg`      | string \| null | Error message if the transaction failed.             |
| `notifyContent` | string         | JSON string containing transaction details.          |
| `createTime`    | string         | ISO 8601 timestamp of request creation.              |
| `updateTime`    | string         | ISO 8601 timestamp of last update.                   |

**HTTP Status Codes:**

| Code  | Description                                |
| ----- | ------------------------------------------ |
| `200` | Transaction result retrieved successfully. |
| `401` | Invalid or expired JWT token.              |
| `404` | Request ID not found.                      |
| `500` | Internal server error.                     |

**Possible Errors:**

| Error Message       | Cause                                   | Solution                             |
| ------------------- | --------------------------------------- | ------------------------------------ |
| `Invalid token`     | JWT token is invalid or expired.        | Re-authenticate the user.            |
| `Request not found` | The specified request ID doesn't exist. | Verify the `fgRequestId` is correct. |

> **Usage Note:** After submitting an order or market application, use this endpoint to poll for the transaction result. The `fgRequestId` is returned in the response of those endpoints.

***

### Query Merchant Monthly Bill

This endpoint retrieves the monthly commission bill for a merchant, showing all fees, commissions, and income for a specific billing period.

**Use Case:** Generate monthly financial reports for merchants showing trading fees, settlement fees, and commission income.

| Property           | Value                                                     |
| ------------------ | --------------------------------------------------------- |
| **Method**         | `POST`                                                    |
| **Path**           | `/api/order/openapi/merchant-commission-bill/query/month` |
| **Authentication** | Required (JWT)                                            |

**Request Body:**

| Field        | Type   | Required | Description                                                        |
| ------------ | ------ | -------- | ------------------------------------------------------------------ |
| `billPeriod` | number | Yes      | Billing period in format YYYYMM (e.g., `202601` for January 2026). |
| `merchantId` | number | Yes      | The merchant ID.                                                   |

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

```bash
curl -X POST "https://apidev.forepass.org/api/order/openapi/merchant-commission-bill/query/month" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-jwt-token" \
  -d '{
    "billPeriod": 202601,
    "merchantId": 102001001
  }'
```

{% endtab %}

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

```javascript
const response = await fetch(
  `${baseUrl}/api/order/openapi/merchant-commission-bill/query/month`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${jwtToken}`
    },
    body: JSON.stringify({
      billPeriod: 202601,
      merchantId: 102001001
    })
  }
);

const bill = await response.json();
bill.data.forEach(statement => {
  console.log(`Period: ${statement.periodMonth}`);
  console.log(`Total Income: $${statement.merchantTotalIncome}`);
  console.log(`Trade Fees: $${statement.tradeFeeTotal}`);
});
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.post(
    f'{base_url}/api/order/openapi/merchant-commission-bill/query/month',
    headers={'Authorization': f'Bearer {jwt_token}'},
    json={
        'billPeriod': 202601,
        'merchantId': 102001001
    }
)

bill = response.json()
for statement in bill['data']:
    print(f"Period: {statement['periodMonth']}")
    print(f"Total Income: ${statement['merchantTotalIncome']}")
    print(f"Trade Fees: ${statement['tradeFeeTotal']}")
```

{% endtab %}

{% tab title="Response" %}

```json
{
  "code": 200,
  "msg": "success",
  "current": 1,
  "size": 10,
  "total": 0,
  "pages": 0,
  "data": [
    {
      "statementId": "b35badc1-f6c3-11f0-be4a-00163e1e436a",
      "merchantId": "102",
      "periodMonth": "202601",
      "currency": "FMUSD",
      "selfCommissionFee": 1,
      "tradeFeeTotal": 2,
      "settlementFeeTotal": 3,
      "unclaimedPoolTotal": 4,
      "agentCommissionTotal": 1,
      "commissionRate": 1,
      "merchantTotalIncome": 0,
      "adjustmentAmount": 0,
      "createTime": "2026-01-21T12:21:23",
      "updateTime": "2026-01-21T12:21:23"
    }
  ],
  "totalRow": null,
  "empty": false
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field                  | Type   | Description                           |
| ---------------------- | ------ | ------------------------------------- |
| `statementId`          | string | Unique bill statement identifier.     |
| `merchantId`           | string | Merchant ID.                          |
| `periodMonth`          | string | Billing period (YYYYMM format).       |
| `currency`             | string | Currency code (e.g., `FMUSD`).        |
| `selfCommissionFee`    | number | Self-commission fee amount.           |
| `tradeFeeTotal`        | number | Total trading fees collected.         |
| `settlementFeeTotal`   | number | Total settlement fees collected.      |
| `unclaimedPoolTotal`   | number | Total unclaimed pool amount.          |
| `agentCommissionTotal` | number | Total agent commission.               |
| `commissionRate`       | number | Commission rate percentage.           |
| `merchantTotalIncome`  | number | Total merchant income for the period. |
| `adjustmentAmount`     | number | Any adjustment amount applied.        |
| `createTime`           | string | ISO 8601 timestamp of creation.       |
| `updateTime`           | string | ISO 8601 timestamp of last update.    |

**HTTP Status Codes:**

| Code  | Description                                       |
| ----- | ------------------------------------------------- |
| `200` | Bill retrieved successfully.                      |
| `401` | Invalid or expired JWT token.                     |
| `400` | Invalid parameters (billPeriod format incorrect). |
| `500` | Internal server error.                            |

**Possible Errors:**

| Error Message                | Cause                            | Solution                          |
| ---------------------------- | -------------------------------- | --------------------------------- |
| `Invalid token`              | JWT token is invalid or expired. | Re-authenticate the user.         |
| `Invalid request parameters` | billPeriod format is incorrect.  | Use YYYYMM format (e.g., 202601). |

***

### Query Merchant User Bill Details

This endpoint retrieves detailed billing information for a specific merchant user, showing all their trading transactions and associated fees.

**Use Case:** View granular transaction-level details for a specific user within your merchant account.

| Property           | Value                                  |
| ------------------ | -------------------------------------- |
| **Method**         | `GET`                                  |
| **Path**           | `/api/order/openapi/bill/query-detail` |
| **Authentication** | Required (JWT)                         |

**Query Parameters:**

| Parameter        | Type   | Required | Description           |
| ---------------- | ------ | -------- | --------------------- |
| `merchantId`     | number | Yes      | The merchant ID.      |
| `merchantUserId` | string | Yes      | The merchant user ID. |

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

```bash
curl -X GET "https://apidev.forepass.org/api/order/openapi/bill/query-detail?merchantId=102001001&merchantUserId=mer0018" \
  -H "Authorization: Bearer your-jwt-token"
```

{% endtab %}

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

```javascript
const response = await fetch(
  `${baseUrl}/api/order/openapi/bill/query-detail?merchantId=102001001&merchantUserId=mer0018`,
  {
    headers: {
      'Authorization': `Bearer ${jwtToken}`
    }
  }
);

const details = await response.json();
console.log(`Found ${details.total} transactions`);
details.data.forEach(tx => {
  console.log(`${tx.type} ${tx.optionTitle} @ Market ${tx.marketId}: ${tx.currency} ${tx.amount}`);
});
```

{% endtab %}

{% tab title="Python" %}

```python
response = requests.get(
    f'{base_url}/api/order/openapi/bill/query-detail',
    params={
        'merchantId': 102001001,
        'merchantUserId': 'mer0018'
    },
    headers={'Authorization': f'Bearer {jwt_token}'}
)

details = response.json()
print(f"Found {details['total']} transactions")
for tx in details['data']:
    print(f"{tx['type']} {tx['optionTitle']} @ Market {tx['marketId']}: {tx['currency']} {tx['amount']}")
```

{% endtab %}

{% tab title="Response" %}

```json
{
  "code": 200,
  "msg": "success",
  "current": 1,
  "size": 10,
  "total": 0,
  "pages": 0,
  "data": [
    {
      "userId": "39688",
      "merchantUserId": "mer0018",
      "merchantId": 102001001,
      "type": "BUY",
      "marketId": "10016",
      "outcomeId": "21",
      "optionId": "61",
      "optionTitle": "tiger",
      "optionIndex": 0,
      "shares": null,
      "tranDate": null,
      "currency": "USDT",
      "amount": "99.0000000000"
    }
  ],
  "totalRow": null,
  "empty": false
}
```

{% endtab %}
{% endtabs %}

**Response Fields:**

| Field            | Type           | Description                                |
| ---------------- | -------------- | ------------------------------------------ |
| `userId`         | string         | User ID in the system.                     |
| `merchantUserId` | string         | Merchant's user identifier.                |
| `merchantId`     | number         | Merchant ID.                               |
| `type`           | string         | Transaction type (`BUY`, `SELL`).          |
| `marketId`       | string         | Market where transaction occurred.         |
| `outcomeId`      | string         | Outcome ID.                                |
| `optionId`       | string         | Option ID.                                 |
| `optionTitle`    | string         | Option title (e.g., `tiger`, `YES`, `NO`). |
| `optionIndex`    | number         | Option index position.                     |
| `shares`         | number \| null | Number of shares (if applicable).          |
| `tranDate`       | string \| null | Transaction date.                          |
| `currency`       | string         | Currency code (e.g., `USDT`).              |
| `amount`         | string         | Transaction amount.                        |

**HTTP Status Codes:**

| Code  | Description                          |
| ----- | ------------------------------------ |
| `200` | Bill details retrieved successfully. |
| `401` | Invalid or expired JWT token.        |
| `400` | Invalid parameters.                  |
| `404` | Merchant or user not found.          |
| `500` | Internal server error.               |

**Possible Errors:**

| Error Message    | Cause                            | Solution                              |
| ---------------- | -------------------------------- | ------------------------------------- |
| `Invalid token`  | JWT token is invalid or expired. | Re-authenticate the user.             |
| `User not found` | Merchant user ID doesn't exist.  | Verify the merchantUserId is correct. |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forepaas.org/api-reference/api-reference/order.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
