跳到主要内容

合约交易

以下部分概述了认证要求并提供访问合约API的代码示例。

认证类型:

接口类型认证要求
RESTful公共接口不需要认证
RESTful私有接口需要API密钥和签名
Websocket公共接口不需要认证
Websocket私有接口需要API密钥和密钥

代码示例

RESTful公共接口

Python

import requests

def FuturesRestfulPublic(api_url, params):
base_url = "https://api.coinw.com"
url = f'{base_url}{api_url}'

response = requests.get(url, params)
if response.status_code == 200:
return response.json()
else:
return print("Failed to get data. Status code:", response.status_code)

Java

package com.coinw.test.busi.publicCode;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class FuturesRestfulPublic {

private static final String BASE_URL = "https://api.coinw.com";

public static void restfulPublic(String apiUrl, Map<String, String> params) {
String fullUrl = BASE_URL + apiUrl;
if (!params.isEmpty()) {
String query = params.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
fullUrl += "?" + query;
}

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fullUrl))
.build();

try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
System.out.println("API Response: " + response.body());
} else {
System.out.println("Failed to get data. Status code: " + response.statusCode());
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

// Get Instrument Information (获取交易品种信息)
String apiUrl1 = "/v1/perpum/instruments";
Map<String, String> params1 = new HashMap<>();
params1.put("name", "btc");
restfulPublic(apiUrl1, params1);

// Get Funding Fee Rate(获取资金费率)
String apiUrl2 = "/v1/perpum/fundingRate";
Map<String, String> params2 = new HashMap<>();
params2.put("instrument", "btc");
restfulPublic(apiUrl2, params2);


//Get Last Trade Summary of All Instruments(获取所有交易品种最新交易摘要)
String apiUrl3 = "/v1/perpumPublic/tickers";
Map<String, String> params3 = new HashMap<>();
restfulPublic(apiUrl3, params3);

// Get K-Line of an Instrument(获取交易品种K线数据)
String apiUrl4 = "/v1/perpumPublic/klines";
Map<String, String> params4 = new HashMap<>();
params4.put("currencyCode" ,"BTC");
params4.put("granularity", "3");
params4.put("limit", "6");
restfulPublic(apiUrl4, params4);

// Get Last Trade Smmary of an Instrument(获取指定交易品种最新交易摘要)
String apiUrl5 = "/v1/perpumPublic/ticker";
Map<String, String> params5 = new HashMap<>();
params5.put("instrument" ,"BTC");
restfulPublic(apiUrl5, params5);


// Get Trade Data of an Instrument(获取指定交易品种的交易数据)
String apiUrl6 = "/v1/perpumPublic/trades";
Map<String, String> params6 = new HashMap<>();
params6.put("base" ,"sand");
restfulPublic(apiUrl6, params6);


// Get Order Book of an Instrument(获取指定交易品种的订单簿 )
String apiUrl7 = "/v1/perpumPublic/depth";
Map<String, String> params7 = new HashMap<>();
params7.put("base" ,"BTC");
restfulPublic(apiUrl7, params7);


// Get Batch Instruments Info (获取批量交易品种信息)
String apiUrl8 = "/v1/perpum/instrumentList";
Map<String, String> params8 = new HashMap<>();
params8.put("symbols", "BTC,ETH");
restfulPublic(apiUrl8, params8);


// Get Batch Last Summary (获取批量最新交易摘要)
String apiUrl9 = "/v1/perpumPublic/ticker/list";
Map<String, String> params9 = new HashMap<>();
params9.put("symbols", "BTC,ETH");
restfulPublic(apiUrl9, params9);

}
}

RESTful私有接口

Python

import time
import hmac, hashlib, base64
import json


def FuturesRestfulPrivate(params, api_url, method, sec_key, api_key):
"""
Make an API request with HMAC authentication for GET, POST, DELETE, and PUT methods.
"""
# Validate method
valid_methods = {"GET", "POST", "DELETE", "PUT"}
if method.upper() not in valid_methods:
return None, {"error": f"Invalid method: {method}. Supported methods: {valid_methods}"}

# Generate timestamp and base URL
timestamp = str(int(time.time() * 1000))
base_url = "https://api.coinw.com"
request_url = f'{base_url}{api_url}'

# Generate encoded parameters for signature
if method.upper() == "GET":
query_params = "&".join(f"{key}={value}" for key, value in params.items() if value is not None)
encoded_params = f'{timestamp}{method}{api_url}?{query_params}' if query_params else f'{timestamp}{method}{api_url}'
else:
encoded_params = f'{timestamp}{method}{api_url}{json.dumps(params)}'

# Generate HMAC SHA256 signature
signature = base64.b64encode(
hmac.new(bytes(sec_key, 'utf-8'), msg=bytes(encoded_params, 'utf-8'), digestmod=hashlib.sha256).digest()
).decode("US-ASCII")

# Prepare headers
headers = {
"sign": signature,
"api_key": api_key,
"timestamp": timestamp,
}
if method.upper() in ["POST", "DELETE", "PUT"]:
headers["Content-type"] = "application/json"

# Make the API request
if method.upper() == "GET":
response = requests.get(request_url, params=params, headers=headers)
elif method.upper() == "POST":
response = requests.post(request_url, data=json.dumps(params), headers=headers)
elif method.upper() == "DELETE":
response = requests.delete(request_url, data=json.dumps(params), headers=headers)
elif method.upper() == "PUT":
response = requests.put(request_url, data=json.dumps(params), headers=headers)

return response.status_code, response.json()
sec_key = "your_secret_key"
api_key = "your_api_key"

Java

package com.coinw.test.busi.privateCode;

import org.json.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class FuturesRestfulPrivate {
private static final String BASE_URL = "https://api.coinw.com";
private static final String SEC_KEY = "Your_Sec_key";
private static final String API_KEY = "Your_Api_key";

public static Response restfulPrivate(Object params, String apiUrl, String method) throws Exception {
// Generate timestamp
long timestamp = System.currentTimeMillis();
String requestUrl = BASE_URL + apiUrl;
// Generate encoded parameters for signature
String encodedParams;
String queryParams = "";
if (method.equalsIgnoreCase("GET")) {
Map<String,Object> paramsMap = (Map<String,Object>)params;
queryParams = paramsMap.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.map(entry -> {
try {
return URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" + URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.joining("&"));
encodedParams = queryParams.isEmpty() ? timestamp + method + apiUrl : timestamp + method + apiUrl + "?" + queryParams;
if (!queryParams.isEmpty()) {
requestUrl += "?" + queryParams;
}
} else {
String jsonParams = JSONObject.valueToString(params);
encodedParams = timestamp + method + apiUrl + jsonParams;
}

// Generate HMAC SHA256 signature
String signature = generateSignature(encodedParams, SEC_KEY);

// Prepare headers
Map<String, String> headers = new HashMap<>();
headers.put("sign", signature);
headers.put("api_key", API_KEY);
headers.put("timestamp", String.valueOf(timestamp));
if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("DELETE") || method.equalsIgnoreCase("PUT")) {
headers.put("Content-type", "application/json");
}

// Make the API request
return makeRequest(requestUrl, method, headers, params);
}

private static String generateSignature(String data, String secretKey) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] hash = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}

private static Response makeRequest(String requestUrl, String method, Map<String, String> headers,Object params) throws IOException {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);

// Set headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}

if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("DELETE")) {
connection.setDoOutput(true);
String jsonParams = JSONObject.valueToString(params);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
}

int responseCode = connection.getResponseCode();
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line.trim());
}
}

return new Response(responseCode, response.toString());
}

static class Response {
private final int statusCode;
private final String body;

public Response(int statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}

public int getStatusCode() {
return statusCode;
}

public String getBody() {
return body;
}
}

public static void main(String[] args) {
try {

Response response;
Map<String, Object> params = new HashMap<>();
String apiUrl;
String method;

// Place an Order(下单)
System.out.println("----- 下单 Place Order ---------");
apiUrl = "/v1/perpum/order";
method = "POST";
params = new HashMap<>();
params.put("leverage", "5"); //#0 leverage not supported, leverage is mandatory
params.put("instrument", "eth");
params.put("direction", "long");
params.put("quantityUnit", "0"); // # 0 is for usdt, 1 for contracts, 2 for coins
params.put("quantity", "20");
params.put("positionModel", "1"); // #0 for isolated, 1 for cross margin
params.put("positionType", "plan");
params.put("thirdOrderId", "334343434343563xx");
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Current Orders(获取当前订单)
System.out.println("----- Get Current Orders(获取当前订单) -----");
apiUrl = "/v1/perpum/orders/open";
method = "GET";
params.put("instrument", "eth"); // # upper ,lower both valid , #### mandatory
params.put("positionType", "plan"); //mandatory, without it, its error # even you specify execute, you get response for limit orders
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Pending Order Count(获取待处理订单数量)
String apiUrl2 = "/v1/perpum/orders/openQuantity";
String method2 = "GET";
Map<String, Object> params2 = new HashMap<>();
response = restfulPrivate(params2, apiUrl2, method2);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Margin Requirements of All Instruments(获取所有交易品种保证金要求)
String apiUrl3 = "/v1/perpum/ladders";
String method3 = "GET";
Map<String, Object> params3 = new HashMap<>();
response = restfulPrivate(params3, apiUrl3, method3);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Coin Conversion(单位转换)
System.out.println("----- Coin Conversion(单位转换)---------");
String apiUrl4 = "/v1/perpum/pieceConvert";
String method4 = "POST";
Map<String, Object> params4 = new HashMap<>();
params4.put("convertType", "1");
params4.put("dealPiece", "11");
params4.put("faceValue", "0.01");
params4.put("baseSize", "10");
response = restfulPrivate(params4, apiUrl4, method4);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Historical Position Information(获取历史持仓信息)
System.out.println("----- Get Historical Position Information(获取历史持仓信息)---------");
String apiUrl7 = "/v1/perpum/positions/history";
String method7 = "GET";
Map<String, Object> params7 = new HashMap<>();
params7.put("instrument", "eth"); //lower upper both valid
// params7.put("positionModel", "1"); //not mandatory, 0 for isolated, 1 for cross margin
response = restfulPrivate(params7, apiUrl7, method7);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Set Margin Mode(设置持仓模式)
System.out.println("----- Set Margin Mode(设置持仓模式)---------");
String apiUrl8 = "/v1/perpum/positions/type";
String method8 = "POST";
Map<String, Object> params8 = new HashMap<>();
params8.put("layout", "1"); //0: Close warehouse 1: Split warehouse
params8.put("positionModel", "0");
response = restfulPrivate(params8, apiUrl8, method8);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Margin Mode(获取持仓模式)
System.out.println("----- Get Margin Mode(获取持仓模式)---------");
String apiUrl9 = "/v1/perpum/positions/type";
String method9 = "GET";
Map<String, Object> params9 = new HashMap<>();
response = restfulPrivate(params9, apiUrl9, method9);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Max Contract Size(获取最大合约规模)
System.out.println("----- Get Max Contract Size(获取最大合约规模)---------");
String apiUrl10 = "/v1/perpum/orders/maxSize";
String method10 = "GET";
Map<String, Object> params10 = new HashMap<>();
params10.put("leverage", "5");
params10.put("instrument", "eth");
params10.put("positionModel", 1);
response = restfulPrivate(params10, apiUrl10, method10);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Max Users's Contract Size(获取用户最大合约规模)
System.out.println("----- Get Max Users's Contract Size(获取用户最大合约规模)---------");
String apiUrl11 = "/v1/perpum/orders/availSize";
String method11 = "GET";
Map<String, Object> params11 = new HashMap<>();
params11.put("instrument", "eth");
response = restfulPrivate(params11, apiUrl11, method11);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Max Transferable Balance(获取最大可转账余额)
System.out.println("----- Get Max Transferable Balance(获取最大可转账余额)---------");
String apiUrl12 = "/v1/perpum/account/available";
String method12 = "GET";
Map<String, Object> params12 = new HashMap<>();
response = restfulPrivate(params12, apiUrl12, method12);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Adjust Margin(调整保证金)
System.out.println("----- Adjust Margin(调整保证金)---------");
String apiUrl13 = "/v1/perpum/positions/margin";
String method13 = "POST";
Map<String, Object> params13 = new HashMap<>();
params13.put("id", 2435521222632845410l); //Long
params13.put("reduceMargin", new BigDecimal(100));
params13.put("type", "all");
response = restfulPrivate(params13, apiUrl13, method13);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Leverage Information(获取杠杆信息)
System.out.println("----- Get Leverage Information(获取杠杆信息)---------");
String apiUrl14 = "/v1/perpum/positions/leverage";
String method14 = "GET";
params = new HashMap<>();
// params.put("positionId", 122434543454l); // #mandatory if put any other id, still gives response
params.put("orderId", 33308784763561839l);
response = restfulPrivate(params, apiUrl14, method14);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Futures Account Assets(获取合约账户资产)
System.out.println("----- Get Futures Account Assets(获取合约账户资产)---------");
String apiUrl15 = "/v1/perpum/account/fees";
String method15 = "GET";
Map<String, Object> params15 = new HashMap<>();
response = restfulPrivate(params15, apiUrl15, method15);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Current Position Information(获取当前持仓信息)
System.out.println("----- Get Current Position Information(获取当前持仓信息)---------");
apiUrl = "/v1/perpum/positions";
method = "GET";
params = new HashMap<>();
params.put("instrument", "eth"); // #lower upper both valid # mandatory
// params5.put("openIds", "2435521222632817481"); // #positionid format for this #'2435521222631227679,2435521222631227681
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Place Batch Orders(批量下单)
System.out.println("----- Place Batch Orders(批量下单)---------");
String apiUrl17 = "/v1/perpum/batchOrders";
String method17 = "POST";
Map<String, Object> params17 = new HashMap<>();
params17.put("leverage", "5"); //0 leverage not supported, leverage is mandatory
params17.put("instrument", "eth");
params17.put("direction", "long");
params17.put("quantityUnit", "0"); //0 is for usdt, 1 for contracts, 2 for coins
params17.put("quantity", "20");
params17.put("positionModel", "1"); //0 for isolated, 1 for cross margin
params17.put("positionType", "plan");
params17.put("openPrice", "400"); //mandatory for limit order
params17.put("thirdOrderId", "334343434343x");
response = restfulPrivate(Arrays.asList(params17), apiUrl17, method17);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Close Batch Positions(批量平仓)
String apiUrl18 = "/v1/perpum/batchClose";
String method18 = "DELETE";
Map<String, Object> params18 = new HashMap<>();
params18.put("thirdOrderId", "2345324534524");
response = restfulPrivate(Arrays.asList(params18), apiUrl18, method18);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Cancel an Order(取消订单)
System.out.println("----- Cancel an Order(取消订单)---------");
String apiUrl19 = "/v1/perpum/order";
String method19 = "DELETE";
params = new HashMap<>();
params.put("id", "33308784850674484"); //# should take more orderIDs
response = restfulPrivate(params, apiUrl19, method19);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Cancel Batch Orders(取消批量订单)
System.out.println("----- Cancel Batch Orders(取消批量订单)---------");
String apiUrl20 = "/v1/perpum/batchOrders";
String method20 = "DELETE";
Map<String, Object> params20 = new HashMap<>();
params20.put("posType", "plan"); //#not mandatory
params20.put("sourceIds", Arrays.asList(33308784825959506l,33308784826199754l)); //#list of long acceptable
response = restfulPrivate(params20, apiUrl20, method20);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Close a Position(平仓)
System.out.println("----- Close a Position(平仓) ---------");
String apiUrl21 = "/v1/perpum/positions";
String method21 = "DELETE";
Map<String, Object> params21 = new HashMap<>();
params21.put("id", 2435521222632818000l); //mnadatory
params21.put("positionType", "plan");
// params21.put("closeNum", 1);
params21.put("orderPrice", 80000); //open price
params21.put("closeRate", "0.3"); //closeRate or closeNum, one is mandatory
response = restfulPrivate(params21, apiUrl21, method21);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Close Positions at Market Price(市价平仓)
System.out.println("----- Close Positions at Market Price(市价平仓) ---------");
String apiUrl22 = "/v1/perpum/allpositions";
String method22 = "DELETE";
Map<String, Object> params22 = new HashMap<>();
params22.put("instrument", "eth");
response = restfulPrivate(params22, apiUrl22, method22);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Reverse a Position(反向持仓)
System.out.println("----- Reverse a Position(反向持仓) ---------");
String apiUrl101 = "/v1/perpum/positions/reverse";
String method101 = "POST";
params = new HashMap<>();
params.put("id", "2435521222632819975");
response = restfulPrivate(params, apiUrl101, method101);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Order Information(获取订单信息)
System.out.println("----- Get Order Information(获取订单信息) ---------");
String apiUrl23 = "/v1/perpum/order";
String method23 = "GET";
Map<String, Object> params23 = new HashMap<>();
// params23.put("instrument", "eth");
params23.put("positionType", "plan"); //# mandatory # even if the order is limit order, you specify execute, still get the results for limit orders.
params23.put("sourceIds", 33308784770015880l); //not a list # doesnt show any information for orders which get fille
response = restfulPrivate(params23, apiUrl23, method23);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Historical Orders (7 Days)(获取历史订单(7天)"
System.out.println("----- Get Historical Orders (7 Days)(获取历史订单(7天) ---------");
String apiUrl102 = "/v1/perpum/orders/history";
String method102 = "GET";
params = new HashMap<>();
params.put("page", 1);
params.put("instrument", "eth"); //# mandatory
// params.put("originType", "plan");
response = restfulPrivate(params, apiUrl102, method102);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Historical Orders (3 Months)(获取历史订单(3个月)
System.out.println("----- Get Historical Orders (3 Months)(获取历史订单(3个月) ---------");
apiUrl = "/v1/perpum/orders/archive";
method = "GET";
params = new HashMap<>();
params.put("page", 1);
params.put("instrument", "eth"); //# mandatory
params.put("originType", "plan");
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Transaction Details (3 Days)(获取交易详情(3天))
System.out.println("----- Get Transaction Details (3 Days)(获取交易详情(3天)) ---------");
apiUrl = "/v1/perpum/orders/deals";
method = "GET";
params = new HashMap<>();
params.put("page", 1);
params.put("instrument", "eth"); //# mandatory
// params.put("originType", "plan");
params.put("positionModel", 1);
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Transaction Details (3 Months)(获取交易详情(3个月)
System.out.println("----- Get Transaction Details (3 Months)(获取交易详情(3个月) ---------");
apiUrl = "/v1/perpum/orders/deals/history";
method = "GET";
params = new HashMap<>();
params.put("page", 1);
params.put("instrument", "eth"); //# mandatory
// params.put("originType", "plan");
params.put("positionModel", 1);
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Set SL/TP(设置止损/止盈)
System.out.println("----- Set SL/TP(设置止损/止盈) ----");
apiUrl = "/v1/perpum/TPSL";
method = "POST";
params = new HashMap<>();
params.put("id", 2435521222632844158l); //#mnadatory id
params.put("instrument", "eth");
params.put("stopLossOrderPrice", new BigDecimal(100)); //# BigDecimal - Stop-loss limit price
params.put("stopProfitOrderPrice", new BigDecimal(100000)); //BigDecimal - Take-profit limit price
params.put("stopLossPrice",new BigDecimal(100));
params.put("stopProfitPrice",new BigDecimal(10000));
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


//Set SL/TP in Batches(批量设置止损/止盈)
System.out.println("----- Set SL/TP in Batches(批量设置止损/止盈) -----");
apiUrl = "/v1/perpum/addTpsl";
method = "POST";
params = new HashMap<>();
params.put("id", "2435521222632844158"); //#Long orderId
params.put("instrument", "ETH");
// params.put("stopLossOrderPrice", new BigDecimal(100)); //# BigDecimal - Stop-loss limit price
// params.put("stopProfitOrderPrice", new BigDecimal(100000)); //BigDecimal - Take-profit limit price
params.put("stopLossPrice", new BigDecimal(101)); //# BigDecimal - Stop-loss price
params.put("stopProfitPrice", new BigDecimal(10001)); //BigDecimal - Take-profit price
// params.put("stopProfitRate", new BigDecimal(1)); //BigDecimal - Stop-loss rate
// params.put("stopLossRate", new BigDecimal(1)); //BigDecimal - Stop-loss rate
params.put("priceType", 3); //#Integer: Take Profit and Stop Loss trigger price type 1: Index ,2: Latest, 3: Mark
params.put("stopFrom", 2); //#Integer: Stop profit and stop loss order type 1: Limit order, 2: Position, 3: Plan order
params.put("stopType", 2); //#Integer: Stop profit and stop loss type 1: Batch stop profit and stop loss 2: All stop profit and stop loss (only applicable to positions)
// params.put("closePiece", new BigDecimal(1)); //#BigDecimal: Number of take-profit and stop-loss contracts(required when taking profit and stop-loss in batches)
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Modify SL/TP in Batches(批量修改止损/止盈)
System.out.println("----- Modify SL/TP in Batches(批量修改止损/止盈) ----");
apiUrl = "/v1/perpum/updateTpsl";
method = "POST";
params = new HashMap<>();
params.put("id", "2435521222632844158"); //#Long orderId
params.put("instrument", "eth");
// params.put("stopLossOrderPrice", new BigDecimal(200)); //# BigDecimal - Stop-loss limit price
// params.put("stopProfitOrderPrice", new BigDecimal(90000)); //BigDecimal - Take-profit limit price
params.put("stopLossPrice", new BigDecimal(300)); //# BigDecimal - Stop-loss price
params.put("stopProfitPrice", new BigDecimal(10050)); //BigDecimal - Take-profit price
// params.put("stopProfitRate", new BigDecimal(1)); //BigDecimal - Stop-loss rate
// params.put("stopLossRate", new BigDecimal(1)); //BigDecimal - Stop-loss rate
params.put("priceType", 1); //#Integer: Take Profit and Stop Loss trigger price type 1: Index ,2: Latest, 3: Mark
params.put("stopFrom", 2); //#Integer: Stop profit and stop loss order type 1: Limit order, 2: Position, 3: Plan order
params.put("stopType", 2); //#Integer: Stop profit and stop loss type 1: Batch stop profit and stop loss 2: All stop profit and stop loss (only applicable to positions)
params.put("closePiece", new BigDecimal(1)); //#BigDecimal: Number of take-profit and stop-loss contracts(required when taking profit and stop-loss in batches)
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get SL/TP Information(获取止损/止盈信息)
System.out.println("----- 查看止盈止损信息 View SL-TP -----");
apiUrl = "/v1/perpum/TPSL";
method = "GET";
params = new HashMap<>();
// params.put("orderId", 33308784850674484l); //#mnadatory orderID
params.put("openId", 2435521222632844158l); //# position ID
// params.put("planOrderId", 33308784850674484l);
params.put("stopFrom", "2"); //#mandatory # Stop-profit and stop-loss order types 1: Limit order 2: Position 3: Plan order
params.put("instrument", "eth");
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Set Trailing SL/TP(设置追踪止损/止盈)
System.out.println("----- Set Trailing SL/TP(设置追踪止损/止盈)---------");
apiUrl = "/v1/perpum/moveTPSL";
method = "POST";
params = new HashMap<>();
params.put("openId", "2435521222632819975"); // # mandatory # Position ID (Required)
params.put("callbackRate", "0.05"); // # mandatory # Callback rate (Required)
params.put("triggerPrice", new BigDecimal(1900)); //# Activation Price (Optional)
params.put("quantity", new BigDecimal(1)); // # mandatory# Number of positions, contracts/USDT (Required)
params.put("quantityUnit", 1); //# mandatory # Quantity unit, 0: USDT, 1: Number of sheets (Optional)
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());

// Get Trailing SL/TP Information(获取追踪止损/止盈信息)
System.out.println("----- Get Trailing SL/TP Information(获取追踪止损/止盈信息) ---------");
apiUrl = "/v1/perpum/moveTPSL";
method = "GET";
params = new HashMap<>();
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Get Mega Coupon Balance(获取万能金余额)
System.out.println("----- 查看合约万能金信息 View Contract Information ---------");
apiUrl = "/v1/perpum/account/almightyGoldInfo";
method = "GET";
params = new HashMap<>();
params.put("type", 1); // # 0: To be effective 1: Not used 2: Used 3: Expired 4 Issuance failed
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


// Enable/Disable Mega Coupon(启用/禁用万能金)
System.out.println("----- 设置合约万能金状态 Set the Contract Universal Fund Status ---------");
apiUrl = "/v1/perpum/account/almightyGoldInfo";
method = "POST";
params = new HashMap<>();
params.put("status", 1); // # mnadatory #Status 1: On 0: Of
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


//Get Futures Account Assets(获取合约账户资产)
System.out.println("----- Get Futures Account Assets(获取合约账户资产) ---------");
String apiUrl24 = "/v1/perpum/account/getUserAssets";
String method24 = "GET";
params = new HashMap<>();
response = restfulPrivate(params, apiUrl24, method24);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


//Get Public Trades(获取公开交易)
System.out.println("----- 查看用户成交数据 View user transaction data ---------");
apiUrl = "/v1/perpum/orders/trades";
method = "GET";
params = new HashMap<>();
params.put("instrument", "ETH");
params.put("page", 1); // # default 1
params.put("pageSize", 50); // # default 50
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());


//Get Current Positions.(获取当前持仓)
System.out.println("----- Get Current Positions.(获取当前持仓) ---------");
apiUrl = "/v1/perpum/positions/all";
method = "GET";
params = new HashMap<>();
response = restfulPrivate(params, apiUrl, method);
System.out.println("Status : "+response.getStatusCode());
System.out.println("ResponseBody :"+response.getBody());




} catch (Exception e) {
e.printStackTrace();
}
}
}

Websocket公共接口

Python

import websocket
import json
import time

def FuturesWebsocketPublic(url, subscription_params):
try:
ws = websocket.WebSocket()
ws.connect(url)

# Send subscription message
ws.send(json.dumps(subscription_params))
print("Subscription sent")

while True:
# Send ping
ws.send(json.dumps({"event": "ping"}))
print("Ping sent")

# Receive and print message
response = ws.recv()
print(" Received:", response)

time.sleep(0.5)

except KeyboardInterrupt:
print("Disconnected by user.")
ws.close()
except Exception as e:
print(" Error:", e)
ws.close()

Java

package com.coinw.test.busi.publicCode;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FuturesWebsocketPublic extends WebSocketClient {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private boolean authenticated = true;

public FuturesWebsocketPublic(URI serverUri) {
super(serverUri);
}

@Override
public void onOpen(ServerHandshake handshakedata) {
startHeartbeat();

// 24H Trade Summary Subscription(24小时交易摘要订阅)
JSONObject subscriptionJson = new JSONObject();
JSONObject paramsJson = new JSONObject();
paramsJson.put("pairCode", "BTC");
paramsJson.put("type", "ticker_swap");
paramsJson.put("biz", "futures");
subscriptionJson.put("event","sub"); // sub / unsub
subscriptionJson.put("params",paramsJson);
String subscription = subscriptionJson.toString();
this.send(subscription);


// Order Book Subscription(订单簿订阅)
// JSONObject subscriptionJson1 = new JSONObject();
// JSONObject paramsJson1 = new JSONObject();
// paramsJson1.put("pairCode", "BTC");
// paramsJson1.put("type", "deep");
// paramsJson1.put("biz", "futures");
// subscriptionJson1.put("event","sub");
// subscriptionJson1.put("params",paramsJson);
// String subscription1 = subscriptionJson1.toString();
// this.send(subscription1);


// Trade Data Subscription(交易数据订阅)
// JSONObject subscriptionJson2 = new JSONObject();
// JSONObject paramsJson2 = new JSONObject();
// paramsJson2.put("pairCode", "BTC");
// paramsJson2.put("type", "fills");
// paramsJson2.put("biz", "futures");
// subscriptionJson2.put("event","sub");
// subscriptionJson2.put("params",paramsJson);
// String subscription2 = subscriptionJson2.toString();
// this.send(subscription2);


//K-Line(UTC+8) Subscription(K线(UTC+8)数据订阅)
// JSONObject subscriptionJson3 = new JSONObject();
// JSONObject paramsJson3 = new JSONObject();
// paramsJson3.put("pairCode", "BTC");
// paramsJson3.put("type", "candles_swap");
// paramsJson3.put("biz", "futures");
// paramsJson3.put("interval", "1");
// subscriptionJson3.put("event","sub");
// subscriptionJson3.put("params",paramsJson);
// String subscription3 = subscriptionJson3.toString();
// this.send(subscription3);


//K-line(UTC+0) Subscription(K线(UTC+0)数据订阅)
// JSONObject subscriptionJson3 = new JSONObject();
// JSONObject paramsJson3 = new JSONObject();
// paramsJson3.put("pairCode", "BTC");
// paramsJson3.put("type", "candles_swap_utc");
// paramsJson3.put("biz", "futures");
// paramsJson3.put("interval", "1");
// subscriptionJson3.put("event","sub");
// subscriptionJson3.put("params",paramsJson);
// String subscription3 = subscriptionJson3.toString();
// this.send(subscription3);


//Index Price subscription(指数价格订阅)
// JSONObject subscriptionJson3 = new JSONObject();
// JSONObject paramsJson3 = new JSONObject();
// paramsJson3.put("pairCode", "BTC");
// paramsJson3.put("type", "index_price");
// paramsJson3.put("biz", "futures");
// subscriptionJson3.put("event","sub");
// subscriptionJson3.put("params",paramsJson);
// String subscription3 = subscriptionJson3.toString();
// this.send(subscription3);


//Mark Price subscription(标记价格订阅)
// JSONObject subscriptionJson3 = new JSONObject();
// JSONObject paramsJson3 = new JSONObject();
// paramsJson3.put("pairCode", "BTC");
// paramsJson3.put("type", "mark_price");
// paramsJson3.put("biz", "futures");
// subscriptionJson3.put("event","sub");
// subscriptionJson3.put("params",paramsJson);
// String subscription3 = subscriptionJson3.toString();
// this.send(subscription3);


//Funding Fee Rate Subscription (资金费率订阅)
// JSONObject subscriptionJson3 = new JSONObject();
// JSONObject paramsJson3 = new JSONObject();
// paramsJson3.put("pairCode", "BTC");
// paramsJson3.put("type", "funding_rate");
// paramsJson3.put("biz", "futures");
// subscriptionJson3.put("event","sub");
// subscriptionJson3.put("params",paramsJson);
// String subscription3 = subscriptionJson3.toString();
// this.send(subscription3);




System.out.println("Sent subscriptionAssets message");
}

@Override
public void onMessage(String message) {
System.out.println("Received: " + message);

try {
JSONObject json = new JSONObject(message);
// 处理心跳响应
if (json.has("event") && "pong".equals(json.getString("event"))) {
scheduleNextPing();
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void startHeartbeat() {
scheduler.schedule(this::sendPing, 10, TimeUnit.SECONDS);
}

private void scheduleNextPing() {
if (!scheduler.isShutdown()) {
scheduler.schedule(this::sendPing, 10, TimeUnit.SECONDS);
}
}

public void sendPing() {
if (this.isOpen() && authenticated) {
JSONObject ping = new JSONObject();
ping.put("event", "ping");
this.send(ping.toString());
System.out.println("Sent ping");
}
}

@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed: " + reason);
scheduler.shutdown();
}

@Override
public void onError(Exception ex) {
System.err.println("WebSocket error:");
ex.printStackTrace();
}

public static void main(String[] args) throws Exception {
URI uri = new URI("wss://ws.futurescw.com/perpum");
FuturesWebsocketPublic client = new FuturesWebsocketPublic(
uri);
client.connect();
}
}

Websocket私有接口

Python

import websocket
import json
import time

def FuturesWebsocketPrivate(url, subscription_payload, api_key, sec_key):
try:
ws = websocket.WebSocket()
ws.connect(url)

# send payload
ws.send(json.dumps({"event": "login",
"params": { "api_key": api_key,
"passphrase": sec_key}}))
# send subscription
ws.send(json.dumps(subscription_payload))

while True:
# Send ping
ws.send(json.dumps({"event": "ping"}))
print("Ping sent")

# Receive and print message
response = ws.recv()
print(" Received:", response)

time.sleep(0.5)

except KeyboardInterrupt:
print("Disconnected by user.")
ws.close()
except Exception as e:
print(" Error:", e)
ws.close()

Java

package com.coinw.test.busi.privateCode;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FuturesWebsocketPrivate extends WebSocketClient {
private final String API_KEY;
private final String SEC_KEY;
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private boolean authenticated = false;

public FuturesWebsocketPrivate(URI serverUri, String apiKey, String secKey) {
super(serverUri);
this.API_KEY = apiKey;
this.SEC_KEY = secKey;
}

@Override
public void onOpen(ServerHandshake handshakedata) {
// login
JSONObject login = new JSONObject();
login.put("event", "login");
JSONObject params = new JSONObject();
params.put("api_key", API_KEY);
params.put("passphrase", SEC_KEY);
login.put("params", params);
this.send(login.toString());
System.out.println("Sent login message");

// Current Orders Subscription(当前订单订阅)
JSONObject subscribeOrder = new JSONObject();
subscribeOrder.put("event", "sub");
JSONObject subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "order");
subscribeOrder.put("params", subParams);
this.send(subscribeOrder.toString());
System.out.println("Sent subscriptionOrder message");

// Position Subscription(持仓订阅)
JSONObject subscribe = new JSONObject();
subscribe.put("event", "sub");
subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "position");
subscribe.put("params", subParams);
this.send(subscribe.toString());
System.out.println("Sent subscriptionPosition message");

// Position Change Subscription(持仓变更订阅)
JSONObject subscribe = new JSONObject();
subscribe.put("event", "sub");
subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "position_change");
subscribe.put("params", subParams);
this.send(subscribe.toString());
System.out.println("Sent subscriptionPosition message");


// Asset Subscription(资产订阅)
subscribe = new JSONObject();
subscribe.put("event", "sub");
subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "assets");
subscribe.put("params", subParams);
this.send(subscribe.toString());
System.out.println("Sent subscriptionAssets message");

//Mega Coupon Subscription(万能金订阅)
subscribe = new JSONObject();
subscribe.put("event", "sub");
subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "assets_ag");
subscribe.put("params", subParams);
this.send(subscribe.toString());
System.out.println("Sent subscriptionAssets_Ag message");

//Margin Mode Subscription(持仓模式订阅)
subscribe = new JSONObject();
subscribe.put("event", "sub");
subParams = new JSONObject();
subParams.put("biz", "futures");
subParams.put("type", "user_setting");
subscribe.put("params", subParams);
this.send(subscribe.toString());
System.out.println("Sent subscriptionUser_Setting message");


}

@Override
public void onMessage(String message) {
System.out.println("Received: " + message);

try {
JSONObject json = new JSONObject(message);
// 处理登录响应
if (json.has("channel") && "login".equals(json.getString("channel"))) {
if (json.getJSONObject("data").getBoolean("result")) {
authenticated = true;
startHeartbeat();
}
}
// 处理心跳响应
if (json.has("event") && "pong".equals(json.getString("event"))) {
scheduleNextPing();
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void startHeartbeat() {
scheduler.schedule(this::sendPing, 10, TimeUnit.SECONDS);
}

private void scheduleNextPing() {
if (!scheduler.isShutdown()) {
scheduler.schedule(this::sendPing, 10, TimeUnit.SECONDS);
}
}

public void sendPing() {
if (this.isOpen() && authenticated) {
JSONObject ping = new JSONObject();
ping.put("event", "ping");
this.send(ping.toString());
System.out.println("Sent ping");
}
}

@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("Connection closed: " + reason);
scheduler.shutdown();
}

@Override
public void onError(Exception ex) {
System.err.println("WebSocket error:");
ex.printStackTrace();
}

public static void main(String[] args) throws Exception {
URI uri = new URI("wss://ws.futurescw.com/perpum");
FuturesWebsocketPrivate client = new FuturesWebsocketPrivate(
uri,
"YOUR API KEY", // your API KEY
"YOUR SECRET KEY" // your secret KEY
);
client.connect();
}
}
```