# Guide

## DCA (Dollar Cost Averaging) API Integration Documentation

### Overview

This document provides comprehensive integration guidelines for the OpenOcean DCA (Dollar Cost Averaging) API, based on the implementation in `Dca.js`. The API allows users to create and manage automated recurring buy strategies for token accumulation on supported blockchain networks.

{% embed url="<https://github.com/openocean-finance/OpenOcean-API-Examples/blob/main/frontend/src/pages/Dca.js>" %}

### API Base Information

#### Base URL

```
https://open-api.openocean.finance
```

### Supported Networks

The DCA API supports the following blockchain networks:

```
// Some code
const dcaChains = ["eth", "bsc", "base", "sonic", "bera", "arbitrum", "hyperevm", "avax"];

```

### Authentication & Wallet Integration

#### Prerequisites

* MetaMask or compatible Web3 wallet
* User must be connected to a supported network
* User must have sufficient token balance and gas fees
* Total allocation must be less than $5

### Token Configuration

#### Token Approval

Before creating a DCA strategy, users must approve the contract to spend their tokens:

```javascript
// Check current allowance
const currentAllowance = await tokenContract.allowance(account, contractAddress);

// Approve if needed
if (currentAllowance < requiredAmount) {
  const maxAmount = ethers.MaxUint256;
  const tx = await tokenContract.approve(contractAddress, maxAmount);
  await tx.wait();
}
```

### API Endpoints

#### 1. Create DCA Strategy

**Endpoint:** `POST /v2/{chainId}/dca/swap`

**URL Parameters:**

* `chainId`: The blockchain network ID (e.g., 8453 for Base)

**Request Body:**

```json
{
  "makerAsset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "takerAsset": "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2",
  "makerAmount": "20000000",
  "signature": "0x...",
  "orderMaker": "0x...",
  "minPrice": 0,
  "maxPrice": 0,
  "time": 3600,
  "times": 2
}
```

**Field Descriptions:**

* `makerAsset`: Address of the token being sold (e.g., USDC)
* `takerAsset`: Address of the token being bought (e.g., USDT)
* `makerAmount`: Total allocation amount in smallest units
* `signature`: signMessage
* `orderMaker`: User's wallet address
* `minPrice`: Minimum price limit in USD (optional, 0 for no limit)
* `maxPrice`: Maximum price limit in USD (optional, 0 for no limit)
* `time`: Time interval between trades in seconds
* `times`: Number of trades to execute

**Response:**

```json
{
  "success": true,
  "data": {
    "orderHash": "0x...",
    "status": "pending"
  }
}
```

#### 2. Cancel DCA Strategy

**Endpoint:** `POST /v2/{chainId}/dca/cancel`

**Request Body:**

```json
{
  "orderHash": "0x...",
  "signature": "0x..."
}
```

**Field Descriptions:**

* `orderHash`: Hash of the DCA strategy to cancel
* `signature`: signMessage

**Response:**

```json
{
  "code": 200,
  "success": true,
  "data": {
    "status": "cancelled"
  }
}
```

#### 3. Get User DCA Orders

**Endpoint:** `GET /v2/{chainId}/dca/address/{address}`

**URL Parameters:**

* `chainId`: The blockchain network ID
* `address`: User's wallet address

**Query Parameters:**

* `page`: Page number (default: 1)
* `limit`: Number of orders per page (default: 100)
* `statuses`: Array of order statuses to filter \[1,2,5]
* `sortBy`: Sort field (default: createDateTime)
* `exclude`: Exclude certain orders (default: 0)

**Example URL:**

```
/v2/8453/dca/address/0x1234...?page=1&limit=100&statuses=[1,2,5]&sortBy=createDateTime&exclude=0
```

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "123",
      "orderHash": "0x...",
      "makerAsset": "0x...",
      "takerAsset": "0x...",
      "makerAmount": "20000000",
      "createDateTime": "2024-01-01T00:00:00Z",
      "statuses": 2,
      "time": 3600,
      "times": 2,
      "minPrice": 0,
      "maxPrice": 0
    }
  ]
}
```

### Request/Response Formats

#### Order Status Codes

| Code | Status    | Description                                 |
| ---- | --------- | ------------------------------------------- |
| 1    | Pending   | DCA strategy is pending execution           |
| 2    | Active    | DCA strategy is active and executing trades |
| 3    | Filled    | DCA strategy has completed all trades       |
| 4    | Cancelled | DCA strategy has been cancelled             |
| 5    | Expired   | DCA strategy has expired                    |

#### Message Signing Format

**For DCA Strategy Creation:**

```
makerAsset:
{makerAssetAddress}
takerAsset:
{takerAssetAddress}
makerAmount:
{makerAmount}
```

**For DCA Strategy Cancellation:**

```
orderHash:
{orderHash}
```

#### Signature Generation

```javascript
const message = `makerAsset:\n${makerAsset}\ntakerAsset:\n${takerAsset}\nmakerAmount:\n${makerAmount}`;
const signature = await signer.signMessage(message);
```

### Integration Examples

#### Complete DCA Strategy Creation Flow

```javascript
async function createDcaStrategy(makerAmount, time, frequency, minPrice, maxPrice) {
  try {
    // 1. Validate inputs
    if (!makerAmount || makerAmount <= 0) {
      throw new Error('Invalid amount');
    }

    if (makerAmount >= 5) {
      throw new Error('Amount must be less than $5');
    }

    // 2. Check wallet connection
    if (!isWalletConnected) {
      throw new Error('Wallet not connected');
    }

    // 3. Get contract address
    const contractAddress = '0x6cBB2598881940D08d5Ea3fA8F557E02996e1031';

    // 4. Check and approve token if needed
    if (!isNativeToken(inToken.address)) {
      const approvalAmount = makerAmount * (10 ** inToken.decimals);
      await checkTokenApproval(inToken.address, contractAddress, approvalAmount, walletAccount, provider);
    }

    // 5. Prepare DCA parameters
    const messageParams = {
      makerAsset: inToken.address,
      takerAsset: outToken.address,
      makerAmount: (makerAmount * (10 ** inToken.decimals)).toString(),
    };

    // 6. Create and sign message
    const message = `makerAsset:\n${messageParams.makerAsset}\ntakerAsset:\n${messageParams.takerAsset}\nmakerAmount:\n${messageParams.makerAmount}`;
    const signer = await provider.getSigner();
    const signature = await signer.signMessage(message);

    // 7. Submit DCA strategy
    const order = {
      ...messageParams,
      signature,
      orderMaker: walletAccount,
      minPrice: minPrice || 0,
      maxPrice: maxPrice || 0,
      time: everyUnit * time,
      times: frequency,
    };

    const response = await axios.post(
      `https://open-api.openocean.finance/v2/${chainId}/dca/swap`,
      order,
      { 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 strategy:', error);
    throw error;
  }
}
```

#### DCA Strategy Management

```javascript
const { orderHash } = order;

 // Create message for signing
 const message = 'orderHash:\n' + orderHash;
 const signer = await provider.getSigner();
 const signature = await signer.signMessage(message);

// Cancel order through API
const { data } = await axios.post(
     `https://open-api.openocean.finance/v2/${chain.chainId}/dca/cancel`,
     {
      orderHash,
      signature
     }
   );
```

### Support

For technical support or questions about the API:

* Check the [OpenOcean Documentation](https://docs.openocean.finance)
* Contact the development team
* Review error logs and API responses
