Skip to content

bitmartexchange/bitmart-java-sdk-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

74 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Logo

BitMart-Java-SDK-API

Maven Central License: MIT

BitMart Exchange official Java client for the BitMart Cloud API.

Feature

  • Provides exchange quick trading API
  • Easier withdrawal
  • Efficiency, higher speeds, and lower latencies
  • Priority in development and maintenance
  • Dedicated and responsive technical support
  • Provide webSocket apis calls
  • Supported APIs:
    • /spot/*
    • /contract/*
    • /account/*
    • Spot WebSocket Market Stream
    • Spot User Data Stream
    • Contract User Data Stream
    • Contract WebSocket Market Stream
  • Test cases and examples

Installation

The latest version:1.0.1

<dependency>
    <groupId>io.github.bitmartexchange</groupId>
    <artifactId>bitmart-java-sdk-api</artifactId>
    <version>1.0.1</version>
</dependency>

Run mvn install where pom.xml is located to install the dependency. How do ues maven

Documentation

API Documentation

Example

Spot Market API Example

import com.bitmart.api.Call;
import com.bitmart.api.CloudContext;

public class TestSpotMarket {

    public static void main(String[] args) {
        Call call = new Call(new CloudContext());
        
        // Get Currency List
        call.callCloud(new CurrenciesRequest());
        
        // Get List of Trading Pair Details
        call.callCloud(new SymbolsDetailsRequest());
        
        // Get Ticker of a Trading Pair
        call.callCloud(new V3TickerRequest().setSymbol("BTC_USDT"));
    }

}

Spot Trade API Example

import com.bitmart.api.Call;
import com.bitmart.api.CloudContext;

public class TestSpotTrading {

    private static String API_KEY = "YOUR ACCESS KEY";
    private static String API_SECRET = "YOUR SECRET KEY";
    private static String API_MEMO = "YOUR MEMO";

    public static void main(String[] args) {
        CloudContext cloudContext = new CloudContext(new CloudKey(API_KEY, API_SECRET, API_MEMO));
        Call call = new Call(cloudContext);

        CloudResponse cloudResponse = call.callCloud(new SubmitOrderRequest()
                .setSide("sell")
                .setType("limit")
                .setSymbol("BTC_USDT")
                .setPrice("800000")
                .setSize("100"));

        System.out.println(cloudResponse);
    }

}

Spot WebSocket Public Channel Example

public class TestWebSocket {

    public static void main(String[] args) throws Exception {

        // 1.Connection
        WebSocketClient webSocketClient = new WebSocketClient(
                "wss://ws-manager-compress.bitmart.com/api?protocol=1.1", new ReceiveMessage());

        // 2. send subscribe message
        webSocketClient.subscribe(ImmutableList.of(

                // public channel
                "spot/ticker:BTC_USDT",
                "spot/kline1m:BTC_USDT",
                "spot/depth5:BTC_USDT",
                "spot/trade:BTC_USDT"
        ));

    }

    public class ReceiveMessage extends WebSocketCallBack {
        @Override
        public void onMessage(String text) {
            System.out.println(text);
        }

    }
}

Spot WebSocket Private Channel Example

public class TestWebSocket {

    private static String API_KEY = "YOUR ACCESS KEY";
    private static String API_SECRET = "YOUR SECRET KEY";
    private static String API_MEMO = "YOUR MEMO";

    public static void main(String[] args) throws Exception {

        // 1.Connection
        WebSocketClient webSocketClient = new WebSocketClient(
                "wss://ws-manager-compress.bitmart.com/user?protocol=1.1", new ReceiveMessage());

        // 2. login
        webSocketClient.login();

        Thread.sleep(2000L); // wait login

        // 3. send subscribe message
        webSocketClient.subscribe(ImmutableList.of(

                // private channel
                "spot/user/order:BTC_USDT"
        ));

    }

    public class ReceiveMessage extends WebSocketCallBack {
        @Override
        public void onMessage(String text) {
            System.out.println(text);
        }

    }
}

Futures Market API Example

import com.bitmart.api.Call;
import com.bitmart.api.CloudContext;

public class TestFuturesMarket {

    public static void main(String[] args) {
        Call call = new Call(new CloudContext());
        
        // Get Contract Details
        call.callCloud(new DetailsRequest().setSymbol("ETHUSDT"));
        
        // Get Market Depth
        call.callCloud(new DepthRequest().setSymbol("ETHUSDT"));
        
        // Get Futures Open Interest
        call.callCloud(new OpenInterestRequest().setSymbol("ETHUSDT"));
        
        // Get Current Funding Rate
        call.callCloud(new FundingRateRequest().setSymbol("ETHUSDT"));
    }

}

Futures API Example

public class TestFuturesTrading {

    private static String API_KEY = "YOUR ACCESS KEY";
    private static String API_SECRET = "YOUR SECRET KEY";
    private static String API_MEMO = "YOUR MEMO";

    public static void main(String[] args) {
        CloudContext cloudContext = new CloudContext(new CloudKey(API_KEY, API_SECRET, API_MEMO));
        Call call = new Call(cloudContext);

        final CloudResponse cloudResponse = call.callCloud(new SubmitOrderRequest()
                .setSymbol("ETHUSDT")
                .setType("limit")
                .setSide(4)
                .setLeverage("1")
                .setOpen_type("isolated")
                .setSize(1000)
                .setPrice("200000"));

        System.out.println(cloudResponse);
    }

}

Futures WebSocket Public Channel Example

public class TestContractWebSocket {

    public static void main(String[] args) throws Exception {

        // 1.Connection
        ContractWebSocket webSocketClient = new ContractWebSocket(
                "wss://openapi-ws.bitmart.com/api?protocol=1.1", new ReceiveMessage());

        // 2. send subscribe message
        webSocketClient.subscribe(ImmutableList.of(

                // public channel
                "futures/ticker:BTCUSDT",
                "futures/depth20:BTCUSDT",
                "futures/trade:BTCUSDT",
                "futures/klineBin1m:BTCUSDT"
        ));

    }

    public class ReceiveMessage extends WebSocketCallBack {
        @Override
        public void onMessage(String text) {
            System.out.println(text);
        }

    }
}

Futures WebSocket Private Channel Example

public class TestContractWebSocket {

    private static String API_KEY = "YOUR ACCESS KEY";
    private static String API_SECRET = "YOUR SECRET KEY";
    private static String API_MEMO = "YOUR MEMO";

    public static void main(String[] args) throws Exception {

        // 1.Connection
        ContractWebSocket webSocketClient = new ContractWebSocket(
                "wss://openapi-ws.bitmart.com/user?protocol=1.1", new ReceiveMessage());

        // 2. login
        webSocketClient.login();

        Thread.sleep(2000L); // wait login

        // 3. send subscribe message
        webSocketClient.subscribe(ImmutableList.of(

                // private channel
                "futures/asset:BTC",
                "futures/position",
                "futures/order"
        ));

    }

    public class ReceiveMessage extends WebSocketCallBack {
        @Override
        public void onMessage(String text) {
            System.out.println(text);
        }

    }
}

Logging

This SDK uses SLF4J as an abstraction layer for diverse logging frameworks.

It's end-user's responsibility to select the appropriate SLF4J binding to use as the logger (e.g, logback-classic). Otherwise, you might see the following informative output:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

If you prefer to not use a logger and suppress the SLF4J messages instead, you can refer to slf4j-nop.

Timeout

After initializing the CloudContext, you can set the OkHttpClient timeout.

  • Connect Timeout: A connect timeout defines a time period in which our client should establish a connection with a target host.
  • Read Timeout: A read timeout is applied from the moment the connection between a client and a target host has been successfully established.
  • Write Timeout: A write timeout defines a maximum time of inactivity between two data packets when sending the request to the server.

In SDK, if you do not set it, its value will use the default value. The default setting of Connect Timeout and Write Timeout is 2 second, and the default setting of Read Timeout is 10 second.

CloudContext cloudContext = new CloudContext(CLOUD_URL, new CloudKey(API_KEY, API_SECRET, API_MEMO));
cloudContext.setReadTimeoutMilliSeconds(10000); // 10 second
cloudContext.setWriteTimeoutMilliSeconds(2000); // 2 second
cloudContext.setConnectTimeoutMilliSeconds(2000); // 2 second
call = new Call(cloudContext);

Debug

If you want to print the request and response information, you can set it to true.

CloudContext cloudContext = new CloudContext(CLOUD_URL, new CloudKey(API_KEY, API_SECRET, API_MEMO));
cloudContext.setDebug(true);
call = new Call(cloudContext);

Add new endpoint

If the interface you need is not in the SDK, you can add it yourself. Create a new class, inherit CloudRequest, and implement the CloudRequest interface. The field definitions in the class are the requested parameters, and the field names must be consistent with the parameter names in the interface document. If it is inconsistent, you can use the annotation @ParamKey to specify it.

import com.bitmart.api.annotations.ParamKey;
import com.bitmart.api.request.Auth;
import com.bitmart.api.request.CloudRequest;
import com.bitmart.api.request.Method;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.experimental.Accessors;

@EqualsAndHashCode(callSuper = true)
@Data
@ToString
@Accessors(chain = true)
public class NewPointRequest extends CloudRequest {

    @ParamKey(value = "symbol", required = true)
    private String symbol;

    @ParamKey("limit")
    private Integer limit;

    // param1: api path 
    // param2: api method
    // param3: api auth (NONE,KEYED, SIGNED)
    public NewPointRequest() {
        super("/xxx/xxx", Method.GET, Auth.NONE);
    }

}
After the definition is complete, it can be used as follows:
public class TestSpotMark {

    public static void main(String[] args) {
        Call call = new Call(new CloudContext());

        // Call and get response
        CloudResponse cloudResponse = call.callCloud(new NewPointRequest().setSymbol("BTCUSD").setLimit(100));
    }
}
Output: CloudResponse Description
  • responseContent: the server original data returned
  • responseHttpStatus: returned http status code
  • cloudLimit: limit on the number of interface calls
INFO: CloudResponse(responseContent={"code":1000,"message":"success","data":{...},"trace":"b731916b11234da281d888d1f19c8d6c.53.16933945763822873"}, responseHttpStatus=200, cloudLimit=CloudLimit(remaining=1, limit=15, reset=2)