> For the complete documentation index, see [llms.txt](https://docs.thedex.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thedex.cloud/documentation/api-overview/integration-examples.md).

# Integration Examples

<details>

<summary>Python</summary>

```python
import base64
import hashlib
import hmac
import json
import time

import requests


api_key = ''  # put here your public key
secret_key = ''  # put here your secret key
request = '/api/v1/invoices/create'  # put here request path. For obtaining trading balance use: /api/v1/invoices/create
baseUrl = 'https://sitex.com'  # domain without last slash. Do not use https://sitex.com/
# If the nonce is similar to or lower than the previous request number, you will receive the 'too many requests' error message
nonce = 1000  # nonce is a number (preferrably epoch time in milliseconds) that is always higher than the previous request number
merchantId = ''  # put here your merchant ID

data = {
    'amount': 10,
    'currency': "USD",
    'merchantId': merchantId,
    'request': request,
    'nonce': nonce
}

# preparing request URL
completeUrl = baseUrl + request

data_json = json.dumps(data, separators=(',', ':'))  # use separators param for deleting spaces
payload = base64.b64encode(data_json.encode('ascii'))
signature = hmac.new(secret_key.encode('ascii'), payload, hashlib.sha512).hexdigest()

# preparing headers
headers = {
    'Content-type': 'application/json',
    'X-EX-APIKEY': api_key,
    'X-EX-PAYLOAD': payload,
    'X-EX-SIGNATURE': signature,
}

# sending request
resp = requests.post(completeUrl, headers=headers, data=data_json)

# receiving data
print(json.dumps(resp.json(), sort_keys=True, indent=4))
```

</details>

<details>

<summary>PHP</summary>

```php
<?php
$apiKey = ''; //put here your api key
$apiSecret = ''; //put here your secret key
$merchantId = ''; //put here your merchant ID
$request = '/api/v1/invoices/create'; //put here request path
$baseUrl = 'https://sitex.com'; 

$data = [
    'amount' => '10',
    'currency' => 'USD',
    'merchantId' => $merchantId,
    'title' => 'test',
    'description' => 'test'
];

//preparing request URL
$completeUrl = $baseUrl . $request;
$dataJsonStr = json_encode($data, JSON_UNESCAPED_SLASHES);
$payload = base64_encode($dataJsonStr);
$signature = hash_hmac('sha512', $payload, $apiSecret);

//preparing headers
$headers = [
    'Content-type: application/json',
    'X-EX-APIKEY:'.$apiKey,
    'X-EX-PAYLOAD:'.$payload,
    'X-EX-SIGNATURE:'.$signature
];

$connect = curl_init($completeUrl);
curl_setopt($connect, CURLOPT_POSTFIELDS, $dataJsonStr);
curl_setopt($connect, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connect, CURLOPT_RETURNTRANSFER, true);

$apiResponse = curl_exec($connect);
curl_close($connect);

//receiving data
$jsonArrayResponse = json_decode($apiResponse);
var_dump($jsonArrayResponse);
```

</details>

<details>

<summary>NodeJS</summary>

```javascript
let crypto = require('crypto');
let https = require('https');

let apiKey = ''; //put here your api key
let apiSecret = ''; //put here your secret key
let merchantId = ''; //put here your merchant ID
let request = '/api/v1/invoices/create'; //put here request path
let hostname = 'https://sitex.com';

let data = {
    amount: "10", 
    currency: "USD",
    merchantId: merchantId,
    title: "title",
    description: "description"
}


let dataJsonStr = JSON.stringify(data);
let payload = Buffer.from(dataJsonStr).toString('base64');
let hash = crypto.createHmac('sha512', apiSecret);
let signature = hash.update(payload).digest('hex');

let options = {
    hostname: hostname,
    path: request,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-EX-APIKEY': apiKey,
        'X-EX-PAYLOAD': payload,
        'X-EX-SIGNATURE': signature
    }
}

const req = https.request(options, res => {
    res.setEncoding('utf8')

    console.log(`statusCode: ${res.statusCode}`)

    let responseBody = '';

    res.on('data', chunk => {
        responseBody += chunk;
    });

    res.on('end', () => {
        if (res.statusCode !== 200) {
            console.error("Api call failed with response code", res.statusCode);
        }

        console.log('Body:', responseBody);
    });
})

req.on('error', error => {
    console.error("Request error", error);
})

req.write(dataJsonStr);

req.end();
```

</details>

<details>

<summary>Go</summary>

```go
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha512"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"time"
)

type apiHelper struct {
	PublicKey string
	SecretKey string
	BaseURL   string
}

func (api *apiHelper) SendRequest(requestURL string, data map[string]interface{}) (responseBody []byte, err error) {
	//If the nonce is similar to or lower than the previous request number, you will receive the 'too many requests' error message
	nonce := int(time.Now().Unix()) //nonce is a number that is always higher than the previous request number

	data["request"] = requestURL
	data["nonce"] = strconv.Itoa(nonce)
	data["nonceWindow"] = true //boolean, enable nonce validation in time range of current time +/- 5s, also check if nonce value is unique

	requestBody, err := json.Marshal(data)
	if err != nil {
		return
	}

	//preparing request URL
	completeURL := api.BaseURL + requestURL

	//calculating payload
	payload := base64.StdEncoding.EncodeToString(requestBody)

	//calculating signature using sha512
	h := hmac.New(sha512.New, []byte(api.SecretKey))
	h.Write([]byte(payload))
	signature := fmt.Sprintf("%x", h.Sum(nil))

	client := http.Client{}

	request, err := http.NewRequest("POST", completeURL, bytes.NewBuffer(requestBody))
	if err != nil {
		log.Fatal(err)
	}

	//setting neccessarry headers
	request.Header.Set("Content-type", "application/json")
	request.Header.Set("X-EX-APIKEY", api.PublicKey)
	request.Header.Set("X-EX-PAYLOAD", payload)
	request.Header.Set("X-EX-SIGNATURE", signature)

	//sending request
	response, err := client.Do(request)
	if err != nil {
		return
	}
	defer response.Body.Close()

	//reciving data
	responseBody, err = ioutil.ReadAll(response.Body)

	return
}

func main() {
	provider := apiHelper{
		PublicKey: "",                     //put here your public key
		SecretKey: "",                     //put here your secret key
		BaseURL:   "https://sitex.com", //domain without last slash. Do not use https://sitex.com/
	}

	//put here request path. For obtaining trading balance use: /api/v1/invoices/create
	request := "/api/v1/invoices/create"

	//put here data to send
	data := map[string]interface{}{
		"ticker": "BTC", //for example for obtaining trading balance for BTC currency
	}

	resultData, err := provider.SendRequest(request, data)
	if err != nil {
		log.Fatal(err)
	}

	var result interface{}
	if err := json.Unmarshal(resultData, &result); err != nil {
		log.Fatal(err)
	}

	//printing response body to default output
	log.Println(result)
}
```

</details>

<details>

<summary>Java</summary>

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Formatter;

public class ApiQuickStart {
    private static final String URL = "https://sitex.com"; //API Domain URL
    private static final String METHOD = "/api/v1/balances"; //TODO: Change to the required method
    private static final String SECRET_KEY = "12345eXaMpLeOnlY"; //TODO: Change to yours secret-key
    private static final String API_KEY = "12345eXaMpLeOnlY"; //TODO: Change to yours api-key

    private static final String JSON_REQUEST_METHOD_BODY = ""; // TODO: required JSON for request method.
                                                               //  String is Empty if method does not need any parameter
    private static final long NONCE_ATTRIBUTE = System.currentTimeMillis();

    //Whole JSON request body:
    // "request" attribute contains json body specific to yours request.
    // "nonce"   attribute is a number that is always higher than the previous request number
    private static final String REQUEST_BODY = String.format("{\"request\":\"%1$s\",\"nonce\":\"%2$s\"}", JSON_REQUEST_METHOD_BODY, NONCE_ATTRIBUTE);


    public static void main(String[] args) throws Exception {
        String payload = Base64.getEncoder().encodeToString(REQUEST_BODY.getBytes());
        String signature = calcSignature(payload);

        // I am using the standard HttpClient (You should use your favorite HTTP client library)
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(URL + METHOD))
                .header("Content-type", "application/json")
                .header("X-EX-APIKEY", API_KEY)
                .header("X-EX-PAYLOAD", payload)
                .header("X-EX-SIGNATURE", signature)
                .POST(HttpRequest.BodyPublishers.ofString(REQUEST_BODY))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }

    private static String calcSignature(String data)
            throws NoSuchAlgorithmException, InvalidKeyException {

        final String HMAC_SHA512 = "HmacSHA512";
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), HMAC_SHA512);
        Mac mac = Mac.getInstance(HMAC_SHA512);
        mac.init(secretKeySpec);

        byte[] bytes = mac.doFinal(data.getBytes());
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }

        return formatter.toString();
    }
}
```

</details>

<details>

<summary>Kotlin</summary>

```kotlin
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

private const val API_KEY = "" //TODO: put here your public key
private const val API_SECRET = "" //TODO: put here your secret key

private const val URL = "https://sitex.com" // Domain
private const val BALANCE_METHOD = "/api/v1/invoices/create" // Method

fun main() {
    val ticker = "BTC" // I want to get the balance for the BTC ticker
    val nonce = System.currentTimeMillis() // nonce is a number that is always higher than the previous request number

    // Create Json object (You should use your favorite Json de-serialization library)
    val dataJson = "{\"request\":\"$BALANCE_METHOD\",\"ticker\":\"$ticker\",\"nonce\":\"$nonce\",\"nonceWindow\":true}";

    // Payload and signature
    val payload = Base64.getEncoder().encodeToString(dataJson.toByteArray())
    val signature = calcSignature(payload)

    // I am using the standard HttpClient (You should use your favorite HTTP client library)
    val client = HttpClient.newHttpClient()
    val request = HttpRequest.newBuilder()
            .uri(URI.create(URL + BALANCE_METHOD))
            .header("Content-type", "application/json")
            .header("X-EX-APIKEY", API_KEY)
            .header("X-EX-PAYLOAD", payload)
            .header("X-EX-SIGNATURE", signature)
            .POST(HttpRequest.BodyPublishers.ofString(dataJson))
            .build()

    val response = client.send(request, HttpResponse.BodyHandlers.ofString())
    println(response.body())
}

private fun calcSignature(data: String): String? {
    val HMAC_SHA512 = "HmacSHA512"
    val secretKeySpec = SecretKeySpec(API_SECRET.toByteArray(), HMAC_SHA512)
    val mac = Mac.getInstance(HMAC_SHA512)
    mac.init(secretKeySpec)
    val bytes = mac.doFinal(data.toByteArray())
    val formatter = Formatter()
    for (b in bytes) {
        formatter.format("%02x", b)
    }
    return formatter.toString()
}
```

</details>

<details>

<summary>DotNet</summary>

```csharp
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CreateInvoice
{
    internal class Payload
    {
        [JsonProperty("amount")]
        public string Amount { get; set; }

        [JsonProperty("currency")]
        public string Currency { get; set; }
        
        [JsonProperty("merchantId")]
        public string MerchantId { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }
    }

    internal static class Program
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        private static async Task Main()
        {
            var apiKey = ""; // put here your api key
            var apiSecret = ""; // put here your secret key
            var merchantId = ""; // put here your merchant id
            var request = "/api/v1/invoices/create";
            var hostname = "https://sitex.com";

            var data = new Payload
            {
                Amount = "10",
                Currency = "USD",
                MerchantId = merchantId,
                Title = "Title",
                Description = "Description"
            };

            var dataJsonStr = JsonConvert.SerializeObject(data);
            var payload = Base64Encode(dataJsonStr);
            var signature = CalcSignature(payload, apiSecret);

            var content = new StringContent(dataJsonStr, Encoding.UTF8, "application/json");
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"{hostname}{request}")
            {
                Content = content
            };
            requestMessage.Headers.Add("X-EX-APIKEY", apiKey);
            requestMessage.Headers.Add("X-EX-PAYLOAD", payload);
            requestMessage.Headers.Add("X-EX-SIGNATURE", signature);

            var response = await _httpClient.SendAsync(requestMessage);
            var responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseBody);
        }

        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }

        public static string CalcSignature(string text, string apiSecret)
        {
            using (var hmac = new HMACSHA512(Encoding.UTF8.GetBytes(apiSecret)))
            {
                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(text));
                return BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
            }
        }
    }
}
```

</details>

<details>

<summary>Ruby</summary>

```ruby
require 'json'
require 'base64'
require 'openssl'
require 'net/http'

api_key = '' # put here your public key
api_secret = '' # put here your secret key
base_url = 'https://sitex.com' # domain without last slash. Do not use https://sitex.com/

ticker = 'BTC'
request = '/api/v1/invoices/create' # put here request path. For obtaining trading balance use: /api/v1/invoices/create
nonce = (Time.now.to_f * 1000).to_i
nonce_window = true # boolean, enable nonce validation in time range of current time +/- 5s, also check if nonce value is unique

data = {
    'ticker': ticker,
    'request': request,
    'nonce': nonce,
    'nonceWindow': nonce_window
}

complete_url = base_url + request
data_json_str = data.to_json
payload = Base64.strict_encode64(data_json_str)
signature = OpenSSL::HMAC.hexdigest('SHA512', api_secret, payload)

header = {
    'Content-Type': 'application/json',
    'X-EX-APIKEY': api_key,
    'X-EX-PAYLOAD': payload,
    'X-EX-SIGNATURE': signature
}

uri = URI.parse(complete_url)
request_data = Net::HTTP::Post.new(uri.request_uri, header)
request_data.body = data_json_str
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request_data) }

puts response.code
puts response.message
puts response.body
```

</details>

<details>

<summary>C++</summary>

```cpp
#include <string>
#include <chrono>
#include <curl/curl.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;
using namespace std::chrono;
using namespace boost::archive::iterators;

constexpr string_view public_key = ""; // put here your public key
constexpr string_view secret_key = ""; // put here your secret key

string hmac_hex(const string &msg) {
    unsigned char hash[64];
    HMAC_CTX *hmac = HMAC_CTX_new();
    HMAC_Init_ex(hmac, secret_key.data(), secret_key.length(), EVP_sha512(), nullptr);
    HMAC_Update(hmac, reinterpret_cast<const unsigned char *>(msg.data()), msg.length());
    unsigned int len = 64;
    HMAC_Final(hmac, hash, &len);
    HMAC_CTX_free(hmac);
    std::stringstream ss;
    ss << std::hex << setfill('0');
    for (int i = 0; i < len; i++) {
        ss << std::setw(2) << static_cast<unsigned int> (hash[i]);
    }
    return ss.str();
}

string calculate_payload(const string &data_json) {
    using it_base64_t = base64_from_binary<transform_width<string::const_iterator, 6, 8> >;
    unsigned int write_padd_chars = (3 - data_json.length() % 3) % 3;
    string payload(it_base64_t(data_json.begin()), it_base64_t(data_json.end()));
    payload.append(write_padd_chars, '=');
    return payload;
}

int main() {
    static const string_view method = R"(/api/v1/invoices/create)"; // Method
    static const string_view ticker = "BTC"; // I want to get the balance for the BTC ticker
    auto nonce = duration_cast<milliseconds>(
            system_clock::now().time_since_epoch()
    ); // nonce is a number that is always higher than the previous request number
    static const string_view nonce_window = "true"; //This feature can be useful in high-frequency concurrent systems.

    string data_json = string(R"({"request":")").append(method).
                       append(R"(","ticker":")").append(ticker).
                       append(R"(","nonce":")").append(to_string(nonce.count())).
                       append(R"(","nonceWindow":)").append(nonce_window).
                       append(R"(})");

    // payload and signature
    string payload = calculate_payload(data_json);
    string signature = hmac_hex(payload);

    /* get a curl handle */
    CURL *curl = curl_easy_init();
    if (!curl) {
        cerr << "Failed to initialize curl";
        return -1;
    }

    static const string url = "https://sitex.com"; // Example site
    curl_easy_setopt(curl, CURLOPT_URL, string(url).append(method).c_str());

    curl_slist *chunk = nullptr;

    const string headers[] = {
            "Content-Type:application/json",
            (string("X-EX-APIKEY:").append(public_key)),
            ("X-EX-PAYLOAD:" + payload),
            ("X-EX-SIGNATURE:" + signature)
    };

    for (auto &header: headers) {
        chunk = curl_slist_append(chunk, header.c_str());
    }


    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data_json.c_str());


    CURLcode result_code = curl_easy_perform(curl);
    curl_slist_free_all(chunk);
    /* Check for errors */
    if (result_code != CURLE_OK)
        cout << "curl_easy_perform() failed: \n" << curl_easy_strerror(result_code);

    /* always cleanup */
    curl_easy_cleanup(curl);

    return 0;
}
```

</details>

<details>

<summary>Rust</summary>

<pre class="language-rust"><code class="lang-rust"><strong>extern crate base64;
</strong>
use reqwest::{Client,Error};
use base64::{encode};
use sha2::{Sha512};
use hmac::{Hmac, Mac, NewMac};
use std::string::{String};
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::json;

#[tokio::main]
async fn main() -> Result&#x3C;(), Error> {

    let api_key = "your key";
    let api_secret = "your key";
    let request = "/api/v1/invoices/create";
    let base_url = "https://sitex.com";

    let from_the_epoch = SystemTime::now();

    let nonce = from_the_epoch.duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis()
            .to_string();
    let nonceWindow = true;

    let data = json!({
        "ticker": "BTC",
        "request": request,
        "nonce": &#x26;nonce,
        "nonceWindow": nonceWindow
    });

    let payload = encode(data.to_string());

    type HmacSha512 = Hmac&#x3C;Sha512>;
    let mut mac = HmacSha512::new_from_slice(api_secret.as_bytes())
        .expect("HMAC can take key of any size");
    mac.update(payload.as_bytes());
    let signature_bytes = mac.finalize().into_bytes();
    let mut signature = String::new();
    for byte_entry in &#x26;signature_bytes {
        let hex_byte = format!("{:02x}",byte_entry);
        signature.push_str(&#x26;hex_byte);
    }

    let complete_url = format!("{}{}", base_url, request);

    let client = Client::new();

    let res = client.post(complete_url)
        .json(&#x26;data)
        .header(reqwest::header::CONTENT_TYPE, "application/json")
        .header("X-EX-APIKEY", api_key)
        .header("X-EX-PAYLOAD", payload)
        .header("X-EX-SIGNATURE", signature)
        .send()
        .await
        .unwrap();

    println!("{}", "OK");
    Ok(println!("{}", res.text().await.unwrap()))
}
</code></pre>

</details>
