Documentation
API Basic Information
- This
Spot Trading
document lists the REST interface's baseurl ashttps://openapi.fameex.net
. - This
Contract Trading
document lists the REST interface's baseurl ashttps://futuresopenapi.fameex.net
. - All interfaces will return a JSON, object, or array.
- If the response contains an array, the array elements are arranged in reverse chronological order, with earlier data appearing first.
- All times and timestamps are in Unix time, with units in milliseconds.
Document Input Parameter Specifications
Input parameter names marked with a red * indicate that the parameter is mandatory; otherwise, it is optional.
The interface is case-sensitive to input parameter characters, and this will be explicitly stated in the interface.
For example, if the interface requires an uppercase trading pair name, you must input BTCUSDT
; inputting btcusdt
is not allowed.
The document specifies the types of input parameters, and you must input according to the specified type.
For example, the integer
type can only accept numeric inputs;3
is correct, but "3"
is not allowed.
General Interface Information
- All requests are based on the Https protocol, and the
Content-Type
in the request header must be set to:'application/json'
. - For
GET
method interfaces, parameters must be sent in thequery string
. - For
POST
method interfaces, parameters must be sent in therequest body
. - The order of parameters does not matter.
Whether the Interface Requires Signature Verification
Interface types are divided into: public, market, trade, and account.
- Public and market-type interfaces can be accessed without an API-KEY or signature.
- Trade and account security interfaces require API-KEY and signature verification before access.
- The signature content is related to the parameters; if the parameters are input incorrectly, an error or empty value will be returned.
- Interfaces requiring signature verification must include
X-CH-SIGN
,X-CH-APIKEY
, andX-CH-TS
in the Header for verification. -
X-CH-TS
(timestamp) is Unix time, in milliseconds. -
X-CH-APIKEY
is the user'sapiKey
. -
X-CH-SIGN
is the signature encryption key, which is the secretKey.The signature rules and examples can be referenced as follows: Signature Rules, Signature Example(#ExampleWithRequestParameters). - (The
apiKey
andsecretKey
in the document are virtual values; the actual content needs to be obtained by the user through the API management on the front-end page.)
Interface Type | Authentication Type |
---|---|
Public | NONE |
Market | NONE |
Trade | TRADE |
Account | USER_DATA |
Interface Authentication Types
- Each interface has its own authentication type, which determines what kind of authentication should be performed when accessing it.
- If an API-KEY is required, it should be passed in the HTTP header as the
X-CH-APIKEY
field. - API-KEY and API-Secret are case-sensitive.
- You can modify the permissions of the API-KEY in the user center on the web page, such as reading account information, sending trade instructions, and sending withdrawal instructions.
Authentication Type | Description | Header |
---|---|---|
NONE | Interfaces that do not require authentication | |
TRADE | Interfaces that require a valid API-KEY and signature | X-CH-SIGN ,X-CH-APIKEY ,X-CH-TS |
USER_DATA | Interfaces that require a valid API-KEY and signature | X-CH-SIGN ,X-CH-APIKEY ,X-CH-TS |
USER_STREAM | Interfaces that require a valid API-KEY | X-CH-APIKEY ,X-CH-TS |
MARKET_DATA | Interfaces that require a valid API-KEY | X-CH-APIKEY ,X-CH-TS |
Interfaces Requiring Signature (TRADE and USER_DATA)
- When calling
TRADE
orUSER_DATA
interfaces, the signature parameter should be passed in the HTTP header as theX-CH-SIGN
. -
X-CH-SIGN
uses theHMAC SHA256
encryption algorithm, with the API-Secret corresponding to the API-KEY as the key forHMAC SHA256
. - The
X-CH-SIGN
request header uses the (+string concatenation) of timestamp + method + requestPath + body as the object. - The timestamp value is the same as the
X-CH-TS
request header, the method is the request method in uppercase:GET
/POST
. - requestPath is the request interface path, for example:
sapi/v1/order?symbol=ethusdt&orderID=111000111
. -
body
is the string of the request body (post only), and if it is aGET
request,body
can be omitted. - The signature is case-insensitive.
Interface Examples
Below are examples of interfaces, showing the interface format, access links, and parameter descriptions.
GET Example: Get Server Time
GET https://openapi.fameex.net/sapi/v1/time
GET without request parameters
Request Example
GET https://openapi.fameex.net/sapi/v1/time
// Headers
Content-Type:application/json
curl -X GET "https://openapi.fameex.net/sapi/v1/time"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create URL using URI
URI uri = new URI("https://openapi.fameex.net/sapi/v1/time");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://openapi.fameex.net/sapi/v1/time"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read response:", err)
return
}
// Print response
fmt.Println("Server returned:", string(body))
}
import requests
url = "https://openapi.fameex.net/sapi/v1/time"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
<?
$url = "https://openapi.fameex.net/sapi/v1/time";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if API requires)
// Execute request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://openapi.fameex.net/sapi/v1/time';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Response Example
{
"timezone": "China Standard Time",
"serverTime": 1705039779880
}
Response Parameters
Parameter Name | Type | Example | Description |
---|---|---|---|
timezone | string | China Standard Time |
Server timezone |
serverTime | long | 1705039779880 |
Server timestamp |
GET Example: Order Query
GET https://openapi.fameex.net/sapi/v1/order
GET with request parameters
Request Headers
Parameter Name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API-key |
X-CH-TS* | integer | Timestamp |
Request Parameters
Parameter Name | Type | Description |
---|---|---|
orderId* | string | Order ID |
symbol* | string | Lowercase trading pair name, e.g.,ethusdt |
API Data
Key | Value |
---|---|
apiKey |
your API-KEY |
secretKey |
your API-SECRET |
The following is an example of calling the interface to place an order using echo, openssl, and curl tools in a Linux bash environment.(The above apikey
and secretKey
are for demonstration only; please replace them with your real apiKey
and secretKey
)
Request Example
GET https://openapi.fameex.net/sapi/v1/order?orderId=12&symbol=ethusdt
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/order"
QUERY_STRING="?orderId=12&symbol=ethusdt"
# Calculate the full request path
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate current millisecond timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET request has no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debug information**
echo "==== Request Information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (string to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/order";
String queryString = "?orderId=12&symbol=ethusdt";
// Calculate the full request path
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate current millisecond timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET request has no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debug information**
System.out.println("==== Request Information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (string to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/order"
queryString := "?orderId=12&symbol=ethusdt"
// Calculate the full request path
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate current millisecond timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET request has no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debug information**
fmt.Println("==== Request Information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (string to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Calculate HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create a request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Settings Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send the request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read the response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API Related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/order"
QUERY_STRING = "?orderId=12&symbol=ethusdt"
# Calculate the complete request path
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET Request without body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print the response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/order";
$QUERY_STRING = "?orderId=12&symbol=ethusdt";
// Calculate the complete request path
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET Request without body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print the response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/order";
const QUERY_STRING = "?orderId=12&symbol=ethusdt";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debug information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
HMAC-SHA256 Signature example
// Switch to Node.js to view 『JavaScript code (categorized under HTTP)』
# Generate Signature (X-CH-SIGN) - GET Requests Have No Body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
// HMAC-SHA256 Signature Calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Calculate HMAC-SHA256 Signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
# Generate Signature (X-CH-SIGN) - GET Requests Have No Body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
// Generate Signature (X-CH-SIGN) - GET request has no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// Generate Signature (X-CH-SIGN) - GET request has no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// JavaScript code (categorized under HTTP)
let secretKey = pm.environment.get("SecretKey"); // Retrieve API key from environment variables
let timestampString = String(Date.now()); // Generate timestamp (accurate to milliseconds)
let method = pm.request.method; // Get request method (GET, POST, etc.)
let fullUrl = pm.request.url.toString();
let requestPath = "/"+fullUrl.split("/").slice(3).join("/"); // Get the part after `example.com`
// The X-CH-SIGN request header is composed of the string:timestamp + method + requestPath + body (where + represents string concatenation)
// The `body` is the string representation of the request payload (POST only). If it is a GET request, the `body` can be omitted.
let signPayload = timestampString + method.toUpperCase() + requestPath;
if (method.toUpperCase() === "POST") {
let body = pm.request.body ? pm.request.body.raw : null; // Get the request body (if present)
if (body) {
try {
const parsedBody = JSON.parse(body); // Attempt to parse JSON
let bodyString = JSON.stringify(parsedBody);
signPayload += bodyString
} catch (e) {
signPayload += body; // If not JSON, directly append the raw body
}
} else {
console.log("POST method failed to process body data");
}
}
//The signature uses the HMAC-SHA256 algorithm, with the API-Secret corresponding to the API-KEY as the HMAC-SHA256 key.
const crypto = require('crypto-js'); // Load the CryptoJS library.
// Calculate the signature
let signature = crypto.HmacSHA256(signPayload, secretKey).toString(crypto.enc.Hex);
// Set Headers
pm.variables.set('xChTs', timestampString);
pm.variables.set('xChSign', signature);
Return example
{}
POST Example: Create a Test Order
POST https://openapi.fameex.net/sapi/v1/order/test
Request Headers
Parameter Name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request parameters
Parameter name | Example |
---|---|
symbol | BTCUSDT |
side | BUY |
type | LIMIT |
volume | 1 |
price | 9300 |
API Data
Key | Value |
---|---|
apiKey |
your API-KEY |
secretKey |
your API-SECRET |
The following is an example of placing an order by calling an API in a Linux Bash environment using echo
, openssl
, and curl
tools.(The apikey
and secretKey
above are for demonstration purposes only. Please replace them with your actual apiKey
and secretKey
.)
Request Example
POST https://openapi.fameex.net/sapi/v1/order/test
// Headers Set up
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
URL="https://openapi.fameex.net"
REQUEST_PATH="/sapi/v1/order/test"
API_URL="${URL}${REQUEST_PATH}"
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="POST"
# Define the request body (JSON format)
BODY_JSON='{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}'
# Generate signature (X-CH-SIGN)
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}${BODY_JSON}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debug information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request Body: $BODY_JSON"
echo "=================="
# Send request
curl -X POST "$API_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json" \
-d "$BODY_JSON"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Base64;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API Relevant information
String url = "https://openapi.fameex.net";
String requestPath = "/sapi/v1/order/test";
String apiUrl = url + requestPath;
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Get the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "POST";
// Define the request body (JSON format)
String bodyJson = "{\"symbol\":\"BTCUSDT\",\"price\":\"9300\",\"volume\":\"1\",\"side\":\"BUY\",\"type\":\"LIMIT\"}";
// Generate signature (X-CH-SIGN)
String signPayload = timestamp + method + requestPath + bodyJson;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debug information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request Body: " + bodyJson);
System.out.println("==================");
// Send request
sendPostRequest(apiUrl, apiKey, timestamp, signature, bodyJson);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendPostRequest(String apiUrl, String apiKey, String timestamp, String signature, String bodyJson) {
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
conn.setDoOutput(true);
// Send request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = bodyJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API Relevant information
url := "https://openapi.fameex.net"
requestPath := "/sapi/v1/order/test"
apiURL := url + requestPath
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "POST"
// Define the request body (JSON format)
bodyJSON := `{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}`
// Generate Signature (X-CH-SIGN)
signPayload := timestamp + method + requestPath + bodyJSON
signature := hmacSHA256(signPayload, apiSecret)
// **Print debug information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request Body:", bodyJSON)
fmt.Println("==================")
// Send request
sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON)
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP POST request
func sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
import time
import hmac
import hashlib
import requests
import json
# API-related information
URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v1/order/test"
API_URL = URL + REQUEST_PATH
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "POST"
# Define the request body (JSON format)
body_json = {
"symbol": "BTCUSDT",
"price": "9300",
"volume": "1",
"side": "BUY",
"type": "LIMIT"
}
body_str = json.dumps(body_json, separators=(',', ':')) # Ensure the JSON string format is correct
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
# **Print debug information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", sign_payload)
print("Signature (X-CH-SIGN):", signature)
print("Request Body:", body_str)
print("==================")
# Send request
headers = {
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.post(API_URL, headers=headers, data=body_str)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API Relevant information
$url = "https://openapi.fameex.net";
$request_path = "/sapi/v1/order/test";
$api_url = $url . $request_path;
$api_key = "your API-KEY";
$api_secret = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$method = "POST";
// Define the request body (JSON format)
$body_json = json_encode([
"symbol" => "BTCUSDT",
"price" => "9300",
"volume" => "1",
"side" => "BUY",
"type" => "LIMIT"
], JSON_UNESCAPED_SLASHES); // Ensure the JSON format is correct
// Generate signature (X-CH-SIGN)
$sign_payload = $timestamp . $method . $request_path . $body_json;
$signature = hash_hmac('sha256', $sign_payload, $api_secret);
// **Print debug information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $sign_payload . "\n";
echo "Signature (X-CH-SIGN): " . $signature . "\n";
echo "Request Body: " . $body_json . "\n";
echo "==================\n";
// Send request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $signature",
"X-CH-APIKEY: $api_key",
"X-CH-TS: $timestamp"
];
// Use cURL to send a POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_json);
// Execute the request and retrieve the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print the response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v1/order/test";
const API_URL = URL + REQUEST_PATH;
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "POST";
// Define the request body (in JSON format)
const bodyJson = JSON.stringify({
symbol: "BTCUSDT",
price: "9300",
volume: "1",
side: "BUY",
type: "LIMIT",
});
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// **Print debug information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", signPayload);
console.log("Signature (X-CH-SIGN):", signature);
console.log("Request Body:", bodyJson);
console.log("==================");
// Send request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.post(API_URL, bodyJson, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
body
{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}
HMAC-SHA256 Signature example
// Switch to Node.js to view 『JavaScript code (categorized under HTTP)』
# Generate X-CH-SIGN signature command
echo -n "1739520816000POST/sapi/v1/order/test{\"symbol\":\"BTCUSDT\",\"price\":\"9300\",\"volume\":\"1\",\"side\":\"BUY\",\"type\":\"LIMIT\"}" | openssl dgst -sha256 -hmac "709f1e13068f5e51123252d1e6851117"
# Generate X-CH-SIGN signature data
(stdin)= e496db94ec168f23d836d7c7be7223135e6fe6d9593e9c985a9e4017ed78a3f3
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
// Generate signature (X-CH-SIGN)
$sign_payload = $timestamp . $method . $request_path . $body_json;
$signature = hash_hmac('sha256', $sign_payload, $api_secret);
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// JavaScript Code (categorized under HTTP)
let secretKey = pm.environment.get("SecretKey"); // Get API key from environment variables
let timestampString = String(Date.now()); // Generate a timestamp (precise to milliseconds)
let method = pm.request.method; // Get the request method (GET, POST, etc.)
let fullUrl = pm.request.url.toString();
let requestPath = "/"+fullUrl.split("/").slice(3).join("/"); // Get the part after `example.com`
// The `X-CH-SIGN` header is formed by concatenating the string `timestamp + method + requestPath + body` (where `+` indicates string concatenation)
// The `body` is the request body string (for POST requests only). If it's a GET request, the body can be omitted.
let signPayload = timestampString + method.toUpperCase() + requestPath;
if (method.toUpperCase() === "POST") {
let body = pm.request.body ? pm.request.body.raw : null; // Get the request body (if available)
if (body) {
try {
const parsedBody = JSON.parse(body); // Try to parse JSON
let bodyString = JSON.stringify(parsedBody);
signPayload += bodyString
} catch (e) {
signPayload += body; // If it's not JSON, directly append the raw body
}
} else {
console.log("Failed to process body data for POST method");
}
}
// The signature uses the HMAC SHA256 algorithm, with the API-Secret corresponding to the API-KEY as the key for HMAC SHA256.
const crypto = require('crypto-js'); // Load the CryptoJS library
// Calculate the signature
let signature = crypto.HmacSHA256(signPayload, secretKey).toString(crypto.enc.Hex);
// Set up Headers
pm.variables.set('xChTs', timestampString);
pm.variables.set('xChSign', signature);
Return example
{}
HTTP status code types
- The
HTTP 4XX
error codes are used to indicate errors in the request content, behavior, or format. - The
HTTP 429
error code indicates a warning for exceeding the access rate limit, meaning the IP will be blocked soon. -
HTTP 418
indicates that after receiving a429
error, the client continued to make requests, resulting in being blocked. - The
HTTP 5XX
error codes indicate internal server errors; this means the problem is on the server side. When handling this error, never treat it as a failed task because the execution status is unknown—it could be either successful or failed. -
HTTP 504
indicates that the API server has submitted a request to the business core but has not received a response. It is important to note that the504
code does not represent a failed request, but rather an unknown status. It is likely that the request has been executed, but it may also have failed, requiring further confirmation. - Any API may return an ERROR. The error response
payload
is as follows:
Return example
{
"code": -1121,
"msg": "Invalid symbol."
}
For more details, refer to Response Code Types
Access restriction
- Each API will have a rate limit description below it.
- Violating the rate limit will result in receiving an
HTTP 429
error, which is a warning. - When receiving an
HTTP 429
warning, the caller should reduce the access frequency or stop accessing the service.
Time synchronization security
- The signature interfaces require the timestamp to be passed in the HTTP header with the
X-CH-TS
field. Its value should be the Unix timestamp (in milliseconds) at the time the request is sent, e.g.,1528394129373
. - When the server receives a request, it will check the timestamp in the request. If the timestamp is older than
5000
milliseconds, the request will be considered invalid. This time window value can be customized by sending the optional parameterrecvWindow
. - Additionally, if the server calculates that the client’s timestamp is more than one second ahead of the server’s time, the request will also be rejected.
Java Logical Pseudocode:
if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) {
// process request
} else {
// reject request
}
Return Code Type
Description and Causes of Exception Codes and Error Codes
10XX - General Server and Network Errors
Code:-1000 UNKNOWN
Code | Tag | msg | Cause |
---|---|---|---|
1000 | UNKNOWN | An unknown error occurred while processing the request | An unknown error occurred while processing the request |
Code:-1001 DISCONNECTED
Code | Tag | msg | Cause |
---|---|---|---|
1001 | DISCONNECTED | Internal error; unable to process your request. Please try again | Internal error; unable to process your request |
Code:-1002 UNAUTHORIZED
Code | Tag | msg | Cause |
---|---|---|---|
1002 | UNAUTHORIZED | You do not have permission to execute this request. The request requires an API Key. We recommend attaching X-CH-APIKEY in all request headers |
The request header is missing X-CH-APIKEY |
Code:-1003 TOO_MANY_REQUESTS
Code | Tag | msg | Cause |
---|---|---|---|
1003 | TOO_MANY_REQUESTS | The request is too frequent and exceeds the limit | The request is too frequent and exceeds the limit |
Code:-1004 NO_THIS_COMPANY
Code | Tag | msg | Cause |
---|---|---|---|
1004 | NO_THIS_COMPANY | You do not have permission to execute this request. User does not exist | You do not have permission to execute this request. User does not exist |
Code:-1006 UNEXPECTED_RESP
Code | Tag | msg | Cause |
---|---|---|---|
1006 | UNEXPECTED_RESP | The received message does not conform to the preset format, and the order status is unknown | The received message does not conform to the preset format, and the order status is unknown |
Code:-1007 TIMEOUT
Code | Tag | msg | Cause |
---|---|---|---|
1007 | TIMEOUT | Timeout waiting for backend server response. Sending status unknown; execution status unknown | Request timeout |
Code:-1014 UNKNOWN_ORDER_COMPOSITION
Code | Tag | msg | Cause |
---|---|---|---|
1014 | UNKNOWN_ORDER_COMPOSITION | Unsupported order combination | The order combination does not exist or an incorrect order combination was entered |
Code:-1015 TOO_MANY_ORDERS
Code | Tag | msg | Cause |
---|---|---|---|
1015 | TOO_MANY_ORDERS | Too many orders. Please reduce the number of your orders | The order quantity exceeds the maximum limit |
Code:-1016 SERVICE_SHUTTING_DOWN
Code | Tag | msg | Cause |
---|---|---|---|
1016 | SERVICE_SHUTTING_DOWN | Server offline | The server is offline and the interface is unavailable |
Code:-1017 NO_CONTENT_TYPE
Code | Tag | msg | Cause |
---|---|---|---|
1017 | NO_CONTENT_TYPE | We recommend attaching Content-Type in all request headers and setting it to application/json |
The request header is missing Content-Type |
Code:-1020 UNSUPPORTED_OPERATION
Code | Tag | msg | Cause |
---|---|---|---|
1020 | UNSUPPORTED_OPERATION | This operation is not supported | An incorrect request operation was made. You need to coordinate with the technical team to resolve the issue |
Code:-1021 INVALID_TIMESTAMP
Code | Tag | msg | Cause |
---|---|---|---|
1021 | INVALID_TIMESTAMP | Invalid timestamp, the time offset is too large | The timestamp offset is too large. The server determines that the client’s time is more than 1 second ahead of the server’s time based on the timestamp in the request |
Code:-1022 INVALID_SIGNATURE
Code | Tag | msg | Cause |
---|---|---|---|
1022 | INVALID_SIGNATURE | Invalid signature | Signature verification failed |
Code:-1023 UNAUTHORIZED
Code | Tag | msg | Cause |
---|---|---|---|
1023 | UNAUTHORIZED | You do not have permission to execute this request. The request requires a timestamp. We recommend attaching X-CH-TS in all request headers |
The request header is missing X-CH-TS |
Code:-1024 UNAUTHORIZED
Code | Tag | msg | Cause |
---|---|---|---|
1024 | UNAUTHORIZED | You do not have permission to execute this request. The request requires a sign. We recommend attaching X-CH-SIGN in all request headers |
The request header is missing X-CH-SIGN |
11XX - Issue in the request content
Code:-1100 ILLEGAL_CHARS
Code | Tag | msg | Cause |
---|---|---|---|
1100 | ILLEGAL_CHARS | Issue in the request content | Issue in the request content |
Code:-1101 TOO_MANY_PARAMETERS
Code | Tag | msg | Cause |
---|---|---|---|
1101 | TOO_MANY_PARAMETERS | Too many parameters sent | The parameter content is too large or duplicate parameter values have been detected |
Code:-1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED
Code | Tag | msg | Cause |
---|---|---|---|
1102 | MANDATORY_PARAM_EMPTY_OR_MALFORMED | Mandatory parameter {0} was not sent, is empty, or has an incorrect format | The parameter is empty; a required parameter was not provided or has an incorrect input format |
Code:-1103 UNKNOWN_PARAM
Code | Tag | msg | Cause |
---|---|---|---|
1103 | UNKNOWN_PARAM | An unknown parameter was sent | The parameter content or format in the request is incorrect. Please check if the fields contain spaces |
Code:-1104 UNREAD_PARAMETERS
Code | Tag | msg | Cause |
---|---|---|---|
1104 | UNREAD_PARAMETERS | Not all sent parameters were read | Not all sent parameters were read; the parameter '%s' was read, but '%s' was sent |
Code:-1105 PARAM_EMPTY
Code | Tag | msg | Cause |
---|---|---|---|
1105 | PARAM_EMPTY | Parameter {0} is empty | A required parameter is empty |
Code:-1106 PARAM_NOT_REQUIRED
Code | Tag | msg | Cause |
---|---|---|---|
1106 | PARAM_NOT_REQUIRED | This parameter does not need to be sent | The parameter '%s' does not need to be sent |
Code:-1111 BAD_PRECISION
Code | Tag | msg | Cause |
---|---|---|---|
1111 | BAD_PRECISION | The precision exceeds the maximum value defined for this asset | The precision exceeds the maximum value defined for this asset |
Code:-1112 NO_DEPTH
Code | Tag | msg | Cause |
---|---|---|---|
1112 | NO_DEPTH | There are no open orders for the trading pair | The order to be canceled does not exist |
Code:-1116 INVALID_ORDER_TYPE
Code | Tag | msg | Cause |
---|---|---|---|
1116 | INVALID_ORDER_TYPE | Invalid order type | Invalid order type |
Code:-1117 INVALID_SIDE
Code | Tag | msg | Cause |
---|---|---|---|
1117 | INVALID_SIDE | Invalid buy/sell direction | Invalid buy/sell direction |
Code:-1121 BAD_SYMBOL
Code | Tag | msg | Cause |
---|---|---|---|
1121 | BAD_SYMBOL | Invalid contract | Incorrect trading pair name or contract name |
Code:-1136 ORDER_QUANTITY_TOO_SMALL
Code | Tag | msg | Cause |
---|---|---|---|
1136 | ORDER_QUANTITY_TOO_SMALL | The order quantity is less than the minimum value | The order quantity is less than the minimum value |
Code:-1138 ORDER_PRICE_WAVE_EXCEED
Code | Tag | msg | Cause |
---|---|---|---|
1138 | ORDER_PRICE_WAVE_EXCEED | The order price exceeds the allowed range | The order price exceeds the allowed range |
Code:-1139 ORDER_NOT_SUPPORT_MARKET
Code | Tag | msg | Cause |
---|---|---|---|
1139 | ORDER_NOT_SUPPORT_MARKET | This trading pair does not support market orders | This trading pair does not support market orders |
Code:-1145 ORDER_NOT_SUPPORT_CANCELLATION
Code | Tag | msg | Cause |
---|---|---|---|
1145 | ORDER_NOT_SUPPORT_CANCELLATION | The order status does not allow cancellation | The order cannot be canceled |
Code:-1147 PRICE_VOLUME_PRESION_ERROR
Code | Tag | msg | Cause |
---|---|---|---|
1147 | PRICE_VOLUME_PRESION_ERROR | Price or quantity precision exceeds the maximum limit | The order price or quantity exceeds the maximum limit |
2XXX - Other related return codes
Code:-2013 NO_SUCH_ORDER
Code | Tag | msg | Cause |
---|---|---|---|
2013 | NO_SUCH_ORDER | The order does not exist | The order does not exist |
Code:-2015 REJECTED_API_KEY
Code | Tag | msg | Cause |
---|---|---|---|
2015 | REJECTED_API_KEY | Invalid API key, IP, or operation permission | Signature or IP verification failed |
Code:-2016 EXCHANGE_LOCK
Code | Tag | msg | Cause |
---|---|---|---|
2016 | EXCHANGE_LOCK | Trading is frozen | The user's trading is frozen |
Code:-2017 BALANCE_NOT_ENOUGH
Code | Tag | msg | Cause |
---|---|---|---|
2017 | BALANCE_NOT_ENOUGH | Insufficient balance | The user’s account has an insufficient balance |
Code:-2100 PARAM_ERROR
Code | Tag | msg | Cause |
---|---|---|---|
2100 | PARAM_ERROR | Parameter issue | Parameter input error |
Code:-2200 ORDER_CREATE_FAILS
Code | Tag | msg | Cause |
---|---|---|---|
2200 | ORDER_CREATE_FAILS | Illegal IP | Not a trusted IP |
Code:35
Code | Tag | msg | Cause |
---|---|---|---|
35 | Order placement is prohibited | The user's trading may be restricted |
Enumeration type
Trading pair
Value | Description |
---|---|
base |
Refers to the trading asset of a trading pair, specifically the asset name that appears in the front part |
quote |
Refers to the pricing asset of a trading pair, specifically the asset name that appears in the latter part |
Order status
Value | Description |
---|---|
New Order |
Create a new order |
Partially Filled |
Partially filled |
Filled |
Fully filled |
Cancelled |
Canceled |
To be Cancelled |
Canceling |
Partially Filled/Cancelled |
Partially filled/Canceled |
REJECTED |
Order rejected |
Order type
Value | Description |
---|---|
LIMIT |
Limit order |
MARKET |
Market order |
Order direction
Value | Description |
---|---|
BUY |
Buy order |
SELL |
Sell order |
K-line interval
Value | Description | Example |
---|---|---|
min |
Minute | 1min , 5min , 15min , 30min , 60min |
h |
Hour | 1h , 4h |
day |
Day | 1day |
week |
Week | 1week |
month |
Month |
Spot trading
Public
Security type: None
Test connection
GET https://openapi.fameex.net/sapi/v1/ping
Test the connectivity of the REST API
Request example
GET https://openapi.fameex.net/sapi/v1/ping
// Headers Setting
Content-Type:application/json
curl -X GET "https://openapi.fameex.net/sapi/v1/ping"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://openapi.fameex.net/sapi/v1/ping");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://openapi.fameex.net/sapi/v1/ping"
// Send a GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print the response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://openapi.fameex.net/sapi/v1/ping"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
<?
$url = "https://openapi.fameex.net/sapi/v1/ping";
// Initialization cURL
$ch = curl_init();
// Settings cURL Option
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://openapi.fameex.net/sapi/v1/ping';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Return example
{}
Server time
GET https://openapi.fameex.net/sapi/v1/time
Get server time
Request example
GET https://openapi.fameex.net/sapi/v1/time
// Headers Setting
Content-Type:application/json
curl -X GET "https://openapi.fameex.net/sapi/v1/time"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://openapi.fameex.net/sapi/v1/time");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Create a URL using URI.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://openapi.fameex.net/sapi/v1/time"
// Send a GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print the response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://openapi.fameex.net/sapi/v1/time"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
<?
$url = "https://openapi.fameex.net/sapi/v1/time";
// Initialization cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://openapi.fameex.net/sapi/v1/time';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Return example
{
"timezone": "China Standard Time",
"serverTime": 1705039779880
}
Return parameters
parameter name | Type | Example | Description |
---|---|---|---|
timezone | string | China Standard Time |
Server time zone |
serverTime | long | 1705039779880 |
Server timestamp |
Currency Pair List
GET https://openapi.fameex.net/sapi/v1/symbols
Retrieve the set of currency pairs supported by the market
Request Example
GET https://openapi.fameex.net/sapi/v1/symbols
// Headers setting
Content-Type:application/json
curl -X GET "https://openapi.fameex.net/sapi/v1/symbols"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Use URI to create URL
URI uri = new URI("https://openapi.fameex.net/sapi/v1/symbols");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://openapi.fameex.net/sapi/v1/symbols"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://openapi.fameex.net/sapi/v1/symbols"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request is successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
<?
$url = "https://openapi.fameex.net/sapi/v1/symbols";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://openapi.fameex.net/sapi/v1/symbols';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Return example
{
"symbols": [
{
"quantityPrecision": 3,
"limitVolumeMin": 0.0001,
"symbol": "sccadai",
"pricePrecision": 6,
"marketBuyMin": 0.0001,
"marketSellMin": 0.0001,
"baseAsset": "SCCA",
"limitPriceMin": 0.001,
"quoteAsset": "DAI"
},
{
"quantityPrecision": 8,
"limitVolumeMin": 0.0001,
"symbol": "btcusdt",
"pricePrecision": 2,
"marketBuyMin": 0.0001,
"marketSellMin": 0.0001,
"baseAsset": "BTC",
"limitPriceMin": 0.001,
"quoteAsset": "USDT"
},
{
"quantityPrecision": 3,
"limitVolumeMin": 0.0001,
"symbol": "bchusdt",
"pricePrecision": 2,
"marketBuyMin": 0.0001,
"marketSellMin": 0.0001,
"baseAsset": "BCH",
"limitPriceMin": 0.001,
"quoteAsset": "USDT"
},
{
"quantityPrecision": 2,
"limitVolumeMin": 0.0001,
"symbol": "etcusdt",
"pricePrecision": 2,
"marketBuyMin": 0.0001,
"marketSellMin": 0.0001,
"baseAsset": "ETC",
"limitPriceMin": 0.001,
"quoteAsset": "USDT"
},
{
"quantityPrecision": 2,
"limitVolumeMin": 0.0001,
"symbol": "ltcbtc",
"pricePrecision": 6,
"marketBuyMin": 0.0001,
"marketSellMin": 0.0001,
"baseAsset": "LTC",
"limitPriceMin": 0.001,
"quoteAsset": "BTC"
}
]
}
Return parameter
Parameter name | Type | Example | Description |
---|---|---|---|
symbol | string | btcusdt |
Lowercase currency pair name |
baseAsset | string | BTC |
Base currency |
quoteAsset | string | USDT |
Quote currency |
pricePrecision | integer | 6 |
Price precision |
quantityPrecision | integer | 3 |
Quantity precision |
limitVolumeMin | BigDecimal | 0.0001 |
Minimum order quantity limit for limit orders |
marketBuyMin | BigDecimal | 0.0001 |
Minimum purchase quantity for market orders |
marketSellMin | BigDecimal | 0.0001 |
Minimum sell quantity for market orders |
limitPriceMin | BigDecimal | 0.001 |
Minimum price limit for limit orders |
Market data
Security type: None
Order book
GET https://openapi.fameex.net/sapi/v1/depth
Get market order book depth information
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase currency pair name, for example:BTCUSDT |
limit | integer | Default: 100; Maximum: 100 |
Request example
GET https://openapi.fameex.net/sapi/v1/depth?symbol=BTCUSDT&limit=100
// Headers setting
Content-Type: application/json
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/depth"
QUERY_STRING="?symbol=BTCUSDT&limit=100"
# Calculate the complete request path
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# Define request method
METHOD="GET"
# **Print debug information**
echo "==== Request information ===="
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL"
\ -H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/depth";
String queryString = "?symbol=BTCUSDT&limit=100";
// Calculate the full request path
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// Request method
String method = "GET";
// **Print debug information**
System.out.println("==== Request information ====");
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/depth"
queryString := "?symbol=BTCUSDT&limit=100"
// Calculate the full request path
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// Request method
method := "GET"
// **Print debug information**
fmt.Println("==== Request information ====")
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, method)
}
// Send HTTP GET request
func sendGetRequest(fullURL, method string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/depth"
QUERY_STRING = "?symbol=BTCUSDT&limit=100"
# Calculate the complete request path
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# **Print debug information**
print("==== Request information ====")
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/depth";
$QUERY_STRING = "?symbol=BTCUSDT&limit=100";
// Calculate the complete request path
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// **Print debug information**
echo "==== Request information ====\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
];
//Send GET request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute request and get response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/depth";
const QUERY_STRING = "?symbol=BTCUSDT&limit=100";
// Calculate the full request path
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// **Print debug information**
console.log("==== Request information ====");
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Return example
{
"time": 1701658276000,
"bids": [
[
3.90000000, // Price
43.10000000 // Quantity
],
[
4.00000000,
19.20000000
]
],
"asks": [
[
4.00000200, // Price
12.00000000 // Quantity
],
[
5.10000000,
28.00000000
]
]
}
Return parameter
Parameter name | Type | Example | Description |
---|---|---|---|
time | long | 1595563624731 |
Current timestamp |
bids | array | [[3.9,43.1],[4.0,19.2]] |
Order book bid information, the array length is 2, index 1 is the price, type is float; index 2 is the quantity corresponding to the current price, type is float |
asks | array | [[4.0,12.0],[5.1,28.0]] |
Order book ask information, the array length is 2, index 1 is the price, type is float; index 2 is the quantity corresponding to the current price, type is float |
The information corresponding to bids and asks represents all the prices in the order book and the quantities corresponding to those prices, arranged from the best price (highest bid and lowest ask) downwards
Market Ticker
GET https://openapi.fameex.net/sapi/v1/ticker
Get 24-hour price change data
Request example
GET https://openapi.fameex.net/sapi/v1/ticker?symbol=BTCUSDT
// Set Headers
Content-Type: application/json
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/ticker"
QUERY_STRING="?symbol=BTCUSDT"
# Calculate the complete request path
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# Define request method
METHOD="GET"
# **Print debug information**
echo "==== Request information ===="
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/ticker";
String queryString = "?symbol=BTCUSDT";
// Calculate the complete request path
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// Request method
String method = "GET";
// **Print debug information**
System.out.println("==== Request information ====");
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/ticker"
queryString := "?symbol=BTCUSDT"
// Calculate the complete request path
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// Request method
method := "GET"
// **Print debug information**
fmt.Println("==== Request information ====")
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, method)
}
// Send HTTP GET request
func sendGetRequest(fullURL, method string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/ticker"
QUERY_STRING = "?symbol=BTCUSDT"
# Calculate the full request path
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# **Print debug information**
print("==== Request information ====")
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/ticker";
$QUERY_STRING = "?symbol=BTCUSDT";
// Calculate the complete request path
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// **Print debug information**
echo "==== Request information ====\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
];
// Send GET request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute request and get response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/ticker";
const QUERY_STRING = "?symbol=BTCUSDT";
// Calculate the full request path
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// **Print debug information**
console.log("==== Request information ====");
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase currency pair name, for example: BTCUSDT |
Return example
{
"amount": 22400.0,
"high": 9900.51,
"vol": 4691.0,
"last": 9211.60,
"low": 9100.34,
"buy": 9210.0,
"sell": 9213.0,
"rose": "+0.05",
"time": 1595563624731
}
Return parameter
Parameter name | Type | Example | Description |
---|---|---|---|
time | long | 1595563624731 |
Current timestamp |
high | float | 9900.51 |
Highest price |
low | float | 9100.34 |
Lowest price |
last | float | 9211.60 |
Latest trade price |
vol | float | 4691.0 |
Trading volume |
amount | float | 22400.0 |
Transaction Amount |
buy | float | 9210.0 |
Bid price |
sell | float | 9213.0 |
Ask price |
rose | string | +0.05 |
Price change percentage,+ indicates an increase,- indicates a decrease, and +0.05 indicates a5% increase |
Market Ticker-V2
GET https://openapi.fameex.net/v2/public/ticker
Get 24-hour price change data
Request example
GET https://openapi.fameex.net/v2/public/ticker
// Set Headers
Content-Type: application/json
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/v2/public/ticker"
# Calculate the complete request path
REQUEST_PATH="${REQUEST_URL}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# Define request method
METHOD="GET"
# **Print debug information**
echo "==== Request information ===="
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/v2/public/ticker";
// Calculate the complete request path
String requestPath = requestUrl;
String fullUrl = apiUrl + requestPath;
// Request method
String method = "GET";
// **Print debug information**
System.out.println("==== Request information ====");
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/v2/public/ticker"
// Calculate the complete request path
requestPath := requestURL
fullURL := apiURL + requestPath
// Request method
method := "GET"
// **Print debug information**
fmt.Println("==== Request information ====")
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, method)
}
// Send HTTP GET request
func sendGetRequest(fullURL, method string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/v2/public/ticker"
# Calculate the full request path
REQUEST_PATH = REQUEST_URL
FULL_URL = API_URL + REQUEST_PATH
# **Print debug information**
print("==== Request information ====")
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/v2/public/ticker";
// Calculate the complete request path
$REQUEST_PATH = $REQUEST_URL;
$FULL_URL = $API_URL . $REQUEST_PATH;
// **Print debug information**
echo "==== Request information ====\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
];
// Send GET request using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute request and get response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/v2/public/ticker";
// Calculate the full request path
const REQUEST_PATH = REQUEST_URL;
const FULL_URL = API_URL + REQUEST_PATH;
// **Print debug information**
console.log("==== Request information ====");
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Response example
{
"code": "0",
"msg": "Succeed",
"data": {
"MNT_USDT": {
"base_id": "MNT",
"quote_volume": 3049025.662482,
"quote_id": "USDT",
"base_volume": 4123162.07,
"isFrozen": 1,
"last_price": 0.7491
},
"PEPE_USDT": {
"base_id": "PEPE",
"quote_volume": 19215044.55550406,
"quote_id": "USDT",
"base_volume": 2733395751472,
"isFrozen": 1,
"last_price": 0.00000731
}
},
"message": null,
"succ": true
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
code | string | 0 |
Return Code |
msg | string | Succeed |
Return information |
message | string | null |
error message |
succ | boolean | true | Operation ID |
data | object | ||
base_id | string | MNT |
Trading Currency |
quote_id | string | USDT |
Denominated currency |
base_volume | float | 4123162.07 |
Trading Volume |
quote_volume | float | 3049025.662482 |
Transaction Amount |
last_price | float | 0.7491 |
Latest transaction price |
isFrozen | number | 1 |
Freeze flag |
Recent transactions
GET https://openapi.fameex.net/sapi/v1/trades
Get recent transaction data
Request Example
GET https://openapi.fameex.net/sapi/v1/trades?symbol=BTCUSDT&limit=10
// Headers Setup
Content-Type: application/json
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/trades"
QUERY_STRING="?symbol=BTCUSDT&limit=10"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# Define the request method
METHOD="GET"
# **Print debugging information**
echo "==== Request information ===="
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/trades";
String queryString = "?symbol=BTCUSDT&limit=10";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// Request method
String method = "GET";
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Sending a GET request
sendGetRequest(fullUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/trades"
queryString := "?symbol=BTCUSDT&limit=10"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// Request method
method := "GET"
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, method)
}
// Send HTTP GET request
func sendGetRequest(fullURL, method string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/trades"
QUERY_STRING = "?symbol=BTCUSDT&limit=10"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# **Print debugging information**
print("==== Request information ====")
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/trades";
$QUERY_STRING = "?symbol=BTCUSDT&limit=10";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// **Print debugging information**
echo "==== Request information ====\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/trades";
const QUERY_STRING = "?symbol=BTCUSDT&limit=10";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// **Print debugging information**
console.log("==== Request information ====");
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Capitalize the currency pair name, for example: BTCUSDT |
limit | string | Default: 100; Maximum: 1000 |
Response example
[
{
"side": "buy",
"price": 131.0000000000000000,
"qty": 0.1000000000000000,
"time": 1704788645416
},
{
"side": "sell",
"price": 132.0000000000000000,
"qty": 0.2000000000000000,
"time": 1704788282332
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
price | float | 131.0000000000000000 |
Trading price |
time | long | 1704788645416 |
Current timestamp |
qty | float | 0.1000000000000000 |
Quantity (contracts) |
side | string | buy/sell |
Active order direction |
K-line/Candlestick data
GET https://openapi.fameex.net/sapi/v1/klines
Get K-line data
Request Example
GET https://openapi.fameex.net/sapi/v1/klines?symbol=BTCUSDT&interval=1min&limit=5
// request headers
Content-Type: application/json
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/klines"
QUERY_STRING="?symbol=BTCUSDT&interval=1min&limit=5"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# Define the request method
METHOD="GET"
# **Print debugging information**
echo "==== Request information ===="
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send HTTP GET request
curl -X GET "$FULL_URL" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/klines";
String queryString = "?symbol=BTCUSDT&interval=1min&limit=5";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// Request method
String method = "GET";
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
// Send request and get response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/klines"
queryString := "?symbol=BTCUSDT&interval=1min&limit=5"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// Request method
method := "GET"
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, method)
}
// Send HTTP GET request
func sendGetRequest(fullURL, method string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/klines"
QUERY_STRING = "?symbol=BTCUSDT&interval=1min&limit=5"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# **Print debugging information**
print("==== Request information ====")
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/klines";
$QUERY_STRING = "?symbol=BTCUSDT&interval=1min&limit=5";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// **Print debugging information**
echo "==== Request information ====\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send HTTP GET request
$headers = [
"Content-Type: application/json",
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/klines";
const QUERY_STRING = "?symbol=BTCUSDT&interval=1min&limit=5";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// **Print debugging information**
console.log("==== Request information ====");
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, e.g., BTCUSDT |
interval* | string | K-line chart interval, acceptable values:1min ,5min ,15min ,30min ,60min ,1day ,1week ,1month (min = minutes, day = days, week = weeks, month = months) |
limit | integer | Default: 100; Maximum: 300 |
Return example
[
{
"high": 6228.77,
"vol": 2456.11,
"low": 6220.13,
"idx": 1594640340000,
"close": 6225.63,
"open": 6129.41
},
{
"high": 6228.77,
"vol": 1700.21,
"low": 6228.77,
"idx": 1587632160000,
"close": 6228.77,
"open": 6228.77
},
{
"high": 6228.77,
"vol": 1908.52,
"low": 6228.77,
"idx": 1587632100000,
"close": 6228.77,
"open": 6228.77
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
idx | long | 1538728740000 |
Start timestamp |
open | float | 6129.41 |
Opening price |
close | float | 6225.63 |
Closing price |
high | float | 6228.77 |
Highest price |
low | float | 6220.13 |
Lowest price |
vol | float | 2456.11 |
Trading volume |
Trade
Security type: TRADE
Create a new order
POST https://openapi.fameex.net/sapi/v1/order
Rate limit: 100 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v1/order
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
URL="https://openapi.fameex.net"
REQUEST_PATH="/sapi/v1/order"
API_URL="${URL}${REQUEST_PATH}"
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="POST"
# Define request body (JSON format)
BODY_JSON='{"symbol":"BTCUSDT","volume":0.00001,"side":"BUY","type":"LIMIT","price":97081.19,"newClientOrderId":"111000000111"}'
# Generate signature (X-CH-SIGN)
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}${BODY_JSON}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request Body: $BODY_JSON"
echo "=================="
# Send request
curl -X POST "$API_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json" \
-d "$BODY_JSON"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Base64;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String url = "https://openapi.fameex.net";
String requestPath = "/sapi/v1/order";
String apiUrl = url + requestPath;
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Get the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method and path
String method = "POST";
// Define the request body (JSON format)
String bodyJson = "{\"symbol\":\"BTCUSDT\",\"volume\":\"0.00001\",\"side\":\"BUY\",\"type\":\"LIMIT\",\"price\":\"97081.19\",\"newClientOrderId\":\"111000000111\"}";
// Generate signature (X-CH-SIGN)
String signPayload = timestamp + method + requestPath + bodyJson;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request Body: " + bodyJson);
System.out.println("==================");
// Send request
sendPostRequest(apiUrl, apiKey, timestamp, signature, bodyJson);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendPostRequest(String apiUrl, String apiKey, String timestamp, String signature, String bodyJson) {
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
conn.setDoOutput(true);
// Send request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = bodyJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
url := "https://openapi.fameex.net"
requestPath := "/sapi/v1/order"
apiURL := url + requestPath
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method and path
method := "POST"
// Define the request body (JSON format)
bodyJSON := `{"symbol":"BTCUSDT","volume":"0.00001","side":"BUY","type":"LIMIT","price":"97081.19","newClientOrderId":"111000000111"}`
// Generate signature (X-CH-SIGN)
signPayload := timestamp + method + requestPath + bodyJSON
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request Body:", bodyJSON)
fmt.Println("==================")
// Send request
sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON)
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP POST request
func sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
import time
import hmac
import hashlib
import requests
import json
# API-related information
URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v1/order"
API_URL = URL + REQUEST_PATH
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method and path
METHOD = "POST"
# Define the request body (JSON format)
body_json = {
"symbol": "BTCUSDT",
"volume": "0.00001",
"side": "BUY",
"type": "LIMIT",
"price": "97081.19",
"newClientOrderId": "111000000111",
}
body_str = json.dumps(body_json, separators=(',', ':')) # Ensure the JSON string is correctly formatted
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", sign_payload)
print("Signature (X-CH-SIGN):", signature)
print("Request Body:", body_str)
print("==================")
# Send request
headers = {
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.post(API_URL, headers=headers, data=body_str)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$url = "https://openapi.fameex.net";
$request_path = "/sapi/v1/order";
$api_url = $url . $request_path;
$api_key = "your API-KEY";
$api_secret = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$method = "POST";
// Define request body (JSON format)
$body_json = json_encode([
"symbol" => "BTCUSDT",
"price" => "9300",
"volume" => "1",
"side" => "BUY",
"type" => "LIMIT"
], JSON_UNESCAPED_SLASHES); // Ensure the JSON format is correct
// Generate signature (X-CH-SIGN)
$sign_payload = $timestamp . $method . $request_path . $body_json;
$signature = hash_hmac('sha256', $sign_payload, $api_secret);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $sign_payload . "\n";
echo "Signature (X-CH-SIGN): " . $signature . "\n";
echo "Request Body: " . $body_json . "\n";
echo "==================\n";
// Send request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $signature",
"X-CH-APIKEY: $api_key",
"X-CH-TS: $timestamp"
];
// Use cURL to send a POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_json);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v1/order";
const API_URL = URL + REQUEST_PATH;
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "POST";
// Define request body (JSON format)
const bodyJson = JSON.stringify({
symbol: "BTCUSDT",
price: "9300",
volume: "1",
side: "BUY",
type: "LIMIT",
});
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", signPayload);
console.log("Signature (X-CH-SIGN):", signature);
console.log("Request Body:", bodyJson);
console.log("==================");
// Send request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.post(API_URL, bodyJson, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
body
{"symbol":"BTCUSDT","volume":1.00,"side":"BUY","type":"LIMIT","price":65000.00,"newClientOrderId":"111000000111"}
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, e.g.,BTCUSDT (refer to Trading Pair List forsymbol ) |
volume* | number | Order quantity, with precision restrictions configured by the administrator (refer to[Trading Pair List]for limitVolumeMin ) |
side* | string | Order direction,BUY/SELL |
type* | string | Order type,LIMIT/MARKET |
price | number | Order price, required forLIMIT orders, with precision restrictions configured by the administrator (refer to[Recent Transactions]forprice ) |
newClientOrderId | string | Client order ID |
Response example
{
"symbol": "BTCUSDT",
"side": "BUY",
"executedQty": 0,
"orderId": [
"2618039663715064005"
],
"price": 97081.19,
"origQty": 0.00001,
"clientOrderId": "111000000111",
"transactTime": 1739867150800,
"type": "LIMIT",
"status": "NEW"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 2012274607240433332 |
Order ID (system-generated) |
clientOrderId | string | 213443 |
Order ID (user-generated) |
symbol | string | BTCUSDT |
Uppercase trading pair name |
transactTime | integer | 1704959985403 |
Order creation timestamp |
price | float | 47651.29 |
Order price |
origQty | float | 0.01 |
Order quantity |
executedQty | float | 0 |
Filled order quantity |
type | string | LIMIT |
Order type. Possible values:LIMIT (Limit Order) andMARKET (Market Order) |
side | string | BUY |
Order direction. Possible values:BUY (Long) andSELL (Short). |
status | string | NEW |
Order status. Possible values:New Order (New order, no fills),Partially Filled (Partially filled),Filled (Completely filled) |
Create a new order-V2
POST https://openapi.fameex.net/sapi/v2/order
Rate limit: 100 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v2/order
body
{"symbol":"BTCUSDT","volume":"1.00","side":"BUY","type":"LIMIT","price":"65000.00","newClientOrderId":"111000000111"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/sapi/v2/order"
# Request body (in JSON format)
body='{"symbol":"BTCUSDT","volume":"1.00","side":"BUY","type":"LIMIT","price":"65000.00","newClientOrderId":"111000000111"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send POST request
response=$(curl -s -X POST "https://openapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://openapi.fameex.net";
private static final String REQUEST_PATH = "/sapi/v2/order";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{\"symbol\":\"BTCUSDT\",\"volume\":\"1.00\",\"side\":\"BUY\",\"type\":\"LIMIT\",\"price\":\"65000.00\",\"newClientOrderId\":\"111000000111\"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data The string to be signed
* @param secret The secret key
* @return HMAC SHA256 signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://openapi.fameex.net"
RequestPath = "/sapi/v2/order"
)
func main() {
// Get millisecond timestamp
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"symbol":"BTCUSDT","volume":"1.00","side":"BUY","type":"LIMIT","price":"65000.00","newClientOrderId":"111000000111"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send POST request.
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v2/order"
# Request method and request body
method = "POST"
body = {"symbol":"BTCUSDT","volume":"1.00","side":"BUY","type":"LIMIT","price":"65000.00","newClientOrderId":"111000000111"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body into a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API-KEY";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://openapi.fameex.net";
$requestPath = "/sapi/v2/order";
// Request method and request body
$method = "POST";
$body = json_encode([
"symbol"=> "BTCUSDT",
"volume"=> 1.00,
"side"=> "BUY",
"type"=> "LIMIT",
"price"=> 65000.00,
"newClientOrderId"=> "111000000111"
], JSON_UNESCAPED_SLASHES);
//Get millisecond timestamp
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Use only in the development environment; SSL verification should be enabled in the production environment
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v2/order";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
"symbol": "BTCUSDT",
"volume": 1.00,
"side": "BUY",
"type": "LIMIT",
"price": 65000.00,
"newClientOrderId": "111000000111"
});
// Get millisecond timestamp
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, e.g.,BTCUSDT (refer to Trading Pair List forsymbol ) |
volume* | number | Order quantity, with precision restrictions configured by the administrator (refer to[Trading Pair List]for limitVolumeMin ) |
side* | string | Order direction,BUY/SELL |
type* | string | Order type,LIMIT/MARKET |
price | number | Order price, required forLIMIT orders, with precision restrictions configured by the administrator (refer to[Recent Transactions]forprice ) |
newClientOrderId | string | Client order ID |
Response example
{
"symbol": "ETHUSDT",
"side": "BUY",
"executedQty": 0,
"orderId": [
"2012274607240433332"
],
"price": 47651.29,
"origQty": 0.01,
"clientOrderId": "213443",
"transactTime": 1704959985403,
"type": "MARKET",
"status": "NEW"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 2012274607240433332 |
Order ID (system-generated) |
clientOrderId | string | 213443 |
Order ID (user-generated) |
symbol | string | BTCUSDT |
Uppercase trading pair name |
transactTime | integer | 1704959985403 |
Order creation timestamp |
price | float | 47651.29 |
Order price |
origQty | float | 0.01 |
Order quantity |
executedQty | float | 0 |
Filled order quantity |
type | string | LIMIT |
Order type. Possible values:LIMIT (Limit Order) andMARKET (Market Order) |
side | string | BUY |
Order direction. Possible values:BUY (Long) andSELL (Short). |
status | string | NEW |
Order status. Possible values:New Order (New order, no fills),Partially Filled (Partially filled),Filled (Completely filled) |
Create a test order
POST https://openapi.fameex.net/sapi/v1/order/test
Create and validate a new order, but it will not be sent to the matching engine
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v1/order/test
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
URL="https://openapi.fameex.net"
REQUEST_PATH="/sapi/v1/order/test"
API_URL="${URL}${REQUEST_PATH}"
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="POST"
# Define the request body (JSON format)
BODY_JSON='{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}'
# Generate signature (X-CH-SIGN)
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}${BODY_JSON}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request Body: $BODY_JSON"
echo "=================="
# Send request
curl -X POST "$API_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json" \
-d "$BODY_JSON"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Base64;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String url = "https://openapi.fameex.net";
String requestPath = "/sapi/v1/order/test";
String apiUrl = url + requestPath;
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Get the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "POST";
// Define the request body (JSON format)
String bodyJson = "{\"symbol\":\"BTCUSDT\",\"price\":\"9300\",\"volume\":\"1\",\"side\":\"BUY\",\"type\":\"LIMIT\"}";
// Generate signature (X-CH-SIGN)
String signPayload = timestamp + method + requestPath + bodyJson;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request Body: " + bodyJson);
System.out.println("==================");
// Send request
sendPostRequest(apiUrl, apiKey, timestamp, signature, bodyJson);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendPostRequest(String apiUrl, String apiKey, String timestamp, String signature, String bodyJson) {
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
conn.setDoOutput(true);
// Send request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = bodyJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
url := "https://openapi.fameex.net"
requestPath := "/sapi/v1/order/test"
apiURL := url + requestPath
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "POST"
// Define the request body (JSON format)
bodyJSON := `{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}`
// Generate signature (X-CH-SIGN)
signPayload := timestamp + method + requestPath + bodyJSON
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request Body:", bodyJSON)
fmt.Println("==================")
// Send request
sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON)
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP POST request
func sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
import time
import hmac
import hashlib
import requests
import json
# API-related information
URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v1/order/test"
API_URL = URL + REQUEST_PATH
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "POST"
# Define the request body (JSON format)
body_json = {
"symbol": "BTCUSDT",
"price": "9300",
"volume": "1",
"side": "BUY",
"type": "LIMIT"
}
body_str = json.dumps(body_json, separators=(',', ':')) # Ensure the JSON string format is correct
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", sign_payload)
print("Signature (X-CH-SIGN):", signature)
print("Request Body:", body_str)
print("==================")
# Send request
headers = {
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.post(API_URL, headers=headers, data=body_str)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$url = "https://openapi.fameex.net";
$request_path = "/sapi/v1/order/test";
$api_url = $url . $request_path;
$api_key = "your API-KEY";
$api_secret = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$method = "POST";
// Define the request body (JSON format)
$body_json = json_encode([
"symbol" => "BTCUSDT",
"price" => "9300",
"volume" => "1",
"side" => "BUY",
"type" => "LIMIT"
], JSON_UNESCAPED_SLASHES); // Ensure the JSON format is correct
// Generate signature (X-CH-SIGN)
$sign_payload = $timestamp . $method . $request_path . $body_json;
$signature = hash_hmac('sha256', $sign_payload, $api_secret);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $sign_payload . "\n";
echo "Signature (X-CH-SIGN): " . $signature . "\n";
echo "Request Body: " . $body_json . "\n";
echo "==================\n";
// Send request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $signature",
"X-CH-APIKEY: $api_key",
"X-CH-TS: $timestamp"
];
// Use cURL to send a POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_json);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v1/order/test";
const API_URL = URL + REQUEST_PATH;
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "POST";
// Define the request body (JSON format)
const bodyJson = JSON.stringify({
symbol: "BTCUSDT",
price: "9300",
volume: "1",
side: "BUY",
type: "LIMIT",
});
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", signPayload);
console.log("Signature (X-CH-SIGN):", signature);
console.log("Request Body:", bodyJson);
console.log("==================");
// Send request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.post(API_URL, bodyJson, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
body
{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, such asBTCUSDT (refer to Trading Pair List forsymbol ) |
volume* | number | Order quantity, with precision limits configured by the administrator (refer to Trading Pair List forlimitVolumeMin ) |
side* | string | Order direction,BUY/SELL |
type* | string | Order type, LIMIT/MARKET |
price | number | Order price, required forLIMIT orders. It has precision limits configured by the administrator (refer to[Recent Transactions]forprice ) |
newClientOrderId | string | Client order identifier |
Response example
{}
Order query
GET https://openapi.fameex.net/sapi/v1/order
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v1/order?orderId=2618039663715064005&symbol=btcusdt
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/order"
QUERY_STRING="?orderId=2618039663715064005&symbol=btcusdt"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/order";
String queryString = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send the request and get the response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/order"
queryString := "?orderId=2618039663715064005&symbol=btcusdt"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/order"
QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/order";
$QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/order";
const QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
orderId* | string | Order ID (system-generated) |
symbol* | string | Lowercase trading pair name, such asethusdt |
Response example
{
"symbol": "btcusdt",
"side": "BUY",
"executedQty": 0E-16,
"orderId": 2618039663715064005,
"price": 97081.1900000000000000,
"origQty": 0.0000100000000000,
"avgPrice": 0E-16,
"transactTime": 1739867150753,
"type": "LIMIT",
"status": "New Order"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 150695552109032492 |
Order ID (system-generated) |
clientOrderId | string | 213443 |
Order ID (user-generated) |
symbol | string | ethusdt |
Lowercase trading pair name |
price | float | 4765.29 |
Order price |
origQty | float | 1.01 |
Order quantity |
executedQty | float | 0 |
Filled order quantity |
avgPrice | float | 4754.24 |
The average price of the filled order |
type | string | LIMIT |
Order type. Possible values are:LIMIT (Limit Order) andMARKET (Market Order) |
transactTime | long | 1672274311107 |
Timestamp |
side | string | BUY |
Order direction. Possible values are:BUY (Buy/Long) andSELL (Sell/Short) |
status | string | New Order |
Order status. Possible values are:New Order (New order, no fills),Partially Filled (Partially filled),Filled (Fully filled) |
订单查询-V2
GET https://openapi.fameex.net/sapi/v2/order
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v2/order?orderId=2618039663715064005&symbol=btcusdt
// request headers
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v2/order"
QUERY_STRING="?orderId=2618039663715064005&symbol=btcusdt"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v2/order";
String queryString = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v2/order"
queryString := "?orderId=2618039663715064005&symbol=btcusdt"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v2/order"
QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v2/order";
$QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v2/order";
const QUERY_STRING = "?orderId=2618039663715064005&symbol=btcusdt";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
orderId* | string | Order ID (system-generated) |
symbol* | string | Lowercase trading pair name, such asethusdt |
Response example
{
"symbol": "ethusdt",
"side": "BUY",
"executedQty": 0,
"orderId": "150695552109032492",
"price": 4765.29,
"origQty": 1.01,
"avgPrice": 4754.24,
"transactTime": 1672274311107,
"type": "LIMIT",
"status": "New Order"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 150695552109032492 |
Order ID (system-generated) |
clientOrderId | string | 213443 |
Order ID (user-generated) |
symbol | string | ethusdt |
Lowercase trading pair name |
price | float | 4765.29 |
Order price |
origQty | float | 1.01 |
Order quantity |
executedQty | float | 0 |
Filled order quantity |
avgPrice | float | 4754.24 |
The average price of the filled order |
type | string | LIMIT |
Order type. Possible values are:LIMIT (Limit Order) andMARKET (Market Order) |
transactTime | long | 1672274311107 |
Timestamp |
side | string | BUY |
Order direction. Possible values are:BUY (Buy/Long) andSELL (Sell/Short) |
status | string | New Order |
Order status. Possible values are:New Order (New order, no fills),Partially Filled (Partially filled),Filled (Fully filled) |
Cancel order
POST https://openapi.fameex.net/sapi/v1/cancel
Rate limit rule: 100 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v1/cancel
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739945835000
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 3c22ee3d2940df5e9dc5b7b862ba3d75e805e97a242f52f12fec9d16bc73e1c7
#!/bin/bash
# Set API-related information
URL="https://openapi.fameex.net"
REQUEST_PATH="/sapi/v1/cancel"
API_URL="${URL}${REQUEST_PATH}"
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="POST"
# Define the request body (JSON format)
BODY_JSON='{"symbol":"btcusdt","orderId":"2618039663715064005"}'
# Generate signature (X-CH-SIGN)
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}${BODY_JSON}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request Body: $BODY_JSON"
echo "=================="
# Send request
curl -X POST "$API_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json" \
-d "$BODY_JSON"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Base64;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String url = "https://openapi.fameex.net";
String requestPath = "/sapi/v1/cancel";
String apiUrl = url + requestPath;
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Get the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "POST";
// Define the request body (JSON format)
String bodyJson = "{\"symbol\":\"btcusdt\",\"orderId\":\"2618039663715064005\"";
// Generate signature (X-CH-SIGN)
String signPayload = timestamp + method + requestPath + bodyJson;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request Body: " + bodyJson);
System.out.println("==================");
// Send request
sendPostRequest(apiUrl, apiKey, timestamp, signature, bodyJson);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendPostRequest(String apiUrl, String apiKey, String timestamp, String signature, String bodyJson) {
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
conn.setDoOutput(true);
// Send request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = bodyJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
url := "https://openapi.fameex.net"
requestPath := "/sapi/v1/cancel"
apiURL := url + requestPath
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "POST"
// Define the request body (JSON format)
bodyJSON := `{"symbol":"btcusdt","orderId":"2618039663715064005"}`
// Generate signature (X-CH-SIGN)
signPayload := timestamp + method + requestPath + bodyJSON
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request Body:", bodyJSON)
fmt.Println("==================")
// Send request
sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON)
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP POST request
func sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
import time
import hmac
import hashlib
import requests
import json
# API-related information
URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v1/cancel"
API_URL = URL + REQUEST_PATH
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "POST"
# Define the request body (JSON format)
body_json = {
"symbol": "btcusdt",
"orderId": "2618039663715064005"
}
body_str = json.dumps(body_json, separators=(',', ':')) # Ensure the JSON string format is correct
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", sign_payload)
print("Signature (X-CH-SIGN):", signature)
print("Request Body:", body_str)
print("==================")
# Send request
headers = {
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.post(API_URL, headers=headers, data=body_str)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$url = "https://openapi.fameex.net";
$request_path = "/sapi/v1/cancel";
$api_url = $url . $request_path;
$api_key = "your API-KEY";
$api_secret = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$method = "POST";
// Define the request body (JSON format)
$body_json = json_encode([
"symbol" => "btcusdt",
"orderId" => "2618039663715064005"
], JSON_UNESCAPED_SLASHES); // Ensure the JSON format is correct
// Generate signature (X-CH-SIGN)
$sign_payload = $timestamp . $method . $request_path . $body_json;
$signature = hash_hmac('sha256', $sign_payload, $api_secret);
// **Print debugging information**
echo "==== Request information息 ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $sign_payload . "\n";
echo "Signature (X-CH-SIGN): " . $signature . "\n";
echo "Request Body: " . $body_json . "\n";
echo "==================\n";
// Send request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $signature",
"X-CH-APIKEY: $api_key",
"X-CH-TS: $timestamp"
];
// Use cURL to send a POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_json);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v1/cancel";
const API_URL = URL + REQUEST_PATH;
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "POST";
// Define the request body (JSON format)
const bodyJson = JSON.stringify({
symbol: "btcusdt",
orderId: "2618039663715064005",
});
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", signPayload);
console.log("Signature (X-CH-SIGN):", signature);
console.log("Request Body:", bodyJson);
console.log("==================");
// Send request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.post(API_URL, bodyJson, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
body
{"symbol":"btcusdt","orderId":"2618039663715064005"}
Request parameters
Parameter name | Type | Description |
---|---|---|
orderId* | string | Order ID (system-generated) |
symbol* | string | Lowercase trading pair name, such asethusdt |
Response example
{
"symbol": "btcusdt",
"orderId": [
"2618039663715064005"
],
"status": "PENDING_CANCEL"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 1938321163093079425 |
Order ID (system-generated) |
symbol | string | ethusdt |
Trading pair name |
status | string | PENDING_CANCEL |
Order status:PENDING_CANCEL |
Cancel order-V2
POST https://openapi.fameex.net/sapi/v2/cancel
Rate limit: 100 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v2/cancel
body
{"symbol": "ethusdt","orderId": "111000111"}
#!/bin/bash
# API-related information
api_key="your API-KEY"
api_secret="your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/sapi/v2/cancel"
# Request body (in JSON format)
body='{"symbol": "ethusdt","orderId": "111000111"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send POST request
response=$(curl -s -X POST "https://openapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "your API-KEY";
private static final String API_SECRET = "your API-SECRET";
private static final String BASE_URL = "https://openapi.fameex.net";
private static final String REQUEST_PATH = "/sapi/v2/cancel";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{\"symbol\":\"ethusdt\",\"orderId\":\"111000111\"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "your API-KEY"
APISecret = "your API-SECRET"
BaseURL = "https://openapi.fameex.net"
RequestPath = "/sapi/v2/cancel"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"symbol": "ethusdt","orderId": "111000111"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
BASE_URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v2/cancel"
# Request method and request body
method = "POST"
body = {"symbol": "ethusdt","orderId": "111000111"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "your API-KEY";
$apiSecret = "your API-SECRET";
$baseUrl = "https://openapi.fameex.net";
$requestPath = "/sapi/v2/cancel";
// Request method and request body
$method = "POST";
$body = json_encode([
"symbol"=> "ethusdt",
"orderId"=> "111000111"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
const BASE_URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v2/cancel";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
"symbol": "ethusdt",
"orderId": "111000111"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
orderId* | string | Order ID (system-generated) |
symbol* | string | Lowercase trading pair name, such asethusdt |
Response example
{
"symbol": "ethusdt",
"orderId": [
"1938321163093079425"
],
"status": "PENDING_CANCEL"
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 1938321163093079425 |
Order ID (system-generated) |
symbol | string | ethusdt |
Trading pair name |
status | string | PENDING_CANCEL |
Order status:PENDING_CANCEL |
Bulk cancel orders
POST https://openapi.fameex.net/sapi/v1/batchCancel
Rate limit rule: 50 requests per 2 seconds, with a maximum of 10 orders per batch
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://openapi.fameex.net/sapi/v1/batchCancel
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739945835000
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 3c22ee3d2940df5e9dc5b7b862ba3d75e805e97a242f52f12fec9d16bc73e1c7
#!/bin/bash
# Set API-related information
URL="https://openapi.fameex.net"
REQUEST_PATH="/sapi/v1/batchCancel"
API_URL="${URL}${REQUEST_PATH}"
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="POST"
# Define the request body (JSON format)
BODY_JSON='{"symbol":"BTCUSDT","orderId":["111000111","111000112"]}'
# Generate signature (X-CH-SIGN)
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}${BODY_JSON}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request Body: $BODY_JSON"
echo "=================="
# Send request
curl -X POST "$API_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json" \
-d "$BODY_JSON"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.io.OutputStream;
import java.time.Instant;
import java.util.Base64;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String url = "https://openapi.fameex.net";
String requestPath = "/sapi/v1/batchCancel";
String apiUrl = url + requestPath;
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Get the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "POST";
// Define the request body (JSON format)
String bodyJson = "{\"symbol\":\"BTCUSDT\",\"orderId\":[\"111000111\",\"111000112\"]}";
// Generate signature (X-CH-SIGN)
String signPayload = timestamp + method + requestPath + bodyJson;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request Body: " + bodyJson);
System.out.println("==================");
// Send request
sendPostRequest(apiUrl, apiKey, timestamp, signature, bodyJson);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 Signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP POST request
public static void sendPostRequest(String apiUrl, String apiKey, String timestamp, String signature, String bodyJson) {
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
conn.setDoOutput(true);
// Send request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = bodyJson.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
url := "https://openapi.fameex.net"
requestPath := "/sapi/v1/batchCancel"
apiURL := url + requestPath
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "POST"
// Define the request body (JSON format)
bodyJSON := `{"symbol":"BTCUSDT","orderId":["111000111","111000112"]}`
// Generate signature (X-CH-SIGN)
signPayload := timestamp + method + requestPath + bodyJSON
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request Body:", bodyJSON)
fmt.Println("==================")
// Send request
sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON)
}
// HMAC-SHA256 Signature calculation
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP POST request
func sendPostRequest(apiURL, apiKey, timestamp, signature, bodyJSON string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer([]byte(bodyJSON)))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
}
import time
import hmac
import hashlib
import requests
import json
# API-related information
URL = "https://openapi.fameex.net"
REQUEST_PATH = "/sapi/v1/batchCancel"
API_URL = URL + REQUEST_PATH
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "POST"
# Define the request body (JSON format)
body_json = {
"symbol": "BTCUSDT",
"orderId": {
111000111,
111000112
}
}
body_str = json.dumps(body_json, separators=(',', ':')) # Ensure the JSON string format is correct
# Generate signature (X-CH-SIGN)
sign_payload = timestamp + METHOD + REQUEST_PATH + body_str
signature = hmac.new(API_SECRET.encode(), sign_payload.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", sign_payload)
print("Signature (X-CH-SIGN):", signature)
print("Request Body:", body_str)
print("==================")
# Send request
headers = {
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.post(API_URL, headers=headers, data=body_str)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const URL = "https://openapi.fameex.net";
const REQUEST_PATH = "/sapi/v1/batchCancel";
const API_URL = URL + REQUEST_PATH;
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "POST";
// Define the request body (JSON format)
const bodyJson = JSON.stringify({
symbol: "BTCUSDT",
orderId: ["111000111", "111000112"],
});
// Generate signature (X-CH-SIGN)
const signPayload = timestamp + METHOD + REQUEST_PATH + bodyJson;
const signature = crypto
.createHmac("sha256", API_SECRET)
.update(signPayload)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", signPayload);
console.log("Signature (X-CH-SIGN):", signature);
console.log("Request Body:", bodyJson);
console.log("==================");
// Send request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": signature,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.post(API_URL, bodyJson, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
body
{"symbol":"BTCUSDT","oderIds":[111000111, 111000112]}
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, such as BTCUSDT |
orderIds* | array | Set of order IDs to be canceled, with ID values entered in numeric format [123,456] |
Successful response data
{
"success": [
165964665990709251,
165964665990709252,
165964665990709253
],
"failed": [ // Cancellation failure is usually due to the order not existing or already reaching a final state
165964665990709250
]
}
Failed response data
{} //Usually due to an incorrect order ID. Please check if the contents of `orderIds` are correct
Current order
GET https://openapi.fameex.net/sapi/v1/openOrders
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v1/openOrders?symbol=btcusdt&limit=10
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/openOrders"
QUERY_STRING="?symbol=btcusdt&limit=10"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/openOrders";
String queryString = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (string to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send the request and get the response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/openOrders"
queryString := "?symbol=btcusdt&limit=10"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (string to be signed): ", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/openOrders"
QUERY_STRING = "?symbol=btcusdt&limit=10"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/openOrders";
$QUERY_STRING = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/openOrders";
const QUERY_STRING = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (string to be signed): ", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Lowercase trading pair name, such as ethusdt |
limit | integer | Maximum 1000 |
Response example
[
{
"symbol": "ETHUSDT",
"side": "BUY",
"executedQty": "0",
"orderId": 1938321163093077686,
"price": "0",
"origQty": "0.10",
"avgPrice": "0",
"time": 1701240367864,
"type": "MARKET",
"status": "NEW_"
},
{
"symbol": "ETHUSDT",
"side": "BUY",
"executedQty": "0",
"orderId": 1938321163093078022,
"price": "0",
"origQty": "0.01",
"avgPrice": "0",
"time": 1701243281850,
"type": "MARKET",
"status": "NEW_"
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 150695552109032492 |
Order ID (system-generated) |
symbol | string | ETHUSDT |
Trading pair name |
price | float | 4765.29 |
Order price |
origQty | float | 1.01 |
Order quantity |
executedQty | float | 1.01 |
Filled order quantity |
avgPrice | float | 4754.24 |
The average price of the filled order |
type | string | LIMIT |
Order type. Possible values are:LIMIT (Limit Order) andMARKET (Market Order) |
time | long | 1701243281850 |
Timestamp |
side | string | BUY |
Order direction. Possible values are: BUY (Buy/Long) and SELL (Sell/Short) |
status | string | New Order |
Order status. Possible values are:New Order (New order, no fills),Partially Filled (Partially filled), Filled (Fully filled) |
Current order-V2
GET https://openapi.fameex.net/sapi/v2/openOrders
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v2/openOrders?symbol=btcusdt&limit=10
// request headers
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v2/openOrders"
QUERY_STRING="?symbol=btcusdt&limit=10"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v2/openOrders";
String queryString = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Read response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v2/openOrders"
queryString := "?symbol=btcusdt&limit=10"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v2/openOrders"
QUERY_STRING = "?symbol=btcusdt&limit=10"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v2/openOrders";
$QUERY_STRING = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v2/openOrders";
const QUERY_STRING = "?symbol=btcusdt&limit=10";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
参数名 | 类型 | 描述 |
---|---|---|
symbol* | string | 小写 币对名称,例如:ethusdt |
limit* | integer | 最大1000 |
Response example
[
{
"symbol": "ETHUSDT",
"side": "BUY",
"executedQty": "0",
"orderId": "1938321163093077686",
"price": "0",
"origQty": "0.10",
"avgPrice": "0",
"time": 1701240367864,
"type": "MARKET",
"status": "NEW_"
},
{
"symbol": "ETHUSDT",
"side": "BUY",
"executedQty": "0",
"orderId": "1938321163093078022",
"price": "0",
"origQty": "0.01",
"avgPrice": "0",
"time": 1701243281850,
"type": "MARKET",
"status": "NEW_"
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 150695552109032492 |
Order ID (system-generated) |
symbol | string | ETHUSDT |
Trading pair name |
price | float | 4765.29 |
Order price |
origQty | float | 1.01 |
Order quantity |
executedQty | float | 1.01 |
Filled order quantity |
avgPrice | float | 4754.24 |
The average price of the filled order |
type | string | LIMIT |
Order type. Possible values are:LIMIT (Limit Order) andMARKET (Market Order) |
time | long | 1701243281850 |
Timestamp |
side | string | BUY |
Order direction. Possible values are: BUY (Buy/Long) and SELL (Sell/Short) |
status | string | New Order |
Order status. Possible values are:New Order (New order, no fills),Partially Filled (Partially filled), Filled (Fully filled) |
Transaction records
GET https://openapi.fameex.net/sapi/v1/myTrades
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v1/myTrades?symbol=BTCUSDT&limit=100
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/myTrades"
QUERY_STRING="?symbol=BTCUSDT&limit=100"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/myTrades";
String queryString = "?symbol=BTCUSDT&limit=100";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send the request and get the response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/myTrades"
queryString := "?symbol=BTCUSDT&limit=100"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/myTrades"
QUERY_STRING = "?symbol=BTCUSDT&limit=100"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/myTrades";
$QUERY_STRING = "?symbol=BTCUSDT&limit=100";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/myTrades";
const QUERY_STRING = "?symbol=BTCUSDT&limit=100";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbol* | string | Uppercase trading pair name, such asBTCUSDT |
limit | string | Default: 100; Maximum: 1000 |
Response example
[
{
"symbol": "ETHUSDT",
"side": "BUY",
"fee": 0.00000000428,
"isMaker": false,
"isBuyer": true,
"bidId": 1954603951049381893,
"bidUserId": 10083,
"feeCoin": "ETH",
"price": 2334,
"qty": 0.00000428,
"askId": 1856176838352995447,
"id": 159,
"time": 1701623660989,
"isSelf": false,
"askUserId": 10671
},
{
"symbol": "ETHUSDT",
"side": "BUY",
"fee": 0.00000004284,
"isMaker": false,
"isBuyer": true,
"bidId": 1938321163093068889,
"bidUserId": 10083,
"feeCoin": "ETH",
"price": 2334,
"qty": 0.00004284,
"askId": 1856176838352995447,
"id": 158,
"time": 1701165091964,
"isSelf": false,
"askUserId": 10671
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
symbol | string | ETHBTC |
Uppercase currency name |
id | integer | 159 |
Transaction ID |
bidId | long | 1954603951049381893 |
Buyer order ID |
askId | long | 1856176838352995447 |
Seller order ID |
price | integer | 2334 |
Transaction price |
qty | float | 0.00004284 |
Transaction quantity |
time | number | 1701165091964 |
Transaction timestamp |
isBuyer | boolean | true |
true =Buyer,false =Seller |
isMaker | boolean | false |
true =Maker,false =Taker |
feeCoin | string | ETH |
Transaction fee currency |
fee | number | 0.00000000428 |
Transaction fee |
bidUserId | integer | 10083 |
Buyer user UID |
askUserId | integer | 10671 |
Seller user UID |
isSelf | boolean | false |
Is it a self-trade?true = yes, it is a self-trade;false = no, it is not a self-trade |
side | string | BUY |
Active order direction:BUY /SELL |
Account
Security type: USER_DATA
Account information (deprecated)
GET https://openapi.fameex.net/sapi/v1/account
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
GET https://openapi.fameex.net/sapi/v1/account
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/account"
QUERY_STRING=""
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/account";
String queryString = "";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send the request and get the response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/account"
queryString := ""
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/v1/account"
QUERY_STRING = ""
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/account";
$QUERY_STRING = "";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET reques
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/account";
const QUERY_STRING = "";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Return example
{
"balances": [
{
"asset": "ABAT",
"free": "10.00",
"locked": "20.00"
},
{
"asset": "DOT",
"free": "10.00",
"locked": "10.00"
},
{
"asset": "TT",
"free": "50.00",
"locked": "50.00"
}
]
}
Response parameters
Parameter name | Type | Description |
---|---|---|
balances | array | Account balance set. |
asset | string | Trading pair |
free | string | Available balance |
locked | string | Frozen balance |
Account information (recommended)
GET https://openapi.fameex.net/sapi/v1/account/balance
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
// Query all currencies
GET https://openapi.fameex.net/sapi/v1/account/balance
// Query USDT, BTC, ETH
GET https://openapi.fameex.net/sapi/v1/account/balance?symbols=USDT,BTC,ETH
// Headers Configuration
Content-Type: application/json
X-CH-TS: 1739503617552
X-CH-APIKEY: your API-KEY
X-CH-SIGN: 325b02a8444da041c71fb6e3c35c6baf87e5cb48acc19e4cd312b8bf821bfc1b
#!/bin/bash
# Set API-related information
API_URL="https://openapi.fameex.net"
REQUEST_URL="/sapi/v1/account/balance"
QUERY_STRING="?symbols=USDT,BTC,ETH"
# Calculate the complete request URL
REQUEST_PATH="${REQUEST_URL}${QUERY_STRING}"
FULL_URL="${API_URL}${REQUEST_PATH}"
# API authentication information
API_KEY="your API-KEY"
API_SECRET="your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp=$(date +%s | awk '{print $1 * 1000}')
# Define the request method
METHOD="GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD="${timestamp}${METHOD}${REQUEST_PATH}"
SIGNATURE=$(echo -n "$SIGN_PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')
# **Print debugging information**
echo "==== Request information ===="
echo "Timestamp (X-CH-TS): $timestamp"
echo "Sign Payload (String to be signed): $SIGN_PAYLOAD"
echo "Signature (X-CH-SIGN): $SIGNATURE"
echo "Request URL: ${FULL_URL}"
echo "=================="
# Send GET request
curl -X GET "$FULL_URL" \
-H "X-CH-SIGN: $SIGNATURE" \
-H "X-CH-APIKEY: $API_KEY" \
-H "X-CH-TS: $timestamp" \
-H "Content-Type: application/json"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Scanner;
public class FameexApiRequest {
public static void main(String[] args) {
try {
// API-related information
String apiUrl = "https://openapi.fameex.net";
String requestUrl = "/sapi/v1/account/balance";
String queryString = "?symbols=USDT,BTC,ETH";
// Calculate the complete request URL
String requestPath = requestUrl + queryString;
String fullUrl = apiUrl + requestPath;
// API authentication information
String apiKey = "your API-KEY";
String apiSecret = "your API-SECRET";
// Generate the current millisecond-level timestamp
String timestamp = String.valueOf(Instant.now().toEpochMilli());
// Request method
String method = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
String signPayload = timestamp + method + requestPath;
String signature = hmacSha256(signPayload, apiSecret);
// **Print debugging information**
System.out.println("==== Request information ====");
System.out.println("Timestamp (X-CH-TS): " + timestamp);
System.out.println("Sign Payload (String to be signed): " + signPayload);
System.out.println("Signature (X-CH-SIGN): " + signature);
System.out.println("Request URL: " + fullUrl);
System.out.println("==================");
// Send GET request
sendGetRequest(fullUrl, apiKey, timestamp, signature);
} catch (Exception e) {
e.printStackTrace();
}
}
// HMAC-SHA256 signature calculation
public static String hmacSha256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// Send HTTP GET request
public static void sendGetRequest(String fullUrl, String apiKey, String timestamp, String signature) {
try {
URL url = new URL(fullUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// Set request headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("X-CH-APIKEY", apiKey);
conn.setRequestProperty("X-CH-TS", timestamp);
// Send the request and get the response
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(conn.getInputStream(), StandardCharsets.UTF_8.name());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
func main() {
// API-related information
apiURL := "https://openapi.fameex.net"
requestURL := "/sapi/v1/account/balance"
queryString := "?symbols=USDT,BTC,ETH"
// Calculate the complete request URL
requestPath := requestURL + queryString
fullURL := apiURL + requestPath
// API authentication information
apiKey := "your API-KEY"
apiSecret := "your API-SECRET"
// Generate the current millisecond-level timestamp
timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
// Request method
method := "GET"
// Generate signature (X-CH-SIGN) - GET requests have no body
signPayload := timestamp + method + requestPath
signature := hmacSHA256(signPayload, apiSecret)
// **Print debugging information**
fmt.Println("==== Request information ====")
fmt.Println("Timestamp (X-CH-TS):", timestamp)
fmt.Println("Sign Payload (String to be signed):", signPayload)
fmt.Println("Signature (X-CH-SIGN):", signature)
fmt.Println("Request URL:", fullURL)
fmt.Println("==================")
// Send GET request
sendGetRequest(fullURL, apiKey, timestamp, signature)
}
// Compute HMAC-SHA256 signature
func hmacSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
// Send HTTP GET request
func sendGetRequest(fullURL, apiKey, timestamp, signature string) {
client := &http.Client{}
// Create request
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set Headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-SIGN", signature)
req.Header.Set("X-CH-APIKEY", apiKey)
req.Header.Set("X-CH-TS", timestamp)
// Send request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Read response
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response Code:", resp.StatusCode)
fmt.Println("Response Body:", string(body))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_URL = "https://openapi.fameex.net"
REQUEST_URL = "/sapi/account/balance"
QUERY_STRING = "?symbols=USDT,BTC,ETH"
# Calculate the complete request URL
REQUEST_PATH = REQUEST_URL + QUERY_STRING
FULL_URL = API_URL + REQUEST_PATH
# API authentication information
API_KEY = "your API-KEY"
API_SECRET = "your API-SECRET"
# Generate the current millisecond-level timestamp
timestamp = str(int(time.time() * 1000))
# Request method
METHOD = "GET"
# Generate signature (X-CH-SIGN) - GET requests have no body
SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH
SIGNATURE = hmac.new(API_SECRET.encode(), SIGN_PAYLOAD.encode(), hashlib.sha256).hexdigest()
# **Print debugging information**
print("==== Request information ====")
print("Timestamp (X-CH-TS):", timestamp)
print("Sign Payload (String to be signed):", SIGN_PAYLOAD)
print("Signature (X-CH-SIGN):", SIGNATURE)
print("Request URL:", FULL_URL)
print("==================")
# Send GET request
headers = {
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
"Content-Type": "application/json"
}
response = requests.get(FULL_URL, headers=headers)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
<?
// API-related information
$API_URL = "https://openapi.fameex.net";
$REQUEST_URL = "/sapi/v1/account/balance";
$QUERY_STRING = "?symbols=USDT,BTC,ETH";
// Calculate the complete request URL
$REQUEST_PATH = $REQUEST_URL . $QUERY_STRING;
$FULL_URL = $API_URL . $REQUEST_PATH;
// API authentication information
$API_KEY = "your API-KEY";
$API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
$timestamp = round(microtime(true) * 1000);
// Request method
$METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
$SIGN_PAYLOAD = $timestamp . $METHOD . $REQUEST_PATH;
$SIGNATURE = hash_hmac('sha256', $SIGN_PAYLOAD, $API_SECRET);
// **Print debugging information**
echo "==== Request information ====\n";
echo "Timestamp (X-CH-TS): " . $timestamp . "\n";
echo "Sign Payload (String to be signed): " . $SIGN_PAYLOAD . "\n";
echo "Signature (X-CH-SIGN): " . $SIGNATURE . "\n";
echo "Request URL: " . $FULL_URL . "\n";
echo "==================\n";
// Send GET request
$headers = [
"Content-Type: application/json",
"X-CH-SIGN: $SIGNATURE",
"X-CH-APIKEY: $API_KEY",
"X-CH-TS: $timestamp"
];
// Use cURL to send a GET request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $FULL_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and get the response
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Print response
echo "Response Code: $http_code\n";
echo "Response Body: $response\n";
?>
const axios = require("axios");
const crypto = require("crypto");
// API-related information
const API_URL = "https://openapi.fameex.net";
const REQUEST_URL = "/sapi/v1/account/balance";
const QUERY_STRING = "?symbols=USDT,BTC,ETH";
// Calculate the complete request URL
const REQUEST_PATH = REQUEST_URL + QUERY_STRING;
const FULL_URL = API_URL + REQUEST_PATH;
// API authentication information
const API_KEY = "your API-KEY";
const API_SECRET = "your API-SECRET";
// Generate the current millisecond-level timestamp
const timestamp = Date.now().toString();
// Request method
const METHOD = "GET";
// Generate signature (X-CH-SIGN) - GET requests have no body
const SIGN_PAYLOAD = timestamp + METHOD + REQUEST_PATH;
const SIGNATURE = crypto
.createHmac("sha256", API_SECRET)
.update(SIGN_PAYLOAD)
.digest("hex");
// **Print debugging information**
console.log("==== Request information ====");
console.log("Timestamp (X-CH-TS):", timestamp);
console.log("Sign Payload (String to be signed):", SIGN_PAYLOAD);
console.log("Signature (X-CH-SIGN):", SIGNATURE);
console.log("Request URL:", FULL_URL);
console.log("==================");
// Send GET request
const headers = {
"Content-Type": "application/json",
"X-CH-SIGN": SIGNATURE,
"X-CH-APIKEY": API_KEY,
"X-CH-TS": timestamp,
};
axios
.get(FULL_URL, { headers })
.then((response) => {
console.log("Response Code:", response.status);
console.log("Response Body:", response.data);
})
.catch((error) => {
console.error("Error:", error.response ? error.response.data : error.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
symbols | string | Uppercase currency name, such asBTC . Supports querying multiple currencies, up to 20, separated by commas |
Response example
{
"balances": [
{
"asset": "USDT",
"free": "15.00",
"locked": "30.00"
},
{
"asset": "BTC",
"free": "10.00",
"locked": "20.00"
},
{
"asset": "ETH",
"free": "100.00",
"locked": "70.00"
}
]
}
Response parameters
Parameter name | Type | Description |
---|---|---|
balances | array | Account balance |
asset | string | Trading pair |
free | string | Available balance |
locked | string | Frozen balance |
Contract trading
Public
Security type: None
Test connection
GET https://futuresopenapi.fameex.net/fapi/v1/ping
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/ping
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/ping"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/ping");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/ping"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/ping"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/ping";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/ping';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Response example
{}
Response parameters
{}
Test the connectivity of the REST API
Get server time
GET https://futuresopenapi.fameex.net/fapi/v1/time
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/time
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/time"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/time");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/time"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/time"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/time";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/time';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Response example
{
"timezone": "China Standard Time",
"serverTime": 1704962055664
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
timezone | string | China Standard Time |
Server timezone |
serverTime | long | 1607702400000 |
Server timestamp |
Contract list
GET https://futuresopenapi.fameex.net/fapi/v1/contracts
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/contracts
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/contracts"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/contracts");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/contracts"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/contracts"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/contracts";
// 初始化 cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/contracts';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Response example
[
{
"symbol": "E-ETC-USDT",
"pricePrecision": 3,
"side": 1,
"maxMarketVolume": 200000,
"multiplier": 1.0000000000000000,
"minOrderVolume": 1,
"maxMarketMoney": 500000.0000000000000000,
"type": "E",
"maxLimitVolume": 300000,
"maxValidOrder": 10,
"multiplierCoin": "ETC",
"minOrderMoney": 1.0000000000000000,
"maxLimitMoney": 500000.0000000000000000,
"status": 1
},
{
"symbol": "E-ATOM-USDT",
"pricePrecision": 3,
"side": 1,
"maxMarketVolume": 100000,
"multiplier": 1.0000000000000000,
"minOrderVolume": 1,
"maxMarketMoney": 200000.0000000000000000,
"type": "E",
"maxLimitVolume": 200000,
"maxValidOrder": 10,
"multiplierCoin": "ATOM",
"minOrderMoney": 20.0000000000000000,
"maxLimitMoney": 2000000.0000000000000000,
"status": 1
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
symbol | string | E-BTC-USDT |
Uppercase contract name |
pricePrecision | number | 3 |
Price precision |
status | number | 1 |
Contract status (0:Not tradable , 1:Tradable ) |
type | string | E |
Contract type (E:Perpetual contract , S:Simulated contract , others areHybrid contract ) |
side | number | 1 |
Contract direction (0:Inverse , 1:Linear ) |
multiplier | number | 1.0000000000000000 |
Contract nominal value |
minOrderVolume | number | 1 |
Minimum order quantity |
minOrderMoney | number | 1.0000000000000000 |
Minimum order amount |
maxMarketVolume | number | 200000 |
Maximum order quantity for market orders |
maxMarketMoney | number | 500000.0000000000000000 |
Maximum order amount for market orders |
maxLimitVolume | number | 300000 |
Maximum order quantity for limit orders |
maxLimitMoney | number | 500000.0000000000000000 |
Maximum order amount for limit orders |
maxValidOrder | number | 10 |
Maximum number of active orders allowed |
Market data
Security type: None
Order book
GET https://futuresopenapi.fameex.net/fapi/v1/depth
Market order book depth information
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("读取响应失败:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/depth?contractName=E-BTC-USDT&limit=100';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
limit | integer | Default: 100; Maximum: 100 |
Response example
{
"time": 1704962463000,
"bids": [
[
3.90000000, //Price
16.10000000 //Quantity
],
[
4.00000000,
29.30000000
]
],
"asks": [
[
4.00000200, //Price
12.00000000 //Quantity
],
[
5.10000000,
28.00000000
]
]
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
time | long | 1595563624731 |
Current timestamp |
bids | list | [[3.9,16.1],[4.0,29.3]] |
Order book bid information, where the first element is the price (type: float), and the second element is the quantity corresponding to the current price (type: float) |
asks | list | [[4.00000200,12.0],[5.1,28.0]] |
Order book ask information, where the first element is the price (type: float), and the second element is the quantity corresponding to the current price (type: float) |
The information corresponding to bids and asks represents all the prices and their associated quantities in the order book, arranged from the best price downwards
Market Ticker
GET https://futuresopenapi.fameex.net/fapi/v1/ticker
24-hour price change data
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT";
// Initialize cURL
$ch = curl_init();
// Skip SSL certificate verification (if required by the API)
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过 SSL 证书验证(如果 API 需要)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/ticker?contractName=E-BTC-USDT';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
Return example
{
"high": 56120.22,
"vol": 51.21,
"last": 55989.93,
"low": 55982.24,
"buy": 55988.10,
"sell": 55990.10,
"rose": "+0.05",
"time": 1704966225000
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
time | long | 1595563624731 |
Timestamp |
high | float | 56120.22 |
Highest price |
low | float | 55982.24 |
Lowest price |
last | float | 55989.93 |
Latest price |
vol | float | 51.21 |
Trading volume |
rose | string | +0.05 |
Price change percentage.+ indicates an increase,- indicates a decrease, and+0.05 means a5% increase |
buy | float | 55988.10 |
Buy price (highest bid price) |
sell | float | 55990.10 |
Sell price (lowest ask price) |
Market Ticker-V2
GET https://futuresopenapi.fameex.net/swap-api/v2/tickers
Get 24-hour price change data
Request example
GET https://futuresopenapi.fameex.net/swap-api/v2/tickers
// request headers
Content-Type:application/json
Return example
[
{
"base_currency": "ETH",
"open_interest_usd": "3158506.047",
"quote_volume": "475254656162",
"base_volume": "2135453.51",
"open_interest": "1372.13",
"index_price": "2302.705",
"basis": "0.0003",
"quote_currency": "USDT",
"ticker_id": "ETH-USDT",
"funding_rate": "0.0000632068687814",
"high": "2318.84",
"product_type": "Perpetual",
"low": "2160.71",
"ask": "2301.96",
"next_funding_rate_timestam": 1741248000000,
"bid": "2301.8",
"last_price": "2301.9"
}
]
Return parameter
Name | Type | Example | Description |
---|---|---|---|
ticker_id | string | ETH-USDT |
Trading Pairs |
product_type | string | Perpetual |
Contract Type |
base_currency | string | ETH |
Trading Currency |
quote_currency | string | USDT |
Denominated currency |
last_price | float | 2301.9 |
Latest transaction price |
index_price | float | 2302.705 |
Index Price |
base_volume | float | 2135453.51 |
Trading Volume |
quote_volume | string | 475254656162 |
Transaction Amount |
bid | float | 2301.8 |
Buy one price |
ask | float | 2301.96 |
Selling price |
high | float | 2318.84 |
Highest Price |
low | float | 2160.71 |
Lowest Price |
open_interest | float | 1372.13 |
Number of open positions |
open_interest_usd | float | 3158506.047 |
Opening amount |
basis | float | 0.0003 |
Basis |
funding_rate | float | 0.0000632068687814 |
Funding Rate |
next_funding_rate_timestam | float | 1741248000000 |
Next funding rate time |
Get index/mark price
GET
https://futuresopenapi.fameex.net/fapi/v1/index
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100";
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/index?contractName=E-BTC-USDT&limit=100';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
limit | string | Default: 100; Maximum: 1000 |
Return example
{
"currentFundRate": -0.0037500000000000,
"indexPrice": 27905.9800000000000000,
"tagPrice": 27824.4422146875000000,
"nextFundRate": -0.0037500000000000
}
Response parameters
Name | Type | Example | Description |
---|---|---|---|
indexPrice | float | 27905.9800000000000000 |
Index price |
tagPrice | float | 27824.4422146875000000 |
Mark price |
nextFundRate | float | -0.0037500000000000 |
Funding rate price |
currentFundRate | float | -0.0037500000000000 |
Previous funding rate (used for this period's settlement) |
K-line / Candlestick chart data
GET https://futuresopenapi.fameex.net/fapi/v1/klines
Request example
GET https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000
// Headers Configuration
Content-Type:application/json
curl -X GET "https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000"
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Create a URL using URI
URI uri = new URI("https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Java-Client");
// Read response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output result
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000"
// Send GET request
resp, err := http.Get(url)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read the response:", err)
return
}
// Print response
fmt.Println("Server response:", string(body))
}
import requests
url = "https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000"
try:
response = requests.get(url)
response.raise_for_status() # Check if the request was successful
print("Response:", response.text)
except requests.exceptions.RequestException as e:
print("Request error:", e)
$url = "https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000";
// Initialize cURL.
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Skip SSL certificate verification (if required by the API)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo "cURL Error:" . curl_error($ch);
} else {
echo "Response: " . $response;
}
// Close cURL
curl_close($ch);
const https = require('https');
const url = 'https://futuresopenapi.fameex.net/fapi/v1/klines?contractName=E-BTC-USDT&interval=1min&limit=100&startTime=1739116800000&endTime=1739852318000';
https.get(url, (res) => {
let data = '';
// A chunk of data has been received.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received.
res.on('end', () => {
console.log("Response:", data);
});
}).on('error', (err) => {
console.log('Request error:', err.message);
});
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
interval* | string | The time intervals for K-line charts, recognizable parameter values are:1min ,5min ,15min ,30min ,1h ,1day ,1week ,1month (min = minute, h = hour, day = day, week = week, month = month) |
limit | integer | 默认:100;最大:300 |
startTime | long | Start timestamp |
endTime | long | End timestamp |
Response example.
[
{
"high": 6228.77,
"vol": 111,
"low": 6190.48,
"idx": 15946403400000,
"close": 6210.51,
"open": 6195.80
},
{
"high": 6228.77,
"vol": 222,
"low": 6228.77,
"idx": 15876321600000,
"close": 6228.77,
"open": 6228.77
},
{
"high": 6228.77,
"vol": 333,
"low": 6228.77,
"idx": 15876321000000,
"close": 6228.77,
"open": 6228.77
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
idx | long | 15946403400000 |
Start timestamp |
open | float | 6195.80 |
Opening price |
close | float | 6210.51 |
Closing price |
high | float | 6228.77 |
Highest price |
low | float | 6190.48 |
Lowest price |
vol | float | 111 |
Volume traded |
Trading
Security type: TRADE
Create order
POST https://futuresopenapi.fameex.net/fapi/v1/order
Create a single new order
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-TS* | string | Timestamp |
X-CH-APIKEY* | string | Your API key |
X-CH-SIGN* | string | Signature |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/order
body
{"contractName":"E-BTC-USDT","price":65000.00,"volume":1.00,"type":"LIMIT","side":"BUY","open":"OPEN","positionType":1,"clientOrderId":"111000111","timeInForce":"IOC"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/order"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","price":65000.00,"volume":1.00,"type":"LIMIT","side":"BUY","open":"OPEN","positionType":1,"clientOrderId":"111000111","timeInForce":"IOC"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API key";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/order";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{\"contractName\":\"E-BTC-USDT\",\"price\":65000.00,\"volume\":1.00,\"type\":\"LIMIT\",\"side\":\"BUY\",\"open\":\"OPEN\",\"positionType\":1,\"clientOrderId\":\"111000111\",\"timeInForce\":\"IOC\"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data The string to be signed
* @param secret The secret key
* @return HMAC SHA256 signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/order"
)
func main() {
// Get millisecond timestamp
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","price":65000.00,"volume":1.00,"type":"LIMIT","side":"BUY","open":"OPEN","positionType":1,"clientOrderId":"111000111","timeInForce":"IOC"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send POST request.
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API key"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/order"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","price":65000.00,"volume":1.00,"type":"LIMIT","side":"BUY","open":"OPEN","positionType":1,"clientOrderId":"111000111","timeInForce":"IOC"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body into a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/order";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"price" => 65000.00,
"volume" => 1.00,
"type" => "LIMIT",
"side" => "BUY",
"open" => "OPEN",
"positionType" => 1,
"clientOrderId" => "111000111",
"timeInForce" => "IOC"
], JSON_UNESCAPED_SLASHES);
//Get millisecond timestamp
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Use only in the development environment; SSL verification should be enabled in the production environment
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/order";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
price: 65000.00,
volume: 1.00,
type: "LIMIT",
side: "BUY",
open: "OPEN",
positionType: 1,
clientOrderId: "111000111",
timeInForce: "IOC"
});
// Get millisecond timestamp
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
price | number | Order price. This field is mandatory for limit orders. It has precision restrictions set by the administrator |
volume* | number | Order quantity. It has precision restrictions set by the administrator. For market orders, this field represents the order value |
type* | string | Order type:LIMIT /MARKET |
side* | string | Order direction:BUY /SELL |
open* | string | Position direction:OPEN /CLOSE |
positionType* | number | Position type: 1 (Cross Margin) / 2 (Isolated Margin) |
timeInForce | string | IOC, FOK, POST_ONLY |
clientOrderId | string | Client order identifier, a string with a length of fewer than 32 characters |
Response example
{
"orderId": 256609229205684228
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | string | 256609229205684228 |
Order ID |
Create conditional order
POST https://futuresopenapi.fameex.net/fapi/v1/conditionOrder
Request headers
Parameter name | Type | Example |
---|---|---|
X-CH-TS* | string | Timestamp |
X-CH-APIKEY* | string | Your API key |
X-CH-SIGN* | string | Signature |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/conditionOrder
body
{"contractName":"E-BTC-USDT","price":"100.00","volume":"1.00","type":"LIMIT","side":"BUY","positionType":"1","open":"OPEN","triggerType":"1","triggerPrice":"455"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/conditionOrder"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","price":"100.00","volume":"1.00","type":"LIMIT","side":"BUY","positionType":"1","open":"OPEN","triggerType":"1","triggerPrice":"455"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/conditionOrder";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","price":"100.00","volume":"1.00","type":"LIMIT","side":"BUY","positionType":"1","open":"OPEN","triggerType":"1","triggerPrice":"455"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/conditionOrder"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","price":"100.00","volume":"1.00","type":"LIMIT","side":"BUY","positionType":"1","open":"OPEN","triggerType":"1","triggerPrice":"455"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/conditionOrder"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","price":"100.00","volume":"1.00","type":"LIMIT","side":"BUY","positionType":"1","open":"OPEN","triggerType":"1","triggerPrice":"455"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/conditionOrder";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"price" => 65000.00,
"volume" => 1.00,
"type" => "LIMIT",
"side" => "BUY",
"positionType" => 1,
"open" => "OPEN",
"triggerType" => "1",
"triggerPrice" => "455"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/conditionOrder";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
price: "65000.00",
volume: "1.00",
type: "LIMIT",
side: "BUY",
positionType: "1",
open: "OPEN",
triggerType: "1",
triggerPrice: "455"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Construct the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
price* | number | Order price, with precision limits set by the administrator |
volume* | number | Order quantity. For market orders, this represents the value. It has precision limits set by the administrator |
type* | string | Order type:LIMIT /MARKET |
side* | string | Order direction:BUY /SELL |
positionType* | number | Order direction: BUY / SELL; Position type: 1 (Cross Margin), 2 (Isolated Margin) |
open* | string | Position direction:OPEN /CLOSE |
triggerType* | string | Condition type: 1 (Stop Loss), 2 (Take Profit), 3 (Buy on the rise), 4 (Sell on the dip) |
triggerPrice* | string | Trigger price |
clientOrderId | string | Client order identifier, a string with a length of fewer than 32 characters |
Response example
{
"code": "0",
"msg": "Success",
"data": {
"triggerIds": [
"1322738336974712847"
],
"ids": [
],
"cancelIds": [
]
},
"succ": true
}
If this API returns unexpected results, please contact the technical team, and we will provide relevant assistance
Cancel order
POST https://futuresopenapi.fameex.net/fapi/v1/cancel
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/cancel
body
{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/cancel"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API key";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/cancel";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, ensure to use compact format)
String body = "{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}";
System.out.println("Request body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/cancel"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/cancel"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Construct the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API-KEY";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/cancel";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"orderId" => 2616833860188981826
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Construct the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Use only in the development environment; SSL verification should be enabled in the production environment
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/cancel";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
orderId: "2616833860188981826"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Construct the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
orderId* | string | Order ID |
Return example
{
"orderId": "256609229205684228"
}
Cancel conditional order
POST https://futuresopenapi.fameex.net/fapi/v1/cancel_trigger_order
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter nam | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | integer | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/cancel_trigger_order
body
{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
#!/bin/bash
# API-related information
api_key="Your API key"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/cancel_trigger_order"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/cancel_trigger_order";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/cancel_trigger_order"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API key"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/cancel_trigger_order"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/cancel_trigger_order";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"orderId" => 2616833860188981826
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/cancel_trigger_order";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
orderId: "2616833860188981826"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request.
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | UPPERCASE contract name, for example:E-BTC-USDT |
orderId* | string | Order ID |
clientOrderId | string | Client unique identifier, default: 0 |
Response example
{
"orderId": "256609229205684228"
}
Order details
GET https://futuresopenapi.fameex.net/fapi/v1/order
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | string | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/order
body
{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
#!/bin/bash
# API-related information
api_key="Your API key"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/order"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Use cURL to send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = API-related information";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/order";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/order"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API key"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/order"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","orderId":"2616833860188981826"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/order";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"orderId" => 2616833860188981826
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/order";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
orderId: "2616833860188981826"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Get timestamp in milliseconds
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | UPPERCASE Contract Name, for example:E-BTC-USDT |
orderId* | string | Order ID |
clientOrderId* | string | Client unique identifier, default: 0 |
Response example
{
"side": "BUY",
"executedQty": 0,
"orderId": 2006628907041292645,
"price": 67000.0000000000000000,
"origQty": 2.0000000000000000,
"avgPrice": 0,
"transactTime": 1704967622000,
"action": "OPEN",
"contractName": "E-BTC-USDT",
"type": "LIMIT",
"timeInForce": "1",
"status": "NEW",
"fills": [
]
}
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 2006628907041292645 |
Order ID (system-generated) |
contractName | string | E-BTC-USDT |
UPPERCASE Contract Name |
price | float | 67000.0000000000000000 |
Order price |
origQty | float | 2.0000000000000000 |
Order quantity |
executedQty | float | 0 |
Executed quantity |
avgPrice | float | 0 |
Average execution price |
status | string | NEW |
Order status. Possible values are:NEW (New order, no fills),PARTIALLY_FILLED (Partially filled),FILLED (Fully filled),CANCELED (Cancelled), andREJECTED (Order rejected) |
side | string | BUY |
Order direction. The possible values are:BUY (Buy long) andSELL (Sell short) |
action | string | OPEN |
OPEN/CLOSE |
transactTime | long | 1704967622000 |
Order creation time |
type | string | LIMIT |
Order type:LIMIT / MARKET |
timeInForce | integer | 1 |
Conditional order validity types:1:limit ,2:market ,3:IOC ,4:FOK ,5: POST\_ONLY |
fills | array | Transaction records |
Current order
GET https://futuresopenapi.fameex.net/fapi/v1/openOrders
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | string | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/openOrders
body
{"contractName":"E-BTC-USDT"}
#!/bin/bash
# API-related information
api_key="Your API key"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/openOrders"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API key";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/openOrders";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/openOrders"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/openOrders"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "API-related information";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/openOrders";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/openOrders";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, e.g.,E-BTC-USDT |
Response example
[
{
"side": "BUY",
"executedQty": 0.5,
"orderId": 259396989397942275,
"price": 72000.0000000000000000,
"origQty": 1.0000000000000000,
"avgPrice": 71990.0,
"transactTime": 1607702400000,
"action": "OPEN",
"contractName": "E-BTC-USDT",
"type": "LIMIT",
"status": "NEW"
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
orderId | long | 259396989397942275 |
Order ID (system-generated) |
contractName | string | E-BTC-USDT |
Uppercase contract name |
price | float | 72000.0000000000000000 |
Order price |
origQty | float | 1.0000000000000000 |
Order quantity |
executedQty | float | 0.5 |
Filled order quantity |
avgPrice | float | 71990.0 |
The average price of the filled order |
type | string | LIMIT |
Order type. Possible values are:LIMIT (limit order) andMARKET (market order) |
side | string | BUY |
Order direction. Possible values are:BUY (long position) andSELL (short position) |
status | string | NEW |
Order status. Possible values are:NEW (new order, no fill),PARTIALLY_FILLED (partially filled),FILLED (completely filled),CANCELED (canceled), andREJECTED (order rejected) |
action | string | OPEN |
OPEN/CLOSE |
transactTime | long | 1607702400000 |
Order creation timestamp |
Historical Orders
POST https://futuresopenapi.fameex.net/fapi/v1/orderHistorical
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API key |
X-CH-TS* | string | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/orderHistorical
body
{"contractName":"E-BTC-USDT"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/orderHistorical"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/orderHistorical";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/orderHistorical"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/orderHistorical"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API-KEY";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/orderHistorical";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/orderHistorical";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, for example:E-BTC-USDT |
limit | string | Pagination limit, default: 100; maximum: 1000 |
fromId | long | Start retrieving from this record |
Return example
[
{
"side": "BUY",
"clientId": "0",
"ctimeMs": 1632903411000,
"positionType": 2,
"orderId": 777293886968070157,
"avgPrice": 41000,
"openOrClose": "OPEN",
"leverageLevel": 26,
"type": 4,
"closeTakerFeeRate": 0.00065,
"volume": 2,
"openMakerFeeRate": 0.00025,
"dealVolume": 1,
"price": 41000,
"closeMakerFeeRate": 0.00025,
"contractId": 1,
"ctime": "2021-09-29T16:16:51",
"contractName": "E-BTC-USDT",
"openTakerFeeRate": 0.00065,
"dealMoney": 4.1,
"status": 4
}
]
If this API returns unexpected results, please contact the technical team, and we will provide you with relevant assistance
Profit and Loss Record
POST https://futuresopenapi.fameex.net/fapi/v1/profitHistorical
If this API returns an error, please contact the technical team, and we will provide you with relevant assistance
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API-KEY |
X-CH-TS* | string | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/profitHistorical
body
{"contractName":"E-BTC-USDT"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/profitHistorical"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/profitHistorical";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API key"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/profitHistorical"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/profitHistorical"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API-KEY";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/profitHistorical";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/profitHistorical";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
limit | string | Pagination limit, default: 100; maximum: 1000 |
fromId | long | Start retrieving from this record |
Response example
[
{
"side": "SELL",
"positionType": 2,
"tradeFee": -5.23575,
"realizedAmount": 0,
"leverageLevel": 26,
"openPrice": 44500,
"settleProfit": 0,
"mtime": 1632882739000,
"shareAmount": 0,
"openEndPrice": 44500,
"closeProfit": -45,
"volume": 900,
"contractId": 1,
"historyRealizedAmount": -50.23575,
"ctime": 1632882691000,
"id": 8764,
"capitalFee": 0
}
]
If this API returns unexpected results, please contact the technical team, and we will provide you with relevant assistance
Transaction records
GET https://futuresopenapi.fameex.net/fapi/v1/myTrades
Rate limit rule: 20 requests per 2 seconds
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-SIGN* | string | Signature |
X-CH-APIKEY* | string | Your API-KEY |
X-CH-TS* | integer | Timestamp |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/myTrades
body
{"contractName":"E-BTC-USDT"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/myTrades"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/myTrades";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/myTrades"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/myTrades"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/myTrades";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/myTrades";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Uppercase contract name, such asE-BTC-USDT |
limit | string | Pagination limit, default: 100; maximum: 1000 |
fromId | long | Start retrieving from this tradeId |
Return example
[
{
"amount": 0.30000000000000000000000000000000,
"side": "BUY",
"fee": 0.001,
"isMaker": true,
"isBuyer": true,
"bidId": 1874564572563538130,
"bidUserId": 10034,
"price": 10.0000000000000000,
"qty": 3,
"askId": 1954072405852309104,
"contractName": "E-ETH-USDT",
"time": 1701419186000,
"tradeId": 1528,
"askUserId": 10378
},
{
"amount": 1.00000000000000000000000000000000,
"side": "BUY",
"fee": 0.00025,
"isMaker": true,
"isBuyer": true,
"bidId": 1874564572563538059,
"bidUserId": 10034,
"price": 10.0000000000000000,
"qty": 10,
"askId": 1954072405852309104,
"contractName": "E-ETH-USDT",
"time": 1701419186000,
"tradeId": 1527,
"askUserId": 10378
}
]
Response parameters
Parameter name | Type | Example | Description |
---|---|---|---|
tradeId | number | 1528 |
Transaction ID |
bidId | long | 1874564572563538130 |
Buyer order ID |
askId | long | 1954072405852309104 |
Seller order ID |
bidUserId | integer | 10034 |
Buyer User ID |
askUserId | integer | 10378 |
Seller User ID |
price | float | 10.0 |
Transaction Price |
qty | float | 3 |
Transaction quantity |
amount | float | 30.0 |
Transaction Amount |
time | number | 1499865549590 |
Transaction timestamp |
fee | number | 0.001 |
Transaction fee |
side | string | BUY |
Current Order Direction,BUY : Buy,SELL : Sell |
contractName | string | E-BTC-USDT |
Uppercase contract name |
isMaker | boolean | true |
Is it a maker |
isBuyer | boolean | true |
Is the buyer |
Change position mode
POST https://futuresopenapi.fameex.net/fapi/v1/edit_user_position_model
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-TS* | integer | Timestamp |
X-CH-APIKEY* | string | Your API-KEY |
X-CH-SIGN* | string | Signature |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/edit_user_position_model
body
{"contractName":"E-BTC-USDT","positionModel":"1"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/edit_user_position_model"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","positionModel":"1"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API key";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/edit_user_position_model";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","positionModel":"1"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/edit_user_position_model"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","positionModel":"1"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/edit_user_position_model"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","positionModel":"1"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/edit_user_position_model";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"positionModel" => "1"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API key";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/edit_user_position_model";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
positionModel: "1"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Contract name, e.g.,E-BTC-USDT |
positionModel* | integer | Position mode, 1:Net Position , 2:Hedged Position |
Response example
{
"code": "0",
"msg": "Success",
"data": null
}
Change Margin Mode
POST https://futuresopenapi.fameex.net/fapi/v1/edit_user_margin_model
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-TS* | integer | Timestamp |
X-CH-APIKEY* | string | Your API-KEY |
X-CH-SIGN* | string | Signature |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/edit_user_margin_model
body
{"contractName":"E-BTC-USDT","marginModel":"1"}
#!/bin/bash
# API-related information
api_key="Your API key"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/edit_user_margin_model"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","marginModel":"1"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/edit_user_margin_model";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","marginModel":"1"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/edit_user_margin_model"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","marginModel":"1"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/edit_user_margin_model"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","marginModel":"1"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API-KEY";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/edit_user_margin_model";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"marginModel" => "1"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/edit_user_margin_model";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
marginModel: "1"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Contract Name, e.g.,E-BTC-USDT |
marginModel* | integer | Position Mode:,1:Net Position ,2:Hedge Mode |
Response example
{
"code": "0",
"msg": "Success",
"data": null
}
Change Leverage Ratio
POST
https://futuresopenapi.fameex.net/fapi/v1/edit_lever
Request headers
Parameter name | Type | Description |
---|---|---|
X-CH-TS* | integer | Timestamp |
X-CH-APIKEY* | string | Your API-KEY |
X-CH-SIGN* | string | Signature |
Request example
POST https://futuresopenapi.fameex.net/fapi/v1/edit_lever
body
{"contractName":"E-BTC-USDT","newLever":"1"}
#!/bin/bash
# API-related information
api_key="Your API-KEY"
api_secret="Your API-SECRET"
# Request information
timestamp=$(($(date +%s%N)/1000000)) # Millisecond timestamp
method="POST"
request_path="/fapi/v1/edit_lever"
# Request body (in JSON format)
body='{"contractName":"E-BTC-USDT","newLever":"1"}'
# Remove whitespace characters from the body to ensure signature consistency
body=$(echo "$body" | jq -c)
# Concatenate the signature string
sign_str="${timestamp}${method}${request_path}${body}"
echo "Signature string: $sign_str"
# Generate HMAC SHA256 signature
signature=$(echo -n "$sign_str" | openssl dgst -sha256 -hmac "$api_secret" | awk '{print $2}')
echo "Signature (X-CH-SIGN): $signature"
# Send a POST request
response=$(curl -s -X POST "https://futuresopenapi.fameex.net${request_path}" \
-H "Content-Type: application/json" \
-H "X-CH-TS: $timestamp" \
-H "X-CH-APIKEY: $api_key" \
-H "X-CH-SIGN: $signature" \
-d "$body")
# Output the response result
echo "Response: $response"
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
public class SendOrder {
// API-related information
private static final String API_KEY = "Your API-KEY";
private static final String API_SECRET = "Your API-SECRET";
private static final String BASE_URL = "https://futuresopenapi.fameex.net";
private static final String REQUEST_PATH = "/fapi/v1/edit_lever";
public static void main(String[] args) {
try {
// Get timestamp (in milliseconds)
long timestamp = TimeUnit.MILLISECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
// Request method
String method = "POST";
// Request body (in JSON format, make sure to use compact format)
String body = "{"contractName":"E-BTC-USDT","newLever":"1"}";
System.out.println("Request body (body): " + body);
// Concatenate the signature string
String signStr = timestamp + method + REQUEST_PATH + body;
System.out.println("Signature string: " + signStr);
// Generate HMAC SHA256 signature
String signature = hmacSHA256(signStr, API_SECRET);
System.out.println("Signature (X-CH-SIGN): " + signature);
// Create a URL using URI
URI uri = new URI(BASE_URL + REQUEST_PATH);
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-CH-TS", String.valueOf(timestamp));
conn.setRequestProperty("X-CH-APIKEY", API_KEY);
conn.setRequestProperty("X-CH-SIGN", signature);
conn.setRequestProperty("User-Agent", "Java-Client");
conn.setDoOutput(true);
// Send the request body
try (OutputStream os = conn.getOutputStream()) {
os.write(body.getBytes(StandardCharsets.UTF_8));
os.flush();
}
// Read response
int responseCode = conn.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(
responseCode >= 200 && responseCode < 300 ? conn.getInputStream() : conn.getErrorStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Output the response result
System.out.println("Response (" + responseCode + "): " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generate HMAC SHA256 signature
*
* @param data String to be signed
* @param secret Secret key
* @return HMAC SHA256 Signature
*/
public static String hmacSHA256(String data, String secret) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
mac.init(secretKeySpec);
byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// API-related information
const (
APIKey = "Your API-KEY"
APISecret = "Your API-SECRET"
BaseURL = "https://futuresopenapi.fameex.net"
RequestPath = "/fapi/v1/edit_lever"
)
func main() {
// Get timestamp in milliseconds
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
// Request method
method := "POST"
// Request body (in JSON format)
body := `{"contractName":"E-BTC-USDT","newLever":"1"}`
// Concatenate the signature string
signStr := fmt.Sprintf("%d%s%s%s", timestamp, method, RequestPath, body)
fmt.Println("Signature string:", signStr)
// Generate HMAC SHA256 signature
signature := generateHMACSHA256(signStr, APISecret)
fmt.Println("Signature (X-CH-SIGN):", signature)
// Send a POST request
url := BaseURL + RequestPath
req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(body)))
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CH-TS", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-CH-APIKEY", APIKey)
req.Header.Set("X-CH-SIGN", signature)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
// Read response
responseBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println("Response:", string(responseBody))
}
// Generate HMAC SHA256 signature
func generateHMACSHA256(data, secret string) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
import time
import hmac
import hashlib
import requests
# API-related information
API_KEY = "Your API-KEY"
API_SECRET = "Your API-SECRET"
BASE_URL = "https://futuresopenapi.fameex.net"
REQUEST_PATH = "/fapi/v1/edit_lever"
# Request method and request body
method = "POST"
body = {"contractName":"E-BTC-USDT","newLever":"1"}
# Get timestamp (in milliseconds)
timestamp = int(time.time() * 1000)
# Convert the request body to a compact JSON string
import json
body_str = json.dumps(body, separators=(',', ':'))
print("Request body (body):", body_str)
# Concatenate the signature string
sign_str = f"{timestamp}{method}{REQUEST_PATH}{body_str}"
print("Signature string:", sign_str)
# Generate HMAC SHA256 signature
signature = hmac.new(API_SECRET.encode('utf-8'), sign_str.encode('utf-8'), hashlib.sha256).hexdigest()
print("Signature (X-CH-SIGN):", signature)
# Build the request headers
headers = {
"Content-Type": "application/json",
"X-CH-TS": str(timestamp),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Python-Client"
}
# Send a POST request
url = BASE_URL + REQUEST_PATH
response = requests.post(url, headers=headers, data=body_str)
# Output the response result
print("Response status code:", response.status_code)
print("Response content:", response.text)
// API-related information
$apiKey = "Your API key";
$apiSecret = "Your API-SECRET";
$baseUrl = "https://futuresopenapi.fameex.net";
$requestPath = "/fapi/v1/edit_lever";
// Request method and request body
$method = "POST";
$body = json_encode([
"contractName" => "E-BTC-USDT",
"newLever" => "1"
], JSON_UNESCAPED_SLASHES);
// Get timestamp in milliseconds
$timestamp = round(microtime(true) * 1000);
// Concatenate the signature string
$signStr = $timestamp . $method . $requestPath . $body;
echo "Signature string: " . $signStr . PHP_EOL;
// Generate HMAC SHA256 signature
$signature = hash_hmac('sha256', $signStr, $apiSecret);
echo "Signature (X-CH-SIGN): " . $signature . PHP_EOL;
// Build the request headers
$headers = [
"Content-Type: application/json",
"X-CH-TS: $timestamp",
"X-CH-APIKEY: $apiKey",
"X-CH-SIGN: $signature",
"User-Agent: PHP-Client"
];
// Send a POST request
$url = $baseUrl . $requestPath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Only use in development environments; SSL verification should be enabled in production environments
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
echo "Request failed: " . curl_error($ch) . PHP_EOL;
} else {
echo "Response status code: $httpCode" . PHP_EOL;
echo "Response content: $response" . PHP_EOL;
}
curl_close($ch);
const crypto = require('crypto');
const axios = require('axios');
// API-related information
const API_KEY = "Your API-KEY";
const API_SECRET = "Your API-SECRET";
const BASE_URL = "https://futuresopenapi.fameex.net";
const REQUEST_PATH = "/fapi/v1/edit_lever";
// Request method and request body
const method = "POST";
const body = JSON.stringify({
contractName: "E-BTC-USDT",
newLever: "1"
});
// Get timestamp in milliseconds
const timestamp = Date.now();
// Concatenate the signature string
const signStr = `${timestamp}${method}${REQUEST_PATH}${body}`;
console.log("Signature string:", signStr);
// Generate HMAC SHA256 signature
const signature = crypto.createHmac('sha256', API_SECRET).update(signStr).digest('hex');
console.log("Signature (X-CH-SIGN):", signature);
// Build the request headers
const headers = {
"Content-Type": "application/json",
"X-CH-TS": timestamp.toString(),
"X-CH-APIKEY": API_KEY,
"X-CH-SIGN": signature,
"User-Agent": "Node.js-Client"
};
// Send a POST request
async function sendOrder() {
try {
const response = await axios.post(`${BASE_URL}${REQUEST_PATH}`, body, { headers });
console.log("Response status code:", response.status);
console.log("Response content:", response.data);
} catch (error) {
console.error("Request failed:", error.response ? error.response.data : error.message);
}
}
// Execute the request
sendOrder();
Request parameters
Parameter name | Type | Description |
---|---|---|
contractName* | string | Contract Name, e.g.,E-BTC-USDT |
newLever* | integer | Adjust Leverage Ratio |
Return example
{
"code": "0",
"msg": "Success",
"data": null
}
Websocket
Overview
WebSocket is a new protocol in HTML5. It enables full-duplex communication between the client and the server, allowing data to be transmitted quickly in both directions. A connection between the client and the server can be established through a simple handshake, and the server can actively push information to the client based on business rules. Its advantages are as follows:
- The request header information is relatively small, about 2 bytes, when transmitting data between the client and the server.
- Both the client and the server can actively send data to each other.
- There is no need to create and destroy TCP requests multiple times, saving bandwidth and server resources.
Basic information
- The basic cryptocurrency market data endpoint:wss://ws.fameex.net/kline-api/ws。
- The basic contract market data endpoint:wss://futuresws.fameex.net/kline-api/ws。
- The returned data, except for heartbeat data, will be compressed in binary format (users need to decompress it using the Gzip algorithm).
Heartbeat
To keep the connection active and stable, it is recommended to perform the following actions:
After receiving each message, the user should set a timer with a duration of N seconds, where N is less than 30.
If the timer is triggered (i.e., no new message is received within N seconds), send the string 'ping'.
You should expect a text string 'pong' as a response. If no response is received within N seconds, trigger an error or reconnect.
The heartbeat response
{
"pong": 15359750
}
Demo
Subscribe/Unsubscribe Parameters
event | channel | description |
---|---|---|
sub | market_$symbol_depth_step0 |
Subscribe to Depth |
unsub | market_$symbol_depth_step0 |
Unsubscribe from Depth |
sub | market_$symbol_trade_ticker |
Subscribe to Real-time Trades |
unsub | market_$symbol_trade_ticker |
Unsubscribe from Real-time Trades |
sub | market_$symbol_ticker |
Subscribe to 24h Market Data |
unsub | market_$symbol_ticker |
Unsubscribe from 24h Market Data |
sub | market_$symbol_kline_1min |
Subscribe to 1-Minute Real-time Kline Data |
req | market_$symbol_kline_1month |
Request 1-Month Historical Kline Data |
Subscribe
Subscribe to full depth
Subscription Example
{
"event": "sub",
"params": {
"channel": "market_$symbol_depth_step0", // $symbol E.g. Spot trading:btcusdt Futures:e_btcusdt
"cb_id": "1" // Business ID is optional
}
}
Return example
{
"channel": "market_btcusdt_depth_step0",
"ts": 1506584998239,
"tick": {
"asks": [ //Sell order
[
10000.19,
0.93
],
[
10001.21,
0.2
],
[
10002.22,
0.34
]
],
"bids": [ //Buy order
[
9999.53,
0.93
],
[
9998.2,
0.2
],
[
9997.19,
0.21
]
]
}
}
Subscribe to real-time trades
Subscription Example
{
"event": "sub",
"params": {
"channel": "market_$symbol_trade_ticker", // $symbol E.g. Spot trading: btcusdt,Futures: e_btcusdt
"cb_id": "1" // Business ID is optional
}
}
Response example
{
"channel": "market_$symbol_trade_ticker",
"ts": 1506584998239, // Request time
"tick": {
"id": 12121, // The "maximum transaction ID in the data"
"ts": 1506584998239, // The "maximum timestamp in the data"
"data": [
{
"side": "buy", // Buy/Sell Direction
"price": 32.233, // Unit Price
"vol": 232, // Quantity
"amount": 323, // Total Amount
"ds": "2017-09-1023: 12: 21"
}
]
}
}
Subscribe to K-line market data
Subscription example
{
"event": "sub",
"params": {
"channel": "market_$symbol_kline_[1min/5min/15min/30min/60min/1day/1week/1month]", // $symbol E.g. btcusdt
"cb_id": "1" // Business ID is optional
}
}
Return example
{
"channel": "market_$symbol_kline_1min", // 1min represents 1-minute candlestick
"ts": 1506584998239, // Request time
"tick": {
"id": 1506602880, // The starting value of the time scale
"vol": 1212.12211, // Trading volume
"open": 2233.22, // Opening price
"close": 1221.11, // Closing price
"high": 22322.22, // Highest price
"low": 2321.22 // Lowest price
}
}
Subscribe to 24h market ticker
Subscription Example
{
"event": "sub",
"params": {
"channel": "market_$symbol_ticker", // $symbol E.g. 币币:btcusdt Futures:e_btcusdt
"cb_id": "1" // Business ID is optional
}
}
Response example
{
"channel": "market_$symbol_ticker",
"ts": 1506584998239, // Request time
"tick": {
"amount": 123.1221, // Trading volume
"vol": 1212.12211, // Trading volume
"open": 2233.22, // Opening price
"close": 1221.11, // Closing price
"high": 22322.22, // Highest price
"low": 2321.22, // Lowest price
"rose": -0.2922, // Price change or percentage change
}
}
Request Historical K-line Data
Subscription Example
{
"event": "req",
"params": {
"channel": "market_$symbol_kline_[1min/5min/15min/30min/60min/1day/1week/1month]",
"cb_id": "1",
"endIdx": "1506602880", // Return the previous pageSize number of records before endIdx. This is optional
"pageSize": 100 // Optional
}
}
Response example
{
"event_rep": "rep",
"channel": "market_$symbol_kline_5min",
"cb_id": "Return the same way",
"ts": 1506584998239, // Request time
"data": [ // Up to 300 entries
{
"id": 1506602880, // The starting value of the time scale
"amount": 123.1221, // Trading volume
"vol": 1212.12211, // Trading volume
"open": 2233.22, // Opening price
"close": 1221.11, // Closing price
"high": 22322.22, // Highest price
"low": 2321.22 // Lowest price
},
{
"id": 1506602880, // The starting value of the time scale
"amount": 123.1221, // Trading volume
"vol": 1212.12211, // Trading volume
"open": 2233.22, // Opening price
"close": 1221.11, // Closing price
"high": 22322.22, // Highest price
"low": 2321.22 // Lowest price
}
]
}
Request transaction records
Request example
{
"event": "req",
"params": {
"channel": "market_$symbol_trade_ticker", // $symbol E.g. Spot trading:btcusdt Futures:e_btcusdt
"cb_id": "1" // Business ID is optional
}
}
Response example
{
"event_rep": "rep",
"channel": "market_$symbol_trade_ticker",
"cb_id": "Return along the original route",
"ts": 1506584998239,
"status": "ok",
"data": [
{
"side": "buy", // Order direction:buy,sell
"price": 32.233, // Unit Price
"vol": 232, // Quantity
"amount": 323 // Total Amount
},
{
"side": "buy", // Order direction:buy,sell
"price": 32.233, // Unit Price
"vol": 232, // Quantity
"amount": 323 // Total Amount
}
]
}
SDK development library
Java
"Frequently Asked Questions" (FAQ)
What is the maximum allowable time difference between the timestamp parameter in the API request and the server's received time?
When the server receives a request, it checks the timestamp in the request. If the timestamp is from more than 5000 milliseconds ago, the request is considered invalid. This time window can be customized by sending the optional parameter recvWindow.
The request header 'X-CH-TS' cannot be empty. How to resolve this?
First, it is recommended to print theX-CH-TS
header. When an exception occurs, check ifX-CH-TS
is empty. Additionally, it is suggested to optimize the code by checking ifX-CH-TS
is empty before each request.
Why does the signature authentication always return an invalid signature?
You can print the request header information and the string before signing. Key points to focus on are as follows:
- Compare your request headers with the following sample request headers one by one
Example of request headers:
Content-Type: application/json
X-CH-APIKEY: 44c541a1-****-****-****-10fe390df2
X-CH-SIGN: ssseLeefrffraoEQ3yI9qEtI1CZ82ikZ4xSG5Kj8gnl3uw=
X-CH-TS: 1574327555669
Is the API key correctly configured in the program?
Does the string before signing conform to the standard format? The order of all elements must remain consistent. You can copy the following example and compare it with your string before signing:
GET example
1588591856950GET/sapi/v1/account
POST example
1588591856950POST/sapi/v1/order/test{"symbol":"BTCUSDT","price":"9300","volume":"1","side":"BUY","type":"LIMIT"}
Why does the API return ILLEGAL_CONTENT_TYPE(-1017)?
We recommend attachingContent-Type
in all request headers and setting it to'application/json'
Is there a limit on the API call frequency per second?
There is a limit. You can refer to the documentation for the access frequency limits of each API
What is the basis for the API access frequency limit?
Personal data access is limited based on the*API-key, while public data access is limited based on theIP. It is important to note that if a user provides valid personal information when requesting public data, the limit will be based on theAPI-key*
How is HTTP status code 429 caused?
Requesting the API exceeds the access frequency limit. It is recommended to reduce the access frequency.
Will the IP be blocked if the API call exceeds the access frequency limit? How long will the block last?
Under normal circumstances, the IP will not be blocked. Reducing the access frequency should resolve the issue.
Why did the WebSocket connection get disconnected?
- The WebSocket connection was disconnected because the heartbeat was not added. The client needs to send a pong message to maintain the connection stability
- The WebSocket connection may be disconnected due to network issues, such as the client sending a pong message that the server did not receive, or other network-related causes.
- It is recommended that users implement a WebSocket reconnection mechanism, so that the program can automatically reconnect if the heartbeat (ping/pong) connection is unexpectedly disconnected.
Why does the user get a Time Out error when requesting the API?
Why does the user get a Time Out error when requesting the API?
How to get all the trading pairs from the platform?
You can get all the trading pairs from the/sapi/v1/symbols
endpoint in spot trading.
Is there a limit on the number of orders or cancellations that can be processed in bulk?
Yes. The bulk API has a limit of 10 orders.
What is newClientOrderId and what is its purpose?
- newClientOrderId is a custom order ID that you can use to identify your order. After placing the order, you can use the newClientOrderId and call the "Order Information" API to check the order status.
- The user needs to ensure that this ID is unique, as we do not perform duplicate checks. If there are duplicates, only the most recent order can be canceled or queried when performing cancel or order status operations.
How to get the latest transaction price?
You can get the latest transaction price by fetching the Ticker information. The 'last' value in the returned result is the latest trade price.
Can the 24-hour trading volume in the Ticker API show negative growth?
Yes, it can. The 24-hour trading volume is a rolling data (with a 24-hour sliding window), and it is possible for the cumulative trading volume and trading value in the later window to be smaller than in the previous window.