Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
For additional examples, please refer to the GitHub repository:
https://github.com/bitmartexchange/bitmart-python-sdk-api/tree/master/examples/spot/trade
BitMart Node SDK const Bitmart = require ( ' @bitmartexchange/bitmart-node-sdk-api ' )
const bitmartSpotAPI = new Bitmart . BitmartSpotAPI ({
apiKey : ' your api key ' ,
apiSecret : ' your secret key ' ,
apiMemo : ' your api memo ' ,
})
bitmartSpotAPI . newSpotOrder ( ' BTC_USDT ' , ' sell ' , ' limit ' , {
size : 10000 ,
price : " 500000 "
}). then ( response => bitmartSpotAPI . logger . log ( response . data ))
. catch ( error => {
if ( error . response ) {
bitmartSpotAPI . logger . log ( error . response . data );
} else if ( error . request ) {
bitmartSpotAPI . logger . log ( error . request );
} else {
bitmartSpotAPI . logger . log ( ' Error ' , error . message );
}
});
Usage Instructions:
Step 1 : Install the Node.js Runtime and npm
You can download and install the latest version of Node.js from the Node.js website , which will automatically install npm (Node Package Manager).
Step 2 : Install Dependencies
Run the following command in your terminal to install the SDK dependency:
npm install @bitmartexchange/bitmart-node-sdk-api
.
Step 3 : Save the Example Code
Save the example code on the right as a .js
file (e.g., place_order.js
) and replace api_key
, secret_key
, and memo
in the file with your own credentials.
Step 4 : Execute the Code
Run the following command in the terminal to execute it:
node place_order.js
.
Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
For additional examples, please refer to the GitHub repository:
https://github.com/bitmartexchange/bitmart-node-sdk-api/tree/master/examples/spot/trade
BitMart Go SDK package main
import (
"github.com/bitmartexchange/bitmart-go-sdk-api"
"log"
)
func main () {
var yourApiKey = "Your API KEY"
var yourSecretKey = "Your Secret KEY"
var yourMemo = "Your Memo"
client := bitmart . NewClient ( bitmart . Config {
ApiKey : yourApiKey ,
SecretKey : yourSecretKey ,
Memo : yourMemo ,
TimeoutSecond : 5 ,
})
// New Order(v2) (SIGNED)
var ac , err = client . PostSpotSubmitOrder ( bitmart . Order {
Symbol : "BTC_USDT" ,
Side : "sell" ,
Type : "limit" ,
Size : "0.1" ,
Price : "10000000" ,
})
if err != nil {
log . Panic ( err )
} else {
log . Println ( ac . Response )
}
}
Usage Instructions:
Step 1 : Install the Go Runtime Environment
Step 2 : Set Go Environment Variables
Ensure that GOPATH and GOROOT are properly configured, and add the Go bin
directory to your system’s PATH environment variable so that you can access the go
command from the terminal.
Step 3 : Install Dependencies
Run the following command in your terminal to install the SDK:
go get github.com/bitmartexchange/bitmart-go-sdk-api
.
Step 4 : Save Example Code
Save the example code on the right as a .go
file (e.g., place_order.go
). Replace the api_key
, secret_key
, and memo
in the file with your own credentials.
Step 5 : Execute the Code
Run the following command in the terminal to execute it:
go run place_order.go
.
Step 6 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
For more examples, refer to the GitHub repository:
https://github.com/bitmartexchange/bitmart-go-sdk-api/tree/master/examples
BitMart Java SDK
pom.xml
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
<modelVersion> 4.0.0</modelVersion>
<groupId> com.your</groupId>
<artifactId> bitmart-order</artifactId>
<packaging> jar</packaging>
<version> 1.0-SNAPSHOT</version>
<name> bitmart-order</name>
<url> http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId> io.github.bitmartexchange</groupId>
<artifactId> bitmart-java-sdk-api</artifactId>
<version> 2.1.0</version>
</dependency>
</dependencies>
</project>
PlaceOrder.java
package com.your ;
import com.bitmart.api.Call ;
import com.bitmart.api.CloudContext ;
import com.bitmart.api.common.CloudException ;
import com.bitmart.api.common.CloudResponse ;
import com.bitmart.api.key.CloudKey ;
import com.bitmart.api.request.spot.prv.SubmitOrderRequest ;
public class PlaceOrder {
private static String API_KEY = "YOUR ACCESS KEY" ;
private static String API_SECRET = "YOUR SECRET KEY" ;
private static String API_MEMO = "YOUR MEMO" ;
private static Call call ;
public static void main ( String [] args ) {
CloudContext cloudContext = new CloudContext ( new CloudKey ( API_KEY , API_SECRET , API_MEMO ));
call = new Call ( cloudContext );
try {
CloudResponse cloudResponse = call . callCloud ( new SubmitOrderRequest ()
. setSide ( "sell" )
. setType ( "limit" )
. setSymbol ( "BTC_USDT" )
. setPrice ( "800000" )
. setSize ( "100" ));
System . out . println ( cloudResponse );
} catch ( CloudException e ) {
System . out . println ( "Error:" + e . getMessage ());
}
}
}
Usage Instructions:
Step 1 : Install the Java Runtime Environment
Step 2 : Set Java Environment Variables
Ensure that the JAVA_HOME
environment variable is properly set, and add the Java bin
directory to your system’s PATH environment variable. This will allow you to access the java
and javac
commands from the terminal.
After the installation is complete, you can verify it by running the following command:
java -version
Step 3 : Install Maven
You can download and install Maven from the Maven website . For macOS or Linux systems, you may also use a package manager (such as brew
or apt
) to install it.
After the installation is complete, you can verify it by running the following command:
mvn -v
Step 4 : Create a Maven Project
Use the following command to generate a new Maven project template:
mvn archetype:generate -DgroupId=com.your -DartifactId=bitmart-order -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command will create a new project folder named bitmart-order
in the current directory, with the following structure:
bitmart-order
├── pom.xml
└── src
└── main
└── java
└── com
└── your
└── App.java
└── PlaceOrder.java
Step 5 : Update the pom.xml File
Open the pom.xml
file in your project folder and add your SDK JAR dependency to the <dependencies>
section. (Refer to the example pom.xml file on the right for guidance).
Step 6 : Save the Example Code
Save the example code on the right as a .java
file (e.g., PlaceOrder.java
) in the com/your
directory. Replace the api_key
, secret_key
, and memo
in the file with your own credentials.
Step 7 : Execute the Code
Navigate to the project root directory:
cd bitmart-order
Run the compilation command:
mvn compile
Then, execute the code with:
mvn exec:java -Dexec.mainClass="com.your.PlaceOrder"
Step 8 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
For additional examples, refer to the GitHub repository:
https://github.com/bitmartexchange/bitmart-java-sdk-api/tree/master/src/test/java/com/bitmart/examples
BitMart PHP SDK <?php
use BitMart\Lib\CloudConfig ;
use BitMart\Spot\APISpot ;
require_once __DIR__ . '/../../../vendor/autoload.php' ;
$APISpot = new APISpot ( new CloudConfig ([
'accessKey' => "<your_api_key>" ,
'secretKey' => "<your_secret_key>" ,
'memo' => "<your_memo>" ,
]));
$response = $APISpot -> postSubmitOrder (
'BTC_USDT' ,
'buy' ,
'limit' ,
[
'size' => '0.1' ,
'price' => '8800' ,
'client_order_id' => 'test20000000005'
]
)[ 'response' ];
echo json_encode ( $response );
Usage Instructions:
Step 1 : Install the PHP Runtime
You can download and install the PHP version compatible with your system from the PHP website .
Step 2 : Install Composer
Composer is a dependency management tool for PHP. You can download and install it from the Composer website .
Step 3 : Install Dependencies
Run the following command in your terminal to install the SDK:
composer require bitmartexchange/bitmart-php-sdk-api
.
Step 4 : Save the Example Code
Save the example code on the right as a .php
file (e.g., place_order.php
). and replace api_key
, secret_key
, and memo
in the file with your own credentials.
Step 5 : Execute the Code
Run the following command in the terminal to execute it:
php place_order.php
.
Step 6 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
For additional examples, please refer to the GitHub repository:
https://github.com/bitmartexchange/bitmart-php-sdk-api/tree/master/examples/spot/Trading
Community Node SDK import { RestClient } from ' ../bitmart-api ' ;
// Or, use require, if you prefer:
// const { RestClient } = require('bitmart-api');
const API_KEY = ' your_api_key ' ;
const API_SECRET = ' your_api_secret ' ;
const API_MEMO = ' your_api_memo ' ;
const SYMBOL = ' BTC_USDT ' ;
const SIZE = ' 100 ' ;
const PRICE = ' 500000 ' ;
const SIDE = ' sell ' ;
const TYPE = ' limit ' ;
const client = new RestClient ({
apiKey : API_KEY ,
apiSecret : API_SECRET ,
apiMemo : API_MEMO ,
});
async function placeOrder () {
try {
const res = await client . submitSpotOrderV2 ({
size : SIZE ,
price : PRICE ,
side : SIDE ,
symbol : SYMBOL ,
type : TYPE ,
});
console . log ( " Order result: " , res );
} catch ( e ) {
console . error ( " Error: " , e );
}
}
placeOrder ();
This is a third-party Node.js SDK that supports all BitMart REST APIs and WebSockets.
Usage Instructions:
Step 1 : Install the Node.js Runtime and npm
You can download and install the latest version of Node.js from the Node.js website , which will automatically install npm (Node Package Manager).
Step 2 : Install Dependencies
Run the following command in your terminal to install the SDK dependency:
npm install bitmart-api
.
Step 3 : Save the Example Code
Import the REST or WebSocket client. Create an instance for each client, and if account functionality is needed, use your API key credentials.
Step 4 : Execute
Call the functions as needed to interact with the API.
For more examples, please refer to the GitHub repository:
https://github.com/tiagosiebler/bitmart-api/tree/master/examples
More Programming Languages
The following example demonstrates how to place a spot order using the REST API. We provide sample code in various programming languages, which you can find here.
If you encounter any issues during implementation, feel free to reach out for support in the official Telegram community, BitMart API Club .
Python Signature Request import json
import requests
import time
import hashlib
import hmac
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'
API_MEMO = 'your_api_memo'
BASE_URL = 'https://api-cloud.bitmart.com'
# Get current timestamp
def get_timestamp ():
return str ( int ( time . time () * 1000 ))
# Generate signature
def generate_signature ( timestamp , body ):
message = f ' { str ( timestamp ) } # { API_MEMO } # { body } '
return hmac . new ( API_SECRET . encode (), message . encode (), hashlib . sha256 ). hexdigest ()
# Set key and sign
def generate_header ( body ):
timestamp = get_timestamp ()
return {
'Content-Type' : 'application/json' ,
'X-BM-KEY' : API_KEY ,
'X-BM-TIMESTAMP' : timestamp ,
'X-BM-SIGN' : generate_signature ( timestamp , str ( json . dumps ( body )))
}
# Place order
def place_order ():
path = '/spot/v2/submit_order'
body = {
'size' : '100' ,
'price' : '500000' ,
'side' : 'sell' ,
'symbol' : 'BTC_USDT' ,
'type' : 'limit'
}
url = BASE_URL + path
response = requests . post ( url , headers = generate_header ( body ), json = body )
if response . status_code == 200 :
print ( response . json ())
else :
print ( 'Error: {}' . format ( response . text ))
if __name__ == '__main__' :
place_order ()
This example includes the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the Python 3.x Runtime Environment
You can download and install the appropriate version for your system from the Python website . It is recommended to use version 3.x.
If you have both Python 2 and Python 3 installed, be sure to use the correct commands, such as pip
and pip3
or python
and python3
, when executing.
Step 2 : Install Dependencies
Run the following command in your terminal to install the requests
dependency:
pip install requests
Step 3 : Save the Example Code
Save the example code on the right as a .py
file (e.g., place_order.py
). and replace the api_key
, secret_key
, and memo
fields in the file with your own credentials.
Step 4 : Execute the Code
Run the following command in the terminal to execute it:
python place_order.py
Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Node Signature Request const axios = require ( ' axios ' );
const crypto = require ( ' crypto ' );
const API_KEY = ' your_api_key ' ;
const API_SECRET = ' your_api_secret ' ;
const API_MEMO = ' your_api_memo ' ;
const BASE_URL = ' https://api-cloud.bitmart.com ' ;
// Get current timestamp
function get_timestamp () {
return new Date (). getTime (). toString ();
}
// Generate signature
function generate_signature ( timestamp , body ) {
const message = ` ${ timestamp } # ${ API_MEMO } # ${ body } ` ;
return crypto . createHmac ( ' sha256 ' , API_SECRET ). update ( message ). digest ( ' hex ' );
}
// Place order
async function place_order () {
const path = ' /spot/v2/submit_order ' ;
const timestamp = get_timestamp ();
const body = {
size : 100 ,
price : 50000 ,
side : ' sell ' ,
symbol : ' BTC_USDT ' ,
type : ' limit ' ,
};
const headers = {
' Content-Type ' : ' application/json ' ,
' X-BM-KEY ' : API_KEY ,
' X-BM-TIMESTAMP ' : timestamp ,
' X-BM-SIGN ' : generate_signature ( timestamp , JSON . stringify ( body )),
};
const url = BASE_URL + path ;
try {
const response = await axios . post ( url , body , { headers });
console . log ( response . data );
} catch ( error ) {
console . error ( `Error:` );
console . error ( error . response . data );
}
}
place_order ();
This example provides the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the Node.js Runtime and npm
You can download and install the latest version of Node.js from the Node.js website , which will automatically install npm (Node Package Manager).
Step 2 : Install Dependencies
Run the following command in your terminal to install the required dependency:
npm install axios
.
Note: crypto
is a built-in Node.js module used for generating HMAC SHA-256 signatures, so no additional installation is needed for it.
Step 3 : Save the Example Code
Save the example code on the right as a .js
file (e.g., place_order.js
). and replace the api_key
, secret_key
, and memo
fields in the file with your own credentials.
Step 4 : Execute the Code
Run the following command in the terminal to execute it:
node place_order.js
Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Go Signature Request package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
const (
apiKey = "your_api_key"
apiSecret = "your_api_secret"
apiMemo = "your_api_memo"
baseURL = "https://api-cloud.bitmart.com"
)
type OrderParams struct {
Size string `json:"size"`
Price string `json:"price"`
Side string `json:"side"`
Symbol string `json:"symbol"`
Type string `json:"type"`
}
// Get current timestamp
func getTimestamp () int64 {
return time . Now () . UnixNano () / int64 ( time . Millisecond )
}
// Generate signature
func generateSignature ( timestamp int64 , body string ) string {
message := fmt . Sprintf ( "%d#%s#%s" , timestamp , apiMemo , body )
h := hmac . New ( sha256 . New , [] byte ( apiSecret ))
h . Write ([] byte ( message ))
return fmt . Sprintf ( "%x" , h . Sum ( nil ))
}
// Place order
func main () {
path := "/spot/v2/submit_order"
method := "POST"
timestamp := getTimestamp ()
orderParams := OrderParams {
Size : "100" ,
Price : "500000" ,
Side : "sell" ,
Symbol : "BTC_USDT" ,
Type : "limit" ,
}
orderParamsJSON , _ := json . Marshal ( orderParams )
body := string ( orderParamsJSON )
signature := generateSignature ( timestamp , body )
req , _ := http . NewRequest ( method , baseURL + path , bytes . NewReader ( orderParamsJSON ))
req . Header . Add ( "Content-Type" , "application/json" )
req . Header . Add ( "X-BM-KEY" , apiKey )
req . Header . Add ( "X-BM-TIMESTAMP" , strconv . FormatInt ( timestamp , 10 ))
req . Header . Add ( "X-BM-SIGN" , signature )
client := & http . Client {}
res , err := client . Do ( req )
if err != nil {
fmt . Println ( "Error:" , err )
return
}
defer res . Body . Close ()
bodyBytes , err := ioutil . ReadAll ( res . Body )
if err != nil {
fmt . Println ( "Error:" , err )
return
}
bodyString := string ( bodyBytes )
if res . StatusCode == 200 {
fmt . Println ( bodyString )
} else {
fmt . Println ( "Error:" , bodyString )
}
}
This example includes the correct method for generating a signature, applicable to all BitMart APIs in this document.
Usage Instructions:
Step 1 : Install the Go Runtime Environment
Step 2 : Set Go Environment Variables
Ensure that GOPATH
and GOROOT
are properly configured, and add the Go bin
directory to your system’s PATH environment variable so that you can access the go
command from the terminal.
Step 3 : Save the Example Code
Save the example code on the right as a .go
file (e.g., place_order.go
) and replace the api_key
, secret_key
, and memo
fields with your own credentials.
Step 4 : Execute the Code
Run the following command in the terminal to execute it:
go run place_order.go
.
Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Java Signature Request
pom.xml
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >
<modelVersion> 4.0.0</modelVersion>
<groupId> com.your</groupId>
<artifactId> bitmart-order</artifactId>
<packaging> jar</packaging>
<version> 1.0-SNAPSHOT</version>
<name> bitmart-order</name>
<url> http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId> javax.servlet</groupId>
<artifactId> javax.servlet-api</artifactId>
<version> 4.0.1</version>
<scope> provided</scope>
</dependency>
<dependency>
<groupId> com.squareup.okhttp3</groupId>
<artifactId> okhttp</artifactId>
<version> 4.9.1</version>
</dependency>
<dependency>
<groupId> com.fasterxml.jackson.core</groupId>
<artifactId> jackson-databind</artifactId>
<version> 2.13.4</version>
</dependency>
<dependency>
<groupId> commons-codec</groupId>
<artifactId> commons-codec</artifactId>
<version> 1.15</version>
</dependency>
</dependencies>
</project>
PlaceOrder.java
package com.your ;
import com.fasterxml.jackson.core.JsonProcessingException ;
import com.fasterxml.jackson.databind.ObjectMapper ;
import okhttp3.* ;
import org.apache.commons.codec.binary.Hex ;
import javax.crypto.Mac ;
import javax.crypto.spec.SecretKeySpec ;
import java.io.IOException ;
import java.security.InvalidKeyException ;
import java.security.NoSuchAlgorithmException ;
import java.time.Instant ;
import java.time.temporal.ChronoUnit ;
import java.util.HashMap ;
import java.util.Map ;
public class PlaceOrder {
private static final String BASE_URL = "https://api-cloud.bitmart.com" ;
private static final String API_KEY = "your_api_key" ;
private static final String API_SECRET = "your_api_secret" ;
private static final String API_MEMO = "your_api_memo" ;
private static final String SYMBOL = "BTC_USDT" ;
private static final String SIZE = "100" ;
private static final String PRICE = "500000" ;
private static final String SIDE = "sell" ;
private static final String TYPE = "limit" ;
private static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8" ;
private static final OkHttpClient httpClient = new OkHttpClient ();
public static void main ( String [] args ) throws NoSuchAlgorithmException , InvalidKeyException , JsonProcessingException {
placeOrder ();
}
private static String getTimestamp () {
return Long . toString ( Instant . now (). truncatedTo ( ChronoUnit . MILLIS ). toEpochMilli ());
}
private static String generateSignature ( String timestamp , String body )
throws NoSuchAlgorithmException , InvalidKeyException {
String message = timestamp + "#" + API_MEMO + "#" + body ;
Mac mac = Mac . getInstance ( "HmacSHA256" );
mac . init ( new SecretKeySpec ( API_SECRET . getBytes (), "HmacSHA256" ));
return Hex . encodeHexString ( mac . doFinal ( message . getBytes ()));
}
private static void placeOrder () throws JsonProcessingException , InvalidKeyException , NoSuchAlgorithmException {
String timestamp = getTimestamp ();
String path = "/spot/v2/submit_order" ;
String url = BASE_URL + path ;
ObjectMapper mapper = new ObjectMapper ();
Map < String , String > order = new HashMap <>();
order . put ( "symbol" , SYMBOL );
order . put ( "type" , TYPE );
order . put ( "side" , SIDE );
order . put ( "size" , SIZE );
order . put ( "price" , PRICE );
String body = mapper . writeValueAsString ( order );
String signature = generateSignature ( timestamp , body );
Map < String , String > headers = new HashMap <>();
headers . put ( "Content-Type" , MEDIA_TYPE_JSON );
headers . put ( "X-BM-KEY" , API_KEY );
headers . put ( "X-BM-TIMESTAMP" , timestamp );
headers . put ( "X-BM-SIGN" , signature );
RequestBody requestBody = RequestBody . create ( body , MediaType . parse ( MEDIA_TYPE_JSON ));
Request request = new Request . Builder ()
. url ( url )
. headers ( okhttp3 . Headers . of ( headers ))
. post ( requestBody )
. build ();
try ( Response response = httpClient . newCall ( request ). execute ()) {
if ( response . isSuccessful ()) {
System . out . println ( response . body (). string ());
} else {
System . err . println ( "Error: " + response . body (). string ());
}
} catch ( IOException e ) {
e . printStackTrace ();
}
}
}
This example provides the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the Java Runtime Environment
Step 2 : Set Java Environment Variables
Ensure the JAVA_HOME
environment variable is properly set, and add the Java bin
directory to your system’s PATH environment variable. This will allow you to access the java
and javac
commands from the terminal.
After the installation is complete, you can verify it by running the following command:
java -version
Step 3 : Install Maven
You can download and install Maven from the Maven website . On macOS or Linux systems, you may also install it via a package manager (such as brew
or apt
).
After the installation is complete, you can verify it by running the following command:
mvn -v
Step 4 : Create a Maven Project
Use the following command to generate a new Maven project template:
mvn archetype:generate -DgroupId=com.your -DartifactId=bitmart-order -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command will create a new project folder named bitmart-order
in the current directory with the following structure:
bitmart-order
├── pom.xml
└── src
└── main
└── java
└── com
└── your
└── App.java
└── PlaceOrder.java
Step 5 : Update the pom.xml
File
Open the pom.xml
file in your project folder and add the SDK JAR dependency to the <dependencies>
section (refer to the example pom.xml
on the right for guidance).
Step 6 : Save the Example Code
Save the example code on the right as a .java
file (e.g., PlaceOrder.java
) in the com/your
directory. Replace the api_key
, secret_key
, and memo
fields with your own credentials.
Step 7 : Execute the Code
Navigate to the project root directory:
cd bitmart-order
Compile the code with:
mvn compile
Then, run the application:
mvn exec:java -Dexec.mainClass="com.your.PlaceOrder"
Step 8 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
PHP Signature Request <?php
$API_KEY = 'your_api_key' ;
$API_SECRET = 'your_api_secret' ;
$API_MEMO = 'your_api_memo' ;
$BASE_URL = 'https://api-cloud.bitmart.com' ;
$SYMBOL = 'BTC_USDT' ;
$SIZE = '100' ;
$PRICE = '500000' ;
$SIDE = 'sell' ;
$TYPE = 'limit' ;
// Get current timestamp
function get_timestamp () {
return strval ( round ( microtime ( true ) * 1000 ));
}
// Generate signature
function generate_signature ( $timestamp , $body ) {
$message = $timestamp . '#' . $GLOBALS [ 'API_MEMO' ] . '#' . $body ;
return hash_hmac ( 'sha256' , $message , $GLOBALS [ 'API_SECRET' ]);
}
// Place order
function place_order () {
$path = '/spot/v2/submit_order' ;
$timestamp = get_timestamp ();
$body = json_encode ( array (
'size' => $GLOBALS [ 'SIZE' ],
'price' => $GLOBALS [ 'PRICE' ],
'side' => $GLOBALS [ 'SIDE' ],
'symbol' => $GLOBALS [ 'SYMBOL' ],
'type' => $GLOBALS [ 'TYPE' ]
));
$headers = array (
'Content-Type: application/json' ,
'X-BM-KEY: ' . $GLOBALS [ 'API_KEY' ],
'X-BM-TIMESTAMP: ' . $timestamp ,
'X-BM-SIGN: ' . generate_signature ( $timestamp , $body )
);
$url = $GLOBALS [ 'BASE_URL' ] . $path ;
$ch = curl_init ( $url );
curl_setopt ( $ch , CURLOPT_POST , 1 );
curl_setopt ( $ch , CURLOPT_POSTFIELDS , $body );
curl_setopt ( $ch , CURLOPT_HTTPHEADER , $headers );
curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , true );
$response = curl_exec ( $ch );
curl_close ( $ch );
if ( $response ) {
$response_json = json_decode ( $response , true );
print_r ( $response_json );
} else {
echo 'Error: ' . curl_error ( $ch );
}
}
place_order ();
?>
This example provides the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the PHP Runtime
You can download and install the appropriate PHP version for your system from the PHP website .
Step 2 : Save the Example Code
Save the example code on the right as a .php
file (e.g., place_order.php
). and replace the api_key
, secret_key
, and memo
fields in the file with your own credentials.
Step 3 : Execute the Code
Run the following command in the terminal to execute it:
php place_order.php
Step 4 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
C# Signature Request using System ;
using System.Net.Http ;
using System.Security.Cryptography ;
using System.Text ;
using System.Text.Json ;
using System.Threading.Tasks ;
namespace BitMartAPI
{
class Program
{
const string API_KEY = "your_api_key" ;
const string API_SECRET = "your_api_secret" ;
const string API_MEMO = "your_api_memo" ;
const string BASE_URL = "https://api-cloud.bitmart.com" ;
static async Task Main ( string [] args )
{
await PlaceOrderAsync ();
}
// Get current timestamp
static string GetTimestamp ()
{
return DateTimeOffset . Now . ToUnixTimeMilliseconds (). ToString ();
}
// Gennerate sign
static string GenerateSignature ( string timestamp , string body )
{
string message = $" { timestamp } # { API_MEMO } # { body } " ;
using HMACSHA256 hmac = new HMACSHA256 ( Encoding . UTF8 . GetBytes ( API_SECRET ));
byte [] hash = hmac . ComputeHash ( Encoding . UTF8 . GetBytes ( message ));
return BitConverter . ToString ( hash ). Replace ( "-" , "" ). ToLower ();
}
// Place spot order
static async Task PlaceOrderAsync ()
{
string path = "/spot/v2/submit_order" ;
var body = new
{
size = "100" ,
price = "500000" ,
side = "sell" ,
symbol = "BTC_USDT" ,
type = "limit"
};
string url = BASE_URL + path ;
string requestBody = JsonSerializer . Serialize ( body );
string timestamp = GetTimestamp ();
string signature = GenerateSignature ( timestamp , requestBody );
var request = new HttpRequestMessage ( HttpMethod . Post , url );
request . Content = new StringContent ( requestBody , Encoding . UTF8 , "application/json" );
request . Headers . Add ( "X-BM-KEY" , API_KEY );
request . Headers . Add ( "X-BM-TIMESTAMP" , timestamp );
request . Headers . Add ( "X-BM-SIGN" , signature );
using var httpClient = new HttpClient ();
HttpResponseMessage response = await httpClient . SendAsync ( request );
string responseBody = await response . Content . ReadAsStringAsync ();
if ( response . IsSuccessStatusCode )
{
Console . WriteLine ( responseBody );
}
else
{
Console . WriteLine ( $"Error: { responseBody } " );
}
}
}
}
This example provides the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the .NET Runtime
You can download and install the latest version of the .NET SDK from the .NET website .
Step 2 : Create a New .NET Project
Step 3 : Install Required NuGet Packages (Optional)
Although this code primarily uses built-in .NET libraries, such as System.Net.Http
, System.Text.Json
, and System.Security.Cryptography
—which are usually included with the .NET SDK—if you encounter missing dependencies, you can manually install the relevant packages.
Navigate to the project root directory: cd BitMartNet
Install the packages using the following commands:
dotnet add package System.Net.Http
dotnet add package System.Text.Json
Step 4 : Save the Example Code
Overwrite the Program.cs
file in the project with the example code provided on the right. Replace the api_key
, secret_key
, and memo
fields in the file with your own credentials.
Step 5 : Execute the Code
Run the following command in the terminal to execute it:
dotnet run
Step 6 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Ruby Signature Request require 'json'
require 'openssl'
require 'net/http'
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'
API_MEMO = 'your_api_memo'
BASE_URL = 'https://api-cloud.bitmart.com'
def get_timestamp ()
( Time . now . to_f * 1000 ). to_i . to_s
end
def generate_signature ( timestamp , body )
message = " #{ timestamp } # #{ API_MEMO } # #{ body } "
OpenSSL :: HMAC . hexdigest ( 'sha256' , API_SECRET , message )
end
def generate_header ( body )
timestamp = get_timestamp
{
'Content-Type' => 'application/json' ,
'X-BM-KEY' => API_KEY ,
'X-BM-TIMESTAMP' => timestamp ,
'X-BM-SIGN' => generate_signature ( timestamp , body . to_json )
}
end
def place_order ()
path = '/spot/v2/submit_order'
body = {
'size' : '100' ,
'price' : '500000' ,
'side' : 'sell' ,
'symbol' : 'BTC_USDT' ,
'type' : 'limit'
}
url = URI . parse ( BASE_URL + path )
req = Net :: HTTP :: Post . new ( url )
req . body = body . to_json
req . initialize_http_header ( generate_header ( body ))
res = Net :: HTTP . start ( url . host , url . port , use_ssl: true ) do | http |
http . request ( req )
end
if res . code . to_i == 200
puts JSON . parse ( res . body )
else
puts "Error: #{ res . body } "
end
end
if __FILE__ == $0
place_order ()
end
This example provides the correct method for generating a signature, applicable to all BitMart APIs covered in this document.
Usage Instructions:
Step 1 : Install the Ruby Runtime Environment
You can download and install Ruby from the Ruby website . If you are using macOS or Linux, Ruby may already be pre-installed. You can verify the installation by running the following command:
ruby -v
Step 2 : Install Dependencies
Run the following commands in your terminal to install the required dependencies:
gem install json
gem install openssl
Step 3 : Save the Example Code
Save the example code on the right as a .rb
file (e.g., place_order.rb
). Replace the api_key
, secret_key
, and memo
fields in the file with your own credentials.
Step 4 : Execute the Code
Run the following command in the terminal to execute it:
ruby place_order.rb
Step 5 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Rust Signature Request
Cargo.toml
[ package ]
name = "bitmart_rust"
version = "0.1.0"
edition = "2021"
[ dependencies ]
tokio = { version = "1" , features = [ "full" ]}
reqwest = { version = "0.11.17" , features = [ "json" , "blocking" ]}
serde_json = { version = "1.0.96" }
sha2 = "0.10.6"
hmac = "0.12.1"
hex = "0.4.3"
[[ bin ]]
name = "place_order"
path = "src/place_order.rs"
place_order.rs
use reqwest :: header ::{ HeaderMap , CONTENT_TYPE };
use serde_json :: json ;
use std :: time ::{ SystemTime , UNIX_EPOCH };
use sha2 ::{ Sha256 };
use hmac ::{ Hmac , Mac };
use hex ;
type HmacSha256 = Hmac < Sha256 > ;
const API_KEY : & str = "your_api_key" ;
const API_SECRET : & str = "your_api_secret" ;
const API_MEMO : & str = "your_api_memo" ;
const BASE_URL : & str = "https://api-cloud.bitmart.com" ;
// Get current timestamp
fn get_timestamp () -> String {
let since_epoch = SystemTime :: now () .duration_since ( UNIX_EPOCH ) .expect ( "Time went backwards" );
since_epoch .as_millis () .to_string ()
}
// Generate signature
fn generate_signature ( timestamp : & str , body : & str ) -> String {
let mut hmac = HmacSha256 :: new_from_slice ( API_SECRET .as_bytes ()) .expect ( "HMAC error" );
let message = format! ( "{}#{}#{}" , timestamp , API_MEMO , body );
hmac .update ( message .as_bytes ());
let result = hmac .finalize ();
hex :: encode ( result .into_bytes ())
}
// Set key and sign
fn generate_header ( body : & serde_json :: Value ) -> HeaderMap {
let timestamp = get_timestamp ();
let signature = generate_signature ( & timestamp , & body .to_string ());
let mut headers = HeaderMap :: new ();
headers .insert ( CONTENT_TYPE , "application/json" .parse () .unwrap ());
headers .insert ( "X-BM-KEY" , API_KEY .parse () .unwrap ());
headers .insert ( "X-BM-TIMESTAMP" , timestamp .parse () .unwrap ());
headers .insert ( "X-BM-SIGN" , signature .parse () .unwrap ());
headers
}
// Place order
#[tokio::main]
async fn main () -> Result < (), Box < dyn std :: error :: Error >> {
let path = "/spot/v2/submit_order" ;
let body = json! ({
"size" : "100" ,
"price" : "500000" ,
"side" : "sell" ,
"symbol" : "BTC_USDT" ,
"type" : "limit"
});
let url = format! ( "{}{}" , BASE_URL , path );
let response = reqwest :: Client :: new ()
.post ( & url )
.headers ( generate_header ( & body ))
.json ( & body )
.send ()
.await ? ;
if response .status () .is_success () {
let data = response .json :: < serde_json :: Value > () .await ? ;
println! ( "{:#?}" , data );
if data [ "code" ] .as_u64 () == Some ( 1000 ) {
println! ( "Success" );
} else {
println! ( "Fail Reason:{:#?}" , data [ "message" ] .as_str ());
}
} else {
println! ( "Error: {}" , response .text () .await ? );
}
Ok (())
}
Usage Instructions:
Step 1 : Install the Rust Runtime Environment
Step 2 : Create a New Rust Project
Step 3 : Save the Example Code
Create a new code file within the src
directory in the project’s root directory (the file location is important for successful execution).
Save the example code on the right as a .rs
file (e.g., place_order.rs
). Replace the api_key
, secret_key
, and memo
fields with your own credentials.
Step 4 : Edit the Cargo.toml
File to Add Dependencies and Build the Project
Open the Cargo.toml
file located in your project directory. Under [dependencies]
, add the required dependencies and update the [[bin]]
section for binary execution (refer to the code on the right for guidance).
Then, run the following command in the current directory’s terminal to build the project:
cargo build
Step 5 : Execute the Code
Run the following command in the terminal to execute the code:
cargo run --bin place_order
Step 6 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
C++ Signature Request #include <iostream>
#include <string>
#include <chrono>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <curl/curl.h>
#include "json.hpp"
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
using namespace std ;
using namespace std :: chrono ;
using json = nlohmann :: json ;
string API_KEY = "your_api_key" ;
string API_SECRET = "your_api_secret" ;
string API_MEMO = "your_api_memo" ;
string BASE_URL = "https://api-cloud.bitmart.com" ;
string get_timestamp () {
auto now = time_point_cast < milliseconds > ( system_clock :: now ());
auto value = now . time_since_epoch (). count ();
return to_string ( value );
}
string generate_signature ( string timestamp , string body ) {
string message = timestamp + "#" + API_MEMO + "#" + body ;
string digest ;
try {
CryptoPP :: HMAC < CryptoPP :: SHA256 > hmac ( reinterpret_cast < const CryptoPP :: byte *> ( API_SECRET . data ()), API_SECRET . size ());
CryptoPP :: StringSource ( message , true ,
new CryptoPP :: HashFilter ( hmac ,
new CryptoPP :: HexEncoder (
new CryptoPP :: StringSink ( digest ), false
)
)
);
} catch ( const CryptoPP :: Exception & e ) {
cerr << "HMAC generation error: " << e . what () << endl ;
}
return digest ;
}
size_t curl_callback ( char * ptr , size_t size , size_t nmemb , string * stream ) {
size_t bytes = size * nmemb ;
stream -> append ( ptr , bytes );
return bytes ;
}
void place_order () {
string path = "/spot/v2/submit_order" ;
json body = {
{ "size" , "100" },
{ "price" , "500000" },
{ "side" , "sell" },
{ "symbol" , "BTC_USDT" },
{ "type" , "limit" }
};
string url = BASE_URL + path ;
CURL * curl = curl_easy_init ();
if ( curl )
{
string timestamp = get_timestamp ();
string signature = generate_signature ( timestamp , body . dump (). c_str ());
struct curl_slist * headers = NULL ;
headers = curl_slist_append ( headers , "Content-Type: application/json" );
headers = curl_slist_append ( headers , ( "X-BM-KEY: " + API_KEY ). c_str ());
headers = curl_slist_append ( headers , ( "X-BM-TIMESTAMP: " + timestamp ). c_str ());
headers = curl_slist_append ( headers , ( "X-BM-SIGN: " + signature ). c_str ());
curl_easy_setopt ( curl , CURLOPT_HTTPHEADER , headers );
curl_easy_setopt ( curl , CURLOPT_URL , url . c_str ());
curl_easy_setopt ( curl , CURLOPT_CUSTOMREQUEST , "POST" );
curl_easy_setopt ( curl , CURLOPT_FOLLOWLOCATION , 1L );
curl_easy_setopt ( curl , CURLOPT_DEFAULT_PROTOCOL , "https" );
curl_easy_setopt ( curl , CURLOPT_POSTFIELDSIZE , body . dump (). size ());
curl_easy_setopt ( curl , CURLOPT_POSTFIELDS , strdup ( body . dump (). c_str ()));
curl_easy_setopt ( curl , CURLOPT_WRITEFUNCTION , curl_callback );
curl_easy_setopt ( curl , CURLOPT_CONNECTTIMEOUT , 6 );
curl_easy_setopt ( curl , CURLOPT_TIMEOUT , 6 );
string response ;
curl_easy_setopt ( curl , CURLOPT_WRITEDATA , & response );
CURLcode res = curl_easy_perform ( curl );
if ( res == CURLE_OK ) {
json j = json :: parse ( response );
cout << "resp: " << j . dump ( 4 ) << endl ;
} else {
cerr << "Error: " << response << endl ;
cerr << "Error: " << curl_easy_strerror ( res ) << endl ;
}
curl_easy_cleanup ( curl );
}
curl_global_cleanup ();
}
int main () {
place_order ();
return 0 ;
}
Usage Instructions:
This example provides a correct method for creating a signature, applicable to all BitMart APIs discussed in this document.
Step 1 : Install a C++ Compiler
Supports C++20 or higher is required.
On Ubuntu or Debian, you can install it by running: sudo apt-get install g++
.
On macOS, g++
is typically provided through Xcode Command Line Tools and may not require additional installation.
Step 2 : Install the curl
Library
On Ubuntu or Debian, you can install it by running: sudo apt-get install libcurl4-openssl-dev
.
On macOS, you can install it via Homebrew: brew install curl
.
Step 3 : Install the nlohmann/json
Library
This code uses the nlohmann/json
library for handling JSON data.
To use this library, download the json.hpp
header file and place it in the same directory as the sample code.
1.Download the header file directly: In your project folder, download and add json.hpp
, available from the nlohmann/json GitHub repository .
Step 4 : Install Crypto++
Library
Before using this example, ensure that the Crypto++ library is installed on your system:
On Ubuntu or Debian, you can install it by running: sudo apt-get install libcrypto++-dev
.
On macOS, you can install it via Homebrew: brew install cryptopp
.
Step 5 : Save the Example Code
Save the example code on the right as a .cpp
file (e.g., place_order.cpp
). Replace the api_key
, secret_key
, and memo
fields with your own credentials.
Step 6 : Compile the Code
Use the following command to compile the code and link the curl
and cryptopp
libraries:
g++ place_order.cpp -o place_order -std=c++20 -lcryptopp -lcurl
For example, if you are on macOS, check the installation directory using brew info cryptopp
. If Crypto++ is installed in /opt/homebrew/Cellar/cryptopp/8.9.0/
, you can compile with the following command:
g++ place_order.cpp -o place_order -std=c++20 -I/opt/homebrew/Cellar/cryptopp/8.9.0/include -L/opt/homebrew/Cellar/cryptopp/8.9.0/lib -lcryptopp -lcurl
Step 7 : Run the Code
Execute the compiled binary file in the terminal by running:
./place_order
Step 8 : Verify the Result
After execution, you should receive a response in the following format. If the response contains code=1000
and the data
field includes an order_id
, this indicates that your order was successfully placed:
{
"message": "OK",
"code": 1000,
"trace": "f7f74924-14da-42a6-b7f2.***. ",
"data": { "order_id": "762455937****" }
}
Postman Quick Experience
Now you can quickly experience and use the API interface through BitMart Postman
Disclaimer
For ease of reference, this statement collectively refers to our platform as "We." Any individual or entity accessing our platform is considered a user, hereafter referred to as "You." We would like to inform you of the following risks associated with using third-party SDKs (Software Development Kits):
Your use of any third-party SDKs through our platform is entirely voluntary and at your discretion; we neither recommend nor endorse any third-party SDKs.
We are not responsible for reviewing third-party SDKs and make no warranties or representations concerning the validity, accuracy, reliability, quality, stability, completeness, or timeliness of the technology and information provided by these services.
You assume full responsibility for any risks associated with your use of third-party SDKs services.
Any issues arising from the use of third-party SDKs, including but not limited to legal disputes, contractual obligations, or financial losses, must be resolved directly between you and the third-party provider. We disclaim any liability in such matters.
By clicking "Next", you confirm that you have read and agree to all terms of this Disclaimer.
Cancel
Next
免责声明
为了本声明表述之方便,本平台在声明中合称使用“我们”。只要登录本平台的自然人或其他主体均为本平台的用户,以下使用“您”。我们在此特向您提醒第三方SDK(Software Development Kit)风险如下:
您通过本平台而使用任何第三方SDK的行为,均为您个人的自由选择行为,我们并不向您推荐或建议使用;
我们不对任何第三方SDK负有审核责任,也不对其服务所涉及的技术及信息的有效性、准确性、正确性、可靠性、质量、稳定性、完整性和及时性作出任何承诺和保证;
您自行承担使用第三方SDK服务产生的全部责任;
您因使用第三方SDK而涉及的包括但不限于法律问题、合同责任问题、经济损失问题等,均由您与第三方SDK自行解决,我们不对此承担责任。
点击“下一步”即表示您已阅读并同意本免责声明的所有条款。
取消
下一步