{"id":13591053,"url":"https://github.com/binance/binance-connector-java","last_synced_at":"2025-04-13T22:33:30.679Z","repository":{"id":37339977,"uuid":"436171669","full_name":"binance/binance-connector-java","owner":"binance","description":"Simple Java connector to Binance Spot API","archived":false,"fork":false,"pushed_at":"2025-01-08T10:02:50.000Z","size":942,"stargazers_count":447,"open_issues_count":16,"forks_count":192,"subscribers_count":24,"default_branch":"master","last_synced_at":"2025-04-06T20:03:34.449Z","etag":null,"topics":["binance-api","connector","crypto","java","library","market-data","real-time","spot","trading"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binance.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-12-08T08:29:07.000Z","updated_at":"2025-04-05T20:28:07.000Z","dependencies_parsed_at":"2023-02-09T14:45:58.593Z","dependency_job_id":"e788c5ed-7387-426c-af9c-bd2050087ead","html_url":"https://github.com/binance/binance-connector-java","commit_stats":{"total_commits":45,"total_committers":8,"mean_commits":5.625,"dds":0.6666666666666667,"last_synced_commit":"5da82a1b2f9fde8a7bc550ea13475db0ba81ac1c"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binance","download_url":"https://codeload.github.com/binance/binance-connector-java/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248790624,"owners_count":21162058,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binance-api","connector","crypto","java","library","market-data","real-time","spot","trading"],"created_at":"2024-08-01T16:00:53.111Z","updated_at":"2025-04-13T22:33:30.622Z","avatar_url":"https://github.com/binance.png","language":"Java","readme":"# Binance Public API connector Java\n[![maven](https://img.shields.io/maven-central/v/io.github.binance/binance-connector-java)](https://repo1.maven.org/maven2/io/github/binance/binance-connector-java/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Code Style](https://img.shields.io/badge/code%20style-checkstyle-yellow)](https://checkstyle.org/checks.html)\n\nThis is a lightweight library that works as a connector to the [Binance public API](https://github.com/binance/binance-spot-api-docs).\n\nIt supports the following APIs:\n  - `/api/*` endpoints;\n  - `/sapi/*` endpoints;\n  - Spot WebSocket Market Stream;\n  - Spot User Data Stream;\n  - Spot WebSocket API;\n\nAdditionally, it includes test cases and examples.\n\n## Documentation\n[https://www.javadoc.io/doc/io.github.binance/binance-connector-java/latest/index.html](https://www.javadoc.io/doc/io.github.binance/binance-connector-java/latest/index.html)\n\n## Getting Started\n### Maven\nCopy and paste the following dependency snippet into your `pom.xml` file, replacing `LATEST_VERSION` with the most [recent version](https://mvnrepository.com/artifact/io.github.binance/binance-connector-java) available:\n```\n\u003cdependency\u003e\n    \u003cgroupId\u003eio.github.binance\u003c/groupId\u003e\n    \u003cartifactId\u003ebinance-connector-java\u003c/artifactId\u003e\n    \u003cversion\u003eLATEST_VERSION\u003c/version\u003e\n\u003c/dependency\u003e\n```\nNext, install the dependency by executing `mvn install` in the directory where your `pom.xml` is located.\n\n### Gradle\nCopy and paste the following dependency snippet into your `build.gradle` file, replacing `LATEST_VERSION` with the most [recent version](https://mvnrepository.com/artifact/io.github.binance/binance-connector-java) available:\n```\nimplementation 'io.github.binance:binance-connector-java:LATEST_VERSION'\n```\n\nMake sure to add the Jitpack repository to the `repositories` section of your `build.gradle` file:\n```\nmaven { url 'https://jitpack.io' }\n```\nNext, install the dependency by executing `gradle dependencies` in the directory where your `build.gradle` is located.\n\n## Examples\nThe 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).\n\nNote that this `PrivateConfig.java` is only used for examples, you should have your own configuration file when using the library.\n\n### REST APIs\n\n#### Market Endpoint: Exchange Information\n```java\nSpotClient client = new SpotClientImpl();\nMap\u003cString, Object\u003e parameters = new LinkedHashMap\u003c\u003e();\nString result = client.createMarket().exchangeInfo(parameters);\n```\n\n#### Trade Endpoint: Testing a new order\n```java\nSpotClient client = new SpotClientImpl(PrivateConfig.API_KEY, PrivateConfig.SECRET_KEY);\n\nMap\u003cString,Object\u003e parameters = new LinkedHashMap\u003cString,Object\u003e();\nparameters.put(\"symbol\",\"BTCUSDT\");\nparameters.put(\"side\", \"SELL\");\nparameters.put(\"type\", \"LIMIT\");\nparameters.put(\"timeInForce\", \"GTC\");\nparameters.put(\"quantity\", 0.01);\nparameters.put(\"price\", 9500);\n\nString result = client.createTrade().testNewOrder(parameters);\n```\n\n### WebSocket Stream\n```java\nWebSocketStreamClient wsStreamClient = new WebSocketStreamClientImpl(); // defaults to live exchange unless stated.\n\n// Single stream\nint streamID1 = wsStreamClient.aggTradeStream(\"btcusdt\",((event) -\u003e {\n    System.out.println(event);\n}));\n\n// Combined streams\nArrayList\u003cString\u003e streams = new ArrayList\u003c\u003e();\nstreams.add(\"btcusdt@trade\");\nstreams.add(\"bnbusdt@trade\");\n\nint streamID2 = wsStreamClient.combineStreams(streams, ((event) -\u003e {\n    System.out.println(event);\n}));\n\n// Close single stream\nwsStreamClient.closeConnection(streamID1); //closes aggTradeStream-btcusdt\n        \n// Close all streams\nwsStreamClient.closeAllConnections();\n```\n\nDifferent types of WebSocket callbacks are available. Please refer to the `src/test/java/examples/websocketstream/TradeStreamWithAllCallbacks.java` example file to explore their usage.\n\n### WebSocket API\n```java\nRsaSignatureGenerator signatureGenerator =  new RsaSignatureGenerator(\"PRIVATE_KEY_PATH\");\nWebSocketApiClient wsApiClient = new WebSocketApiClientImpl(\"API_KEY\", signatureGenerator); // defaults to live exchange unless stated\n\n// Open connection with a callback as parameter\nwsApiClient.connect(((message) -\u003e {\nSystem.out.println(message);\n}));\n\nJSONObject optionalParams = new JSONObject();\noptionalParams.put(\"requestId\", \"request123\");\noptionalParams.put(\"quantity\", 1);\n\nwsApiClient.trade().testNewOrder(\"BTCUSDT\", \"BUY\", \"MARKET\", optionalParams);\n\nThread.sleep(60000);\n\n// Close connection\nwsApiClient.close();\n```\n\nIf `requestId` is empty (`\"\"`), `null` or not sent, this library will generate a `UUID` string for it. \n\nDifferent types of WebSocket callbacks are available. Please refer to the `src/test/java/examples/websocketapi/WsApiwithAllCallbacks.java` example file to explore their usage.\n\n## Features\n### Testnet\nWhile `/sapi/*` endpoints do not yet have a testnet environment, `/api/*` endpoints can be tested on the [Spot Testnet](https://testnet.binance.vision/).\nYou can use it by changing the base URL:\n\n```java\nMap\u003cString,Object\u003e parameters = new LinkedHashMap\u003c\u003e();\n\nSpotClient client = new SpotClientImpl(PrivateConfig.TESTNET_API_KEY, PrivateConfig.TESTNET_SECRET_KEY, PrivateConfig.TESTNET_URL);\nString result = client.createMarket().time();\n```\n\n### Base URL\nIf `baseUrl` is not provided, it defaults to `api.binance.com`.\n\nIt's recommended to pass in the `baseUrl` parameter, even in production as Binance provides alternative URLs:\n- `https://api1.binance.com`\n- `https://api2.binance.com`\n- `https://api3.binance.com`\n- `https://api4.binance.com`\n\n### Optional parameters\nParameters can be set in any implementation of `Map\u003cString, Object\u003e` interface, where `String` represents the parameter name and `Object` the parameter value. These parameters should have the same naming as in the API doc.\"\n\n```java\nMap\u003cString,Object\u003e parameters = new LinkedHashMap\u003cString,Object\u003e();\n\nparameters.put(\"symbol\",\"BTCUSDT\");\nparameters.put(\"side\", \"SELL\");\nparameters.put(\"type\", \"LIMIT\");\nparameters.put(\"timeInForce\", \"GTC\");\nparameters.put(\"quantity\", 0.01);\nparameters.put(\"price\", 9500);\n```\n\n### Response MetaData\nThe Binance API server provides weight usages in the headers of each response, which can be returned if you set `setShowLimitUsage(true)`.\n```java\nSpotClient client = new SpotClientImpl();\nclient.setShowLimitUsage(true);\nString result = client.createMarket().time();\nlogger.info(result);\n```\nOutput:\n```\nINFO: {\"data\":\"{\"serverTime\":1633434339494}\",\"x-mbx-used-weight\":\"1\",\"x-mbx-used-weight-1m\":\"1\"}\n```\n\n### Proxy\nTo set HTTP Proxy, call `setProxy()` with `ProxyAuth` and before submitting requests:\n\n```java\nSpotClient client = new SpotClientImpl();\nProxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"127.0.0.1\", 8080));\nProxyAuth proxy = new ProxyAuth(proxyConn, null);\n\nclient.setProxy(proxy);\nlogger.info(client.createMarket().time());\n```\n\nFor authenticated `Proxy`, define `ProxyAuth` with [`Authenticator` from `okhttp3`](https://square.github.io/okhttp/3.x/okhttp/index.html?okhttp3/Authenticator.html):\n\n```java\nSpotClient client = new SpotClientImpl();\nProxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"127.0.0.1\", 8080));\nAuthenticator auth = new Authenticator() {\n    public Request authenticate(Route route, Response response) throws IOException {\n        if (response.request().header(\"Proxy-Authorization\") != null) {\n            return null; // Give up, we've already failed to authenticate.\n          }\n      \n        String credential = Credentials.basic(\"username\", \"password\");\n        return response.request().newBuilder().header(\"Proxy-Authorization\", credential).build();\n        \n    }\n};\nProxyAuth proxy = new ProxyAuth(proxyConn, auth);\n\nclient.setProxy(proxy);\nlogger.info(client.createMarket().time());\n```\n\nTo undo `Proxy`, use `unsetProxy()` before submitting requests:\n```java\nclient.unsetProxy();\nlogger.info(client.createMarket().time());\n```\n\nComplete examples are available at `src/test/java/examples/spot/proxy` folder.\n\n### Logging\nThis connector uses [`SLF4J`](https://www.slf4j.org/) as an abstraction layer for diverse logging frameworks.\n\nIt's end-user's responsibility to select the appropriate `SLF4J` binding to use as the logger (e.g, `slf4j-jdk14` or `logback-classic`).\nOtherwise, you might see the following informative output:\n\n```shell\nSLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.\n```\n\nIn case you want to use our custom `logback-classic`, it's available at [`binance-logback`](https://central.sonatype.com/artifact/io.github.binance/binance-logback).\n\nIf you prefer to not use a logger and suppress the `SLF4J` messages instead, you can refer to `slf4j-nop`.\n\n### Types of Signature Generator\nWhen 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:\n\n- `HmacSignatureGenerator` - Use of API Key and Secret Key.\n```java\n  HmacSignatureGenerator signGenerator = new HmacSignatureGenerator(\"SecretKey\");\n  SpotClient client = new SpotClientImpl(\"ApiKey\", signGenerator);\n```\n\n- `RsaSignatureGenerator` - Use of API Key and RSA algorithm keys.\n```java\n  RsaSignatureGenerator signGenerator =  new RsaSignatureGenerator(\"PathToPrivateKey\"); \n  // or if Private Key is protected\n  // RsaSignatureGenerator signGenerator = new RsaSignatureGenerator(\"PathToPrivateKey\", \"PrivateKeyPassword\")\n  SpotClient client = new SpotClientImpl(\"ApiKey\", signGenerator);\n```\n\n- `Ed25519SignatureGenerator` - Use of API Key and Ed25519 algorithm keys.\n```java\n  Ed25519SignatureGenerator signGenerator =  new Ed25519SignatureGenerator(\"PathToPrivateKey\");\n  SpotClient client = new SpotClientImpl(\"ApiKey\", signGenerator);\n```\n\n## Errors\n\nThere are 3 types of error which may be thrown by this library.\n\n- `BinanceConnectorException`\n  - 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.\n- `BinanceClientException`\n  - This is thrown when server returns `4XX`, it's an issue from client side.\n  - The error consists of these 3 objects which will help in debugging the error:\n    - `httpStatusCode` - HTTP status code\n    - `errorCode` - API Server's error code, e.g. `-1102`\n    - `errMsg` - API Server's error message, e.g. `Unknown order sent.`\n- `BinanceServerException`\n  - This is thrown when server returns `5XX`, it's an issue from server side.\n```java\ntry {\n      String result = client.createTrade().newOrder(parameters);\n      logger.info(result);\n    } catch (BinanceConnectorException e) {\n      logger.error(\"fullErrMessage: {}\", e.getMessage(), e);\n    } catch (BinanceClientException e) {\n      logger.error(\"fullErrMessage: {} \\nerrMessage: {} \\nerrCode: {} \\nHTTPStatusCode: {}\",\n      e.getMessage(), e.getErrMsg(), e.getErrorCode(), e.getHttpStatusCode(), e);\n    }\n```\n\n## Test Cases\n`mvn clean test`\n\n## Contribution\nContributions are welcome!\n\nIf you've found a bug within this project, please open an issue to discuss what you would like to change.\n\nIf it's an issue with the API itself, you can submit on the [Binance Developer Community](https://dev.binance.vision)\n","funding_links":[],"categories":["Java"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinance%2Fbinance-connector-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-java/lists"}