# Quick Start

## Overview

This guide provides a comprehensive overview of how to use the Monday API endpoints. It covers the essential steps from authentication to making your first API call.

**Important**: All API endpoints require authentication.

## Prerequisites

Before you begin, ensure you have:

* A Monday account
* API credentials created by calling `/v4/public/trader/api-key/create`:
  * **API Key**: Your public API key
  * **Secret Key**: Your private secret key (keep this secure!)
* Basic understanding of REST APIs
* Your preferred programming language environment set up (Python recommended for API examples)

## Authentication

All API endpoints (prefixed with `/v4/public/trader/`) require authentication using API key headers and HMAC-SHA256 signature authentication.

### API Authentication

API endpoints (prefixed with `/v4/public/trader/`) use HMAC-SHA256 signature authentication.

#### Required Headers

```http
X-Api-Key: [your_api_key]
X-Api-Sign: [signature]
X-Api-Ts: [timestamp]
X-Chain-Id: [chain_id]
```

#### Signature Generation

The signature is generated using HMAC-SHA256 and Base64 encoding:

**Message Format:**

```
message = timestamp + method + request_path + body
```

**Signature Calculation:**

```
signature = base64(hmac_sha256(message, secret_key))
```

#### Python Implementation Example

```python
import hmac
import hashlib
import base64
import json
import time
from urllib.parse import urlencode, parse_qs

def compute_signature(message, secret_key):
    """Compute HMAC-SHA256 signature"""
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

def sort_query_string(query_string):
    """Sort query parameters alphabetically (for GET requests)"""
    if not query_string:
        return ""
    params = parse_qs(query_string, keep_blank_values=True)
    sorted_params = []
    for key in sorted(params.keys()):
        for value in params[key]:
            sorted_params.append(f"{key}={value}")
    return "&".join(sorted_params)

def sort_json_keys(json_str):
    """Sort JSON keys alphabetically (for POST JSON requests)"""
    if not json_str:
        return ""
    try:
        data = json.loads(json_str)
        return json.dumps(data, sort_keys=True, separators=(',', ':'))
    except json.JSONDecodeError:
        return json_str

def build_message(timestamp, method, request_path, body="", content_type=""):
    """Build signature message"""
    method = method.upper()
    
    # Handle GET request query parameters
    if method == "GET" and "?" in request_path:
        path, query = request_path.split("?", 1)
        sorted_query = sort_query_string(query)
        request_path = f"{path}?{sorted_query}"
    
    # Handle POST request JSON body
    if method in ["POST", "PUT", "PATCH"] and body:
        if content_type and "application/json" in content_type.lower():
            body = sort_json_keys(body)
    
    return timestamp + method + request_path + body

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    message = build_message(timestamp, method, request_path, body, content_type)
    return compute_signature(message, secret_key)
```

#### Important Notes for API

1. **Timestamp Format**: Use milliseconds since Unix epoch

   ```python
   timestamp = str(int(time.time() * 1000))
   ```
2. **Time Window**: Requests are valid within 30 seconds of the timestamp
3. **GET Requests**: Query parameters must be sorted alphabetically by key
   * Example: `symbol=BTC/USDT&side=buy&amount=0.001` → `amount=0.001&side=buy&symbol=BTC/USDT`
4. **POST Requests**:
   * JSON body keys must be sorted alphabetically
   * Use compact JSON format (no spaces): `json.dumps(data, sort_keys=True, separators=(',', ':'))`
   * Form body: No sorting required, maintain original order

## Base URL

All API requests should be made to:

```
https://api.monday.trade
```

API endpoints use the path prefix `/v4/public/trader/`, so the full URL format is:

```
https://api.monday.trade/v4/public/trader/{endpoint}
```

**Important**: When generating signatures, use the full path including `/v4/public/trader/` (e.g., `/v4/public/trader/server/time`).

## Step-by-Step Examples

### API Examples

#### Step 1: Get Server Time (API)

First, synchronize with the server time:

```python
import hmac
import hashlib
import base64
import json
import requests
from datetime import datetime, timezone

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    # Build message: timestamp + method + request_path + body
    message = timestamp + method.upper() + request_path
    if body and method.upper() in ["POST", "PUT", "PATCH"]:
        if content_type and "application/json" in content_type.lower():
            # Sort JSON keys
            data = json.loads(body)
            body = json.dumps(data, sort_keys=True, separators=(',', ':'))
        message += body
    
    # Compute HMAC-SHA256 signature
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

# Set your API credentials
api_key = "<your-api-key>"
secret_key = "<your-secret-key>"
chain_id = 143

# Generate timestamp in milliseconds
timestamp = str(int(time.time() * 1000))

# Generate signature
request_path = "/v4/public/trader/server/time"
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

# Make request
headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get("https://api.monday.trade/v4/public/trader/server/time", headers=headers)
data = response.json()
print("Server time:", data)
```

#### Step 2: Get Orderbook (API)

Retrieve orderbook data:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path with sorted query parameters
# Note: Query parameters must be sorted alphabetically
request_path = "/v4/public/trader/market/orderbook?limit=100&symbol=BTC/USDT"  # limit comes before symbol alphabetically
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get(
    "https://api.monday.trade/v4/public/trader/market/orderbook?symbol=BTC/USDT&limit=100",
    headers=headers
)
data = response.json()
print("Orderbook:", data)
```

#### Step 3: Get Account Balance (API)

Retrieve your account balance:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path
request_path = "/v4/public/trader/account/balance"
signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
}

response = requests.get("https://api.monday.trade/v4/public/trader/account/balance", headers=headers)
data = response.json()
print("Account balance:", data)
```

#### Step 4: POST Request Example (API)

Example of a POST request with JSON body:

```python
# Generate timestamp
timestamp = str(int(time.time() * 1000))

# Build request path
request_path = "/v4/public/trader/order/market"

# Prepare body (will be sorted by keys)
body_data = {
    "symbol": "BTC/USDT",
    "side": "buy",
    "amount": "0.001",
    "price": "50000"
}
body = json.dumps(body_data, sort_keys=True, separators=(',', ':'))

# Generate signature (body will be sorted)
signature = generate_trader_signature(secret_key, timestamp, "POST", request_path, body, "application/json")

headers = {
    "X-Api-Key": api_key,
    "X-Api-Sign": signature,
    "X-Api-Ts": timestamp,
    "X-Chain-Id": str(chain_id),
    "Content-Type": "application/json",
}

response = requests.post("https://api.monday.trade/v4/public/trader/order/market", headers=headers, data=body)
data = response.json()
print("Order placed:", data)
```

## Error Handling

Always implement proper error handling:

```javascript
try {
    const response = await fetch(apiUrl, options);
    const data = await response.json();

    if (data.code !== 200) {
        console.error("API Error:", data.msg);
        return;
    }

    // Process successful response
    console.log("Success:", data.data);
} catch (error) {
    console.error("Request failed:", error);
}
```

## Rate Limits

Be aware of rate limits:

* **All Endpoints**: 120 requests per minute

Implement rate limiting in your application to avoid hitting these limits.

## Best Practices

### 1. Use HTTPS

Always use HTTPS for API requests to ensure data security.

### 2. Handle Timestamps

* Use server time for synchronization
* Include proper timestamp in requests
* Account for network latency

### 3. Implement Retry Logic

```javascript
async function apiCallWithRetry(url, options, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(url, options);
            if (response.ok) {
                return await response.json();
            }
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)));
        }
    }
}
```

### 4. Validate Responses

Always validate API responses before processing:

```javascript
function validateResponse(data) {
    if (!data || typeof data.code === "undefined") {
        throw new Error("Invalid response format");
    }

    if (data.code !== 200) {
        throw new Error(`API Error: ${data.msg}`);
    }

    return data.data;
}
```

### 5. Use Pagination

For endpoints that return large datasets, use pagination:

```javascript
async function getAllData(endpoint, params = {}) {
    let allData = [];
    let cursor = null;

    do {
        const response = await fetch(
            `${endpoint}?${new URLSearchParams({
                ...params,
                limit: 50,
                ...(cursor && { cursor }),
            })}`
        );

        const data = await response.json();
        allData = allData.concat(data.data);
        cursor = data.data.nextPageCursor;
    } while (cursor);

    return allData;
}
```

## Testing Your Setup

Test your API setup with this Python script:

```python
import hmac
import hashlib
import base64
import json
import requests
from datetime import datetime, timezone

def generate_trader_signature(secret_key, timestamp, method, request_path, body="", content_type=""):
    """Generate API signature"""
    message = timestamp + method.upper() + request_path
    if body and method.upper() in ["POST", "PUT", "PATCH"]:
        if content_type and "application/json" in content_type.lower():
            data = json.loads(body)
            body = json.dumps(data, sort_keys=True, separators=(',', ':'))
        message += body
    
    mac = hmac.new(
        secret_key.encode('utf-8'),
        message.encode('utf-8'),
        hashlib.sha256
    )
    return base64.b64encode(mac.digest()).decode('utf-8')

def test_trader_api_setup():
    """Test API setup"""
    try:
        # Test 1: Get server time
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/server/time"
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get("https://api.monday.trade/v4/public/trader/server/time", headers=headers)
        time_data = response.json()
        print("✓ Server time:", time_data)
        
        # Test 2: Get orderbook
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/market/orderbook?limit=50&symbol=BTC/USDT"  # Sorted: limit before symbol
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get(
            "https://api.monday.trade/v4/public/trader/market/orderbook?symbol=BTC/USDT&limit=50",
            headers=headers
        )
        orderbook_data = response.json()
        print("✓ Orderbook retrieved")
        
        # Test 3: Get account balance
        timestamp = str(int(time.time() * 1000))
        request_path = "/v4/public/trader/account/balance"
        signature = generate_trader_signature(secret_key, timestamp, "GET", request_path)
        
        headers = {
            "X-Api-Key": api_key,
            "X-Api-Sign": signature,
            "X-Api-Ts": timestamp,
            "X-Chain-Id": str(chain_id),
        }
        
        response = requests.get("https://api.monday.trade/v4/public/trader/account/balance", headers=headers)
        balance_data = response.json()
        print("✓ Account balance retrieved")
        
        print("✓ All tests passed!")
    except Exception as e:
        print(f"✗ Test failed: {e}")

# Run tests
if __name__ == "__main__":
    # Use your own credentials
    api_key = "<your-api-key>"
    secret_key = "<your-secret-key>"
    chain_id = 143
    
    test_trader_api_setup()
```

## API Endpoints

The API provides the following endpoints (all prefixed with `/v4/public/trader/`):

* `/v4/public/trader/server/time` - Get server time
* `/v4/public/trader/market/kline` - Get kline/candlestick data
* `/v4/public/trader/market/instruments` - Get instrument information
* `/v4/public/trader/market/tickers` - Get ticker data
* `/v4/public/trader/market/funding/history` - Get funding rate history
* `/v4/public/trader/market/orderbook` - Get orderbook data
* `/v4/public/trader/order/list` - Get open orders
* `/v4/public/trader/order/history` - Get order history
* `/v4/public/trader/execution/history` - Get trade execution history
* `/v4/public/trader/position/list` - Get position information
* `/v4/public/trader/liquidity/list` - Get liquidity positions
* `/v4/public/trader/liquidity/history` - Get liquidity history
* `/v4/public/trader/account/balance` - Get account balance
* `/v4/public/trader/account/transactions` - Get transaction history
* `/v4/public/trader/api-key/list` - Get API key list
* `/v4/public/trader/api-key/create` - Create API key
* `/v4/public/trader/api-key/update` - Update API key
* `/v4/public/trader/api-key/delete` - Delete API key

## Next Steps

1. **Create API Credentials**: If you do not have credentials yet, call `/v4/public/trader/api-key/create` to generate your first `apiKey` and `apiSecret`
2. **Test Basic Endpoints**: Start with simple endpoints like `/v4/public/trader/server/time`
3. **Understand Signature Requirements**:
   * GET requests: Sort query parameters alphabetically
   * POST requests: Sort JSON keys alphabetically
   * Use milliseconds since Unix epoch
4. **Explore Market Data**: Access market data endpoints to understand available instruments
5. **Check Account Status**: Verify your account balance and permissions
6. **Monitor Positions**: Use position endpoints to track your current positions
7. **Review Order History**: Analyze your trading history and performance
8. **Implement Trading Logic**: Build your trading strategies using the API

## Support

For additional help:

* Check the individual API documentation files
* Review error codes and messages
* Ensure your API keys have the correct permissions
* Verify your request format matches the documentation

## Security Notes

* Never expose your API secret key or passphrase in client-side code
* Use environment variables for API credentials
* Implement proper access controls
* Monitor your API usage regularly
* Rotate your API keys periodically
* Keep your passphrase secure - it's required for API authentication
* Ensure timestamps are accurate - requests expire after 30 seconds for API

## Troubleshooting

### Common Issues with API

1. **Signature Mismatch**
   * Verify query parameters are sorted alphabetically for GET requests
   * Ensure JSON keys are sorted alphabetically for POST requests
   * Check timestamp format (must be milliseconds since Unix epoch)
   * Verify the message format: `timestamp + method + request_path + body`
2. **Invalid Timestamp**
   * Ensure your system clock is synchronized
   * Use UTC timezone for timestamps
   * Timestamp must be within 30 seconds of server time
   * Format: milliseconds since Unix epoch, for example `1700000000000`
3. **API Key Not Found**
   * Verify your API key is correct
   * Check if the API key is active
   * Ensure you're using the correct base URL
