API Reference

📍Get Started with LTP API V1(Deprecated)

Attention: If your LTP API was opened after 2023-Oct-19th, you will be using the authentication of LTP API V2 only. For users who created their LTP API before 2023-Oct-19th, you can still utilize LTP API V1 for DMA features. If you wish to begin using PB trading, you must first inform your account manager to obtain permission. Afterward, you will need to use the example code of LTP API V2 for authentication.

LTP REST API

https://api.liquiditytech.com

🖍️

Please note that this API document only covers features related to the LTP API. For information on the Exchange API, please refer to the documentation provided by the relevant exchanges.

Third party class libraries involved

    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.5.0</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.14.RELEASE</version>
    </dependency>
requests
json
hashlib
hmac
base64

Code example

package org.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class LtpClient{
    private static final String API_KEY = "abc";
    private static final String SECRET_KEY = "xyz";
    private static final MediaType JSON_TYPE =
            MediaType.parse("application/json");
    private static final String HOST = "https://api.liquiditytech.com";
    private static final DateTimeFormatter DT_FORMAT = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
    private static final ZoneId ZONE_GMT = ZoneId.of("Z");
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .followSslRedirects(false)
            .followRedirects(false)
            .connectTimeout(50000, TimeUnit.MILLISECONDS)
            .readTimeout(50000, TimeUnit.MILLISECONDS)
            .writeTimeout(50000, TimeUnit.MILLISECONDS)
            .build();

    public static void main(String[] args) {
        //Get Demo
        getTradeAccountList()  ;
        //Post Demo
        testTransfer()  ;
    }
    public static void getTradeAccountList() {
        String now = gmtNow();
        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("apiKey", API_KEY);
        paramMap.put("timestamp", now);
        String sign = getSign(paramMap, SECRET_KEY);
        String url = UriComponentsBuilder.fromUriString(HOST+"/api/v1/tradeAccount/list")
                .queryParam("apiKey", API_KEY)
                .queryParam("sign", sign)
                .queryParam("timestamp", now)
                .build().encode().toString();
        Request executeRequest = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(executeRequest).execute();
            System.out.println("getTradeAccountList : " +
                    response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void testTransfer() {
        //applyTransfer
        Long transferId = applyTransfer(81016L, 50005L, "BTC", "0.001");
        System.out.println("transferId:" + transferId);
        //Verify applyTransfer is successful
        while (!getTradeRecord(transferId).getInteger("status").equals(1)) {
            System.out.println("executing transfer... please wait...");
            await(10000L);
        }
        System.out.println("execute finish");
    }

    public static Long applyTransfer(Long fromAccount, Long toAccount, String
            currency, String amount) {
        String url = HOST + "/api/v1/transfer/apply";
        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("apiKey", API_KEY);
        paramMap.put("fromTradeAccountId", fromAccount);
        paramMap.put("toTradeAccountId", toAccount);
        paramMap.put("currency", currency);
        paramMap.put("amount", amount);
        paramMap.put("timestamp", gmtNow());
        String sign = getSign(paramMap, SECRET_KEY);
        paramMap.put("apiKey", API_KEY);
        paramMap.put("sign", sign);
        String jsonBody = JSON.toJSONString(paramMap);
        RequestBody requestBody = RequestBody.create(jsonBody, JSON_TYPE);
        Request executeRequest = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(executeRequest).execute();
            String responseString = response.body().string();
            System.out.println("applyTransfer : " + responseString);
            JSONObject result = JSONObject.parseObject(responseString);
            result.getString("data");
            return (Long) JSONObject.parseObject(result.getString("data")).get("transferId");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
  
    public static JSONObject getTradeRecord(Long transferId) {
        String now = gmtNow();
        SortedMap<String, Object> paramMap = new TreeMap<>();
        paramMap.put("apiKey", API_KEY);
        paramMap.put("transferId", transferId);
        paramMap.put("timestamp", now);
        String sign = getSign(paramMap, SECRET_KEY);
        String url = UriComponentsBuilder.fromUriString(HOST + "/api/v1/transfer/get")
                .queryParam("apiKey", API_KEY)
                .queryParam("sign", sign)
                .queryParam("timestamp", now)
                .queryParam("transferId", transferId)
                .build().encode().toString();
        Request executeRequest = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(executeRequest).execute();
            String responseString = response.body().string();
            System.out.println("getTradeRecord : " + responseString);
            JSONObject result = JSONObject.parseObject(responseString);
            return result.getJSONObject("data");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getSign(Map<String, Object> param, String secretKey) {
        String payload = getPayload(param);
        try {
            return hmacSHA1EncryptString(payload, secretKey);
        } catch (Exception e) {
            throw new RuntimeException("Error generating sign", e);
        }
    }
    public static String getPayload(Map<String, Object> paramMap) {
        if (Objects.isNull(paramMap) || paramMap.size() <= 0) {
            return null;
        }
        StringBuilder buffer = new StringBuilder();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            Object value = entry.getValue();
            if (value != null) {
                buffer.append(entry.getKey()).append("=").append(value.toString()).append("&");
            }
        }
        return buffer.substring(0, buffer.length() - 1);
    }
    public static String hmacSHA1EncryptString(String encryptText, String
            encryptKey) throws Exception {
        return toHexString(hmacSHA1Encrypt(encryptText, encryptKey));
    }
    public static byte[] hmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {
        String MAC_NAME = "HmacSHA256";
        String ENCODING = "UTF-8";
        byte[] data = encryptKey.getBytes(ENCODING);
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        return mac.doFinal(text);
    }
    public static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }
    static String gmtNow() {
        return Instant.now().atZone(ZONE_GMT).format(DT_FORMAT);
    }
    public static void await(Long millis) {
        try {
            System.out.println("thread await : " + millis + "ms");
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

import hashlib
import hmac
import time
import json

import requests


class LtpClient():
    def __init__(self, host, api_key, secret_key):
        self.headers = {
            'user-agent': 'pythonclient/0.0.1',
            "Content-Type": "application/json"
        }
        self.host = host
        self.api_key = api_key
        self.secret_key = secret_key

    def get_trade_account(self):
        url = self.host + "/api/v1/tradeAccount/list"

        params = {
            "apiKey": self.api_key,
            "timestamp": self.get_time_now()
        }

        sign = self.get_signForSha256(params)
        params['sign'] = sign

        try:
            res = requests.get(url=url, params=params)
            print('response ', res, " json ", res.json())
        except Exception as e:
            print('error:{}'.format(e))

    def apply_transfer(self, fromAccount, toAccount, currency, amount):
        url = HOST + "/api/v1/transfer/apply"
        params = {
            "apiKey": API_KEY,
            "timestamp": self.get_time_now(),
            "fromTradeAccountId": fromAccount,
            "toTradeAccountId": toAccount,
            "currency": currency,
            "amount": amount
        }

        sign = self.get_signForSha256(params)
        params['sign'] = sign
        try:
            res = requests.post(url=url, data=json.dumps(params), params=params, headers=self.headers)
            print('response:{}'.format(res), " json ", res.json())
        except Exception as e:
            print('error:{}'.format(e))
            
    def get_time_now(self):
        local_time = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())
        print("time:{}".format(local_time))
        return local_time

    def get_signForSha256(self, param):
        print("param: {}".format(param))
        payload = self.get_payload(param)
        print("payload: {}".format(payload))
        return self.hmac_SHA256_encrypt_string(payload)

    def get_payload(self, param):
        buffer = ''
        for key in sorted(param.keys()): 
            # key is None,continue
            if param[key] is None:
                continue
            buffer += key + "=" + str(param[key]) + "&"
        # remove last &
        return buffer[0:len(buffer) - 1]

    def hmac_SHA256_encrypt_string(self, encryptText):
        return hmac.new(
            self.secret_key.encode('utf-8'),
            msg=encryptText.encode('utf-8'),
            digestmod=hashlib.sha256).hexdigest()


if __name__ == '__main__':
    API_KEY = "abc"
    SECRET_KEY = "xyz"
    HOST = "https://api.liquiditytech.com"

    client = LtpClient(HOST, API_KEY, SECRET_KEY)

    # Get Demo
    client.get_trade_account()
    
    # Post Demo
    client.apply_transfer(123, 789, "USDT", "60")