For information on changes for our US clients, please visit our Support Center article.

Cerca
Example code for Java REST and WebSocket API

Introduction

Below is a Java example script that can be referenced for both the REST and WebSocket Implementation of the Kraken API.

It demo's the following functionality:
  • Public REST API Endpoints
  • Private REST API Endpoints
  • Public WebSocket API Subscriptions
  • Private WebSocket API Subscriptions

Installation

To run locally, you can copy/paste the code below.

Note that setting the if statement of 1 == 0 to 1 == 1 will execute the specific block of code.

Before running the script, you need to update the script with your Public and Private API Keys.

You can download this file here.

Java Code


import java.net.Socket;

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.net.http.HttpResponse.BodyHandlers;

import java.util.concurrent.CompletableFuture;

import java.util.concurrent.CompletionStage;

import java.util.concurrent.CountDownLatch;

import java.net.http.WebSocket;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import java.util.Base64;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import javax.net.ssl.HttpsURLConnection;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.InputStreamReader;

import java.net.URL;

import java.util.HashMap;

import java.security.MessageDigest;

import java.security.PrivateKey;

import org.codehaus.jackson.JsonFactory;

import org.codehaus.jackson.map.ObjectMapper;

import org.codehaus.jackson.type.TypeReference;

public class App {

publicstaticvoidmain(String[] args) throwsException {

// TODO: UPDATE WITH YOUR KEYS :)

StringapiPublicKey = "YOUR_PUBLIC_KEY";

StringapiPrivateKey = "YOUR_PRIVATE_KEY";

try {

System.out.println("|=========================================|");

System.out.println("| KRAKEN.COM JAVA TEST APP |");

System.out.println("|=========================================|");

System.out.println();

/*

* PUBLIC REST API Examples

*/

if (1 == 0) {

CompletableFuture<String> publicResponse;

StringpublicEndpoint = "SystemStatus";

StringpublicInputParameters = "";

/*

* MORE PUBLIC REST EXAMPLES

*

* String publicEndpoint = "AssetPairs";

* String publicInputParameters = "pair=ethusd,xbtusd";

*

* String publicEndpoint = "Ticker";

* String publicInputParameters = "pair=ethusd";

*

* String publicEndpoint = "Trades";

* String publicInputParameters = "pair=ethusd&since=0";

*/

publicResponse = QueryPublicEndpoint(publicEndpoint, publicInputParameters);

while (publicResponse.isDone() == false) {

// WAIT

}

System.out.println(publicResponse.get());

}

/*

* PRIVATE REST API Examples

*/

if (1 == 0) {

StringprivateResponse = "";

StringprivateEndpoint = "Balance";

StringprivateInputParameters = "";

/*

* MORE PRIVATE REST EXAMPLES

*

* String privateEndpoint = "AddOrder";

* String privateInputParameters =

* "pair=xbteur&type=buy&ordertype=limit&price=1.00&volume=1";

*

* String privateEndpoint = "AddOrder"

* String privateInputParameters =

* "pair=xdgeur&type=sell&ordertype=limit&volume=3000&price=%2b10.0%" //Positive

* Percentage Example (%2 represtes +, which is a reseved character in HTTP)

*

* String privateEndpoint = "AddOrder"

* String privateInputParameters =

* "pair=xdgeur&type=sell&ordertype=limit&volume=3000&price=-10.0%" //Negative

* Percentage Example

*

* String privateEndpoint = "AddOrder"

* String privateInputParameters =

* "pair=xdgeur&type=buy&ordertype=market&volume=3000&userref=789" //Userref

* Example

*

* String privateEndpoint = "Balance" //{"error":[]} IS SUCCESS, Means EMPTY

* BALANCE

* String privateInputParameters = ""

*

* String privateEndpoint = "QueryOrders"

* String privateInputParameters = "txid=OFUSL6-GXIIT-KZ2JDJ"

*

* String privateEndpoint = "AddOrder"

* String privateInputParameters =

* "pair=xdgusd&type=buy&ordertype=market&volume=5000"

*

* String privateEndpoint = "DepositAddresses"

* String privateInputParameters = "asset=xbt&method=Bitcoin"

*

* String privateEndpoint = "DepositMethods"

* String privateInputParameters = "asset=eth"

*

* String privateEndpoint = "WalletTransfer"

* String privateInputParameters =

* "asset=xbt&to=Futures Wallet&from=Spot Wallet&amount=0.0045"

*

* String privateEndpoint = "TradesHistory"

* String privateInputParameters = "start=1577836800&end=1609459200"

*

* String privateEndpoint = "GetWebSocketsToken"

* String privateInputParameters = ""

*/

privateResponse = QueryPrivateEndpoint(privateEndpoint,

privateInputParameters,

apiPublicKey,

apiPrivateKey);

System.out.println(privateResponse);

}

/*

* PUBLIC WEBSOCKET Examples

*/

if (1 == 0) {

StringpublicWebSocketURL = "wss://ws.kraken.com/";

StringpublicWebSocketSubscriptionMsg = "{ \"event\":\"subscribe\", \"subscription\":{\"name\":\"trade\"},\"pair\":[\"XBT/USD\"] }";

/*

* MORE PUBLIC WEBSOCKET EXAMPLES

*

* String publicWebSocketSubscriptionMsg =

* "{ \"event\": \"subscribe\", \"subscription\": { \"interval\": 1440, \"name\": \"ohlc\"}, \"pair\": [ \"XBT/EUR\" ]}"

* ;

* String publicWebSocketSubscriptionMsg =

* "{ \"event\": \"subscribe\", \"subscription\": { \"name\": \"spread\"}, \"pair\": [ \"XBT/EUR\",\"ETH/USD\" ]}"

* ;

*/

OpenAndStreamWebSocketSubscription(publicWebSocketURL, publicWebSocketSubscriptionMsg);

}

/*

* PRIVATE WEBSOCKET Examples

*/

if (1 == 0) {

StringprivateWebSocketURL = "wss://ws-auth.kraken.com/";

// GET THE WEBSOCKET TOKEN FROM THE JSON RESPONSE

ObjectwebSocketToken = "";




StringtokenQuery = QueryPrivateEndpoint("GetWebSocketsToken", "", apiPublicKey, apiPrivateKey);




JsonFactoryfactory = newJsonFactory();

ObjectMappermapper = newObjectMapper(factory);

TypeReference<HashMap<String,Object>> typeRef

= new TypeReference<

HashMap<String,Object>

>() {};

HashMap<String,HashMap<String,Object>> o

= mapper.readValue(tokenQuery, typeRef);

webSocketToken = o.get("result").get("token");

/*

* MORE PRIVATE WEBSOCKET EXAMPLES

*

* String privateWebSocketSubscriptionMsg =

* "{ \"event\": \"subscribe\", \"subscription\": { \"name\": \"openOrders\", \"token\": \""

* + webSocketToken + "\" }}";

* String privateWebSocketSubscriptionMsg =

* "{ \"event\": \"subscribe\", \"subscription\": { \"name\": \"balances\", \"token\": \""

* + webSocketToken + "\" }}";

* String privateWebSocketSubscriptionMsg =

* "{ \"event\":\"addOrder\",\"reqid\":1234,\"ordertype\":\"limit\",\"pair\":\"XBT/EUR\",\"token\":\""

* + webSocketToken +

* "\",\"type\":\"buy\",\"volume\":\"1\", \"price\":\"1.00\"}";

*/

// REPLACE PLACEHOLDER WITH TOKEN

StringprivateWebSocketSubscriptionMsg = "{ \"event\": \"subscribe\", \"subscription\": { \"name\": \"balances\", \"token\": \""

+ webSocketToken + "\" }}";

System.out.println(privateWebSocketSubscriptionMsg);

OpenAndStreamWebSocketSubscription(privateWebSocketURL, privateWebSocketSubscriptionMsg);

}

System.out.println("|=======================================|");

System.out.println("| END OF PROGRAM - HAVE A GOOD DAY :) |");

System.out.println("|=======================================|");

System.out.println("\n");

} catch (Exception e) {

System.out.println(e);

}

}

/*

* Public REST API Endpoints

*/

publicstaticCompletableFuture<String> QueryPublicEndpoint(StringendPointName, StringinputParameters) {

CompletableFuture<String> jsonData;

StringbaseDomain = "https://api.kraken.com";

StringpublicPath = "/0/public/";

StringapiEndpointFullURL = baseDomain + publicPath + endPointName + "?" + inputParameters;

HttpClientclient = HttpClient.newHttpClient();

HttpRequestrequest = HttpRequest.newBuilder()

.uri(URI.create(apiEndpointFullURL))

.build();

jsonData = client.sendAsync(request, BodyHandlers.ofString())

.thenApply(HttpResponse::body);

return jsonData;

}

/*

* Private REST API Endpoints

*/

publicstaticStringQueryPrivateEndpoint(StringendPointName,

StringinputParameters,

StringapiPublicKey,

StringapiPrivateKey) {

StringresponseJson = "";

StringbaseDomain = "https://api.kraken.com";

StringprivatePath = "/0/private/";

StringapiEndpointFullURL = baseDomain + privatePath + endPointName + "?" + inputParameters;

Stringnonce = String.valueOf(System.currentTimeMillis());

StringapiPostBodyData = "nonce=" + nonce + "&" + inputParameters;

Stringsignature = CreateAuthenticationSignature(apiPrivateKey,

privatePath,

endPointName,

nonce,

apiPostBodyData);

// CREATE HTTP CONNECTION

try {

HttpsURLConnectionhttpConnection = null;

URLapiUrl = newURL(apiEndpointFullURL);

httpConnection = (HttpsURLConnection) apiUrl.openConnection();

httpConnection.setRequestMethod("POST");

httpConnection.setRequestProperty("API-Key", apiPublicKey);

httpConnection.setRequestProperty("API-Sign", signature);

httpConnection.setDoOutput(true);

DataOutputStreamos = newDataOutputStream(httpConnection.getOutputStream());

os.writeBytes(apiPostBodyData);

os.flush();

os.close();

BufferedReaderbr = null;

// GET JSON RESPONSE DATA

br = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));

Stringline;

while ((line = br.readLine()) != null) {

responseJson += line;

}

} catch (Exception e) {

System.out.println(e);

}

return responseJson;

}

/*

* Authentication Algorithm

*/

publicstaticStringCreateAuthenticationSignature(StringapiPrivateKey,

StringapiPath,

StringendPointName,

Stringnonce,

StringapiPostBodyData) {

try {

// GET 256 HASH

MessageDigestmd = MessageDigest.getInstance("SHA-256");

md.update((nonce + apiPostBodyData).getBytes());

byte[] sha256Hash = md.digest();

// GET 512 HASH

Macmac = Mac.getInstance("HmacSHA512");

mac.init(newSecretKeySpec(Base64.getDecoder().decode(apiPrivateKey.getBytes()), "HmacSHA512"));

mac.update((apiPath + endPointName).getBytes());

// CREATE API SIGNATURE

Stringsignature = newString(Base64.getEncoder().encodeToString(mac.doFinal(sha256Hash)));

return signature;

} catch (Exception e) {

e.printStackTrace();

return"";

}

}

/*

* WebSocket API

*/

publicstaticvoidOpenAndStreamWebSocketSubscription(StringconnectionURL, StringwebSocketSubscription) {

try {

CountDownLatchlatch = newCountDownLatch(1);

WebSocketws = HttpClient

.newHttpClient()

.newWebSocketBuilder()

.buildAsync(URI.create(connectionURL), new WebSocketClient(latch))

.join();

ws.sendText(webSocketSubscription, true);

latch.await();

} catch (

Exceptione) {

System.out.println();

System.out.println("AN EXCEPTION OCCURED :(");

System.out.println(e);

}

}

privatestaticclassWebSocketClientimplementsWebSocket.Listener {

privatefinalCountDownLatchlatch;

publicWebSocketClient(CountDownLatchlatch) {

this.latch = latch;

}

@Override

publicvoidonOpen(WebSocketwebSocket) {

DateTimeFormatterdtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTimenow = LocalDateTime.now();

System.out.println(dtf.format(now) + ": " + webSocket.getSubprotocol());

WebSocket.Listener.super.onOpen(webSocket);

}

@Override

publicCompletionStage<?> onText(WebSocketwebSocket, CharSequencedata, booleanlast) {

DateTimeFormatterdtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTimenow = LocalDateTime.now();

System.out.println(dtf.format(now) + ": " + data);

returnWebSocket.Listener.super.onText(webSocket, data, false);

}

@Override

publicvoidonError(WebSocketwebSocket, Throwableerror) {

System.out.println("ERROR OCCURED: " + webSocket.toString());

WebSocket.Listener.super.onError(webSocket, error);

}

}

}