· 8 years ago · Jan 20, 2018, 04:20 AM
1private static JsonObject LimitOrder(String symbol, boolean side, String quantity, String price)
2 {
3 BigDecimal dPrice = new BigDecimal(price);
4 BigDecimal dQuantity = new BigDecimal(quantity);
5 String sSide = side?"buy":"sell";
6 String param ="{"size":""+dQuantity.toString()+"","price":""+dPrice.toString()+"","side":""+sSide+"","product_id":""+symbol+"","post_only":true}";
7
8
9 try
10 {
11 String timestamp= Instant.now().getEpochSecond()+"";
12 String accessSign = getAccess(timestamp,"POST","/orders");
13 String apiKey = properties.getProperty("key");
14 String passphrase = properties.getProperty("passphrase");
15
16 URL url = new URL("https://" + properties.getProperty("host") + "/orders");
17 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
18 connection.setDoOutput(true); // Triggers POST.
19 connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
20 connection.setRequestProperty("CB-ACCESS-KEY", apiKey);
21 connection.setRequestProperty("CB-ACCESS-SIGN", accessSign);
22 connection.setRequestProperty("CB-ACCESS-PASSPHRASE", passphrase);
23 connection.setRequestProperty("CB-ACCESS-TIMESTAMP", timestamp);
24 connection.setRequestProperty("accept", "application/json");
25 connection.setConnectTimeout(5000);
26 connection.setReadTimeout(5000);
27
28 // System.out.println("WRiting: " + param);
29 try (OutputStream output = connection.getOutputStream()) {
30 output.write(param.getBytes("UTF-8"));
31 }
32
33 String status = connection.getResponseMessage();
34 System.out.println("STATUS: "+status);
35
36 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
37 String inputLine;
38 StringBuffer content = new StringBuffer();
39 while ((inputLine = in.readLine()) != null) {
40 content.append(inputLine);
41 }
42 if(content.length()>0){
43 System.out.println(content);
44 }else{
45 System.out.println("Empty Response");
46
47 }
48 in.close();
49
50 connection.disconnect();
51 }catch(Exception e) {
52 e.printStackTrace();
53 }
54 return null;
55 }
56
57private static String getAccess(String timestamp, String method, String path) throws NoSuchAlgorithmException, InvalidKeyException {
58 String secret = properties.getProperty("secret");
59 String prehash = timestamp+method+path;
60
61 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
62 byte[] secretDecoded = Base64.getDecoder().decode(secret);
63 SecretKeySpec secret_key = new SecretKeySpec(secretDecoded, "HmacSHA256");
64 sha256_HMAC.init(secret_key);
65
66 return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(prehash.getBytes()));
67 }