How to Place Market Order or Limit Order in Kraken using Java

Posted By : Harikesh Maurya | 31-Jul-2019

Market and Limit orders are two trading terms we need to be aware before start trading. Let’s take a tour of this:-

 

  1. Market Order

A market order is used for quick execution of an order. In this buy or sell order is placed on the best market price.The drawback of a market order is that you’re not guaranteed the exact price you’re trying to buy or sell at, it’s usually relatively small unless the price moves very quickly. 

 

  1. Limit Order

    A limit order is placed on a fixed price, that means you buy or sell at a fixed price that you determine. The advantage of limit orders over market orders is that they limit order can ensure a better average fill price.

 

The disadvantage of limit orders is that there's no guarantee the order will completely fill (or fill at all).


 

Java Implementation

/**
     * Create payload for kraken
     * 
     * @param limitOrderDto
     * @return
     */
    public ResponseEntity<Object> createPayloadAndSendLimitOrder(PlaceLimitOrderDto limitOrderDto) {
        String pair="XBTUSD";
        String nonce = String.valueOf(System.currentTimeMillis());
        BigDecimal amount=limitOrderDto.getAmount().setScale(1,RoundingMode.DOWN);
        /**
         * To place market order you just need to change ordertype as market.
         */
        String data="nonce=" + nonce+"&price="+amount+"&volume="+limitOrderDto.getQuantity()+
                "&type=sell&ordertype=limit&pair="+pair+"&expiretm="+((System.currentTimeMillis()+6000)/1000);

        String answer =this.post(krakenBaseUrl + "/0/private/AddOrder", data,
                this.calculateSignature(nonce , data , "/0/private/AddOrder"));

    }

    /**
     * This method is used to send data to kraken 
     * 
     * @param address
     * @param output
     * @param signature
     * @return
     */
    public String post(String address, String data , String signature) {
        String answer = "";
        HttpsURLConnection c = null;
        try {
            URL u = new URL(address); 
            c = (HttpsURLConnection)u.openConnection();
            c.setRequestMethod("POST");
            c.setRequestProperty("API-Key", API_KEY);
            c.setRequestProperty("API-Sign", signature);
            c.setDoOutput(true);
            DataOutputStream os = new DataOutputStream(c.getOutputStream());
            os.writeBytes(data);
            os.flush();
            os.close();
            BufferedReader br = null;
            if(c.getResponseCode() >= 400) {
                System.out.println("response code ="+ c.getResponseCode() );
                System.out.println("response message = " + c.getResponseMessage());
                System.out.println("here");
                System.exit(1);
            }
            br = new BufferedReader(new InputStreamReader((c.getInputStream())));
            String line;
            while ((line = br.readLine()) != null)
                answer += line;
        } catch (Exception x) {
            x.printStackTrace();
        } finally {
            c.disconnect();
        }
        return answer;        
    }


    /**
     * This method is used for signature calculation
     * 
     * @param nonce
     * @param data
     * @param uri
     * @return
     */
    public String calculateSignature(String nonce , String data , String uri) {
        String  signature = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update((nonce + data).getBytes());
            Mac mac = Mac.getInstance("HmacSHA512");
            mac.init(new SecretKeySpec(Base64.decodeBase64(SECRET_KEY.getBytes()), "HmacSHA512"));
            mac.update(uri.getBytes());
            signature = new String(Base64.encodeBase64(mac.doFinal(md.digest())));
        } catch(Exception e) {}
        return signature;
    }

About Author

Author Image
Harikesh Maurya

Harikesh is an Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Java Enterprise Edition, Java, Spring Boot, Spring Security, and Hibernate. He has a good sense of humor.

Request for Proposal

Name is required

Comment is required

Sending message..