Skip to main content

Broker Integration Guide

The LBank Broker project is a capability initiative designed specifically for digital currency ecosystem partners. If you are a quant institution, asset management platform, trading tool developer, or traffic aggregation platform, by integrating our API, you can seamlessly embed LBank's strong liquidity and trading depth into your business systems.

Prerequisites​

  • Please contact BD or the support group to apply for a Broker ID and Broker signing credential, and confirm the enabled APIs, source IP, and request quotas.
  • The binding interface requires the user's API Key and signature, which must be obtained through prior user authorization.
  • The target API Key for query and modification requests must belong to a user who has already bound to the current Broker.
  • The API key and private key are used only in a controlled signing environment and are not sent with requests.

Host​

TypeHost
RESThttps://openapi.lbank.com

Protocol and Authentication​

  • Protocol: HTTPS / REST.
  • API version: v3.
  • HTTP Method: POST. Business parameters are passed in the JSON body, not in URL query.
  • Request Headers: Content-Type: application/json. Recommended Accept: application/json.
  • Authentication position for these three management interfaces: brokerAuth / userAuth are located in the JSON body. They follow the signing rules for the management interface described on this page and do not require separate transmission of ex-api-key, ex-timestamp, ex-nonce, ex-signature, ex-broker-id, or ex-broker-sign.
  • Unified response format: code / message / data / extras. Business success when code=200.

Common authentication parameters​

broker authentication object brokerAuth

ParameterTypeRequiredDescription
brokerAuthobjectYesAll three interfaces must provide.
brokerAuth.brokerIdstringYesBroker ID. A string of positive decimal integers without leading zeros, ranging from 1 to 9223372036854775807.
brokerAuth.timestampstringYesUnix epoch in nanoseconds. Must be within an effective window relative to the server time, currently defaulting to ±5 seconds. Clients should maintain clock synchronization.
brokerAuth.noncestringYes16~128 characters of random string, allowing only A-Z, a-z, 0-9, underscore, and hyphen. A new nonce must be generated for each request to the same Broker's interfaces.
brokerAuth.signaturestringYesGenerate HMAC-SHA256 of the normalized request using Broker Secret, output as a 64-bit hexadecimal string, recommended in lowercase.

User Authentication Object (userAuth)

ParameterTypeRequiredDescription
userAuth.apiKeystringBinding endpoint onlyThe authorized API Key bound to the user, 1 to 128 characters long, containing only letters, digits, underscores, and hyphens.
userAuth.signatureMethodstringBinding endpoint onlyCase-sensitive HmacSHA256, SHA256withRSA, or RSASSA-PSS. Use the algorithm enabled for the user’s credential.
userAuth.signaturestringBinding endpoint onlyThe user generates a signature for the same normalized request. HMAC is in hex. RSA/PSS is in Base64.

Common response parameters

{
"code": 200,
"message": "success",
"data": {},
"extras": null
}
FieldTypeDescription
codeintBusiness code; 200 indicates success. The caller must verify this field.
messagestringResult explanation. Business logic is determined by code
dataobjectBusiness result of each interface.
extrasobject / nullextended information, currently usually null. Clients should allow it to be null
  • Normal business responses use HTTP 200. Authentication failure, parameter errors, etc., may also return non-200 business codes. HTTP 200 does not guarantee business success.
  • Network or service entry anomalies may still result in other HTTP status codes or unexpected response formats, which should be handled independently

Signing​

Generate a standardized request body

  1. Prepare complete business fields, brokerAuth.brokerId, timestamp, nonce. For bound interfaces, additionally prepare userAuth.apiKey and signatureMethod.
  2. Remove the brokerAuth.signature and userAuth.signature signature fields. Retain all other specified fields.
  3. All JSON object field names are sorted in ascending order, output as compact UTF-8 JSON without extra spaces or newlines. Array elements retain original order, neither sorted nor deduplicated.
  4. Only send fields defined by the current interface. To modify an interface, the ips must be included in the normalized request body. CLEAR uses an empty array ips: [].
EndpointStandard request body fields
bindbrokerAuth: brokerId、nonce、timestamp. UserAuth: apiKey、signatureMethod.
QueryapiKeys. BrokerAuth: brokerId、nonce、timestamp.
modifyapiKeys. BrokerAuth: brokerId、nonce、timestamp. Ips. Operation.

Generate signature payload

Compute SHA-256 hash of the normalized request body, convert to lowercase hex to obtain bodyHash. Then concatenate the following six items using the actual line feed character LF (0x0A), without adding a newline after the last item:

POST
{path}

{bodyHash}
{timestamp}
{nonce}
  • Item 3 is an empty string, thus there is a blank line between path and bodyHash.
  • path is the actual API endpoint path called, excluding the domain and query. The path must match exactly in case sensitivity and trailing slash.
  • The timestamp and nonce are obtained from brokerAuth. The signing and sending must use the same original values.
  • The signature string uses UTF-8. The bodyHash is derived from the normalized JSON excluding the signed fields. It is not the final HTTP body including the signature.

Calculate and Return Signature

Signature TypeAlgorithmEncoding
BrokerSign the canonical request with HMAC-SHA256 using the Broker Secret.64-bit hex
User HmacSHA256Use the corresponding Secret of the user's API Key to perform HMAC-SHA256 on the original text.64-bit hex
SHA256withRSA used by the userUse the corresponding private key of the registered public key to perform RSASSA-PKCS1-v1_5 / SHA-256 signing.Base64
User RSASSA-PSSUse user's private key. SHA-256, MGF1-SHA256, saltLength=32. Ensure this algorithm is activated prior to use.Base64

Write the Broker signature into brokerAuth.signature. Upon binding the interface, write the user's signature into userAuth.signature. Both signatures are generated from the same original message and do not contain each other's signature values. After refill, no business parameters, timestamps, random strings, or array order may be altered.

Offline reference example

The following are fictitious public demo values for validation and hash checking only. Fixed timestamps are not applicable to real requests. Real calls must regenerate timestamp and nonce.

{"brokerAuth":{"brokerId":"123","nonce":"nonce_0123456789a","timestamp":"1795132800000000000"},"userAuth":{"apiKey":"caller-key","signatureMethod":"HmacSHA256"}}
041e15ab03fdc45f41d89ee31e47743a10c2665b93eeb8aa48fc9c10a35ca467

Anti-replay and retry protection​

  • timestamp uses the current nanosecond timestamp, nonce must be regenerated for each request. Three interfaces under the same Broker should use different nonces.
  • Repeated requests with the same authentication information may be rejected. After business timeout, first verify the status, then retry with new timestamp, nonce, and signature if needed.
  • Binding and setting the same target value has business idempotency, but consumed nonces must not be reused.
  • Setting changes may experience brief propagation delays. Use bounded backoff to avoid infinite retries.

Signing Example​

The following example only implements HmacSHA256 using standard library, without loading credentials or sending network requests. broker_secret and user_secret should be obtained by the caller from secure storage.

"""Broker API HMAC signing helpers. No network or credential loading."""
import copy
import hashlib
import hmac
import json


def canonical_body(request):
body = copy.deepcopy(request)
body['brokerAuth'].pop('signature', None)
if 'userAuth' in body:
body['userAuth'].pop('signature', None)
# Send only the fields defined for this endpoint. Arrays retain their input order.
return json.dumps(body, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')


def canonical_request(path, request):
if not path.startswith('/') or '?' in path or '\n' in path:
raise ValueError('Use the configured HTTP path without a query')
auth = request['brokerAuth']
return '\n'.join(('POST', path, '', hashlib.sha256(canonical_body(request)).hexdigest(),
auth['timestamp'], auth['nonce'])).encode('utf-8')


def sign_hmac(path, request, broker_secret, user_secret=None):
"""Secrets are plaintext UTF-8 values loaded by the caller from controlled storage."""
payload = copy.deepcopy(request)
canonical = canonical_request(path, payload)
payload['brokerAuth']['signature'] = hmac.new(broker_secret.encode('utf-8'), canonical, hashlib.sha256).hexdigest()
if 'userAuth' in payload:
if user_secret is None or payload['userAuth']['signatureMethod'] != 'HmacSHA256':
raise ValueError('The HMAC helper requires the user HMAC credential')
payload['userAuth']['signature'] = hmac.new(user_secret.encode('utf-8'), canonical, hashlib.sha256).hexdigest()
return payload

import secrets
import time

path = "/api/v3/broker/api-key/ips/query"
request = {
"brokerAuth": {
"brokerId": "123",
"timestamp": str(time.time_ns()),
"nonce": secrets.token_urlsafe(24),
},
"apiKeys": ["TARGET_KEY_A"],
}
# Load broker_secret securely outside this example.
# signed_request = sign_hmac(path, request, broker_secret)
# Send signed_request as application/json.

Add userAuth.apiKey and signatureMethod=HmacSHA256 to the request, and pass user_secret to sign_hmac. Update the interface to include operation and ips. Retain ips:[] for CLEAR. Regenerate timestamp, nonce, and two signatures before each request or retry.

Error Code​

Error CodeError MessageMeaningRecommendation for handling
200successsuccess.Read data
1710101Invalid requestRequest fields, formats, or quantities do not meet requirements.corrected request, will not be retried verbatim.
1710102Authentication failedAuthentication failed or credential invalidValidate credentials, algorithm, and normalized signature. Do not retry the same request.
1710103Request expiredRequest time exceeds valid windowSynchronize clock, regenerate timestamp, random string, and signature
1710104Request already usedRequested random string has been used.Generate a new nonce, timestamp, and signature, then proceed based on business status.
1710105Access deniedSource, destination, or operation permission does not meet requirements.Check source IP, binding relationship, and clear permission.
1710106Too many requestsRequest exceeds current quota.Reduce frequency, retry with new authentication parameters after backoff.
1710107Service unavailableTemporarily unavailable.Exponential backoff. Contact support if failures persist