Signature Code Examples
- Go
- Python
- JavaScript
- cURL
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
const (
APIKey = "your_api_key"
SecretKey = "your_secret_key"
BaseURL = "https://test.test9527.xyz/api/v1/stock/open-api"
)
// sign generates signature
func sign(method, requestPath, queryString, body string, timestamp int64) string {
// Concatenate signature string: timestamp + method + requestPath + queryString + body
timestampStr := strconv.FormatInt(timestamp, 10)
preHash := timestampStr + method + requestPath + queryString + body
// HMAC-SHA256 signature
mac := hmac.New(sha256.New, []byte(SecretKey))
mac.Write([]byte(preHash))
// Base64 encoding
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// request sends POST request
func request(endpoint string, params map[string]interface{}) (map[string]interface{}, error) {
timestamp := time.Now().UnixMilli()
requestPath := "/api/v1/stock/open-api" + endpoint
body, _ := json.Marshal(params)
signature := sign("POST", requestPath, "", string(body), timestamp)
req, _ := http.NewRequest("POST", BaseURL+endpoint, bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("ACCESS-KEY", APIKey)
req.Header.Set("ACCESS-SIGN", signature)
req.Header.Set("ACCESS-TIMESTAMP", strconv.FormatInt(timestamp, 10))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
// requestGET sends GET request
func requestGET(endpoint string, params map[string]interface{}) (map[string]interface{}, error) {
timestamp := time.Now().UnixMilli()
requestPath := "/api/v1/stock/open-api" + endpoint
// Construct query string
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
queryParts := make([]string, 0, len(keys))
for _, k := range keys {
queryParts = append(queryParts, fmt.Sprintf("%s=%v", k, url.QueryEscape(fmt.Sprintf("%v", params[k]))))
}
queryString := "?" + strings.Join(queryParts, "&")
signature := sign("GET", requestPath, queryString, "", timestamp)
req, _ := http.NewRequest("GET", BaseURL+endpoint+queryString, nil)
req.Header.Set("ACCESS-KEY", APIKey)
req.Header.Set("ACCESS-SIGN", signature)
req.Header.Set("ACCESS-TIMESTAMP", strconv.FormatInt(timestamp, 10))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
func main() {
// Example of placing an order
result, _ := request("/order", map[string]interface{}{
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"price": "185.50",
"quantity": "1000",
"clientOid": "test-001",
})
fmt.Printf("%+v\n", result)
// Example of querying depth
depth, _ := requestGET("/depth", map[string]interface{}{
"symbol": "XSM",
"limit": 20,
})
fmt.Printf("%+v\n", depth)
}
import hmac
import hashlib
import base64
import json
import time
import requests
from urllib.parse import urlencode
API_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"
BASE_URL = "https://test.test9527.xyz/api/v1/stock/open-api"
def sign(method: str, request_path: str, query_string: str, body: str, timestamp: int) -> str:
"""Generate signature"""
# Concatenate signature string
pre_hash = f"{timestamp}{method}{request_path}{query_string}{body}"
# HMAC-SHA256 signature
signature = hmac.new(
SECRET_KEY.encode('utf-8'),
pre_hash.encode('utf-8'),
hashlib.sha256
).digest()
# Base64 encoding
return base64.b64encode(signature).decode('utf-8')
def request_post(endpoint: str, params: dict) -> dict:
"""Send POST request"""
timestamp = int(time.time() * 1000)
request_path = "/api/v1/stock/open-api" + endpoint
body = json.dumps(params, separators=(',', ':'))
signature = sign("POST", request_path, "", body, timestamp)
headers = {
"Content-Type": "application/json",
"ACCESS-KEY": API_KEY,
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": str(timestamp),
}
response = requests.post(
f"{BASE_URL}{endpoint}",
headers=headers,
data=body
)
return response.json()
def request_get(endpoint: str, params: dict) -> dict:
"""Send GET request"""
timestamp = int(time.time() * 1000)
request_path = "/api/v1/stock/open-api" + endpoint
# Construct query string (sorted by key, empty if no parameters)
if params:
sorted_params = sorted(params.items())
query_string = "?" + urlencode(sorted_params)
else:
query_string = ""
signature = sign("GET", request_path, query_string, "", timestamp)
headers = {
"ACCESS-KEY": API_KEY,
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": str(timestamp),
}
response = requests.get(
f"{BASE_URL}{endpoint}{query_string}",
headers=headers
)
return response.json()
# Example of placing an order
result = request_post("/order", {
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"price": "185.50",
"quantity": "1000",
"clientOid": "test-001"
})
print(result)
# Example of querying depth
depth = request_get("/depth", {"symbol": "XSM", "limit": 20})
print(depth)
const crypto = require('crypto');
const API_KEY = 'your_api_key';
const SECRET_KEY = 'your_secret_key';
const BASE_URL = 'https://test.test9527.xyz/api/v1/stock/open-api';
/**
* Generate signature
*/
function sign(method, requestPath, queryString, body, timestamp) {
// Concatenate signature string
const preHash = `${timestamp}${method}${requestPath}${queryString}${body}`;
// HMAC-SHA256 signature + Base64 encoding
return crypto
.createHmac('sha256', SECRET_KEY)
.update(preHash)
.digest('base64');
}
/**
* Send POST request
*/
async function requestPost(endpoint, params) {
const timestamp = Date.now();
const requestPath = '/api/v1/stock/open-api' + endpoint;
const body = JSON.stringify(params);
const signature = sign('POST', requestPath, '', body, timestamp);
const response = await fetch(BASE_URL + endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'ACCESS-KEY': API_KEY,
'ACCESS-SIGN': signature,
'ACCESS-TIMESTAMP': timestamp.toString()
},
body: body
});
return response.json();
}
/**
* Send GET request
*/
async function requestGet(endpoint, params) {
const timestamp = Date.now();
const requestPath = '/api/v1/stock/open-api' + endpoint;
// Construct query string (sorted by key, empty if no parameters)
const sortedKeys = Object.keys(params).sort();
const queryString = sortedKeys.length > 0
? '?' + sortedKeys.map(k => `${k}=${encodeURIComponent(params[k])}`).join('&')
: '';
const signature = sign('GET', requestPath, queryString, '', timestamp);
const response = await fetch(BASE_URL + endpoint + queryString, {
method: 'GET',
headers: {
'ACCESS-KEY': API_KEY,
'ACCESS-SIGN': signature,
'ACCESS-TIMESTAMP': timestamp.toString()
}
});
return response.json();
}
// Example of placing an order
(async () => {
const result = await requestPost('/order', {
symbol: 'AAPL',
side: 'buy',
type: 'limit',
price: '185.50',
quantity: '1000',
clientOid: 'test-001'
});
console.log(result);
// Example of querying depth
const depth = await requestGet('/depth', { symbol: 'XSM', limit: 20 });
console.log(depth);
})();
# Calculate signature (example)
# timestamp=1705737600000
# preHash="1705737600000POST/api/v1/stock/open-api/order{\"symbol\":\"AAPL\",\"side\":\"buy\",\"type\":\"limit\",\"price\":\"185.50\",\"quantity\":\"1000\"}"
# signature=HMAC-SHA256(preHash, secretKey) -> Base64
# Place order request
curl -X POST "https://test.test9527.xyz/api/v1/stock/open-api/order" \
-H "Content-Type: application/json" \
-H "ACCESS-KEY: your_api_key" \
-H "ACCESS-SIGN: your_signature" \
-H "ACCESS-TIMESTAMP: 1705737600000" \
-d '{
"symbol": "AAPL",
"side": "buy",
"type": "limit",
"price": "185.50",
"quantity": "1000",
"clientOid": "test-001"
}'
# Query depth request
curl -X GET "https://test.test9527.xyz/api/v1/stock/open-api/depth?limit=20&symbol=XSM" \
-H "ACCESS-KEY: your_api_key" \
-H "ACCESS-SIGN: your_signature" \
-H "ACCESS-TIMESTAMP: 1705737600000"