> ## Documentation Index
> Fetch the complete documentation index at: https://docs.whitebit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# First API Call

> Make a first WhiteBIT API call — public market data with no authentication, then an authenticated balance check with HMAC-SHA512 signing.

export const RegionBaseUrl = ({className = "", showBaseUrl = true}) => {
  const [region, setRegionState] = useState(() => {
    if (typeof window !== 'undefined') {
      return localStorage.getItem("api-region-preference") || "com";
    }
    return "com";
  });
  const [mounted, setMounted] = useState(false);
  const observerRef = useRef(null);
  const isSyncingRef = useRef(false);
  const updateAllContentOnPage = targetRegion => {
    try {
      const domainFrom = targetRegion === "eu" ? "whitebit.com" : "whitebit.eu";
      const domainTo = targetRegion === "eu" ? "whitebit.eu" : "whitebit.com";
      const links = document.querySelectorAll('a');
      links.forEach(link => {
        let href = link.getAttribute('href');
        if (href && href.includes(domainFrom)) {
          link.setAttribute('href', href.replace(domainFrom, domainTo));
        }
      });
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
        acceptNode: node => {
          if (node.parentElement?.closest('.region-toggle-component')) {
            return NodeFilter.FILTER_REJECT;
          }
          return node.textContent.includes(domainFrom) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        }
      });
      let currentNode;
      while (currentNode = walker.nextNode()) {
        currentNode.textContent = currentNode.textContent.replace(new RegExp(domainFrom, 'g'), domainTo);
      }
      console.log(`[RegionSync] Global content updated to ${domainTo}`);
    } catch (e) {
      console.error("[RegionSync] Error updating content:", e);
    }
  };
  const updateRegion = (newRegion, source) => {
    if (region === newRegion) return;
    console.log(`[RegionBaseUrl] Updating to "${newRegion}" (Source: ${source})`);
    if (source === 'observer') {
      isSyncingRef.current = true;
      setTimeout(() => isSyncingRef.current = false, 1000);
    }
    setRegionState(newRegion);
    localStorage.setItem("api-region-preference", newRegion);
    updateAllContentOnPage(newRegion);
    if (source === 'user-click') {
      window.dispatchEvent(new CustomEvent("regionChange", {
        detail: newRegion
      }));
      attemptToUpdateNativeDropdown(newRegion, 0);
      setTimeout(() => attemptToUpdateNativeDropdown(newRegion, 1), 500);
      setTimeout(() => attemptToUpdateNativeDropdown(newRegion, 2), 1500);
    }
  };
  const attemptToUpdateNativeDropdown = (targetRegion, attempt) => {
    if (isSyncingRef.current) return;
    try {
      const targetUrl = targetRegion === "eu" ? "https://whitebit.eu" : "https://whitebit.com";
      const targetDesc = targetRegion === "eu" ? "EU Server" : "Production Server";
      const selects = document.querySelectorAll('select');
      for (const select of selects) {
        if (select.innerHTML.includes('whitebit.com') || select.innerHTML.includes('whitebit.eu')) {
          select.value = targetUrl;
          select.dispatchEvent(new Event('change', {
            bubbles: true
          }));
          return;
        }
      }
      const buttons = Array.from(document.querySelectorAll('button, [role="combobox"]'));
      const serverSelector = buttons.find(btn => {
        if (btn.closest('a') || btn.closest('[class*="card"]') || btn.closest('nav')) {
          return false;
        }
        const txt = btn.textContent || "";
        const isServerDropdown = (txt.includes('Production Server') || txt.includes('EU Server') || txt.includes('WhiteBIT Global Server') || txt.includes('WhiteBIT EU Server')) && !txt.includes('Run') && !txt.includes('Send') || btn.getAttribute('role') === 'combobox';
        return isServerDropdown;
      });
      if (serverSelector) {
        const currentText = serverSelector.textContent || "";
        if (currentText.includes(targetDesc)) return;
        serverSelector.click();
        setTimeout(() => {
          const options = document.querySelectorAll('[role="option"], li, button');
          for (const opt of options) {
            const optText = opt.textContent || "";
            if (optText.includes(targetDesc) || optText.includes(targetUrl)) {
              opt.click();
              return;
            }
          }
        }, 100);
      }
    } catch (e) {
      console.error("[Sync] Error:", e);
    }
  };
  useEffect(() => {
    setMounted(true);
    updateAllContentOnPage(region);
    const handleStorageChange = e => {
      if (e.key === "api-region-preference" && e.newValue) {
        updateRegion(e.newValue, 'storage');
      }
    };
    const handleRegionChange = e => {
      if (e.detail !== region) {
        updateRegion(e.detail, 'event');
      }
    };
    window.addEventListener("storage", handleStorageChange);
    window.addEventListener("regionChange", handleRegionChange);
    observerRef.current = new MutationObserver(mutations => {
      if (isSyncingRef.current) return;
      updateAllContentOnPage(region);
      for (const mutation of mutations) {
        if (mutation.type !== 'childList' && mutation.type !== 'characterData') continue;
        const target = mutation.target;
        const el = target.nodeType === Node.TEXT_NODE ? target.parentElement : target;
        if (el && (el.getAttribute('role') === 'option' || el.closest('[role="listbox"]'))) continue;
        const text = target.textContent || "";
        if (text.includes('WhiteBIT EU Server') || text.includes('https://whitebit.eu') && text.includes('Server')) {
          if (el && el.tagName !== 'A' && !el.closest('.region-toggle-component')) {
            if (region !== 'eu') updateRegion('eu', 'observer');
          }
        } else if (text.includes('WhiteBIT Global Server') || text.includes('https://whitebit.com') && text.includes('Server')) {
          if (el && el.tagName !== 'A' && !el.closest('.region-toggle-component')) {
            if (region !== 'com') updateRegion('com', 'observer');
          }
        }
      }
    });
    observerRef.current.observe(document.body, {
      childList: true,
      subtree: true,
      characterData: true
    });
    if (typeof window !== 'undefined') {
      const current = localStorage.getItem("api-region-preference");
      if (current) attemptToUpdateNativeDropdown(current, 'init');
    }
    return () => {
      window.removeEventListener("storage", handleStorageChange);
      window.removeEventListener("regionChange", handleRegionChange);
      if (observerRef.current) observerRef.current.disconnect();
    };
  }, [region]);
  const apiBaseUrl = region === "eu" ? "https://whitebit.eu" : "https://whitebit.com";
  if (!mounted) return null;
  return <div className={`flex items-center gap-2 flex-wrap my-4 region-toggle-component ${className}`}>
            <span className="text-sm text-gray-500 dark:text-gray-400 font-mono">
                Base URL
            </span>
            <span className="text-sm text-gray-400">(</span>
            <div className="inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-0.5 border border-gray-200 dark:border-gray-700">
                <button onClick={() => updateRegion("com", "user-click")} className={`px-2 py-0.5 text-xs font-medium rounded-md transition-all ${region === "com" ? "bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm" : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"}`}>
                    .com
                </button>
                <button onClick={() => updateRegion("eu", "user-click")} className={`px-2 py-0.5 text-xs font-medium rounded-md transition-all ${region === "eu" ? "bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm" : "text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"}`}>
                    .eu
                </button>
            </div>
            <span className="text-sm text-gray-400">)</span>
            {showBaseUrl && <>
                    <span className="text-sm text-gray-400">:</span>
                    <a href={apiBaseUrl} target="_blank" rel="noopener noreferrer" className="text-sm font-mono text-primary dark:text-primary-light hover:underline">
                        {apiBaseUrl}
                    </a>
                </>}
        </div>;
};

<RegionBaseUrl />

Make a first WhiteBIT API call — public data with no authentication, then a private request with HMAC-SHA512 signing. The walkthrough is for developers integrating the v4 REST API for the first time and includes curl and Python examples for each step.

<Note>
  WhiteBIT does not offer a public testnet or sandbox environment.
  All API calls in this guide execute against the live API.
  Steps 1 and 2 are read-only public calls — safe to run freely.
  Step 4 reads account balances only — no orders are placed and no funds are moved.
</Note>

## Prerequisites

* curl or Python 3.x installed
* WhiteBIT [API Quick Start Helper](https://github.com/whitebit-exchange/api-quickstart) (optional — provides signing examples in 10+ languages)
* Steps 1–2: No account required
* Steps 3–4: WhiteBIT account ([register](https://whitebit.com/auth/register)), 2FA enabled, API key with **Info + Trading** permissions ([create key](https://whitebit.com/settings/api))

<Steps>
  <Step title="Check server time (public, no auth)">
    Verify connectivity by calling the public server time endpoint. No authentication is required.

    **Endpoint:** `GET https://whitebit.com/api/v4/public/time`

    <Tabs>
      <Tab title="cURL">
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        curl -X GET https://whitebit.com/api/v4/public/time
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
        import requests

        response = requests.get("https://whitebit.com/api/v4/public/time")
        print(response.json())
        ```
      </Tab>
    </Tabs>

    **Expected response:**

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "time": 1700000000
    }
    ```

    The `time` field is a Unix timestamp in seconds.
  </Step>

  <Step title="Fetch market data (public, no auth)">
    Retrieve the list of available spot markets. No authentication is required.

    **Endpoint:** `GET https://whitebit.com/api/v4/public/markets`

    <Tabs>
      <Tab title="cURL">
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        curl -X GET https://whitebit.com/api/v4/public/markets
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
        import requests

        response = requests.get("https://whitebit.com/api/v4/public/markets")
        markets = response.json()
        # Print first 3 markets
        for market in markets[:3]:
            print(market["name"], market["minAmount"], market["tradesEnabled"])
        ```
      </Tab>
    </Tabs>

    **Expected response (truncated — the full response contains 900+ markets):**

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [
      {
        "name": "BTC_USDT",
        "stock": "BTC",
        "money": "USDT",
        "stockPrec": "6",
        "moneyPrec": "2",
        "makerFee": "0.001",
        "takerFee": "0.001",
        "minAmount": "0.0001",
        "minTotal": "1",
        "tradesEnabled": true
      }
    ]
    ```

    Key fields: `name` (pair), `minAmount` (minimum order size in base asset), `tradesEnabled` (pair active status).

    <Note>
      For risk-free Spot trading practice, activate Demo Tokens (DBTC + DUSDT) from the
      [WhiteBIT Codes page](https://whitebit.com/codes). The `DBTC_DUSDT` pair supports
      the same API endpoints as any Spot market — place, query, and cancel orders without
      risking real funds. No KYC required.
    </Note>
  </Step>

  <Step title="Generate an API key">
    An API key is required for all private endpoints. Skip this step if a key is already available.

    1. Navigate to [API key settings](https://whitebit.com/settings/api).
    2. Enable 2FA if not already active — 2FA is required before key creation.
    3. Create a new key with **Info + Trading** permissions.
    4. Optionally whitelist the current IP address (up to 50 addresses per key).
    5. Save the API key and secret immediately — the secret is shown only once and cannot be retrieved later.

    <Warning>
      Store the API secret securely in an environment variable or secrets manager.
      Never commit secrets to version control or include them in client-side code.
    </Warning>
  </Step>

  <Step title="Authenticated balance check (private)">
    Read the spot trading account balance. This call requires HMAC-SHA512 signing.

    **Endpoint:** `POST https://whitebit.com/api/v4/trade-account/balance`

    Every private request requires three headers computed from the request body:

    * `X-TXC-APIKEY` — the API key string
    * `X-TXC-PAYLOAD` — Base64-encoded JSON request body
    * `X-TXC-SIGNATURE` — HMAC-SHA512 of the Base64 payload, hex-encoded, signed with the API secret

    The JSON request body must include `request` (the endpoint path) and `nonce` (an ever-increasing integer — use Unix milliseconds).

    See [Authentication](/api-reference/authentication) for the full signing walkthrough.

    <Tabs>
      <Tab title="Python">
        ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
        import requests
        import hmac
        import hashlib
        import base64
        import json
        import time

        API_KEY = "YOUR_API_KEY"        # Replace with actual API key
        API_SECRET = "YOUR_API_SECRET"  # Replace with actual API secret

        url = "https://whitebit.com/api/v4/trade-account/balance"
        payload = {
            "request": "/api/v4/trade-account/balance",
            "nonce": int(time.time() * 1000)
        }
        # Use compact separators: the server validates the body against a
        # canonical (no-whitespace) serialization and rejects spaced JSON
        # with HTTP 400 `{"code":9,"message":"Invalid payload."}`.
        payload_json = json.dumps(payload, separators=(",", ":"))
        payload_base64 = base64.b64encode(payload_json.encode()).decode()
        signature = hmac.new(
            API_SECRET.encode(),
            payload_base64.encode(),
            hashlib.sha512
        ).hexdigest()

        headers = {
            "Content-Type": "application/json",
            "X-TXC-APIKEY": API_KEY,
            "X-TXC-PAYLOAD": payload_base64,
            "X-TXC-SIGNATURE": signature,
        }
        response = requests.post(url, headers=headers, data=payload_json)
        print(response.json())
        ```
      </Tab>

      <Tab title="cURL">
        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        # The payload and signature must be computed before calling curl.
        # Use the Python example for a complete signing implementation.
        # Replace BASE64_PAYLOAD and HMAC_SIGNATURE with computed values.

        curl -X POST https://whitebit.com/api/v4/trade-account/balance \
          -H "Content-Type: application/json" \
          -H "X-TXC-APIKEY: YOUR_API_KEY" \
          -H "X-TXC-PAYLOAD: BASE64_PAYLOAD" \
          -H "X-TXC-SIGNATURE: HMAC_SIGNATURE" \
          -d '{"request":"/api/v4/trade-account/balance","nonce":1700000000000}'
        ```
      </Tab>
    </Tabs>

    For Go and PHP examples, see [SDKs](/sdks).

    **Expected response:**

    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "BTC": {
        "available": "0.00100000",
        "freeze": "0"
      },
      "USDT": {
        "available": "100.00000000",
        "freeze": "0"
      }
    }
    ```

    Each key is an asset ticker. `available` is the amount ready to trade. `freeze` is locked in open orders. An empty response (`{}`) means the Trade balance holds no assets — transfer funds from Main first. See [Balances & Transfers](/concepts/balances) for details on Main, Trade, and Collateral account types.
  </Step>
</Steps>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Invalid signature error">
    The payload used for Base64 encoding must be the exact same JSON string sent as the request body. Verify:

    * The `request` field matches the endpoint path exactly (e.g., `"/api/v4/trade-account/balance"`).
    * The `nonce` is a string (not an integer) and is larger than the previous request's nonce.
    * The API secret is correct and has not been regenerated.
    * The HMAC uses the Base64-encoded string as input, not the raw JSON.

    See [Authentication](/api-reference/authentication) for the complete signing walkthrough.
  </Accordion>

  <Accordion title="API key not found or 401 Unauthorized">
    Verify:

    * The API key is copied correctly — no leading or trailing spaces.
    * The key is active. Keys auto-deactivate after 14 days of inactivity. Reactivate at [whitebit.com/settings/api](https://whitebit.com/settings/api).
    * The key has **Info + Trading** permissions for balance endpoints.
  </Accordion>

  <Accordion title="IP address not allowed">
    If the API key has IP whitelisting enabled, the request must come from a whitelisted IP address. Add the current IP at [whitebit.com/settings/api](https://whitebit.com/settings/api).
  </Accordion>

  <Accordion title="Nonce is too small">
    The `nonce` must be greater than the previous request's nonce for the same API key. Use `int(time.time() * 1000)` to generate a millisecond-precision Unix timestamp. Avoid reusing nonces across requests.
  </Accordion>
</AccordionGroup>

## What's Next

<CardGroup cols={2}>
  <Card title="Spot Trading Quickstart" icon="arrow-right-arrow-left" href="/products/spot/quickstart">
    Place a first order on a spot market.
  </Card>

  <Card title="WebSocket Quickstart" icon="plug" href="/guides/websocket-quickstart">
    Stream real-time prices over WebSocket.
  </Card>

  <Card title="Market Data Overview" icon="chart-bar" href="/products/market-data/overview">
    Browse the 14 public endpoints for tickers, orderbooks, trades, and funding rates.
  </Card>
</CardGroup>
