Getting started overview

Integrating with BtcTurk's API enables programmatic access to cryptocurrency trading features, market data, and account management. The process generally involves setting up a BtcTurk account, completing necessary identity verification, generating API credentials, and then constructing authenticated requests to the API endpoints. BtcTurk provides comprehensive API documentation with examples in several programming languages, including Python and Node.js.

The BtcTurk API supports both public endpoints, which do not require authentication for retrieving general market information, and private endpoints, which demand cryptographic signatures for actions such as placing orders, managing balances, or accessing user-specific data. Adherence to security best practices, such as securely storing API keys and implementing proper request signing, is crucial for protecting account assets and data.

Before making your first API call, ensure you understand the requirements for API key generation and signature creation. The platform emphasizes secure key management and details the cryptographic method for authenticating private requests, typically involving HMAC-SHA256 signing.

Here's a quick reference for getting started:

Step What to Do Where
1. Create Account Register on BtcTurk and complete identity verification. BtcTurk website
2. Generate API Keys Access API Management section in account settings. BtcTurk account settings
3. Review Documentation Understand API endpoints, request formats, and authentication. BtcTurk API documentation
4. Install SDK (Optional) Install a BtcTurk-supported SDK for your language. BtcTurk SDK section
5. Make First Request Construct and send a simple public or private API call. Your development environment

Create an account and get keys

To interact with the BtcTurk API, you must first create a user account on the BtcTurk platform. This initial step is free and grants access to the user dashboard where API keys can be managed. Account creation typically involves providing an email address and setting a password.

  1. Register for an account: Navigate to the BtcTurk website and complete the registration process. This usually involves providing an email, setting a strong password, and agreeing to terms of service.
  2. Complete identity verification (KYC): BtcTurk, like other regulated financial services, requires users to complete a Know Your Customer (KYC) process to verify identity. This typically involves submitting identification documents and proof of address. The API key generation process is often restricted until this step is completed to comply with financial regulations and prevent illicit activities.
  3. Access API Management: Once your account is verified, log in to your BtcTurk account. In the user dashboard or settings menu, locate the 'API Management' or 'API Keys' section. The exact path may vary but is generally found under security or profile settings.
  4. Generate API Keys: Within the API Management section, you will find an option to generate new API keys. This process typically yields two distinct values: an API Key (sometimes referred to as a Public Key or Client ID) and a Secret Key. The API Key identifies your application, while the Secret Key is used to cryptographically sign your requests, proving their authenticity. The Secret Key should be treated with the same level of security as a password and never exposed in client-side code or public repositories. You may also be prompted to set permissions for the API key, such as read-only access for market data versus full trading access.

It is important to store your Secret Key securely. Best practices for secret management include using environment variables, dedicated secret management services, or secure configuration files, rather than hardcoding them directly into your application code. For further details on secure API key handling, refer to industry standards like those outlined by Google Cloud's authentication documentation.

Your first request

After obtaining your API Key and Secret Key, you can proceed to make your first API request. This example demonstrates how to fetch server time, a common public endpoint that does not require authentication, and then how to make a simple authenticated request.

Public Endpoint Example: Fetching Server Time (Python)

This example uses the Python requests library to query a public endpoint. Public endpoints are useful for retrieving market data without needing authentication.


import requests

def get_server_time():
    url = "https://api.btcturk.com/api/v2/server/time"
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raise an HTTPError for bad responses (4xx or 5xx)
        data = response.json()
        print("Server Time:", data)
        return data
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")
    except requests.exceptions.RequestException as req_err:
        print(f"An error occurred: {req_err}")
    return None

if __name__ == "__main__":
    get_server_time()

Authenticated Endpoint Example: Getting Account Balances (Node.js)

Private endpoints require a signed request. The BtcTurk API uses HMAC-SHA256 for signing. This Node.js example demonstrates how to fetch account balances, which requires authentication.


const axios = require('axios');
const crypto = require('crypto');

const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API Key
const SECRET_KEY = 'YOUR_SECRET_KEY'; // Replace with your actual Secret Key

async function getAccountBalances() {
    const url = 'https://api.btcturk.com/api/v1/users/balances';
    const timestamp = Date.now().toString();
    const signaturePayload = `${API_KEY}${timestamp}`;
    
    // Encode the secret key as a Buffer
    const secretKeyBuffer = Buffer.from(SECRET_KEY, 'base64');

    const hmac = crypto.createHmac('sha256', secretKeyBuffer);
    hmac.update(signaturePayload);
    const signature = hmac.digest('base64');

    try {
        const response = await axios.get(url, {
            headers: {
                'X-PCK': API_KEY,
                'X-Stamp': timestamp,
                'X-Signature': signature,
                'Content-Type': 'application/json'
            }
        });
        console.log('Account Balances:', response.data);
        return response.data;
    } catch (error) {
        console.error('Error fetching account balances:', error.response ? error.response.data : error.message);
        return null;
    }
}

if (API_KEY === 'YOUR_API_KEY' || SECRET_KEY === 'YOUR_SECRET_KEY') {
    console.warn('WARNING: Please replace YOUR_API_KEY and YOUR_SECRET_KEY with your actual credentials.');
} else {
    getAccountBalances();
}

Ensure you replace YOUR_API_KEY and YOUR_SECRET_KEY with your actual credentials obtained from the BtcTurk API Management section. The X-PCK header is your API Key, X-Stamp is the current timestamp in milliseconds, and X-Signature is the HMAC-SHA256 signature of API_KEY + timestamp using your Secret Key.

Common next steps

After successfully making your first API calls, consider these common next steps to expand your integration with BtcTurk:

  • Explore Market Data: Utilize public endpoints to fetch real-time market data, such as order books, ticker information, and historical trades. This data is essential for building trading strategies or displaying current prices.
  • Implement Trading Logic: Develop functions to place limit or market orders, cancel existing orders, and retrieve your open orders. Pay close attention to the parameters required for each order type, such as price, quantity, and order side (buy/sell).
  • Manage Account & Wallets: Integrate features for checking your wallet balances, reviewing transaction history, and potentially initiating withdrawal or deposit requests (if your API key permissions allow).
  • Error Handling and Rate Limits: Implement robust error handling for API responses, including network errors, authentication failures, and API-specific error codes. Familiarize yourself with BtcTurk's API rate limits to avoid temporary bans or service interruptions.
  • Utilize SDKs: If you are working in Python, Java, C#, Node.js, or Go, consider using one of the official or community-supported SDKs. SDKs often abstract away the complexities of request signing, serialization, and error handling, allowing you to focus on your application's core logic.
  • Webhooks and Real-time Updates: Investigate if BtcTurk offers webhook functionality or WebSocket APIs for real-time updates on market events or account activities, which can be more efficient than polling for data.
  • Security Best Practices: Continuously review and apply security best practices for API integrations, including rotating API keys periodically, restricting key permissions to the minimum necessary, and never hardcoding sensitive credentials in publicly accessible code. Consult resources like the OWASP API Security Top 10 for common vulnerabilities and mitigation strategies.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps:

  • Check API Keys: Double-check that your API Key and Secret Key are copied correctly. Even a single character mismatch can lead to authentication failures. Ensure there are no leading or trailing spaces.
  • Signature Mismatch: The most frequent issue with authenticated calls is an incorrect signature. Verify the following:
    • Is the timestamp in milliseconds and consistent between the X-Stamp header and the signature payload?
    • Is the signature payload correctly constructed as API_KEY + timestamp?
    • Is the Secret Key correctly base64 decoded (if applicable, as shown in the Node.js example with Buffer.from(SECRET_KEY, 'base64')) before being used in the HMAC function?
    • Is the HMAC algorithm correctly set to SHA256?
    • Is the final signature base64 encoded?
    Refer to the BtcTurk API documentation on authentication for precise details.
  • Timestamp Skew: Significant differences between your system's time and the BtcTurk server time can cause authentication issues. Ensure your system's clock is synchronized. Some APIs have a maximum allowable time skew.
  • Endpoint URL: Confirm you are using the correct base URL (e.g., https://api.btcturk.com) and the exact endpoint path (e.g., /api/v1/users/balances).
  • HTTP Headers: Ensure all required headers are present and correctly formatted. For authenticated calls, these typically include X-PCK, X-Stamp, X-Signature, and Content-Type (if sending a JSON body).
  • Permissions: If you receive a permission-denied error, check the permissions associated with your API key in your BtcTurk account. Ensure the key has the necessary access rights for the specific endpoint you are trying to call.
  • Network Issues: Verify your internet connection and ensure no firewalls or proxies are blocking your requests to api.btcturk.com.
  • Rate Limits: If you are making many requests in a short period, you might hit a rate limit. Check the API response headers for rate limit information (e.g., X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) and implement appropriate delays or exponential backoff.
  • Consult Documentation and Support: If problems persist, thoroughly review the BtcTurk API documentation, especially the sections on authentication and specific endpoints. If you cannot resolve the issue, contact BtcTurk API support with details of your error messages and request payload.