### Futures Depth Response Example
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Example JSON response for a futures depth request, showing asks and bids with prices and amounts.
```json
{
"asks":[
[411.8,6],
[411.75,11],
[411.6,22],
[411.5,9],
[411.3,16]
],
"bids":[
[410.65,12],
[410.64,3],
[410.19,15],
[410.18,40],
[410.09,10]
]
}
```
--------------------------------
### Upbit Order Book Response Example
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Example JSON response for the order book endpoint, showing bid and ask units with their respective prices and sizes for a given market.
```json
[
{
"market": "KRW-BTC",
"timestamp": 1529910247984,
"total_ask_size": 8.83621228,
"total_bid_size": 2.43976741,
"orderbook_units": [
{
"ask_price": 6956000,
"bid_price": 6954000,
"ask_size": 0.24078656,
"bid_size": 0.00718341
},
{
"ask_price": 6958000,
"bid_price": 6953000,
"ask_size": 1.12919,
"bid_size": 0.11500074
},
{
"ask_price": 6960000,
"bid_price": 6952000,
"ask_size": 0.08614137,
"bid_size": 0.19019028
},
{
"ask_price": 6962000,
"bid_price": 6950000,
"ask_size": 0.0837203,
"bid_size": 0.28201649
},
{
"ask_price": 6964000,
"bid_price": 6949000,
"ask_size": 0.501885,
"bid_size": 0.01822085
},
{
"ask_price": 6965000,
"bid_price": 6946000,
"ask_size": 1.12517189,
"bid_size": 0.0002
},
{
"ask_price": 6968000,
"bid_price": 6945000,
"ask_size": 2.89900477,
"bid_size": 0.03597913
},
{
"ask_price": 6970000,
"bid_price": 6944000,
"ask_size": 0.2044231,
"bid_size": 0.39291445
},
{
"ask_price": 6972000,
"bid_price": 6939000,
"ask_size": 2.55280097,
"bid_size": 0.12963816
},
{
"ask_price": 6974000,
"bid_price": 6937000,
"ask_size": 0.01308832,
"bid_size": 1.2684239
}
]
}
]
```
--------------------------------
### Upbit Ticker Response Example
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Example JSON response for the ticker endpoint, showing detailed price and trade statistics for a given market.
```json
[
{
"market": "KRW-BTC",
"trade_date": "20180418",
"trade_time": "102340",
"trade_date_kst": "20180418",
"trade_time_kst": "192340",
"trade_timestamp": 1524047020000,
"opening_price": 8450000,
"high_price": 8679000,
"low_price": 8445000,
"trade_price": 8621000,
"prev_closing_price": 8450000,
"change": "RISE",
"change_price": 171000,
"change_rate": 0.0202366864,
"signed_change_price": 171000,
"signed_change_rate": 0.0202366864,
"trade_volume": 0.02467802,
"acc_trade_price": 108024804862.58254,
"acc_trade_price_24h": 232702901371.09309,
"acc_trade_volume": 12603.53386105,
"acc_trade_volume_24h": 27181.31137002,
"highest_52_week_price": 28885000,
"highest_52_week_date": "2018-01-06",
"lowest_52_week_price": 4175000,
"lowest_52_week_date": "2017-09-25",
"timestamp": 1524047026072
}
]
```
--------------------------------
### Futures Trade Response Example
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Example JSON response for a futures trade request, listing individual trades with amount, date, price, and type.
```json
[
{
"amount":11,
"date":140807646,
"price":7.076,
"tid":37,
"type":buy
},
{
"amount":100,
"date":1408076464,
"price":7.076,
"tid":39,
"type":sell
}
]
```
--------------------------------
### Futures Ticker Response Example
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Example JSON response for a futures ticker request, containing price, volume, and contract details.
```json
{
"date":"1411627632",
"ticker":"{
last:409.2,
buy :408.23,
sell:409.18,
high:432.0,
low:405.71,
vol:55168.0,
contract_id:20140926012,
unit_amount:100.0
}"
}
```
--------------------------------
### Format Code with Maven Plugin
Source: https://github.com/knowm/xchange/wiki/Code-Style
Invoke the fmt-maven-plugin from the command line to format your Java code according to Google's style guide.
```bash
mvn com.spotify.fmt:fmt-maven-plugin:format
```
--------------------------------
### Get Public Ticker Data (Java)
Source: https://github.com/knowm/xchange/blob/develop/README.md
Use this to fetch ticker information for a given currency pair from an exchange. No authentication is required.
```java
Exchange bitstamp = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class);
MarketDataService marketDataService = bitstamp.getMarketDataService();
Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD);
System.out.println(ticker.toString());
```
--------------------------------
### Get Ticker Information
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Use this endpoint to retrieve real-time price information for a specific market. Requires a market parameter, e.g., KRW-BTC.
```http
GET https://api.upbit.co.kr/ticker?market=KRW-BTC
```
--------------------------------
### Get Order Book Information
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Retrieve the order book (bid and ask prices and sizes) for a specific market. Requires a market parameter, e.g., KRW-BTC.
```http
GET https://api.upbit.com/v1/orderbook?market=KRW-BTC
```
--------------------------------
### Get Ticker Information
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinone/api-specification.txt
Retrieves real-time ticker information for a specified currency, including trading volume, last price, and price range.
```APIDOC
## GET /ticker
### Description
Retrieves ticker information for a given currency.
### Method
GET
### Endpoint
https://api.coinone.co.kr/ticker
#### Query Parameters
- **currency** (string) - Required - The currency symbol (e.g., btc).
### Request Example
```http
GET https://api.coinone.co.kr/ticker?currency=btc
```
### Response
#### Success Response (200)
- **result** (string) - Indicates the success of the operation.
- **volume** (string) - The trading volume for the period.
- **last** (string) - The last traded price.
- **yesterday_last** (string) - The last traded price from the previous day.
- **timestamp** (string) - The Unix timestamp of the data.
- **yesterday_low** (string) - The lowest price from the previous day.
- **high** (string) - The highest price for the period.
- **currency** (string) - The currency symbol.
- **low** (string) - The lowest price for the period.
- **errorCode** (string) - Error code, '0' indicates success.
- **yesterday_first** (string) - The first traded price from the previous day.
- **yesterday_volume** (string) - The trading volume from the previous day.
- **yesterday_high** (string) - The highest price from the previous day.
- **first** (string) - The first traded price for the period.
#### Response Example
```json
{
"result": "success",
"volume": "2346.4371",
"last": "8461000",
"yesterday_last": "7890000",
"timestamp": "1523695746",
"yesterday_low": "7890000",
"high": "8620000",
"currency": "btc",
"low": "8235000",
"errorCode": "0",
"yesterday_first": "7890000",
"yesterday_volume": "0.0104",
"yesterday_high": "7890000",
"first": "8430000"
}
```
```
--------------------------------
### Fetch Order Book Data (BTC)
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinone/api-specification.txt
This GET request retrieves the order book for a specified currency, such as BTC. The response details current buy (bid) and sell (ask) orders with their respective prices and quantities.
```http
GET https://api.coinone.co.kr/orderbook?currency=btc
```
```json
{
"timestamp": "1523695788",
"bid": [
{
"price": "8463000",
"qty": "0.0033"
},
{
"price": "8462000",
"qty": "0.0736"
},
{
"price": "8460000",
"qty": "1.0000"
}
],
"errorCode": "0",
"currency": "btc",
"result": "success",
"ask": [
{
"price": "8469000",
"qty": "0.5000"
},
{
"price": "8470000",
"qty": "1.2386"
},
{
"price": "8474000",
"qty": "1.9500"
}
]
}
```
--------------------------------
### Fetch Ticker Data (BTC)
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinone/api-specification.txt
Use this GET request to retrieve real-time ticker information for a specific currency, like Bitcoin (BTC). The response includes various price points, volume, and timestamps.
```http
GET https://api.coinone.co.kr/ticker?currency=btc
```
```json
{
"result": "success",
"volume": "2346.4371",
"last": "8461000",
"yesterday_last": "7890000",
"timestamp": "1523695746",
"yesterday_low": "7890000",
"high": "8620000",
"currency": "btc",
"low": "8235000",
"errorCode": "0",
"yesterday_first": "7890000",
"yesterday_volume": "0.0104",
"yesterday_high": "7890000",
"first": "8430000"
}
```
--------------------------------
### Get Order Book (Depth)
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinone/api-specification.txt
Retrieves the order book (depth) for a specified currency, showing current buy (bid) and sell (ask) orders.
```APIDOC
## GET /orderbook
### Description
Retrieves the order book (depth) for a given currency.
### Method
GET
### Endpoint
https://api.coinone.co.kr/orderbook
#### Query Parameters
- **currency** (string) - Required - The currency symbol (e.g., btc).
### Request Example
```http
GET https://api.coinone.co.kr/orderbook?currency=btc
```
### Response
#### Success Response (200)
- **timestamp** (string) - The Unix timestamp of the data.
- **bid** (array) - An array of buy orders, each with 'price' and 'qty'.
- **errorCode** (string) - Error code, '0' indicates success.
- **currency** (string) - The currency symbol.
- **result** (string) - Indicates the success of the operation.
- **ask** (array) - An array of sell orders, each with 'price' and 'qty'.
#### Response Example
```json
{
"timestamp": "1523695788",
"bid": [
{
"price": "8463000",
"qty": "0.0033"
},
{
"price": "8462000",
"qty": "0.0736"
},
{
"price": "8460000",
"qty": "1.0000"
}
],
"errorCode": "0",
"currency": "btc",
"result": "success",
"ask": [
{
"price": "8469000",
"qty": "0.5000"
},
{
"price": "8470000",
"qty": "1.2386"
},
{
"price": "8474000",
"qty": "1.9500"
}
]
}
```
```
--------------------------------
### Get Ticker Information
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Retrieves real-time ticker information for a specified market. This includes details like opening price, high price, low price, and trade price.
```APIDOC
## GET /ticker
### Description
Retrieves real-time ticker information for a specified market.
### Method
GET
### Endpoint
https://api.upbit.co.kr/ticker
### Parameters
#### Query Parameters
- **market** (string) - Required - The market symbol (e.g., KRW-BTC).
### Response
#### Success Response (200)
- **market** (string) - Market symbol.
- **trade_date** (string) - Trade date in YYYYMMDD format.
- **trade_time** (string) - Trade time in HHMMSS format.
- **trade_date_kst** (string) - Trade date in KST (YYYYMMDD).
- **trade_time_kst** (string) - Trade time in KST (HHMMSS).
- **trade_timestamp** (integer) - Trade timestamp in milliseconds.
- **opening_price** (number) - Opening price.
- **high_price** (number) - High price.
- **low_price** (number) - Low price.
- **trade_price** (number) - Current trade price.
- **prev_closing_price** (number) - Previous closing price.
- **change** (string) - Change indicator (RISE, FALL, EVEN).
- **change_price** (number) - Change price.
- **change_rate** (number) - Change rate.
- **signed_change_price** (number) - Signed change price.
- **signed_change_rate** (number) - Signed change rate.
- **trade_volume** (number) - Trade volume.
- **acc_trade_price** (number) - Accumulated trade price.
- **acc_trade_price_24h** (number) - Accumulated trade price in 24 hours.
- **acc_trade_volume** (number) - Accumulated trade volume.
- **acc_trade_volume_24h** (number) - Accumulated trade volume in 24 hours.
- **highest_52_week_price** (number) - Highest price in 52 weeks.
- **highest_52_week_date** (string) - Date of the highest price in 52 weeks.
- **lowest_52_week_price** (number) - Lowest price in 52 weeks.
- **lowest_52_week_date** (string) - Date of the lowest price in 52 weeks.
- **timestamp** (integer) - Timestamp of the response.
### Request Example
```http
GET https://api.upbit.co.kr/ticker?market=KRW-BTC
```
### Response Example
```json
[
{
"market": "KRW-BTC",
"trade_date": "20180418",
"trade_time": "102340",
"trade_date_kst": "20180418",
"trade_time_kst": "192340",
"trade_timestamp": 1524047020000,
"opening_price": 8450000,
"high_price": 8679000,
"low_price": 8445000,
"trade_price": 8621000,
"prev_closing_price": 8450000,
"change": "RISE",
"change_price": 171000,
"change_rate": 0.0202366864,
"signed_change_price": 171000,
"signed_change_rate": 0.0202366864,
"trade_volume": 0.02467802,
"acc_trade_price": 108024804862.58254,
"acc_trade_price_24h": 232702901371.09309,
"acc_trade_volume": 12603.53386105,
"acc_trade_volume_24h": 27181.31137002,
"highest_52_week_price": 28885000,
"highest_52_week_date": "2018-01-06",
"lowest_52_week_price": 4175000,
"lowest_52_week_date": "2017-09-25",
"timestamp": 1524047026072
}
]
```
--------------------------------
### Private Account Info - Get Account Info
Source: https://github.com/knowm/xchange/blob/develop/README.md
Retrieves account information for authenticated users. Requires setting up exchange specifications with API credentials.
```APIDOC
## Private Account Info - Get Account Info
### Description
Retrieves account information for authenticated users. Requires setting up exchange specifications with API credentials.
### Method
```java
// Set up exchange specification with API credentials
ExchangeSpecification exSpec = new BitstampExchange().getDefaultExchangeSpecification();
exSpec.setUserName("YOUR_USERNAME"); // Example for Bitstamp
exSpec.setApiKey("YOUR_API_KEY");
exSpec.setSecretKey("YOUR_SECRET_KEY");
Exchange bitstamp = ExchangeFactory.INSTANCE.createExchange(exSpec);
// Get the account information
AccountService accountService = bitstamp.getAccountService();
AccountInfo accountInfo = accountService.getAccountInfo();
System.out.println(accountInfo.toString());
```
### Parameters
#### Request Body
- **ExchangeSpecification** (ExchangeSpecification) - Required - Contains API credentials such as:
- **userName** (String) - Required for some exchanges (e.g., Bitstamp).
- **apiKey** (String) - Required API key.
- **secretKey** (String) - Required secret key.
- **passphrase** (String) - Required for some exchanges (e.g., Coinbase Pro).
### Response
#### Success Response (200)
- **AccountInfo** (AccountInfo) - Contains detailed account information.
```
--------------------------------
### Get Private Account Information (Java)
Source: https://github.com/knowm/xchange/blob/develop/README.md
After authenticating an exchange instance, use the AccountService to retrieve account details. This requires valid API credentials to be set.
```java
// Get the account information
AccountService accountService = bitstamp.getAccountService();
AccountInfo accountInfo = accountService.getAccountInfo();
System.out.println(accountInfo.toString());
```
--------------------------------
### Initialize and Use Coins.ph REST API
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinsph/README.md
Demonstrates how to create an exchange instance, configure API keys, and perform basic market data and account operations using the REST API. Ensure API keys are set correctly and specify whether to use the sandbox environment.
```java
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(CoinsphExchange.class);
// Configure API keys
ExchangeSpecification spec = exchange.getDefaultExchangeSpecification();
spec.setApiKey("your-api-key");
spec.setSecretKey("your-secret-key");
spec.setExchangeSpecificParametersItem(Exchange.USE_SANDBOX, false); // Set to true for sandbox
exchange.applySpecification(spec);
// Get market data
MarketDataService marketDataService = exchange.getMarketDataService();
Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_PHP);
// Get account info
AccountService accountService = exchange.getAccountService();
AccountInfo accountInfo = accountService.getAccountInfo();
// Place order
TradeService tradeService = exchange.getTradeService();
MarketOrder marketOrder = new MarketOrder.Builder(Order.OrderType.BID, CurrencyPair.BTC_PHP)
.originalAmount(new BigDecimal("0.001"))
.build();
String orderId = tradeService.placeMarketOrder(marketOrder);
```
--------------------------------
### Create Exchange from Program Arguments (Java)
Source: https://github.com/knowm/xchange/wiki/Frequently-Asked-Questions
Initialize an `Exchange` instance using API keys provided as command-line program arguments. The first argument is the public key, and the second is the private key.
```java
public static void main(String[] args) throws IOException {
// API key with All Permissions.
String publicKey = args[0];
String privateKey = args[1];
ExchangeSpecification spec = new ExchangeSpecification(BTCTradeExchange.class);
spec.setApiKey(publicKey);
spec.setSecretKey(privateKey);
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(spec);
}
```
--------------------------------
### Connect and Subscribe to Live Market Data via Websocket
Source: https://github.com/knowm/xchange/blob/develop/README.md
Use `StreamingExchangeFactory` to create an exchange instance and connect to its WebSocket API. Subscribe to live trades and order book updates for a specific currency pair. Remember to dispose of subscriptions and disconnect when finished.
```java
StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange(BitstampStreamingExchange.class);
// Connect to the Exchange WebSocket API. Here we use a blocking wait.
exchange.connect().blockingAwait();
// Subscribe to live trades update.
Disposable subscription1 = exchange.getStreamingMarketDataService()
.getTrades(CurrencyPair.BTC_USD)
.subscribe(
trade -> LOG.info("Trade: {}", trade),
throwable -> LOG.error("Error in trade subscription", throwable));
// Subscribe order book data with the reference to the subscription.
Disposable subscription2 = exchange.getStreamingMarketDataService()
.getOrderBook(CurrencyPair.BTC_USD)
.subscribe(orderBook -> LOG.info("Order book: {}", orderBook));
// Wait for a while to see some results arrive
Thread.sleep(20000);
// Unsubscribe
subscription1.dispose();
subscription2.dispose();
// Disconnect from exchange (blocking again)
exchange.disconnect().blockingAwait();
```
--------------------------------
### Initialize and Use Coins.ph WebSocket API
Source: https://github.com/knowm/xchange/blob/develop/xchange-coinsph/README.md
Shows how to set up a streaming exchange instance for Coins.ph, configure API keys, and subscribe to real-time market data and user-specific updates via WebSockets. Remember to set the correct API keys and sandbox preference.
```java
// Create Streaming Exchange
ExchangeSpecification spec = new ExchangeSpecification(CoinsphStreamingExchange.class);
spec.setApiKey("your-api-key");
spec.setSecretKey("your-secret-key");
spec.setExchangeSpecificParametersItem(StreamingExchange.USE_SANDBOX, false); // Set to true for sandbox
StreamingExchange streamingExchange = StreamingExchangeFactory.INSTANCE.createExchange(spec);
streamingExchange.connect().blockingAwait();
// Subscribe to order book updates
CurrencyPair pair = CurrencyPair.BTC_PHP;
streamingExchange.getStreamingMarketDataService()
.getOrderBook(pair)
.subscribe(orderBook -> {
System.out.println("Received order book: " + orderBook);
});
// Subscribe to user order updates
streamingExchange.getStreamingTradeService()
.getOrderChanges(pair)
.subscribe(order -> {
System.out.println("Order update: " + order);
});
```
--------------------------------
### Create Exchange for Public Market Data (Java)
Source: https://github.com/knowm/xchange/wiki/Frequently-Asked-Questions
Use this snippet to create an `Exchange` instance for accessing public market data when no authentication is required.
```java
Exchange bitstamp = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class.getName());
MarketDataService marketDataService = bitstamp.getMarketDataService();
```
--------------------------------
### Get Order Book
Source: https://github.com/knowm/xchange/blob/develop/xchange-upbit/api-specification.txt
Retrieves the order book for a specified market. This includes bid and ask prices and sizes.
```APIDOC
## GET /orderbook
### Description
Retrieves the order book for a specified market, showing current buy and sell orders.
### Method
GET
### Endpoint
https://api.upbit.com/v1/orderbook
### Parameters
#### Query Parameters
- **market** (string) - Required - The market symbol (e.g., KRW-BTC).
### Response
#### Success Response (200)
- **market** (string) - Market symbol.
- **timestamp** (integer) - Timestamp of the response.
- **total_ask_size** (number) - Total size of all ask orders.
- **total_bid_size** (number) - Total size of all bid orders.
- **orderbook_units** (array) - An array of order book units, each containing:
- **ask_price** (number) - The price of an ask order.
- **bid_price** (number) - The price of a bid order.
- **ask_size** (number) - The size of an ask order.
- **bid_size** (number) - The size of a bid order.
### Request Example
```http
GET https://api.upbit.com/v1/orderbook?market=KRW-BTC
```
### Response Example
```json
[
{
"market": "KRW-BTC",
"timestamp": 1529910247984,
"total_ask_size": 8.83621228,
"total_bid_size": 2.43976741,
"orderbook_units": [
{
"ask_price": 6956000,
"bid_price": 6954000,
"ask_size": 0.24078656,
"bid_size": 0.00718341
},
{
"ask_price": 6958000,
"bid_price": 6953000,
"ask_size": 1.12919,
"bid_size": 0.11500074
},
{
"ask_price": 6960000,
"bid_price": 6952000,
"ask_size": 0.08614137,
"bid_size": 0.19019028
},
{
"ask_price": 6962000,
"bid_price": 6950000,
"ask_size": 0.0837203,
"bid_size": 0.28201649
},
{
"ask_price": 6964000,
"bid_price": 6949000,
"ask_size": 0.501885,
"bid_size": 0.01822085
},
{
"ask_price": 6965000,
"bid_price": 6946000,
"ask_size": 1.12517189,
"bid_size": 0.0002
},
{
"ask_price": 6968000,
"bid_price": 6945000,
"ask_size": 2.89900477,
"bid_size": 0.03597913
},
{
"ask_price": 6970000,
"bid_price": 6944000,
"ask_size": 0.2044231,
"bid_size": 0.39291445
},
{
"ask_price": 6972000,
"bid_price": 6939000,
"ask_size": 2.55280097,
"bid_size": 0.12963816
},
{
"ask_price": 6974000,
"bid_price": 6937000,
"ask_size": 0.01308832,
"bid_size": 1.2684239
}
]
}
]
```
--------------------------------
### Get User Transactions
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves a list of user transactions with options for pagination and sorting. This endpoint requires authentication.
```APIDOC
## GET /api/userTransactions
### Description
Retrieves a list of user transactions. Requires authentication.
### Method
GET
### Endpoint
/api/userTransactions
### Authentication
Requires 'X-PCK', 'X-Stamp', and 'X-Signature' headers.
### Query Parameters
- **offset** (integer) - Optional - The number of transactions to skip.
- **limit** (integer) - Optional - The maximum number of transactions to return.
- **sort** (string) - Optional - The sorting order ('asc' or 'desc').
### Response
#### Success Response (200)
- **id** (integer) - The transaction ID.
- **type** (string) - The type of transaction (e.g., deposit, withdrawal, trade).
- **currency** (string) - The currency involved.
- **amount** (string) - The amount of the transaction.
- **status** (string) - The status of the transaction.
- **timestamp** (integer) - The Unix timestamp of the transaction.
### Request Example
```http
GET /api/userTransactions?offset=0&limit=50&sort=desc
```
```
--------------------------------
### Create Exchange from JSON Configuration (Java)
Source: https://github.com/knowm/xchange/wiki/Frequently-Asked-Questions
Load exchange API keys and secrets from a JSON file located on the classpath. Ensure the file is named `exchangeConfiguration.json` and placed in the correct directory (e.g., `bitcoinde/`).
```java
/**
* Create a exchange using the keys provided in a bitcoinde/exchangeConfiguration.json file on the classpath.
*
* @return Create exchange or null if .json file was not on classpath.
*/
public static Exchange createExchangeFromJsonConfiguration() throws IOException {
ExchangeSpecification exSpec = new ExchangeSpecification(BitcoindeExchange.class);
ObjectMapper mapper = new ObjectMapper();
InputStream is = ExchangeUtils.class.getClassLoader().getResourceAsStream("bitcoinde/exchangeConfiguration.json");
if (is == null) {
logger.warn("No bitcoinde/exchangeConfiguration.json file found. Returning null exchange.");
return null;
}
try {
ExchangeConfiguration conf = mapper.readValue(is, ExchangeConfiguration.class);
logger.debug(conf.toString());
if (conf.apiKey != null)
exSpec.setApiKey(conf.apiKey);
if (conf.secretKey != null)
exSpec.setSecretKey(conf.secretKey);
} catch (Exception e) {
logger.warn("An exception occured while loading the bitcoinde/exchangeConfiguration.json file from the classpath. " + "Returning null exchange.", e);
return null;
}
Exchange exchange = ExchangeFactory.INSTANCE.createExchange(exSpec);
exchange.remoteInit();
return exchange;
}
}
```
--------------------------------
### Binance Live Subscription/Unsubscription
Source: https://github.com/knowm/xchange/blob/develop/xchange-stream-binance/README.md
Demonstrates how to subscribe to and unsubscribe from live market data streams on the Binance exchange. It covers initial connection, enabling live updates, and handling individual stream disposals. Note the requirement to call unsubscribe within doOnDispose.
```java
ExchangeSpecification spec = StreamingExchangeFactory.INSTANCE.createExchange(BinanceStreamingExchange.class)
.getDefaultExchangeSpecification();
BinanceStreamingExchange exchange = (BinanceStreamingExchange) StreamingExchangeFactory.INSTANCE.createExchange(spec);
// First, we need to subscribe to at least one currency pair at connection time
// Note: at connection time, the live subscription is disabled
ProductSubscription subscription =
ProductSubscription.create().addTrades(CurrencyPair.BTC_USDT).addOrderbook(CurrencyPair.BTC_USDT).build();
exchange.connect(subscription).blockingAwait();
// We subscribe to trades update for the currency pair subscribed at connection time (BTC)
// For live unsubscription, you need to add a doOnDispose that will call the method unsubscribe in BinanceStreamingMarketDataService
Disposable tradesBtc = exchange.getStreamingMarketDataService()
.getTrades(CurrencyPair.BTC_USDT)
.doOnDispose(
() -> exchange.getStreamingMarketDataService().unsubscribe(CurrencyPair.BTC_USDT, BinanceSubscriptionType.TRADE))
.subscribe(trade -> { LOG.info("Trade: {}", trade); });
// Now we enable the live subscription/unsubscription to add new currencies to the streams
exchange.enableLiveSubscription();
// We live subscribe a new currency pair to the trades update
Disposable tradesEth = exchange.getStreamingMarketDataService()
.getTrades(CurrencyPair.ETH_USDT)
.doOnDispose(
() -> exchange.getStreamingMarketDataService().unsubscribe(CurrencyPair.ETH_USDT, BinanceSubscriptionType.TRADE))
.subscribe(trade -> { LOG.info("Trade: {}", trade); });
Thread.sleep(30000);
// We unsubscribe from the streams
tradesBtc.dispose();
tradesEth.dispose();
```
--------------------------------
### Get Order Book
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves the order book for a specified trading pair, showing buy and sell orders.
```APIDOC
## GET /api/orderbook
### Description
Retrieves the order book for a specified trading pair.
### Method
GET
### Endpoint
/api/orderbook
### Query Parameters
- **pairSymbol** (string) - Required - The symbol of the trading pair (e.g., BTCTRY).
### Response
#### Success Response (200)
- **timestamp** (integer) - The Unix timestamp of the order book data.
- **bids** (array) - An array of buy orders, each with 'price' and 'quantity'.
- **asks** (array) - An array of sell orders, each with 'price' and 'quantity'.
### Request Example
```http
GET /api/orderbook?pairSymbol=BTCTRY
```
```
--------------------------------
### Get Account Balance
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves the current account balance for all cryptocurrencies and fiat currencies. This endpoint requires authentication.
```APIDOC
## GET /api/balance
### Description
Retrieves the user's account balance. Requires authentication.
### Method
GET
### Endpoint
/api/balance
### Authentication
Requires 'X-PCK', 'X-Stamp', and 'X-Signature' headers.
### Response
#### Success Response (200)
- **asset** (string) - The name of the asset (e.g., BTC, TRY).
- **free** (string) - The available balance.
- **locked** (string) - The locked balance (e.g., in open orders).
- **total** (string) - The total balance (free + locked).
### Request Example
```http
GET /api/balance
```
```
--------------------------------
### Get Trades
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves recent trade data for a specified trading pair. The `last` parameter is limited to a maximum value of 500.
```APIDOC
## GET /api/trades
### Description
Retrieves recent trade data for a specified trading pair.
### Method
GET
### Endpoint
/api/trades
### Query Parameters
- **pairSymbol** (string) - Required - The symbol of the trading pair (e.g., BTCTRY).
- **last** (integer) - Optional - The number of recent trades to retrieve (max 500).
### Response
#### Success Response (200)
- **id** (integer) - The trade ID.
- **price** (string) - The price at which the trade occurred.
- **quantity** (string) - The amount traded.
- **time** (integer) - The Unix timestamp of the trade.
### Request Example
```http
GET /api/trades?pairSymbol=BTCTRY&last=100
```
```
--------------------------------
### Get Futures Trade Data
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Retrieve recent trade history for futures contracts. Requires specifying the symbol and contract type.
```http
GET https://www.okcoin.com/api/v1/future_trades.do?symbol=btc_usd&contract_type=this_week
```
--------------------------------
### Get Futures Depth Data
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Retrieve the order book depth for futures contracts. Requires specifying the symbol and contract type.
```http
GET https://www.okcoin.com/api/v1/future_depth.do?symbol=btc_usd&contract_type=this_week
```
--------------------------------
### Configure Sonatype Snapshots Repository
Source: https://github.com/knowm/xchange/wiki/Getting-Started-with-XChange-for-Noobies
Add this repository configuration to your pom.xml to allow Maven to download snapshot dependencies from Sonatype.
```xml
sonatype-oss-snapshot
sonatype-oss-snapshot
https://oss.sonatype.org/content/repositories/snapshots
```
--------------------------------
### Get Futures Ticker Data
Source: https://github.com/knowm/xchange/blob/develop/xchange-okcoin/api-specification.txt
Retrieve real-time ticker information for futures contracts. Requires specifying the symbol and contract type.
```http
GET https://www.okcoin.com/api/v1/future_ticker.do?symbol=btc_usd&contract_type=this_week
```
--------------------------------
### Initialize Services with Resilience Registries
Source: https://github.com/knowm/xchange/wiki/Implementing-resiliency-features
Initializes exchange services, passing the resilience registries to their constructors. This ensures services can utilize resilience features.
```java
public class BinanceExchange extends BaseExchange {
// ...
@Override
protected void initServices() {
// ...
this.marketDataService = new BinanceMarketDataService(this, binance, getResilienceRegistries());
this.tradeService = new BinanceTradeService(this, binance, getResilienceRegistries());
this.accountService = new BinanceAccountService(this, binance, getResilienceRegistries());
}
```
--------------------------------
### Add XChange Core and Exchange Dependencies to pom.xml
Source: https://github.com/knowm/xchange/blob/develop/README.md
Include these dependencies in your pom.xml to use XChange. Ensure you have at least xchange-core and the specific exchange module you need.
```xml
org.knowm.xchange
xchange-core
6.0.0
org.knowm.xchange
xchange-XYZ
6.0.0
```
--------------------------------
### Get Open Orders
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves a list of the user's currently open orders for a specified trading pair. This endpoint requires authentication.
```APIDOC
## GET /api/openOrders
### Description
Retrieves a list of the user's currently open orders. Requires authentication.
### Method
GET
### Endpoint
/api/openOrders
### Authentication
Requires 'X-PCK', 'X-Stamp', and 'X-Signature' headers.
### Query Parameters
- **pairSymbol** (string) - Required - The symbol of the trading pair (e.g., BTCTRY).
### Response
#### Success Response (200)
- **id** (integer) - The order ID.
- **pair** (string) - The trading pair.
- **orderType** (string) - The type of order (e.g., 'BUY', 'SELL').
- **orderMethod** (string) - The method of the order (e.g., 'LIMIT', 'MARKET').
- **price** (string) - The price of the order.
- **quantity** (string) - The quantity of the order.
- **amount** (string) - The total amount for the order.
- **unfilledQuantity** (string) - The remaining quantity to be filled.
- **timestamp** (integer) - The Unix timestamp when the order was placed.
### Request Example
```http
GET /api/openOrders?pairSymbol=BTCTRY
```
```
--------------------------------
### Add Snapshot Repository to pom.xml
Source: https://github.com/knowm/xchange/blob/develop/README.md
Configure this repository in your pom.xml to access XChange snapshot versions.
```xml
Central Portal Snapshots
central-portal-snapshots
https://central.sonatype.com/repository/maven-snapshots/
false
true
```
--------------------------------
### Place Buy Order
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Places a buy order on the exchange. This endpoint requires authentication.
```APIDOC
## POST /api/exchange
### Description
Places a buy or sell order on the exchange. Requires authentication.
### Method
POST
### Endpoint
/api/exchange
### Authentication
Requires 'X-PCK', 'X-Stamp', and 'X-Signature' headers.
### Request Body
- **orderMethod** (string) - Required - The method of the order ('BUY' or 'SELL').
- **pairSymbol** (string) - Required - The symbol of the trading pair (e.g., BTCTRY).
- **quantity** (string) - Required - The quantity to buy or sell.
- **price** (string) - Optional - The price for a limit order. If omitted, a market order is assumed.
### Response
#### Success Response (200)
- **id** (integer) - The ID of the placed order.
- **message** (string) - A confirmation message.
### Request Example
```json
{
"orderMethod": "BUY",
"pairSymbol": "BTCTRY",
"quantity": "0.001",
"price": "500000.00"
}
```
```
--------------------------------
### Public Market Data - Get Ticker
Source: https://github.com/knowm/xchange/blob/develop/README.md
Fetches ticker information for a given currency pair using public APIs that do not require authentication.
```APIDOC
## Public Market Data - Get Ticker
### Description
Fetches ticker information for a given currency pair using public APIs that do not require authentication.
### Method
```java
Exchange bitstamp = ExchangeFactory.INSTANCE.createExchange(BitstampExchange.class);
MarketDataService marketDataService = bitstamp.getMarketDataService();
Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD);
System.out.println(ticker.toString());
```
### Parameters
#### Query Parameters
- **CurrencyPair** (CurrencyPair) - Required - The currency pair for which to fetch ticker data (e.g., BTC_USD).
```
--------------------------------
### Place Order
Source: https://github.com/knowm/xchange/blob/develop/xchange-cexio/api-specification.txt
Places a new buy or sell order for a given trading pair.
```APIDOC
## POST https://cex.io/api/place_order/GHS/BTC
### Description
Places a new order to buy or sell a specified amount of currency at a given price for a trading pair. Requires authentication.
### Method
POST
### Endpoint
https://cex.io/api/place_order/{symbol1}/{symbol2}
### Parameters
#### Path Parameters
- **symbol1** (string) - Required - The base currency symbol (e.g., GHS).
- **symbol2** (string) - Required - The quote currency symbol (e.g., BTC).
#### Request Body
- **key** (string) - Required - Your API key.
- **signature** (string) - Required - The HMAC-SHA256 signature of the request.
- **nonce** (integer) - Required - A unique, increasing integer for the request.
- **type** (string) - Required - The type of order: 'buy' or 'sell'.
- **amount** (string) - Required - The amount of the base currency to trade.
- **price** (string) - Required - The price at which to execute the order.
### Request Example
```json
{
"key": "YOUR_API_KEY",
"signature": "YOUR_SIGNATURE",
"nonce": 1234567893,
"type": "buy",
"amount": "0.01000000",
"price": "0.10789"
}
```
### Response
#### Success Response (200)
- Returns a JSON dictionary representing the placed order:
- **id** (string) - The unique identifier for the order.
- **time** (integer) - The timestamp when the order was placed.
- **type** (string) - The type of order ('buy' or 'sell').
- **price** (string) - The price of the order.
- **amount** (string) - The amount of the order.
- **pending** (string) - The pending amount of the order (if partially executed).
### Response Example
```json
{
"price": "0.10789",
"amount": "0.01000000",
"time": 1383379024072,
"type": "buy",
"id": "6219150",
"pending": "0.00000000"
}
```
```
--------------------------------
### New Offer
Source: https://github.com/knowm/xchange/blob/develop/xchange-bitfinex/api-specification.txt
Submits a new offer for lending or borrowing funds.
```APIDOC
## POST /offer/new
### Description
Submit a new offer for lending or borrowing funds. You need to specify the currency, amount, rate, period, and direction.
### Method
POST
### Endpoint
/offer/new
### Parameters
#### Request Body
- **currency** (string) - Required - The name of the currency.
- **amount** (decimal) - Required - Offer size: how much to lend or borrow.
- **rate** (price) - Required - Rate to lend or borrow at. In percentage per 365 days.
- **period** (integer) - Required - Number of days of the loan (in days).
- **direction** (string) - Required - Either "lend" or "loan".
- **insurance_option** (integer) - Optional - 0 for "No insurance", 1 for "Insurance if available", 2 for "Always insure" (default is 0).
### Response
#### Success Response (200)
- **offer_id** (int) - A randomly generated ID for the offer.
- Information given by `/offer/status`.
### Request Example
```json
{
"currency": "USD",
"amount": 1000.0,
"rate": 5.0,
"period": 30,
"direction": "lend",
"insurance_option": 1
}
```
```
--------------------------------
### Currencies List
Source: https://github.com/knowm/xchange/blob/develop/xchange-openexchangerates/api-specification.txt
Retrieves a list of all supported currencies. Requires an application ID.
```APIDOC
## GET /api/currencies.json
### Description
Retrieves a list of all supported currencies and their codes.
### Method
GET
### Endpoint
/api/currencies.json
### Query Parameters
- **app_id** (string) - Required - Your unique application ID.
```
--------------------------------
### Get Ticker Information
Source: https://github.com/knowm/xchange/blob/develop/xchange-btcturk/api-specification.txt
Retrieves the latest ticker information for all trading pairs or a specific pair. The ticker endpoint is rate-limited to 10 requests per 100 milliseconds.
```APIDOC
## GET /api/ticker
### Description
Retrieves the latest ticker information for all available trading pairs.
### Method
GET
### Endpoint
/api/ticker
### Query Parameters
- **pairSymbol** (string) - Optional - The symbol of the trading pair (e.g., BTCTRY).
### Response
#### Success Response (200)
- **pair** (string) - The trading pair symbol.
- **last** (string) - The last traded price.
- **lowest** (string) - The lowest price in the last 24 hours.
- **highest** (string) - The highest price in the last 24 hours.
- **bid** (string) - The highest buy order price.
- **ask** (string) - The lowest sell order price.
- **volume** (string) - The 24-hour trading volume.
- **timestamp** (integer) - The Unix timestamp of the last update.
### Request Example
```http
GET /api/ticker?pairSymbol=BTCTRY
```
```