Guide

OpenOcean Limit Order API Integration Documentation

For more information, you can explore the OpenOcean API Examples on GitHub.

Overview

OpenOcean Limit Order allows users to create and manage limit orders for token trading. Users can set specific prices and amounts for buying or selling tokens, with orders executed automatically when market conditions are met.

Features

  • Create limit orders with custom prices and amounts

  • Set expiration times from 10 minutes to 1 year

  • Cancel orders before execution

  • View order history and status

  • Support for multiple blockchain networks

Supported Chains

const limitOrderChains = ["bsc","eth","polygon","avax","fantom","arbitrum","optimism",
    "moonriver","harmony","heco","okex","xdai","cronos","zksync","linea","base",
    "sonic","bera","sei"
  ]

Dependencies

{
  "ethers": "^6.0.0",
  "axios": "^1.0.0",
  "@openocean.finance/limitorder-sdk": "^1.0.0"
}

API Endpoints

const baseUrl = 'https://open-api.openocean.finance'

1. Create Limit Order

Endpoint: POST /v1/{chainId}/limit-order

Request Body:

{
  "makerTokenAddress": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "makerTokenDecimals": 6,
  "takerTokenAddress": "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2", 
  "takerTokenDecimals": 6,
  "makerAmount": "10000",
  "takerAmount": "20000",
  "gasPrice": "20000000000",
  "expire": "1H",
  "signature": "0x...",
  "orderHash": "0x...",
  "data": "0x..."
}

Response:

{
  "success": true,
  "data": {
    "orderId": "12345",
    "status": "pending"
  }
}

2. Get User Orders

Endpoint: GET /v1/{chainId}/limit-order/address/{address}

Parameters:

  • page: Page number (default: 1)

  • limit: Items per page (default: 100)

  • statuses: Order status filter [1,2,5]

  • sortBy: Sort field (default: createDateTime)

  • exclude: Exclude flag (default: 0)

Response:

{
  "data": [
    {
      "id": "12345",
      "orderHash": "0x...",
      "makerAmount": "10000",
      "takerAmount": "20000",
      "statuses": 2,
      "createDateTime": "2024-01-01T00:00:00Z",
      "data": "0x..."
    }
  ]
}

3. Cancel Limit Order

Endpoint: POST /v1/{chainId}/limit-order/cancelLimitOrder

Request Body:

{
  "orderHash": "0x..."
}

Response:

{
  "success": true,
  "data": {
    "status": 4
  }
}

SDK Integration

1. Initialize SDK

import { openoceanLimitOrderSdk } from '@openocean.finance/limitorder-sdk';

const providerParams = {
  provider: provider,
  chainKey: 'base',
  account: walletAccount,
  chainId: 8453
};

2. Create Limit Order

const createLimitOrder = async () => {
  // Get gas price with 20% buffer
  const gasPrice = await getGasPrice();
  
  const params = {
    makerTokenAddress: inToken.address,
    makerTokenDecimals: inToken.decimals,
    takerTokenAddress: outToken.address,
    takerTokenDecimals: outToken.decimals,
    makerAmount: makerAmount * (10 ** inToken.decimals) + '',
    takerAmount: takerAmount * (10 ** outToken.decimals) + '',
    gasPrice: gasPrice,
    expire: expireTime,
  };

  // Create order using SDK
  const order = await openoceanLimitOrderSdk.createLimitOrder(
    providerParams,
    params
  );

  // Submit to API
  const result = await axios.post(
    `${baseUrl}/v1/${chainId}/limit-order`,
    order,
    {
      headers: { 'Content-Type': 'application/json' },
    }
  );
};

3. Cancel Order

const cancelOrder = async (order) => {
  const { orderHash } = order;

  // Get cancellation signature
  const signature = await openoceanLimitOrderSdk.cancelOrderSignature(
    providerParams,
    { orderHash }
  );

  // Cancel via API
  const { data } = await axios.post(
    `${baseUrl}/v1/${chainId}/limit-order/cancelLimitOrder`,
    { orderHash }
  );

  const { status } = (data && data.data) || {};

  // If order still active, cancel on blockchain
  if (status && !(status === 3 || status === 4)) {
    const gasPrice = await getGasPrice();
    await openoceanLimitOrderSdk.cancelLimitOrder(
      providerParams,
      {
        orderData: order.data,
        gasPrice,
      }
    );
  }
};

Order Status Codes

Status
Description
Color

1

Pending

Yellow (#ffc107)

2

Active

Green (#28a745)

3

Filled

Blue (#007bff)

4

Cancelled

Red (#dc3545)

5

Expired

Gray (#6c757d)

Expiration Time Options

const limitOrderExpireOptions = [
  { value: "10M", label: "10 Mins" },
  { value: "1H", label: "1 Hour" },
  { value: "1D", label: "1 Day" },
  { value: "3D", label: "3 Days" },
  { value: "7D", label: "7 Days" },
  { value: "30D", label: "1 Month" },
  { value: "3Month", label: "3 Month" },
  { value: "6Month", label: "6 Month" },
  { value: "1Y", label: "1 Year" }
];

Complete Implementation Example

1. Wallet Connection

const connectWallet = async () => {
  if (typeof window.ethereum === 'undefined') {
    throw new Error('Please install MetaMask!');
  }

  await window.ethereum.request({
    method: 'eth_requestAccounts'
  });

  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();
  const address = await signer.getAddress();

  setProvider(provider);
  setWalletAccount(address);
  setIsWalletConnected(true);
};

2. Get Gas Price

const getGasPrice = async () => {
  const feeData = await provider.getFeeData();
  const gasPrice = feeData.gasPrice?.toString();
  return parseInt(Number(gasPrice) * 1.2); // 20% buffer
};

3. Fetch Orders

const getLimitOrder = async (account) => {
  const url = `${baseUrl}/v1/${chainId}/limit-order/address/${walletAccount || account}?page=1&limit=100&statuses=[1,2,5]&sortBy=createDateTime&exclude=0`;
  const res = await axios.get(url);
  setOrders(res.data.data);
};

4. Order Management

// Create order
const createLimitOrder = async () => {
  if (!isWalletConnected) {
    throw new Error('Please connect your wallet first!');
  }

  if (!makerAmount || !takerAmount) {
    throw new Error('Please enter price and amount!');
  }

  const gasPrice = await getGasPrice();
  
  const params = {
    makerTokenAddress: inToken.address,
    makerTokenDecimals: inToken.decimals,
    takerTokenAddress: outToken.address,
    takerTokenDecimals: outToken.decimals,
    makerAmount: makerAmount * (10 ** inToken.decimals) + '',
    takerAmount: takerAmount * (10 ** outToken.decimals) + '',
    gasPrice: gasPrice,
    expire: expireTime,
  };

  const order = await openoceanLimitOrderSdk.createLimitOrder(
    providerParams,
    params
  );

  const result = await axios.post(
    `${baseUrl}/v1/${chainId}/limit-order`,
    order,
    {
      headers: { 'Content-Type': 'application/json' },
    }
  );

  return result.data;
};

// Cancel order
const cancelOrder = async (order) => {
  const { orderHash } = order;

  const { data } = await axios.post(
    `${baseUrl}/v1/${chainId}/limit-order/cancelLimitOrder`,
    { orderHash }
  );

  const { status } = (data && data.data) || {};

  if (status && !(status === 3 || status === 4)) {
    const gasPrice = await getGasPrice();
    await openoceanLimitOrderSdk.cancelLimitOrder(
      providerParams,
      {
        orderData: order.data,
        gasPrice,
      }
    );
  }
};

Error Handling

Common Errors

  1. Wallet Not Connected

    if (!isWalletConnected) {
      throw new Error('Please connect your wallet first!');
    }
  2. Invalid Amounts

    if (!makerAmount || !takerAmount) {
      throw new Error('Please enter price and amount!');
    }
  3. Provider Not Available

    if (!provider) {
      throw new Error('Please connect wallet first');
    }
  4. Order Cancellation Failed

    try {
      await cancelOrder(order);
    } catch (error) {
      console.error('Error canceling order:', error);
      throw new Error('Failed to cancel order: ' + error.message);
    }

Token Configuration

const inToken = {
  "address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "decimals": 6,
  "symbol": "USDC",
};

const outToken = {
  "address": "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2",
  "decimals": 6,
  "symbol": "USDT"
};

Important Notes

  1. Gas Price Buffer: Always add 20% buffer to gas price for reliable execution

  2. Order Expiration: Orders automatically expire based on selected time

  3. Status Monitoring: Regularly check order status for updates

  4. Cancellation: Only active orders can be cancelled

  5. Amount Precision: Use proper decimal places for token amounts

  6. Network Support: Ensure you're on a supported network

  7. Error Handling: Implement proper error handling for all operations

Best Practices

  1. User Experience

    • Provide clear feedback for all operations

    • Show loading states during transactions

    • Display order status with appropriate colors

    • Format amounts with proper decimal places

  2. Error Management

    • Handle network errors gracefully

    • Provide user-friendly error messages

    • Implement retry mechanisms for failed operations

  3. Performance

    • Cache order data when appropriate

    • Implement pagination for large order lists

    • Optimize API calls to reduce latency

  4. Security

    • Validate all user inputs

    • Verify transaction signatures

    • Implement proper wallet connection checks

Last updated