joaopsilva / binance-java-api Goto Github PK
View Code? Open in Web Editor NEWbinance-java-api is a lightweight Java library for the Binance API, supporting synchronous and asynchronous requests, as well as event streaming using WebSockets.
binance-java-api is a lightweight Java library for the Binance API, supporting synchronous and asynchronous requests, as well as event streaming using WebSockets.
Hello João,
thank you for providing API for binance.com.
It is working fine unless the signature is required.
I am raising an issue when run your examples such as AccountBalanceCacheExample or OrdersExample even if API and secret keys are provided.
I am getting the following error message:
Exception in thread "main" com.binance.api.client.exception.BinanceApiException: Signature for this request is not valid.
at com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync(BinanceApiServiceGenerator.java:57)
at com.binance.api.client.impl.BinanceApiRestClientImpl.getAccount(BinanceApiRestClientImpl.java:139)
at com.binance.api.client.impl.BinanceApiRestClientImpl.getAccount(BinanceApiRestClientImpl.java:144)
at com.binance.api.examples.AccountBalanceCacheExample.initializeAssetBalanceCacheAndStreamSession(AccountBalanceCacheExample.java:45)
at com.binance.api.examples.AccountBalanceCacheExample.(AccountBalanceCacheExample.java:34)
at com.binance.api.examples.AccountBalanceCacheExample.main(AccountBalanceCacheExample.java:80)
Maybe it is about how the signature is built or the latest changes in the API of binance (even if couldn't find anything there)
How it could be fixed?
Thanks again and
Best Regards, jgor
Hi Joao!
Great work! is there a way to get the account email?
thank you!
Dnasc - Brazil
public class Main {
public static void main(String[] args) throws IOException {
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
BinanceApiRestClient client = factory.newRestClient();
OrderBook orderBook = client.getOrderBook("BTCUSDT", 10000);
List<OrderBookEntry> asks = orderBook.getAsks();
OrderBookEntry firstAskEntry = asks.get(0);
System.out.println(firstAskEntry.getPrice() + " / " + firstAskEntry.getQty());
}
}
But have
binance-api-client-1.0.2.jar(com/binance/api/client/BinanceApiClientFactory.class)
class file has wrong version 55.0, should be 52.0
Please remove or make sure it appears in the correct subdirectory of the classpath.
com.fasterxml.jackson.databind.deser.impl;
in the function "" public Object deserialize(JsonParser p, DeserializationContext ctxt) ""
Object bean is generated unordered (properties of the class Candlestick),
but the ""SettableBeanProperty[] props"" is generated ordered alfabetically,
so,, when trying the function "" prop.deserializeAndSet(p, ctxt, bean);"" properties and values are mismaching and function try to set string value to Long and Long value to string...
I try to change @JsonPropertyOrder(alphabetic=true) of Candelstick class, but nothing changed...
Anybody has any idea????
Using onAggTradeEvent(). Tried closing the stream using close() but the web socket client keeps sending callbacks.
Running DepthCacheExample.java side by side with binance.com, I noticed that some orders never get removed.
for example the best bid in binance.com would be at 10812.000 and the example application is still holding on to an old bid of 10820.000 even though it was cleared in the website.
Some one have an idea about this topic please?
Thank you
I am trying to solve following isse. The code below will print out just 4-6 symbols but should print every available symbol. Is there any limitation to handlers count?
BinanceApiRestClient restClient = BinanceApiClientFactory.newInstance().newRestClient();
BinanceApiWebSocketClient client = BinanceApiClientFactory.newInstance().newWebSocketClient();
List<TickerPrice> tickets = restClient.getAllPrices().stream().filter(t -> t.getSymbol().contains("BTC")).collect(Collectors.toList());
tickets.forEach(t -> client.onCandlestickEvent(t.getSymbol().toLowerCase(), CandlestickInterval.ONE_MINUTE, response -> System.out.println(response)));
Result:
CandlestickEvent[eventType=kline,eventTime=1517260861554,symbol=BCCBTC,openTime=1517260860000,open=0.14726800,high=0.14726800,low=0.14726800,close=0.14726800,volume=0.06700000,closeTime=1517260919999,intervalId=1m,firstTradeId=4512726,lastTradeId=4512726,quoteAssetVolume=0.00986695,numberOfTrades=1,takerBuyBaseAssetVolume=0.06700000,takerBuyQuoteAssetVolume=0.00986695,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260863205,symbol=NEOBTC,openTime=1517260860000,open=0.01442600,high=0.01442900,low=0.01442600,close=0.01442900,volume=44.49000000,closeTime=1517260919999,intervalId=1m,firstTradeId=7270368,lastTradeId=7270371,quoteAssetVolume=0.64186422,numberOfTrades=4,takerBuyBaseAssetVolume=27.33000000,takerBuyQuoteAssetVolume=0.39426258,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260862695,symbol=LTCBTC,openTime=1517260860000,open=0.01606700,high=0.01606700,low=0.01606700,close=0.01606700,volume=0.20000000,closeTime=1517260919999,intervalId=1m,firstTradeId=5914050,lastTradeId=5914050,quoteAssetVolume=0.00321340,numberOfTrades=1,takerBuyBaseAssetVolume=0.20000000,takerBuyQuoteAssetVolume=0.00321340,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260862316,symbol=ETHBTC,openTime=1517260860000,open=0.10377000,high=0.10383400,low=0.10374100,close=0.10383400,volume=1.24700000,closeTime=1517260919999,intervalId=1m,firstTradeId=27468040,lastTradeId=27468044,quoteAssetVolume=0.12947879,numberOfTrades=5,takerBuyBaseAssetVolume=1.22300000,takerBuyQuoteAssetVolume=0.12698898,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260864456,symbol=ETHBTC,openTime=1517260860000,open=0.10377000,high=0.10383400,low=0.10374100,close=0.10383400,volume=1.63900000,closeTime=1517260919999,intervalId=1m,firstTradeId=27468040,lastTradeId=27468045,quoteAssetVolume=0.17018171,numberOfTrades=6,takerBuyBaseAssetVolume=1.61500000,takerBuyQuoteAssetVolume=0.16769190,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260864000,symbol=NEOBTC,openTime=1517260860000,open=0.01442600,high=0.01443000,low=0.01442600,close=0.01442900,volume=71.31000000,closeTime=1517260919999,intervalId=1m,firstTradeId=7270368,lastTradeId=7270373,quoteAssetVolume=1.02885006,numberOfTrades=6,takerBuyBaseAssetVolume=27.39000000,takerBuyQuoteAssetVolume=0.39512838,isBarFinal=false]
CandlestickEvent[eventType=kline,eventTime=1517260865202,symbol=LTCBTC,openTime=1517260860000,open=0.01606700,high=0.01606700,low=0.01606600,close=0.01606600,volume=0.42000000,closeTime=1517260919999,intervalId=1m,firstTradeId=5914050,lastTradeId=5914051,quoteAssetVolume=0.00674792,numberOfTrades=2,takerBuyBaseAssetVolume=0.42000000,takerBuyQuoteAsset
UPDATE: Yes, it is 5 streams, more is ignored. I cannot find any limitation in API or in your code. Is anybody experiencing the same issue?
it started off well in the console.. then overwrote some its output then sea of red ..
this is from eclipse and I'm fairly savy on not missing obvious deals.. I want to get this running to pull a price pair into a java GCP Servlet .. I did that also with the code underneath this log.. and that blew with a GCP server 500.. any help on either appreciated .. thanks great guys n gals !!
TRADING
0.00000100
0.00000100
Exception in thread "main" com.binance.api.client.exception.BinanceApiException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList
out of START_OBJECT token
at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 1, column: 1]
at com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync(BinanceApiServiceGenerator.java:81)
at com.binance.api.client.impl.BinanceApiRestClientImpl.getAllAssets(BinanceApiRestClientImpl.java:48)
at com.binance.api.examples.GeneralEndpointsExample.main(GeneralEndpointsExample.java:43)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList
out of START_OBJECT token
at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1138)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1092)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:332)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:265)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1611)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1203)
at retrofit2.converter.jackson.JacksonResponseBodyConverter.convert(JacksonResponseBodyConverter.java:32)
at retrofit2.converter.jackson.JacksonResponseBodyConverter.convert(JacksonResponseBodyConverter.java:23)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:122)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:217)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at com.binance.api.client.impl.BinanceApiServiceGenerator.executeSync(BinanceApiServiceGenerator.java:73)
... 2 more
try {
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance();
BinanceApiRestClient client = factory.newRestClient();
// Test connectivity
client.ping();
long serverTime = client.getServerTime();
out.println("<p> Time of ticker from Binance - its Servertime : " + serverTime + "</p>");
TickerStatistics tickerStatistics = client.get24HrPriceStatistics("NEOETH");
out.println("<p> NEO ETH : " + tickerStatistics.getLastPrice() + "</p>");
String price = tickerStatistics.getLastPrice().toString();
out.println("<p> as string .. " + price + "</p>");
TickerStatistics tickerStatistics2 = client.get24HrPriceStatistics("HBARUSDT");
out.println("<p> HBAR USDT : " + tickerStatistics2.getLastPrice() + "</p>");
}
catch (BinanceApiException ex){
LOGGER.log(Level.WARNING, "Exception when calling Binance API", ex);
response.setStatus(500);
response.getWriter().write("Unable to call Binance - see GCP "
+ "logs for more details." + ex.getError().getCode() + " and message " + ex.getError().getMsg());
//System.out.println(e.getError().getCode()); // -1121
//System.out.println(e.getError().getMsg()); // Invalid symbol
out.println("<p> </p><br>");
out.println("<a href='index.html'>Back</a>");
out.println("</body>");
out.println("</html>");
out.close(); // Always close the output writer
return;
}
the api/v1/exchangeInfo API is missing in BinanceApiService.java
No support of 'outboundAccountPosition' in 'UserDataUpdateEventType'.
Apparently this issue closes the web socket client.
How i can get list of P2P trades with Binance API?
I want to get the exact amount in my binance account, when i try the account.getBalances(); method it returns all the coins (The ones i own and the ones i don't), i want something more specific, how to get every coin i own with the total amount existing in my balance using this API ?
Hello,
I am using the library binance-java-api in my java application and I was wondering if it's possible to use the library with the Spot Test Network. I tried to connect with my API Key and Secret generated for testing but I get connection error (Invalid API-key, IP, or permissions for action). I guess it's because the base url it's set to api.binance.com and I can't find a way to switch to testnet.binance.vision which is the url required for using spot test network.
How can I solve this issue?
Many thanks,
Antonio.
Hi,
The okhttp3 WebSocket.cancel() call in WebSocketconnection throws outOfBoundsCheckFromIndexSize.
Have you seen this exception before?
Please show me a an example written in Java as to how to place a futures order followed by take profit and stop loss, I don't understand how to do this, please advise
Binance will delist all WAPI does it affect your api? :)
thank you very much by the way, great job. tks
Well. Ive been doing a chunk of work for @jaggedsoft over on node and php.
Specifically
If this is something you are interested in but have no time, im interested in this area.. . peoples commits will be auto validated for you then.. saves you testing stuff..
E.g:
https://github.com/jaggedsoft/php-binance-api
Ill set up a fork in your interested and create a pull request later on..
Executing BinanceApiRestClient
's getAccount()
never returns. My keys are OK. The same goes for the Async version. Am I missing something?
Hello, thank you for great api but i have problem with following issue:
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
Do you have any idea how to solve this issue?
how to reconnect the websocket server when the connection was closed?
Hello,
When trying getDepositAddress, I get this message:
DepositAddress[address=,success=false,addressTag=,asset=]
api not exist
Is this functional for others?
Thanks
I use the maven config to install, but it not work,what should i do?
<dependency>
<groupId>com.github.binance-exchange</groupId>
<artifactId>binance-java-api</artifactId>
<version>-SNAPSHOT</version>
</dependency>
Hello Silva!
First thank you for your amazing work.
I have a issue with depth. Depth web-socket disconnects sometimes by itself how can i fix it?
And how can we add new depth future (added in 2019-03-1 change log) to your library?
CHANGELOG for Binance's API (2019-03-12)
Websocket streams
@Depth and @Depthx streams no longer have the ignored and empty [].
Best wishes!
https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html#PBEEx
However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords.
Error:
I/System.out: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.ArrayList
out of START_OBJECT token at [Source: (okhttp3.ResponseBody$BomAwareReader); line: 1, column: 1]
The project do not work with the last Jackson version.
Could it be that I'm verified only to Level 1? Without a feedback or error message from the API is very hard to guess. I'm just executing the provided official example with my apiKey and secret:
The problem is that the callback with the response never triggers, the order is never placed and I'm left in the dark about what's going on. The previous lines all work, and it is able to place a test order, but not a real order.
Any help will be appreciated.
-Sergio
Good, I have a problem, I am making Market type orders, what I do is first check the prices of the getAllPrices library and then proceed to place the order, but at that moment when I generate the order the price changes; I imagine that it happens because a call is made to RestApi and that takes a while that when generating the order the price change. I am now using webSocket, do you know where I can get the market price in the methods that are associated with the websocket?
Good day! Please help - I am using the following code in my program:
factory = BinanceApiClientFactory.newInstance(apiKey, apiSecret);
restClient = factory.newRestClient();
webSocketClient = factory.newWebSocketClient();
listenKey = restClient.startUserDataStream();
account = restClient.getAccount();
Then I run the following code at regular intervals:
assetBalances = account.getBalances();
prices = restClient.getAllPrices();
After a few passes, I no longer receive updated balance data. That is, my code is executed normally, it does not give any errors, but the data on balances is not up to date. After restarting the program, the data is updated normally for some time. With what it can be connected?
how to create new OCO trade
User Data Streams for Binance (2019-08-15)
An additional event outboundAccountPosition is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change.
{
"e": "outboundAccountPosition", //Event type
"E": 1564034571105, //Event Time
"u": 1564034571073, //Time of last account update
"B": [ //Balances Array
{
"a": "ETH", //Asset
"f": "10000.000000", //Free
"l": "0.000000" //Locked
}
]
}
If the order is an OCO, an event will be displayed named ListStatus in addition to the executionReport event.
{
"e": "listStatus", //Event Type
"E": 1564035303637, //Event Time
"s": "ETHBTC", //Symbol
"g": 2, //OrderListId
"c": "OCO", //Contingency Type
"l": "EXEC_STARTED", //List Status Type
"L": "EXECUTING", //List Order Status
"r": "NONE", //List Reject Reason
"C": "F4QN4G8DlFATFlIUQ0cjdD", //List Client Order ID
"T": 1564035303625, //Transaction Time
"O": [ //An array of objects
{
"s": "ETHBTC", //Symbol
"i": 17, // orderId
"c": "AJYsMjErWJesZvqlJCTUgL" //ClientOrderId
},
{
"s": "ETHBTC",
"i": 18,
"c": "bfYPSQdLoqAJeNrOr9adzq"
}
]
}
Hello!
Is it possible to move funds (BNB, USDT) from Spot to Futures? It would be really useful.
Thank you!
how do i calculate the delta for a Specific altcoin (Ex: ETH/BTC) in the last 10 mins
I want to get the last price for bnbbtc. I want to know the price of bnb every minute using web sockets api. In the docs https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-ticker-streams
is there a field for the current price for bnb?
The payload looks like this
{
"e": "24hrTicker", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"p": "0.0015", // Price change
"P": "250.00", // Price change percent
"w": "0.0018", // Weighted average price
"x": "0.0009", // Previous day's close price
"c": "0.0025", // Current day's close price
"Q": "10", // Close trade's quantity
"b": "0.0024", // Best bid price
"B": "10", // Best bid quantity
"a": "0.0026", // Best ask price
"A": "100", // Best ask quantity
"o": "0.0010", // Open price
"h": "0.0025", // High price
"l": "0.0010", // Low price
"v": "10000", // Total traded base asset volume
"q": "18", // Total traded quote asset volume
"O": 0, // Statistics open time
"C": 86400000, // Statistics close time
"F": 0, // First trade ID
"L": 18150, // Last trade Id
"n": 18151 // Total number of trades
}
I have 3 'ApiKey' different accounts and 1 invalid, but no matter what I do in the for the purchase is only posted to the account of the first ApiKey, example; if the first one is invalid all are invalid, if you launch the purchase and it is validated, all are being validated for the same account but with the correct values of each purchase.
I do not know how to close or open each "session" something of the type.
What should I do?
List<Ticket> listTicket = (List<Ticket>) ticketServiceImpl.findAll();
for (int i = 0; i < listTicket.size(); i++) {
String apiKey = listTicket.get(i).getUser().getApiKey().toString();
String secretKey = listTicket.get(i).getUser().getSecretKey().toString();
buy(currencyPair, stringAmountBuy, apiKey, secretKey, purchasePrice);
}
}
`public class Buy {
public void buy(String currencyPair,String amountBTC,String apiKey,String secretKey,BigDecimal purchasePrice) {
BinanceApiClientFactory factory = BinanceApiClientFactory.newInstance(apiKey,secretKey);
BinanceApiRestClient client = factory.newRestClient();
String purchasePriceString = String.valueOf(purchasePrice);
NewOrderResponse newOrderResponse = client.newOrder(limitBuy(currencyPair, TimeInForce.GTC, amountBTC, purchasePriceString));
System.out.println("Class buy..."+ newOrderResponse);
}
}`
I'm not seeing a similar API to connect to the binance.us api which looks the same but uses a different baseurl, anyway I can pass that in?
I try todo the following:
client.onAggTradeEvent("btcusdt", (response ->{
binancePrices.setBtcusdt(response.getPrice());
ThreadSleep();
}));
Simple.. but after about 20sek.. it stops updating the price... why ??
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.