Code Monkey home page Code Monkey logo

binance-connector-java's Introduction

Binance Public API connector Java

maven License: MIT Code Style

This is a lightweight library that works as a connector to the Binance public API.

It supports the following APIs:

  • /api/* endpoints;
  • /sapi/* endpoints;
  • Spot WebSocket Market Stream;
  • Spot User Data Stream;
  • Spot WebSocket API;

Additionally, it includes test cases and examples.

Documentation

https://www.javadoc.io/doc/io.github.binance/binance-connector-java/latest/index.html

Getting Started

Copy and paste the following dependency snippet into your pom.xml file, replacing `LATEST_VERSION`` with the most recent version available:

<dependency>
    <groupId>io.github.binance</groupId>
    <artifactId>binance-connector-java</artifactId>
    <version>LATEST_VERSION</version>
</dependency>

Next, install the dependency by executing mvn install in the directory where your pom.xml is located.

Examples

The examples are located under src/test/java/examples. Before running any of it, PrivateConfig.java must be set up correctly with API_KEY and SECRET_KEY or PRIVATE_KEY_PATH (if using RSA Keys).

Note that this PrivateConfig.java is only used for examples, you should have your own configuration file when using the library.

REST APIs

Market Endpoint: Exchange Information

SpotClient client = new SpotClientImpl();
Map<String, Object> parameters = new LinkedHashMap<>();
String result = client.createMarket().exchangeInfo(parameters);

Trade Endpoint: Testing a new order

SpotClient client = new SpotClientImpl(PrivateConfig.API_KEY, PrivateConfig.SECRET_KEY);

Map<String,Object> parameters = new LinkedHashMap<String,Object>();
parameters.put("symbol","BTCUSDT");
parameters.put("side", "SELL");
parameters.put("type", "LIMIT");
parameters.put("timeInForce", "GTC");
parameters.put("quantity", 0.01);
parameters.put("price", 9500);

String result = client.createTrade().testNewOrder(parameters);

WebSocket Stream

WebSocketStreamClient wsStreamClient = new WebSocketStreamClientImpl(); // defaults to live exchange unless stated.

// Single stream
int streamID1 = wsStreamClient.aggTradeStream("btcusdt",((event) -> {
    System.out.println(event);
}));

// Combined streams
ArrayList<String> streams = new ArrayList<>();
streams.add("btcusdt@trade");
streams.add("bnbusdt@trade");

int streamID2 = wsStreamClient.combineStreams(streams, ((event) -> {
    System.out.println(event);
}));

// Close single stream
wsStreamClient.closeConnection(streamID1); //closes aggTradeStream-btcusdt
        
// Close all streams
wsStreamClient.closeAllConnections();

Different types of WebSocket callbacks are available. Please refer to the src/test/java/examples/websocketstream/TradeStreamWithAllCallbacks.java example file to explore their usage.

WebSocket API

RsaSignatureGenerator signatureGenerator =  new RsaSignatureGenerator("PRIVATE_KEY_PATH");
WebSocketApiClient wsApiClient = new WebSocketApiClientImpl("API_KEY", signatureGenerator); // defaults to live exchange unless stated

// Open connection with a callback as parameter
wsApiClient.connect(((message) -> {
System.out.println(message);
}));

JSONObject optionalParams = new JSONObject();
optionalParams.put("requestId", "request123");
optionalParams.put("quantity", 1);

wsApiClient.trade().testNewOrder("BTCUSDT", "BUY", "MARKET", optionalParams);

Thread.sleep(60000);

// Close connection
wsApiClient.close();

If requestId is empty (""), null or not sent, this library will generate a UUID string for it.

Different types of WebSocket callbacks are available. Please refer to the src/test/java/examples/websocketapi/WsApiwithAllCallbacks.java example file to explore their usage.

Features

Testnet

While /sapi/* endpoints do not yet have a testnet environment, /api/* endpoints can be tested on the Spot Testnet. You can use it by changing the base URL:

Map<String,Object> parameters = new LinkedHashMap<>();

SpotClient client = new SpotClientImpl(PrivateConfig.TESTNET_API_KEY, PrivateConfig.TESTNET_SECRET_KEY, PrivateConfig.TESTNET_URL);
String result = client.createMarket().time();

Base URL

If baseUrl is not provided, it defaults to api.binance.com.

It's recommended to pass in the baseUrl parameter, even in production as Binance provides alternative URLs:

  • https://api1.binance.com
  • https://api2.binance.com
  • https://api3.binance.com
  • https://api4.binance.com

Optional parameters

Parameters can be set in any implementation of Map<String, Object> interface, where String represents the parameter name and Object the parameter value. These parameters should have the same naming as in the API doc."

Map<String,Object> parameters = new LinkedHashMap<String,Object>();

parameters.put("symbol","BTCUSDT");
parameters.put("side", "SELL");
parameters.put("type", "LIMIT");
parameters.put("timeInForce", "GTC");
parameters.put("quantity", 0.01);
parameters.put("price", 9500);

Response MetaData

The Binance API server provides weight usages in the headers of each response, which can be returned if you set setShowLimitUsage(true).

SpotClient client = new SpotClientImpl();
client.setShowLimitUsage(true);
String result = client.createMarket().time();
logger.info(result);

Output:

INFO: {"data":"{"serverTime":1633434339494}","x-mbx-used-weight":"1","x-mbx-used-weight-1m":"1"}

Proxy

To set HTTP Proxy, call setProxy() with ProxyAuth and before submitting requests:

SpotClient client = new SpotClientImpl();
Proxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
ProxyAuth proxy = new ProxyAuth(proxyConn, null);

client.setProxy(proxy);
logger.info(client.createMarket().time());

For authenticated Proxy, define ProxyAuth with Authenticator from okhttp3:

SpotClient client = new SpotClientImpl();
Proxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
Authenticator auth = new Authenticator() {
    public Request authenticate(Route route, Response response) throws IOException {
        if (response.request().header("Proxy-Authorization") != null) {
            return null; // Give up, we've already failed to authenticate.
          }
      
        String credential = Credentials.basic("username", "password");
        return response.request().newBuilder().header("Proxy-Authorization", credential).build();
        
    }
};
ProxyAuth proxy = new ProxyAuth(proxyConn, auth);

client.setProxy(proxy);
logger.info(client.createMarket().time());

To undo Proxy, use unsetProxy() before submitting requests:

client.unsetProxy();
logger.info(client.createMarket().time());

Complete examples are available at src/test/java/examples/spot/proxy folder.

Logging

This connector 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, slf4j-jdk14 or 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.

In case you want to use our custom logback-classic, it's available at binance-logback.

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

Types of Signature Generator

When creating SpotClient, WebSocketStreamClient or WebSocketApiClient, you use one of the following types of Signature Generator to create signatures (for SIGNED endpoints) based on your security preference:

  • HmacSignatureGenerator - Use of API Key and Secret Key.
  HmacSignatureGenerator signGenerator = new HmacSignatureGenerator("SecretKey");
  SpotClient client = new SpotClientImpl("ApiKey", signGenerator);
  • RsaSignatureGenerator - Use of API Key and RSA algorithm keys.
  RsaSignatureGenerator signGenerator =  new RsaSignatureGenerator("PathToPrivateKey"); 
  // or if Private Key is protected
  // RsaSignatureGenerator signGenerator = new RsaSignatureGenerator("PathToPrivateKey", "PrivateKeyPassword")
  SpotClient client = new SpotClientImpl("ApiKey", signGenerator);
  • Ed25519SignatureGenerator - Use of API Key and Ed25519 algorithm keys.
  Ed25519SignatureGenerator signGenerator =  new Ed25519SignatureGenerator("PathToPrivateKey");
  SpotClient client = new SpotClientImpl("ApiKey", signGenerator);

Errors

There are 3 types of error which may be thrown by this library.

  • BinanceConnectorException
    • This is thrown when there is a validation error for parameters.For instance, mandatory parameter not sent. This error will be thrown before the request is sent to the server.
  • BinanceClientException
    • This is thrown when server returns 4XX, it's an issue from client side.
    • The error consists of these 3 objects which will help in debugging the error:
      • httpStatusCode - HTTP status code
      • errorCode - API Server's error code, e.g. -1102
      • errMsg - API Server's error message, e.g. Unknown order sent.
  • BinanceServerException
    • This is thrown when server returns 5XX, it's an issue from server side.
try {
      String result = client.createTrade().newOrder(parameters);
      logger.info(result);
    } catch (BinanceConnectorException e) {
      logger.error("fullErrMessage: {}", e.getMessage(), e);
    } catch (BinanceClientException e) {
      logger.error("fullErrMessage: {} \nerrMessage: {} \nerrCode: {} \nHTTPStatusCode: {}",
      e.getMessage(), e.getErrMsg(), e.getErrorCode(), e.getHttpStatusCode(), e);
    }

Test Cases

mvn clean test

Contribution

Contributions are welcome!

If you've found a bug within this project, please open an issue to discuss what you would like to change.

If it's an issue with the API itself, you can submit on the Binance Developer Community

binance-connector-java's People

Contributors

2pd avatar aisling-2 avatar alplabin avatar chairz avatar chairz-2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binance-connector-java's Issues

Can we use it to trade in future by writing extra files ?

Hard to connect to trade in future . But i receive ALL Futures KLine by writing extra files .

when i try trade in future , the problem occured ,

2022-05-09 23:01:48.419[1652108508419] | INFO  | main       | c.b.c.client.utils.RequestHandler    - POST https://dapi.binance.com/fapi/v1/order/test?symbol=BTCUSD_PERP&side=BUY&type=LIMIT&timestamp=1652108508350&signature=060612e707910fc02cc14d3060e52fde363d54b4012849eec1cfcb057b0b74a2
OrderTest Exception:<!DOCTYPE html>
<!-- saved from url=(0032)https://www.binance.com/en/error -->
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <meta name="format-detection" content="telephone=no,email=no,address=no">
  <title>Binance</title>
  <link rel="Shortcut Icon" href="https://www.binance.com/en/favicon.ico">
  <style>
    body {
      margin: 0
    }

    .img {
      width: 611px;
      margin: 68px auto 0
    }

    .info {
      width: 370px;
      margin: 0 auto;
      text-align: center;
      font-family: Arial;
    }

    .info h3 {
      margin: 0;
      font-size: 25px;
      color: #333;
      font-weight: normal;
    }

    .info p {
      font-size: 14px;
      font-family: Arial;
      color: #333;
      line-height: 18px;
      margin: 0
    }

    .info button {
      margin-top: 20px;
      width: 231px;
      height: 34px;
      background: #FFFFFF;
      border: 1px solid #F0B90B;
      box-sizing: border-box;
      border-radius: 3px;
      font-size: 14px;
      line-height: 16px;
      color: #F0B90B;
    }
  </style>
</head>

<body>
  <div class="img"><img alt="" src="/errorPages/404.jpg"></div>
  <div class="info">
    <h3>出错啦!您访问的网页不存在。</h3>
    <p>Sorry! The page you’re looking for cannot be found.</p>
    <a href="/">
      <button>Return to Binance home page</button>
    </a>
  </div>

</body>

</html>

java.lang.NoSuchMethodError: okhttp3

Hi everyone, Need help - what to do with - java.lang.NoSuchMethodError: okhttp3 ?

Simgle method -

public String orderCreate(String currency, double price){
parameters.clear();
parameters.put("symbol",currency);
parameters.put("side", "BUY");
parameters.put("type", "LIMIT");
//parameters.put("timeInForce", "GTC");
//parameters.put("quantity", 0.01);
parameters.put("price", new BigDecimal(price));

String result = client.createTrade().testNewOrder(parameters);
//String result = client.createTrade().newOrder(parameters);
System.out.println(result);
return result;

}

Create exception

2022-01-27 01:55:24.065[1643237724065] | INFO | AWT-EventQueue-0 | c.b.c.client.utils.RequestHandler - POST https://api.binance.com/api/v3/order/test?symbol=ETHUSDT&side=BUY&type=LIMIT&price=10&timestamp=1643237724048&signature=c6195ee4542f50832c5ae35ccf2c8edc03b476c6e60c38fa59515d1328672b29
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: okhttp3.RequestBody.create(Ljava/lang/String;Lokhttp3/MediaType;)Lokhttp3/RequestBody;
at com.binance.connector.client.utils.RequestBuilder.buildApiKeyRequest(RequestBuilder.java:57)
at com.binance.connector.client.utils.RequestHandler.sendApiRequest(RequestHandler.java:48)
at com.binance.connector.client.utils.RequestHandler.sendSignedRequest(RequestHandler.java:77)
at com.binance.connector.client.impl.spot.Trade.testNewOrder(Trade.java:58)

google says need to update okhttp3 library.
But on that version ?
Or how to fix it ?

[“code”:-1102,”msg”:”Mandatory parameter ‘amount’ was not sent”] purchasing staking product with Java API

while using the official Java API Library ( io.github.binance.binance-connector-java v 1.9.0) to execute purchases of Staking products for various assets i came across this error: {“code”:-1102,“msg”:“Mandatory parameter ‘amount’ was not sent, was empty/null, or malformed.”}.
The error occurred only for some assets/products while for other pairs the purchase completed correctly and in every call to the API, the “amount” parameter was correctly set as a Double value as expected by the method “com.binance.connector.client.impl.spot.Staking.purchase(LinkedHashMap<String, Object> parameters)”.

After some troubleshooting I found that the error occurs every time I pass an amount value with decimal digits with every asset/productId pair, while if I pass an integer value, the call completes correctly every time.

Looking at the querystring that is generated with decimal values I found that the library escapes the decimal separator with %2C:

https://api.binance.com/sapi/v1/staking/purchase?product=STAKING&productId=Shib*120&amount=3389%2C34&timestamp=1663486749228&signature=xxxxxxxxxxx

while with integer values there are no escapes and the call succedes:

https://api.binance.com/sapi/v1/staking/purchase?product=STAKING&productId=Shib*120&amount=3389&timestamp=1663487010880&signature=xxxxxxxxxxx

Investigating more on the issue, I found that probably lies in DecimalFormat conversion with locales that differ from EN or US, in fact I'm reproducing the issue on a machine with IT locale.

In class com.binance.connector.client.utils.UrlBuilder there is a method getFormatter() to obtain a DecimalFormat to convert to string Numbers. This method's current implementation uses the System current locale to obtain a DecimalFomat instance and this causes issues when the program is running on Locales that use "," instead of "." for decimal separator.

For reference, I fixed the problem forcing the locale symbols for DecimalFormat initialization to Locale.US:

  	private static DecimalFormat getFormatter() {
		if (null == df) {
			DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
			df = new DecimalFormat("##.########", symbols);
			df.setMaximumFractionDigits(MAX_DECIMAL_DIGITS);
			df.setGroupingUsed(false);

		}
		return df;
	}

Support all endpoints

Either many endpoints are not supported, or it is quite unclear how they can be called with this library. E.g., there seem to be no Simple Earn endpoints. (sapi/v1/simple-earn/locked/history/rewardsRecord etc.) Please add them.

code: -1021 Timestamp for this request was 1000ms ahead of the server's time.

it was fine until for no reason it started saying this

2022-06-12 20:50:23.133[1655059823133] | ERROR | main       | c.m.m.BinanceConnection              - fullErrMessage: {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."} 
errMessage: Timestamp for this request was 1000ms ahead of the server's time. 
errCode: -1021 
HTTPStatusCode: 400
com.binance.connector.client.exceptions.BinanceClientException: {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}

the time is not given by my code but by the binance-connector-java automatically, how can i fix or override it? i tried by manually setting the timestamp parameter in the linked hashmap parameters like this
parameters.put("timestamp", System.currentTimeMillis());
but it gives me the same error.

How to disable build-in logging mechanism

I'm writing a piece of code that uses java-binance-api library and I have a problem. Every time I run program, it leaves so much logs from web services execution. Everything works just fine, so now I would like to disable this feature. But it seems to be hard coded and I don't see any attribute to disable it.

Please someone tell me how to do it - disable logging both to standard output and to file. But please do not write something like 'take source code from GIT and erase logger from code and then compile library for yourself' ;)

Lowercase symbol in stream

Symbol has to be lowercase in websocket, but if not, no error occurs and the stream is opened transparently even if it doesn't work.

Do you think it could be a good idea to add an assertion, log a warn or lower case it in WebsocketClientImpl ? Or it is preferable to let the user deal with it ?

Request request = RequestBuilder.buildWebsocketRequest(String.format("%s/ws/%s@aggTrade", baseUrl, symbol));

OKHTTP3 error

Running the following code:

        LinkedHashMap<String,Object> parameters = new LinkedHashMap<String,Object>();

        parameters.put("symbol","BTCUSDT");
        parameters.put("side", "SELL");
        parameters.put("type", "LIMIT");
        parameters.put("timeInForce", "GTC");
        parameters.put("quantity", 0.01);
        parameters.put("price", 9500);
        
        String result = client.createTrade().testNewOrder(parameters);

Results on the following error:

'okhttp3.RequestBody okhttp3.RequestBody.create(java.lang.String, okhttp3.MediaType)'] with root cause
java.lang.NoSuchMethodError: 'okhttp3.RequestBody okhttp3.RequestBody.create(java.lang.String, okhttp3.MediaType)'
	at com.binance.connector.client.utils.RequestBuilder.buildApiKeyRequest(RequestBuilder.java:57)
RequestBuilder.java:57

Version tested is 1.2.0

Could you please check this?

Thank you

Fiat orders has no information in the data field

Good morning, I am trying to have the deposits and withdrawals that I have made in my account and in the data field it does not show any type of information, and it's okay to say that if I have deposits

Request
LinkedHashMap<String,Object> parameters = new LinkedHashMap<>();
parameters.put("transactionType", "0");
parameters.put("beginTime","1609477200000");
parameters.put("endTime", ""+new Date().getTime());
String result = spotClient.createFiat().orders(parameters);

Response
{"code":"000000","message":"success","data":[],"total":0,"success":true}

Please what could be happening?

Watch dog - Connection recovery

Hello

Has the connector any watchdog implementation to reconnect the websocket in case of failure or after the 24h limit?

Regards

the wallet endpoint is equal to createWallet, but i can access a wallet endpoint method by createTrade, how

i tried to do the following in a class that i called BinanceConnection:

//creation of client with spot Test Network
14-                I_UserConnection connect = new TestUser(); 
15-                SpotClientImpl client = connect.createConnection();
16-                String result = ""; 
17-                
18-                try {
19-                       LinkedHashMap<String,Object> parameters = new LinkedHashMap<>();
                          /*
                          the line below is supposed to return the wallet coins info
                          and to be the same as the binance api Wallet -> All coins' information (USER_DATA)
                          */
20-                       result = client.createWallet().coinInfo(parameters); 
21-                       logger.info(result);
22-                   }
23-                   catch (Ex1 e) { . . . }
26-                   catch (Ex2 e) { . . . }

the result of the code is the following

--- exec-maven-plugin:3.0.0:exec (default-cli) @ projecttest1 ---
2022-06-12 20:38:18.847[1655059098847] | INFO  | main       | c.b.c.client.utils.RequestHandler    - GET https://testnet.binance.vision/sapi/v1/capital/config/getall?timestamp=1655059097707&signature=(HMAC SHA256)
2022-06-12 20:38:21.867[1655059101867] | ERROR | main       | c.m.m.BinanceConnection              - fullErrMessage:  
errMessage: null 
errCode: 0 
HTTPStatusCode: 404
com.binance.connector.client.exceptions.BinanceClientException: 
	at com.binance.connector.client.utils.ResponseHandler.handleErrorResponse(ResponseHandler.java:63)
	at com.binance.connector.client.utils.ResponseHandler.handleResponse(ResponseHandler.java:32)
	at com.binance.connector.client.utils.RequestHandler.sendApiRequest(RequestHandler.java:53)
	at com.binance.connector.client.utils.RequestHandler.sendSignedRequest(RequestHandler.java:77)
	at com.binance.connector.client.impl.spot.Wallet.coinInfo(Wallet.java:58)
	at com.mycompany.mavenproject1test.BinanceConnection.main(BinanceConnection.java:20)

now if i try differently using this:
result = client.createTrade().account(parameters);
it gives me the wallet coins info, why is that?

Trouble while using Trade.newOrder(parameters) method to send an order to binance.

Hi,
What is wrong with this rest query built by the Trade.newOrder(paramters) method of Binance Java Connector :
POST https://api.binance.com/api/v3/order?symbol=XTZBNB&side=BUY&type=MARKET&orderQuoteQty=0.7244&timestamp=1664034364836&signature=4950ba6a96a4076400513710c69ea118d7928d24467af3b410f

I get this BinanceClientException...
com.binance.connector.client.exceptions.BinanceClientException: {"code":-1104,"msg":"Not all sent parameters were read; read '5' parameter(s) but was sent '6'."}

Iassume it's not an binance java connector issue but i follow the doc and it's not working so i ask...

Thanks for your help.
Olivier.

withdrawHistory not working

LinkedHashMap<String,Object> parameters = new LinkedHashMap<>();

SpotClientImpl client = new SpotClientImpl(API_KEY, SECRET_KEY);
String result = client.createWallet().withdrawHistory(parameters);

result is empty !

Websocket got java.io.InterruptedIOException: executor rejected after second time invoke

Hi, I tried to wrap the following function and call it by the Spring controller. The first time works fine and returned right info. However, when I invoked it the second time, it will cause java.io.InterruptedIOException: executor rejected. What happened?

HmacSignatureGenerator signatureGenerator = new HmacSignatureGenerator(accountDetail.getSecretKey());
        WebSocketApiClient client = new WebSocketApiClientImpl(accountDetail.getApiKey(), signatureGenerator, DefaultUrls.WS_API_URL);
        final int waitTime = 5000;
        System.out.println(Thread.currentThread().getName());
        client.connect(((event) -> {
            System.out.println(event);
        }));

        client.account().accountTradeHistory("BTCUSDT", null);
        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
        client = null;

Error:

java.io.InterruptedIOException: executor rejected
	at okhttp3.internal.connection.RealCall$AsyncCall.executeOn(RealCall.kt:501) ~[okhttp-4.9.3.jar:na]
	at okhttp3.Dispatcher.promoteAndExecute(Dispatcher.kt:184) ~[okhttp-4.9.3.jar:na]
	at okhttp3.Dispatcher.enqueue$okhttp(Dispatcher.kt:125) ~[okhttp-4.9.3.jar:na]
	at okhttp3.internal.connection.RealCall.enqueue(RealCall.kt:164) ~[okhttp-4.9.3.jar:na]
	at okhttp3.internal.ws.RealWebSocket.connect(RealWebSocket.kt:165) ~[okhttp-4.9.3.jar:na]
	at okhttp3.OkHttpClient.newWebSocket(OkHttpClient.kt:281) ~[okhttp-4.9.3.jar:na]
	at com.binance.connector.client.utils.WebSocketConnection.connect(WebSocketConnection.java:66) ~[binance-connector-java-3.0.0rc3.jar:na]
	at com.binance.connector.client.impl.WebSocketApiClientImpl.connect(WebSocketApiClientImpl.java:93) ~[binance-connector-java-3.0.0rc3.jar:na]
	at com.binance.connector.client.impl.WebSocketApiClientImpl.connect(WebSocketApiClientImpl.java:84) ~[binance-connector-java-3.0.0rc3.jar:na]
	at com.cryptotal.service.core.service.BinanceUtils.getTransactionAsync(BinanceUtils.java:19) ~[classes/:na]

Market constructors

Since market data endpoints have NONE security type, I think it would be a good option to have a constructor with only baseUrl and showLimitUsage parameters without needing to set apiKey and proxy to null in the constructor call

Wrong timestamp

public static final String buildTimestamp() { return String.valueOf(System.currentTimeMillis()); }

Im get {"code":-1021,"msg":"Timestamp for this request is outside of the recvWindow."}, using postman and pass my params all work fine, but when using lib the currentTimeMillis is wrong

Track onFailure for websocket and check if websocket connection is alive

Hi ,

  1. how can I check if my websocket connection is open/running ?

  2. I wonder if the openEvent,closingEvent and FailureEvent variables can return a value other than null ? I would like to know why my websocket is failing sometimes.

          onOpenCallbackMarket = openEvent -> {
    
         };
          onMessageCallbackMarket = (message) -> {
             
        };
         onClosingCallbackMarket = closingEvent -> {
    
         };
         onFailureCallbackMarket = failureEvent -> { 
        
        };
    

How to get open order status?

I was trying to detect if open order status has been filled, but I can't seem to find a function that can do that.

I'm using Java.

No trading fees from api on testnet

I'm using the trading fees from wallet API in my program.

At some time I'll need to test my program on testnet before going on prod with real money.

But, as the trade fees wallet endpoint returns an empty response on testnet (realized that with postman), my program won't run correctly.

Is there a solution to this problem, other than mocking the call to fees endpoint myself?

Thanks

universalTransfer Unsupported operation

Hi,

I want to make transfer between subaccounts, I'm using createSubAccount().universalTransfer method.
Generated request is
https://api.binance.com/sapi/v1/sub-account/universalTransfer?fromEmail=a&toEmail=b&fromAccountType=SPOT&toAccountType=SPOT&asset=DAI&amount=1&timestamp=1653671807424&signature=6c267d5ef333243dd5d47a3e520384fba43ce20e1858582d64b004456844338e
and response is
{"code":-9000,"msg":"Unsupported operation"}
(status 400)

My API has 'Enable Internal Transfer' option enabled
Please help )

EDIT: i suspect that my account type is broker account, could it be the reason? And how I can check type of account to be sure?

java.lang.NoSuchMethodError: 'okhttp3.RequestBody okhttp3.RequestBody.create(java.lang.String, okhttp3.MediaType)'

java.lang.NoSuchMethodError: 'okhttp3.RequestBody okhttp3.RequestBody.create(java.lang.String, okhttp3.MediaType)'
at com.binance.connector.client.utils.RequestBuilder.buildApiKeyRequest(RequestBuilder.java:56)
at com.binance.connector.client.utils.RequestHandler.sendApiRequest(RequestHandler.java:48)
at com.binance.connector.client.utils.RequestHandler.sendSignedRequest(RequestHandler.java:77)
at com.binance.connector.client.impl.spot.Wallet.fundingWallet(Wallet.java:448)

Tune OkHttpClient settings

Hello.
How can I set OkHttpClient properties with binance-connector-java?
I want to enable pings for WebSocket connections.
OkHttpClient has property pingIntervalMillis, that initialized from OkHttpClient.Builder.
But binance-connector-java calls constructor of OkHttpClient with default Builder.

library return type(s)

hi,

it's intended that the library return string or object without parsing the actual response into jav models?

it seems more like a wrapper around an http client rather than a library, even params need to be send as map, not like method signature or proper modelized in a java fashion

am i missing something?

{code:1022,msg:"Signature for this request is not valid "}

I use withdraw api interface with this SDK
error
{code:1022,msg:"Signature for this request is not valid "}

code:
LinkedHashMap<String, Object> parameters = new LinkedHashMap<>();
parameters.put("coin", trade.getCoin());
parameters.put("address", trade.getAddress());
parameters.put("amount", new BigDecimal(trade.getAmount()));
parameters.put("network", trade.getNetwork());
parameters.put("walletType", Integer.parseInt(trade.getWalletType()));
SpotClientImpl client = new SpotClientImpl(key.getApikey(),key.getSecretKey());
String tradeResult = client.createWallet().withdraw(parameters);
log.info("tradeResult: " +tradeResult);

please help me, thanks!

How to trade in futures

Hi,

I wanted to know what the procedure to place a futures long order is. Is there any specific Order class to adjust the leverage? Or how would you do that? Do I need to request and borrow an specified amount of collateral to get the leverage I want?

Has anybody proved it already?

Thanks in advance!

Proxy support for WebsocketClient

The newly added support of proxy in the SpotClient was a godsend.
Is there any plan to support proxy in the WebsocketClient as well?

Error: Hostname api.binance.com not verified (no certificates)

Hi,
I am using binance-connector-java version 1.6.0 in spring boot 2.7.0 & JDK 11

		<dependency>
		    <groupId>io.github.binance</groupId>
		    <artifactId>binance-connector-java</artifactId>
		    <version>1.6.0</version>
		</dependency>

Sometime I am getting below issues while calling api/v3/ticker/price.

BinanceService_loadExchangeRates: Request={symbols=["TRXBTC","TRXETH","ETHUSDT","ETHBTC","TRXUSDT","BTCUSDT"]}
2023-02-16 12:44:23.855[1676551463855] | INFO  | taskExecutor-1 | c.b.c.client.utils.RequestHandler    - GET https://api.binance.com/api/v3/ticker/price?symbols=%5B%22TRXBTC%22%2C%22TRXETH%22%2C%22ETHUSDT%22%2C%22ETHBTC%22%2C%22TRXUSDT%22%2C%22BTCUSDT%22%5D
Error:[ResponseHandler] **OKHTTP Error: Hostname api.binance.com not verified (no certificates)**
com.binance.connector.client.exceptions.BinanceConnectorException: [ResponseHandler] OKHTTP Error: Hostname api.binance.com not verified (no certificates)
	at com.binance.connector.client.utils.ResponseHandler.handleResponse(ResponseHandler.java:41)
	at com.binance.connector.client.utils.RequestHandler.sendApiRequest(RequestHandler.java:53)
	at com.binance.connector.client.utils.RequestHandler.sendPublicRequest(RequestHandler.java:58)
	at com.binance.connector.client.impl.spot.Market.tickerSymbol(Market.java:256)

Please help me to fix issue.
Thanks.

Why library is not using POJO?

Hello everyone!

Since there is no discussion part I'm going to use an issue for it. I noticed that the library uses String class to return the responses from the Binance. I am curious to know what is the reason behind it. Why have the POJOs not been used for this purpose? also inputs are dynamic and used LinkedHashMap .

"timestamp" differs with server time

I'm faced with next problem:
My OS has autoSync date/time.
Binance test net server were delayed near 18s. It cause error by Binance Timing security
In current implementation "timestamp" setting is hardcoded:
parameters.put("timestamp", UrlBuilder.buildTimestamp()); in RequestHandler.class.
UrlBuilder.buildTimestamp() uses undercover System.currentTimeMillis().

As result, it is not possible to adjust "timestamp"
Java not allows to modify systemTime. UrlBuilder.buildTimestamp() is static.
RequestHandler can be extended with methods override, but all Endpoints (Market, Trade, etc) have finalized field requestHandler with initialization in constructor this.requestHandler = new RequestHandler(apiKey, proxy);.
And "timestamp" set hard Map.put.

So there haven't any valid way to adjust application time to synchronize with server.

Proposed solutions:
Simplest solution is to replace Map.put with Map.putIfAbsent, but not the best.
Best solution from my side is to replace System.currentTimeMillis() with usage static variable Clock clock instantiated by default with Clock systemUTC(), that can be replaced with OffsetClock object.
Also, it can be allowed to inject extend of RequestHandler to all endpoints

Thanks!

Need to plug websocket connection failure callbacks

I need to have the possibility to have callbacks of my own, for connection failure or closure events, get called when such things happen.

That way, as long as my ‘failure’ callbacks hasn’t been called, I can consider that the program is in sync with the exchange and it can continue doing its job safely.

The binance java SDK websocket client, at the time being, doesn’t provide such thing.

Any help?

Field asset is not mandatory

public String flexibleProductPosition(LinkedHashMap<String, Object> parameters) {
ParameterChecker.checkParameter(parameters, "asset", String.class);
return this.requestHandler.sendSignedRequest(this.baseUrl, "/sapi/v1/lending/daily/token/position", parameters, HttpMethod.GET, this.showLimitUsage);
}

When not set, return list with all product positions.

A suggest remove this checkParameter to asset.

my websocket (running test url) automatically resets , calling closingCallback

Hi I get this SocketException inside closingCallback after a sometime, maybe after aprox 30h running streaming the websocket.

Once I got this 3 times in a row, 1min after each time. I dont know why this happens ? I have deployed to GCP VM instance and I am running my websocket in a seperat Thread.

31-08-2022 17:07:02.087 261952625 [OkHttp https://testnet.binance.vision/...] ERROR c.b.c.c.utils.WebSocketConnection - [Connection 11] Failure
java.net.SocketException: Connection reset
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:478)
at java.base/sun.security.ssl.SSLSocketInputRecord.readHeader(SSLSocketInputRecord.java:472)
at java.base/sun.security.ssl.SSLSocketInputRecord.bytesInCompletePacket(SSLSocketInputRecord.java:70)
at java.base/sun.security.ssl.SSLSocketImpl.readApplicationRecord(SSLSocketImpl.java:1454)
at java.base/sun.security.ssl.SSLSocketImpl$AppInputStream.read(SSLSocketImpl.java:1065)
at okio.InputStreamSource.read(JvmOkio.kt:90)
at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:129)
at okio.RealBufferedSource.request(RealBufferedSource.kt:206)
at okio.RealBufferedSource.require(RealBufferedSource.kt:199)
at okio.RealBufferedSource.readByte(RealBufferedSource.kt:209)
at okhttp3.internal.ws.WebSocketReader.readHeader(WebSocketReader.kt:119)
at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.kt:102)
at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.kt:293)
at okhttp3.internal.ws.RealWebSocket$connect$1.onResponse(RealWebSocket.kt:195)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)

please add okhttp proxy

you build OkHttpClient by use OkHttpClient(),but i can`t visit binance in our country ,so i only use proxy to visit this .

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.