> For the complete documentation index, see [llms.txt](https://hertzflow.gitbook.io/hertzflow-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hertzflow.gitbook.io/hertzflow-docs/tech-docs/smart-contract/trade-integration.md).

# Trade Integration

A step-by-step guide to assembling trading and liquidity transactions against the HertzFlow contracts.

This page walks through the full path from a price quote to a signed transaction: reading the oracle price, converting it into contract-scale values, filling every field of `CreateOrderParams` or `CreateDepositParams`, and batching everything into one `multicall`.

### Prerequisites

* Approve the collateral token (USDT, or any token supported by the target market) to the `ExchangeRouter` — the address is listed under [Contract Addresses](/hertzflow-docs/tech-docs/smart-contract.md#contract-addresses). Approvals are consumed from the Router during order and deposit settlement.
* The wallet must hold BNB to pay the execution fee (`executionFee`), which is sent along with `createOrder` / `createDeposit` / `createWithdrawal` as `msg.value`.
* If the initial collateral token differs from the market's long or short token, provide a `swapPath` so the Router can route the amount.

## 1. Read the oracle price

The public Oracle Price API returns the latest price for every supported token as a human-readable decimal string:

```bash
curl "https://oracle-aggregator.hertzflow.xyz/api/v1/latestPrice?get_all=true"
```

```json
{
  "data": {
    "prices": [
      {
        "symbol": "BTC/USD",
        "bsc_token_addr": "0x2d8f28f05113c2dc0a17ebbba60d8f72318bdb1f",
        "price": "77625.4426774856522",
        "timestamp": 1787989326
      },
      {
        "symbol": "ETH/USD",
        "bsc_token_addr": "0x2c08e4b0442381bb2f6e70943c94f991345be236",
        "price": "2497.327261755814",
        "timestamp": 1787989326
      }
    ]
  }
}
```

Response truncated; the live response contains one entry per supported token. Full field reference: [Oracle Price API](/hertzflow-docs/tech-docs/api/api-reference.md).

**Unit conversion**

| Target                                                                                     | Rule                                                                                               |
| ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
| Display to users                                                                           | Use the decimal string as-is. No scaling needed.                                                   |
| Contract USD values (`sizeDeltaUsd`, `triggerPrice`, `acceptablePrice`, `minOutputAmount`) | Multiply the decimal price/amount by `1e30` and floor to an integer.                               |
| Token amounts (`initialCollateralDeltaAmount`)                                             | Expressed in the token's native decimals (for example `1e18` for an 18-decimal token), not `1e30`. |

Example: `BTC/USD` price `77625.4426774856522` becomes `77625442677485652200000000000000000` when used as `acceptablePrice`. A `sizeDeltaUsd` of 1,000 USD becomes `1000 * 10^30`.

## 2. Assemble an order

`createOrder` takes a single `CreateOrderParams` struct. Every field is listed below.

**Addresses (`CreateOrderParamsAddresses`)**

| Field                    | Type        | Description                                                                                                                                                                  |
| ------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `receiver`               | `address`   | Address that receives the output (position collateral, swap proceeds, or withdrawal output).                                                                                 |
| `cancellationReceiver`   | `address`   | Address that receives a refund if the order is cancelled instead of executed.                                                                                                |
| `callbackContract`       | `address`   | Optional contract called back after execution; set to the zero address to skip.                                                                                              |
| `uiFeeReceiver`          | `address`   | Address that earns the UI fee share, typically the integrating frontend.                                                                                                     |
| `market`                 | `address`   | Market contract the order is placed against. Enumerate tradable markets via the Reader contract (see [Reader](/hertzflow-docs/tech-docs/smart-contract/reader-contract.md)). |
| `initialCollateralToken` | `address`   | Token supplied as the starting collateral for the order.                                                                                                                     |
| `swapPath`               | `address[]` | Ordered list of markets used to swap `initialCollateralToken` into the position's collateral token.                                                                          |

**Numbers (`CreateOrderParamsNumbers`)**

| Field                          | Type      | Description                                                                                                  |
| ------------------------------ | --------- | ------------------------------------------------------------------------------------------------------------ |
| `sizeDeltaUsd`                 | `uint256` | Position size change in USD, 1e30 fixed-point.                                                               |
| `initialCollateralDeltaAmount` | `uint256` | Collateral amount supplied with the order, in the token's native decimals.                                   |
| `triggerPrice`                 | `uint256` | Price at which a limit, stop, or take-profit order activates, 1e30 fixed-point. Zero for market orders.      |
| `acceptablePrice`              | `uint256` | Worst execution price the user accepts, 1e30 fixed-point; execution reverts if the filled price is worse.    |
| `executionFee`                 | `uint256` | Fee paid to the keeper that executes the order, in native token wei.                                         |
| `callbackGasLimit`             | `uint256` | Gas allotted to the `callbackContract` call after execution.                                                 |
| `minOutputAmount`              | `uint256` | Minimum output the user accepts, 1e30 fixed-point; the order reverts below this, giving slippage protection. |
| `validFromTime`                | `uint256` | Unix seconds after which the order becomes executable; zero means immediately.                               |

**Top-level scalars**

| Field                      | Type                             | Description                                                                                                                                                                                  |
| -------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `orderType`                | `Order.OrderType`                | Order kind — `MarketSwap`, `LimitSwap`, `MarketIncrease`, `LimitIncrease`, `MarketDecrease`, `LimitDecrease`, `StopLossDecrease`, `Liquidation`, `StopIncrease`, or `EarlyForceLiquidation`. |
| `decreasePositionSwapType` | `Order.DecreasePositionSwapType` | How collateral is swapped back when closing a position whose collateral token differs from the output token — `NoSwap`, `SwapPnlTokenToCollateralToken`, or `SwapCollateralTokenToPnlToken`. |
| `orderPositionType`        | `Order.OrderPositionType`        | Position type — `Normal` or `ZFP`.                                                                                                                                                           |
| `isLong`                   | `bool`                           | Direction: `true` for long, `false` for short.                                                                                                                                               |
| `shouldUnwrapNativeToken`  | `bool`                           | Whether the wrapped native token is unwrapped before funds are sent to the `receiver`.                                                                                                       |
| `autoCancel`               | `bool`                           | Whether a triggered-but-unfilled limit order is re-queued for another attempt instead of being cancelled.                                                                                    |
| `referralCode`             | `bytes32`                        | Referral code credited for the trade; zero bytes if none.                                                                                                                                    |
| `dataList`                 | `bytes32[]`                      | Free-form extension slots reserved for additional data; empty for standard orders.                                                                                                           |

## 3. Execution fee and callback

* `executionFee` is paid in BNB as `msg.value` on the `multicall` transaction; the keeper that submits the execution transaction claims it. Size it generously enough for a keeper to cover gas, otherwise the order stays unexecuted. The HertzFlow SDK exposes `sdk.utils.getExecutionFee(type, tokensData, nativePrice, params, gasLimits?, gasPrice?)` for computing the fee — see the [SDK gas helpers](/hertzflow-docs/tech-docs/hertzflow-sdk.md#gas-and-low-level-helpers).
* `callbackContract` plus `callbackGasLimit` are optional. When set, the contract receives a callback after the order is executed or cancelled, so integrators can react on-chain without polling events.

## 4. Multicall sketch

The Router executes a user action by batching token transfers and the action call in a single `multicall`. The sketch below uses the real `ExchangeRouter` signatures — `sendWnt` ([exchangerouter.md](/hertzflow-docs/tech-docs/smart-contract/exchangerouter.md#token-transfers)), `sendTokens`, `createOrder`, `multicall`:

```solidity
// Pseudocode: encode each call and pass the array to multicall.
// Actual ABI encoding is done with Solidity or ethers.js/viem in your integration.

router.multicall(
    bytes[](
        [
            // 1. Fund the execution fee with wrapped native token.
            abi.encodeCall(
                IExchangeRouter.sendWnt,
                (orderVault, executionFee)          // receiver, amount in wei
            ),
            // 2. Move collateral from the wallet into the order vault.
            abi.encodeCall(
                IExchangeRouter.sendTokens,
                (collateralToken, orderVault, initialCollateralDeltaAmount)
            ),
            // 3. Place the order itself.
            abi.encodeCall(
                IExchangeRouter.createOrder,
                (CreateOrderParams({
                    addresses: CreateOrderParamsAddresses({
                        receiver: user,
                        cancellationReceiver: user,
                        callbackContract: address(0),
                        uiFeeReceiver: uiFeeReceiver,
                        market: market,
                        initialCollateralToken: collateralToken,
                        swapPath: new address[](0)
                    }),
                    numbers: CreateOrderParamsNumbers({
                        sizeDeltaUsd: 1000e30,                 // 1,000 USD notional
                        initialCollateralDeltaAmount: 100e18,  // 100 collateral tokens
                        triggerPrice: 0,                       // market order
                        acceptablePrice: acceptablePrice,      // oracle price x 1e30
                        executionFee: executionFee,
                        callbackGasLimit: 0,
                        minOutputAmount: minOutputAmount,      // slippage guard
                        validFromTime: 0
                    }),
                    orderType: Order.OrderType.MarketIncrease,
                    decreasePositionSwapType: Order.DecreasePositionSwapType.SwapPnlTokenToCollateralToken,
                    orderPositionType: Order.OrderPositionType.Normal,
                    isLong: true,
                    shouldUnwrapNativeToken: false,
                    autoCancel: false,
                    referralCode: bytes32(0),
                    dataList: new bytes32[](0)
                }))
            )
        ]
    )
);
```

`orderVault` above is the vault address the Router forwards transfers to; it is listed under [Contract Addresses](/hertzflow-docs/tech-docs/smart-contract.md#contract-addresses).

## 5. Deposit and withdrawal

`createDeposit` takes a single `CreateDepositParams` struct.

**Addresses (`CreateDepositParamsAddresses`)**

| Field                | Type        | Description                                                            |
| -------------------- | ----------- | ---------------------------------------------------------------------- |
| `receiver`           | `address`   | Address that receives the minted market (liquidity) tokens.            |
| `callbackContract`   | `address`   | Optional contract called back after the deposit executes.              |
| `uiFeeReceiver`      | `address`   | Address that earns the UI fee share.                                   |
| `market`             | `address`   | Market the liquidity is deposited into.                                |
| `initialLongToken`   | `address`   | First token of the market's long/short pair supplied by the depositor. |
| `initialShortToken`  | `address`   | Second token of the pair supplied by the depositor.                    |
| `longTokenSwapPath`  | `address[]` | Markets used to swap part of the input into the long token.            |
| `shortTokenSwapPath` | `address[]` | Markets used to swap part of the input into the short token.           |

**Top-level scalars**

| Field                     | Type        | Description                                                                                             |
| ------------------------- | ----------- | ------------------------------------------------------------------------------------------------------- |
| `minMarketTokens`         | `uint256`   | Minimum acceptable market tokens minted; the deposit reverts below this, giving LP slippage protection. |
| `shouldUnwrapNativeToken` | `bool`      | Whether the native token is unwrapped when refunded on cancellation.                                    |
| `executionFee`            | `uint256`   | Fee paid to the keeper that executes the deposit.                                                       |
| `callbackGasLimit`        | `uint256`   | Gas allotted to the `callbackContract` call.                                                            |
| `dataList`                | `bytes32[]` | Free-form extension slots for additional data.                                                          |

For withdrawals, estimate the payout first with `getWithdrawalAmountOut` on the Reader contract ([reader-contract.md](/hertzflow-docs/tech-docs/smart-contract/reader-contract.md)), then submit `createWithdrawal` with a `CreateWithdrawalParams` struct holding `minOutputAmount` per output token as the LP slippage guard.

***

Contract addresses: [Contract Addresses](/hertzflow-docs/tech-docs/smart-contract.md#contract-addresses). Pre-trade price lookup: [Oracle Price API](/hertzflow-docs/tech-docs/api/api-reference.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://hertzflow.gitbook.io/hertzflow-docs/tech-docs/smart-contract/trade-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
