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

# Balance

> Account reconciliation is critical for maintaining financial accuracy and trust. This guide covers balance queries, fee verification, and funds ledger tracking for end-of-day and periodic reconciliation.

## Overview

GatePay provides multiple reconciliation tools to ensure account accuracy:

* **Balance Query**: Real-time available balance by currency
* **Order Fee Query**: Verify fees and settlement amounts at the order level
* **Funds Ledger Query**: Track all fund movements by transaction

For request headers, signature rules, and callback verification, refer to [Authentication & Security](/essentials/version/100/en/common/authentication).

***

## Balance Query

The balance query API retrieves the available balance of a merchant payment account by currency. For settlement, payout, and risk decisions, real-time query results must be used.

### Common Use Cases

* **Pre-settlement validation**: Confirm available balance before initiating settlement
* **Period-end snapshots**: Capture balance at close of business for accounting
* **Operational monitoring**: Real-time balance alerts and thresholds
* **Multi-currency management**: Track balances across different currencies

### API Reference

**Endpoint:** `GET /v1/pay/balance/query`

**Institutional Endpoint:** `POST /payment/open/institution/v1/balance`

#### Request Parameters

| Parameter    | Type  | Required | Description                                                     |
| ------------ | ----- | -------- | --------------------------------------------------------------- |
| `currencies` | array | No       | List of currency codes to query (e.g., \["USDT", "BTC", "USD"]) |

If no currencies are specified, the API returns balances for all currencies in the account.

#### Response Fields

| Field          | Type      | Description                              |
| -------------- | --------- | ---------------------------------------- |
| `currency`     | string    | Currency code                            |
| `available`    | string    | Balance available for immediate use      |
| `hold`         | string    | Amount held by pending orders or payouts |
| `total`        | string    | Total balance (available + hold)         |
| `last_updated` | timestamp | Timestamp of last balance update         |

#### Example Request

```bash theme={null}
curl -X GET "https://api.gatepay.io/v1/pay/balance/query?currencies=USDT,BTC,USD" \
  -H "X-GatePay-Certificate-ClientId: your_client_id" \
  -H "X-GatePay-Timestamp: 1704067200000" \
  -H "X-GatePay-Nonce: abc123def456" \
  -H "X-GatePay-Signature: your_signature" \
```

#### Example Response

```json theme={null}
{
  "data": [
    {
      "currency": "USDT",
      "available": "10500.50",
      "hold": "499.50",
      "total": "11000.00",
      "last_updated": 1704067205000
    },
    {
      "currency": "BTC",
      "available": "0.25",
      "hold": "0.05",
      "total": "0.30",
      "last_updated": 1704067205000
    },
    {
      "currency": "USD",
      "available": "25000.00",
      "hold": "0.00",
      "total": "25000.00",
      "last_updated": 1704067205000
    }
  ]
}
```

### Integration Steps

1. **Call the balance query API** using `GET /v1/pay/balance/query` with desired currencies
2. **Store balances** by currency in your merchant's local accounting system
3. **Compare with local records** to identify discrepancies
4. **Alert on thresholds** if balance falls below operational minimums

***

## Order Fee Query

The order fee query API provides detailed fee breakdown and settlement amounts at the individual order level. Use this for financial reconciliation and exception investigation.

### Common Use Cases

* **Financial reconciliation**: Verify fees match merchant expectations
* **Multiple or partial payments**: Reconcile complex order scenarios
* **Exception investigation**: Identify fee anomalies or discrepancies
* **Settlement confirmation**: Confirm amounts before initiating payout

### API Reference

**Endpoint:** `GET /api/open/v1/pay/order/fee/query`

#### Request Parameters

| Parameter           | Type   | Required    | Description                     |
| ------------------- | ------ | ----------- | ------------------------------- |
| `orderId`           | string | Conditional | GatePay order ID                |
| `merchant_order_no` | string | Conditional | Merchant-generated order number |

Provide either `orderId` or `merchant_order_no` (at least one required).

#### Response Fields

| Field               | Type      | Description                            |
| ------------------- | --------- | -------------------------------------- |
| `orderId`           | string    | GatePay order ID                       |
| `merchant_order_no` | string    | Merchant order number                  |
| `orderAmount`       | string    | Original order amount                  |
| `payAmount`         | string    | Amount customer paid                   |
| `settlementAmount`  | string    | Amount credited to merchant account    |
| `gatewayFee`        | string    | GatePay processing fee                 |
| `networkFee`        | string    | Blockchain network fee (if applicable) |
| `discountAmount`    | string    | Discounts or rebates applied           |
| `currency`          | string    | Settlement currency                    |
| `status`            | string    | Order status                           |
| `created_at`        | timestamp | Order creation time                    |
| `settled_at`        | timestamp | Settlement completion time             |

#### Example Request

```bash theme={null}
curl -X GET "https://api.gatepay.io/api/open/v1/pay/order/fee/query?merchant_order_no=ORDER_12345" \
  -H "X-GatePay-Certificate-ClientId: your_client_id" \
  -H "X-GatePay-Timestamp: 1704067200000" \
  -H "X-GatePay-Nonce: abc123def456" \
  -H "X-GatePay-Signature: your_signature" \
```

#### Example Response

```json theme={null}
{
  "data": {
    "orderId": "ORD_abc123",
    "merchant_order_no": "ORDER_12345",
    "orderAmount": "1000.00",
    "payAmount": "1000.00",
    "settlementAmount": "980.00",
    "gatewayFee": "20.00",
    "networkFee": "0.00",
    "discountAmount": "0.00",
    "currency": "USDT",
    "status": "SETTLED",
    "created_at": 1704067200000,
    "settled_at": 1704067800000
  }
}
```

### Integration Steps

1. **Call the order fee query API** using `GET /api/open/v1/pay/order/fee/query` with order identifier
2. **Store the query result** alongside your local order master data
3. **Compare settlement amounts** with expected values
4. **Flag discrepancies** for manual review if fee structure differs

***

## Funds Ledger Query

The funds ledger query provides a complete transaction history of all fund movements in and out of the merchant account. This is essential for audit trails and comprehensive reconciliation.

### Common Use Cases

* **End-of-day reconciliation**: Aggregate all fund movements for the day
* **Audit tracing**: Track fund origins and destinations for compliance
* **Exception investigation**: Identify timing issues or missing transactions
* **Financial reporting**: Generate detailed movement reports by type and currency

### API Reference

**Endpoint:** `GET /v1/pay/bill/orderlist`

**Institutional Endpoint:** `GET /payment/open/institution/v1/pay/bill/orderlist`

#### Request Parameters

| Parameter    | Type      | Required | Description                                        |
| ------------ | --------- | -------- | -------------------------------------------------- |
| `start_time` | timestamp | No       | Start of time range (UTC milliseconds)             |
| `end_time`   | timestamp | No       | End of time range (UTC milliseconds)               |
| `page`       | integer   | No       | Page number for pagination (1-indexed, default 1)  |
| `limit`      | integer   | No       | Records per page (default 20, max 100)             |
| `currency`   | string    | No       | Filter by currency code                            |
| `type`       | string    | No       | Filter by transaction type (see enumeration below) |
| `order_id`   | string    | No       | Filter by related order ID                         |

#### Response Fields

| Field            | Type      | Description                                               |
| ---------------- | --------- | --------------------------------------------------------- |
| `ledger_id`      | string    | Unique ledger entry identifier (use as deduplication key) |
| `type`           | string    | Transaction type (see enumeration below)                  |
| `currency`       | string    | Currency of transaction                                   |
| `amount`         | string    | Transaction amount (positive or negative)                 |
| `balance_before` | string    | Balance before transaction                                |
| `balance_after`  | string    | Balance after transaction                                 |
| `business_id`    | string    | Related order, refund, transfer, or payout ID             |
| `description`    | string    | Human-readable description                                |
| `created_at`     | timestamp | Transaction timestamp (UTC milliseconds)                  |
| `metadata`       | object    | Additional context (e.g., fee breakdown)                  |

#### Transaction Type Enumeration

| Type           | Direction | Description                                       |
| -------------- | --------- | ------------------------------------------------- |
| `PAYMENT`      | Inbound   | Customer payment received                         |
| `PAYOUT`       | Outbound  | Settlement to merchant's bank account             |
| `REFUND`       | Outbound  | Refund issued to customer                         |
| `TRANSFER_IN`  | Inbound   | Funds transferred from institution master account |
| `TRANSFER_OUT` | Outbound  | Funds transferred to sub-account or peer account  |
| `CHARGE`       | Outbound  | Platform commission or fee deduction              |
| `SWAP`         | Neutral   | Currency conversion (may show as two entries)     |
| `ADJUSTMENT`   | Variable  | Manual adjustment (credit or debit)               |
| `DEPOSIT`      | Inbound   | Direct deposit by merchant                        |

#### Example Request

```bash theme={null}
curl -X GET "https://api.gatepay.io/v1/pay/bill/orderlist?start_time=1704067200000&end_time=1704153600000&limit=50" \
  -H "X-GatePay-Certificate-ClientId: your_client_id" \
  -H "X-GatePay-Timestamp: 1704067200000" \
  -H "X-GatePay-Nonce: abc123def456" \
  -H "X-GatePay-Signature: your_signature" \
```

#### Example Response

```json theme={null}
{
  "data": [
    {
      "ledger_id": "LED_20240101_001",
      "type": "PAYMENT",
      "currency": "USDT",
      "amount": "500.00",
      "balance_before": "10000.00",
      "balance_after": "10500.00",
      "business_id": "ORD_abc123",
      "description": "Payment from order ORDER_12345",
      "created_at": 1704067200000,
      "metadata": {
        "order_no": "ORDER_12345",
        "payer": "customer@example.com"
      }
    },
    {
      "ledger_id": "LED_20240101_002",
      "type": "REFUND",
      "currency": "USDT",
      "amount": "-100.00",
      "balance_before": "10500.00",
      "balance_after": "10400.00",
      "business_id": "REF_xyz789",
      "description": "Refund for order ORDER_12346",
      "created_at": 1704067800000,
      "metadata": {
        "order_no": "ORDER_12346",
        "reason": "Customer requested"
      }
    },
    {
      "ledger_id": "LED_20240101_003",
      "type": "TRANSFER_OUT",
      "currency": "USDT",
      "amount": "-1000.00",
      "balance_before": "10400.00",
      "balance_after": "9400.00",
      "business_id": "TRN_20240101",
      "description": "Transfer to sub-account",
      "created_at": 1704068400000,
      "metadata": {
        "account_id": "SUB_12345",
        "batch_no": "TRN_20240101"
      }
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 3,
    "has_next": false
  }
}
```

### Integration Steps

1. **Pull funds ledger records** by time range with pagination using `GET /v1/pay/bill/orderlist`
2. **Persist ledger records** in your database using `ledger_id` as the primary deduplication key
3. **Associate ledger records** with business orders using `business_id` and metadata
4. **Generate reconciliation summaries** aggregated by:
   * Currency
   * Transaction type
   * Date or time bucket
   * Related business entity (order, refund, transfer, etc.)
5. **Compare with local records** to identify discrepancies
6. **Flag unmatched records** for investigation

***

## Recommended End-of-Day Reconciliation Flow

Follow this step-by-step process for comprehensive daily reconciliation:

### Step 1: Capture Account Balance Snapshot

```bash theme={null}
GET /v1/pay/balance/query
```

Store the balance snapshot for each currency at end of business day (e.g., 11:59 PM UTC). Record:

* Available balance
* Hold amount
* Total balance
* Snapshot timestamp

### Step 2: Pull Funds Ledger Records

```bash theme={null}
GET /v1/pay/bill/orderlist?start_time={start_of_day}&end_time={end_of_day}&limit=100
```

Retrieve all transactions for the reconciliation period with pagination. Store in local database keyed by `ledger_id`.

### Step 3: Pull Order Fees and Settlement Amounts

For each order settled during the day:

```bash theme={null}
GET /api/open/v1/pay/order/fee/query?merchant_order_no={order_id}
```

Store fee breakdown and settlement details.

### Step 4: Match and Reconcile Records

Create a reconciliation table with the following structure:

| Ledger ID | Type          | Currency | Amount | Business ID | Matched | Notes                |
| --------- | ------------- | -------- | ------ | ----------- | ------- | -------------------- |
| LED\_001  | PAYMENT       | USDT     | +500   | ORD\_123    | ✓       | Matched with order   |
| LED\_002  | REFUND        | USDT     | -100   | REF\_456    | ✓       | Matched with refund  |
| LED\_003  | TRANSFER\_OUT | USDT     | -1000  | TRN\_789    | ✓       | Institution transfer |

**Matching logic:**

* Match PAYMENT ledger entries to your order system using `business_id`
* Match REFUND entries to your refund system
* Match TRANSFER\_OUT/IN entries to your transfer records
* Match PAYOUT entries to your settlement records

### Step 5: Generate Discrepancy Report

Identify records that do not match:

| Category               | Count | Details                                    |
| ---------------------- | ----- | ------------------------------------------ |
| Missing ledger entries | 0     | Orders with no corresponding ledger entry  |
| Extra ledger entries   | 1     | Ledger entries with no corresponding order |
| Amount mismatches      | 0     | Matched records with different amounts     |
| Timing discrepancies   | 2     | Entries recorded on different dates        |

### Step 6: Perform Manual Review

For each discrepancy:

1. **Review the ledger entry** description and metadata
2. **Correlate with business records** (orders, refunds, transfers)
3. **Investigate timing** (same-day vs. next-day settlement)
4. **Document resolution** (matched, explained, or escalated)

### Step 7: Output Reconciliation Result

Generate a formal reconciliation statement:

```
End-of-Day Reconciliation Report
Date: 2024-01-01
Start Balance (USDT): 10,000.00
Ending Balance (USDT): 9,900.00

Transactions:
- Payments In: +5,000.00
- Refunds Out: -2,500.00
- Transfers Out: -1,000.00
- Fees Out: -500.00
- Adjustments: -100.00

Calculated Ending Balance: 9,900.00
Actual Ending Balance: 9,900.00
Status: BALANCED ✓

Discrepancies: 0
Unmatched Records: 0
```

***

## Error Handling and Troubleshooting

### Common Issues

| Issue                              | Cause                                            | Resolution                                                     |
| ---------------------------------- | ------------------------------------------------ | -------------------------------------------------------------- |
| Balance differs from local records | Timing of settlement or fee posting              | Query again after 5-10 minutes; check for pending transactions |
| Missing ledger entries             | Delayed posting or query time range misalignment | Expand time range by 1-2 hours; retry query                    |
| Duplicate ledger entries           | Database deduplication failure                   | Use `ledger_id` as primary key to prevent duplicates           |
| Fee discrepancies                  | Promotion, rebate, or rate change                | Compare with current rate table; check for adjustments         |

For comprehensive error codes, see [Error Codes & Best Practices](/essentials/version/100/en/common/error).

***

## Best Practices

### Data Persistence

* **Primary Key**: Use `ledger_id` for ledger entries to ensure idempotency
* **Unique Constraints**: Enforce unique constraints on (ledger\_id) to prevent duplicates
* **Indexing**: Index by (`created_at`, `currency`, `type`) for fast reconciliation queries

### Query Optimization

* **Time ranges**: Query in 24-hour buckets for faster response times
* **Pagination**: Use `limit=100` and iterate through pages to avoid timeout
* **Filters**: Use `currency` and `type` filters to reduce result sets

### Alerting and Monitoring

* **Threshold alerts**: Alert when available balance falls below operational minimum
* **Discrepancy alerts**: Alert immediately when reconciliation identifies unmatched records
* **Timing alerts**: Alert if ledger entries are delayed by more than 2 hours
* **Callback failure alerts**: Alert if expected callbacks are not received within SLA

### Documentation and Audit

* **Reconciliation logs**: Store reconciliation results with timestamp and user ID
* **Discrepancy tracking**: Maintain audit trail of identified and resolved discrepancies
* **Rate cards**: Document fee structure and any promotional adjustments
* **Settlement terms**: Document when and how funds are settled to merchant accounts

***

## Related Documentation

* [Authentication & Security](/essentials/version/100/en/common/authentication)
* [Institution API](/essentials/version/100/en/internalflow/institution)
* [Notification & Callbacks](/essentials/version/100/en/common/notification)
* [Error Codes & Best Practices](/essentials/version/100/en/common/error)
* [Currency Conversion & Swap](/essentials/version/100/en/internalflow/swap)
* [General Overview](/essentials/version/100/en/common/overview)
