Guide

Browser Wallet Examples

Private Key Wallet Examples

Overview

OpenOcean DCA (Dollar Cost Averaging) allows users to create automated recurring buy orders for token accumulation. Users can set up periodic purchases to average their entry price over time.

Supported Chains

const dcaChains = ["eth","bsc","base","sonic","bera","arbitrum","hyperevm"]

API Endpoints

1. Create DCA Order

Endpoint: POST /v1/{chainId}/dca/swap

Request Body:

{
  // Order data from SDK
  makerTokenAddress: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  makerTokenDecimals: 6,
  takerTokenAddress: "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2", 
  takerTokenDecimals: 6,
  makerAmount: "20000000", // Amount in smallest unit
  takerAmount: "1",
  gasPrice: "15000000000",
  
  // DCA specific parameters
  expireTime: 180,
  time: 3600, // Time interval in seconds
  times: 2, // Number of trades to execute
  version: "v2",
  
  // Optional price limits
  minPrice: 1.0, // Minimum price limit in USD
  maxPrice: 2.0  // Maximum price limit in USD
}

Response:

{
  "code": 200,
  "data": {
    "orderHash": "0x...",
    "status": "pending"
  }
}

2. Cancel DCA Order

Endpoint: POST /v1/{chainId}/dca/cancel

Request Body:

{
  orderHash: "0x...",
  signature: "0x..." // Cancellation signature from SDK
}

Response:

{
  "code": 200,
  "data": {
    "status": "cancelled"
  }
}

3. Get User DCA Orders

Endpoint: GET /v1/{chainId}/dca/address/{address}

Query Parameters:

  • page: Page number (default: 1)

  • limit: Number of orders per page (default: 100)

  • statuses: Order status filter [1,2,5] (1=Pending, 2=Active, 5=Expired)

  • sortBy: Sort field (default: createDateTime)

  • exclude: Exclude flag (default: 0)

Response:

{
  "data": [
    {
      "id": "123",
      "orderHash": "0x...",
      "createDateTime": "2024-01-01T00:00:00Z",
      "makerAmount": "20000000",
      "time": 3600,
      "frequency": 2,
      "minPrice": 1.0,
      "maxPrice": 2.0,
      "statuses": 2
    }
  ]
}

SDK Integration

1. Install Dependencies

npm install @openocean.finance/limitorder-sdk ethers axios

2. Initialize SDK

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

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

const providerParams = {
  provider: provider,
  chainKey: 'base',
  account: address,
  chainId: 8453,
  mode: 'Dca'
};

3. Create DCA Order

const createDCAOrder = async () => {
  try {
    // Get gas price with 20% buffer
    const feeData = await provider.getFeeData();
    const gasPrice = parseInt(Number(feeData.gasPrice?.toString()) * 1.2);
    
    // Prepare order parameters
    const params = {
      makerTokenAddress: inToken.address,
      makerTokenDecimals: inToken.decimals,
      takerTokenAddress: outToken.address,
      takerTokenDecimals: outToken.decimals,
      makerAmount: (makerAmount * (10 ** inToken.decimals)).toString(),
      takerAmount: "1",
      gasPrice: gasPrice
    };
    
    // Create order using SDK
    const orderData = await openoceanLimitOrderSdk.createLimitOrder(
      providerParams,
      params
    );
    
    // Add DCA specific parameters
    const dcaOrder = {
      ...orderData,
      expireTime: 180,
      time: everyUnit * time, // Total time interval
      times: frequency, // Number of trades
      version: 'v2',
      minPrice: minPrice || undefined,
      maxPrice: maxPrice || undefined
    };
    
    // Submit to API
    const response = await axios.post(
      `${baseUrl}/v1/${chainId}/dca/swap`,
      dcaOrder,
      { headers: { 'Content-Type': 'application/json' } }
    );
    
    if (response.data.code === 400) {
      throw new Error(response.data.error);
    }
    
    return response.data;
  } catch (error) {
    console.error('Error creating DCA order:', error);
    throw error;
  }
};

4. Cancel DCA Order

const cancelDCAOrder = async (orderHash) => {
  try {
    // Get cancellation signature from SDK
    const signature = await openoceanLimitOrderSdk.cancelOrderSignature(
      providerParams,
      { orderHash }
    );
    
    // Submit cancellation to API
    const response = await axios.post(
      `${baseUrl}/v1/${chainId}/dca/cancel`,
      { orderHash, signature }
    );
    
    if (response.data.code !== 200) {
      throw new Error(response.data.error);
    }
    
    return response.data;
  } catch (error) {
    console.error('Error canceling DCA order:', error);
    throw error;
  }
};

5. Get User Orders

const getUserDCAOrders = async (address) => {
  try {
    const url = `${baseUrl}/v1/${chainId}/dca/address/${address}?page=1&limit=100&statuses=[1,2,5]&sortBy=createDateTime&exclude=0`;
    const response = await axios.get(url);
    return response.data.data;
  } catch (error) {
    console.error('Error fetching DCA orders:', error);
    throw error;
  }
};

DCA Parameters

Required Parameters

  • makerAmount: Total allocation amount in base token (e.g., USDC)

  • time: Time interval between trades (in seconds)

  • times: Number of trades to execute

  • everyUnit: Time unit multiplier (60=minute, 3600=hour, 86400=day, etc.)

Optional Parameters

  • minPrice: Minimum price limit in USD (only works for stablecoin sell tokens)

  • maxPrice: Maximum price limit in USD (only works for stablecoin sell tokens)

Time Unit Options

const timeUnitOptions = [
  { value: 60, label: "Minute" },
  { value: 60 * 60, label: "Hour" },
  { value: 60 * 60 * 24, label: "Day" },
  { value: 60 * 60 * 24 * 7, label: "Week" },
  { value: 60 * 60 * 24 * 30, label: "Month" }
];

Order Status

Status Code
Status
Description

1

Pending

Order is pending activation

2

Active

Order is active and executing

3

Filled

Order has been completed

4

Cancelled

Order has been cancelled

5

Expired

Order has expired

Important Notes

  1. Price Limits: Min/Max price limits only work when the sell token is a stablecoin (e.g., USDC)

  2. Gas Price: Add 20% buffer to current gas price for reliable execution

  3. Order Expiration: Orders expire after 180 seconds if not executed

  4. Supported Chains: Currently only supports Base network

  5. Token Decimals: Always use smallest unit (wei) for amounts

  6. Frequency Limits: Set reasonable frequency to avoid excessive gas costs

  7. Price Validation: Ensure price limits are within reasonable ranges

Dependencies

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

Rate Limits

  • API calls are subject to rate limiting

  • Implement exponential backoff for retries

  • Cache order data when possible

  • Monitor API response headers for rate limit information

Last updated