· 6 years ago · Jul 21, 2019, 05:00 PM
1public class BitmexClient {
2 private final OkHttpClient client = new OkHttpClient();
3
4 private String api = "";
5 private String secret = "";
6
7 public void setApi(String api, String secret) {
8 this.api = api;
9 this.secret=secret;
10 }
11
12 //API REQUEST BUILDING
13
14 private Response apicall(String verb, String endpoint, JSONObject jsonBody)
15 throws NoSuchAlgorithmException, InvalidKeyException, IOException {
16 String expires = String.valueOf(Instant.now().getEpochSecond()+3600);
17 Request.Builder builder = new Request.Builder()
18 .url("https://www.bitmex.com/api/v1/"+endpoint)
19 .addHeader("user-agent", "bmcTest-v1.122323222")
20 .addHeader("content-type", "application/json; charset=utf-8")
21 .addHeader("accept", "application/json; charset=utf-8")
22 .addHeader("api-expires", expires)
23 .addHeader("api-key", api)
24 .addHeader("api-signature", encodeHexHmacSignature(secret, verb+"/api/v1/"+endpoint
25 +expires+jsonBody.toString()));
26 /*if (verb.equals("POST")){
27 builder.post(RequestBody.create(MediaType.get("text/plain"), jsonBody));
28 } else if (verb.equalsIgnoreCase("PUT")){
29 builder.put(RequestBody.create(MediaType.get("text/plain"), jsonBody));
30 }*/
31 //builder.method("POST", RequestBody.create(MediaType.get("application/json; charset=utf-8"), jsonBody));
32 Request request = builder.build();
33 System.out.println(request.toString()+" - "+request.headers());
34 return client.newCall(request).execute();
35 }
36
37
38 private String encodeHexHmacSignature(String key, String data)
39 throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
40 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
41 SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
42 sha256_HMAC.init(secret_key);
43 return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
44 }
45
46 //TRADING METHODS
47 public void placeOrder(){
48 String data = "{\"symbol\":\"XBTUSD\",\"orderQty\":20,\"ordType\":\"Market\"}";
49 try {
50 Response r = apicall("POST", "order", new JSONObject(data));
51 System.out.println(r.toString()+"\n"+r.headers().toString()+r.body().string());
52 } catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
53 e.printStackTrace();
54 }
55 }
56}