Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions xchange-bybit/src/main/java/org/knowm/xchange/bybit/Bybit.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;
import org.knowm.xchange.bybit.dto.BybitResult;
import org.knowm.xchange.bybit.dto.marketdata.BybitOrderbook;
import org.knowm.xchange.bybit.dto.marketdata.instruments.BybitInstrumentInfo;
import org.knowm.xchange.bybit.dto.marketdata.instruments.BybitInstrumentsInfo;
import org.knowm.xchange.bybit.dto.marketdata.tickers.BybitTicker;
Expand All @@ -26,6 +27,17 @@ BybitResult<BybitTickers<BybitTicker>> getTicker24h(
@QueryParam("category") String category, @QueryParam("symbol") String symbol)
throws IOException, BybitException;

/**
* @apiSpec <a href="https://bybit-exchange.github.io/docs/v5/market/orderbook">API</a>
*/
@GET
@Path("/orderbook")
BybitResult<BybitOrderbook> getOrderbook(
@QueryParam("category") String category,
@QueryParam("symbol") String symbol,
@QueryParam("limit") String limit)
throws IOException, BybitException;

/**
* @apiSpec <a href="https://bybit-exchange.github.io/docs/v5/market/instrument">API</a>
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package org.knowm.xchange.bybit.dto.marketdata;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import lombok.Builder;
import lombok.Value;
import lombok.extern.jackson.Jacksonized;

@Builder
@Jacksonized
@Value
public class BybitOrderbook {

@JsonProperty("s")
String symbol;

@JsonProperty("b")
List<String[]> bids;

@JsonProperty("a")
List<String[]> asks;

@JsonProperty("ts")
long timestamp;

@JsonProperty("u")
long updateId;

@JsonProperty("seq")
long crossSequence;

@JsonProperty("cts")
long crossTimestamp;

public SortedMap<BigDecimal, BigDecimal> getBids() {
TreeMap<BigDecimal, BigDecimal> bidsMap = new TreeMap<>((k1, k2) -> -k1.compareTo(k2));
convertToSortedMap(bidsMap, bids);
return Collections.unmodifiableSortedMap(bidsMap);
}

public SortedMap<BigDecimal, BigDecimal> getAsks() {
TreeMap<BigDecimal, BigDecimal> asksMap = new TreeMap<>();
convertToSortedMap(asksMap, asks);
return Collections.unmodifiableSortedMap(asksMap);
}

private void convertToSortedMap(SortedMap<BigDecimal, BigDecimal> result, List<String[]> asks) {
BiConsumer<String[], Map<BigDecimal, BigDecimal>> entryProcessor =
(entry, map) -> {
BigDecimal price = new BigDecimal(entry[0]);
BigDecimal qty = new BigDecimal(entry[1]);
map.put(price, qty);
};
asks.forEach(e -> entryProcessor.accept(e, result));
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
package org.knowm.xchange.bybit.service;

import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.knowm.xchange.bybit.BybitAdapters;
import org.knowm.xchange.bybit.BybitExchange;
import org.knowm.xchange.bybit.dto.BybitCategory;
import org.knowm.xchange.bybit.dto.BybitResult;
import org.knowm.xchange.bybit.dto.marketdata.BybitOrderbook;
import org.knowm.xchange.bybit.dto.marketdata.tickers.BybitTicker;
import org.knowm.xchange.bybit.dto.marketdata.tickers.BybitTickers;
import org.knowm.xchange.bybit.dto.marketdata.tickers.linear.BybitLinearInverseTicker;
import org.knowm.xchange.bybit.dto.marketdata.tickers.option.BybitOptionTicker;
import org.knowm.xchange.bybit.dto.marketdata.tickers.spot.BybitSpotTicker;
import org.knowm.xchange.client.ResilienceRegistries;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.instrument.Instrument;
import org.knowm.xchange.service.marketdata.MarketDataService;
Expand Down Expand Up @@ -102,4 +109,38 @@ public List<Ticker> getTickers(Params params) throws IOException {
}
return result;
}

@Override
public OrderBook getOrderBook(Instrument instrument, Object... args) throws IOException {
Assert.notNull(instrument, "Null instrument");

BybitCategory category = BybitAdapters.getCategory(instrument);
int limitDepth = 100;
if (args != null && args.length > 0 && args[0] instanceof Integer) {
limitDepth = (Integer) args[0];
}

BybitResult<BybitOrderbook> response =
getOrderbook(category, BybitAdapters.convertToBybitSymbol(instrument), limitDepth);

return convertOrderBook(response.getResult(), instrument);
}

@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
return getOrderBook((Instrument) currencyPair, args);
}

public static OrderBook convertOrderBook(BybitOrderbook ob, Instrument pair) {
List<LimitOrder> bids =
ob.getBids().entrySet().stream()
.map(e -> new LimitOrder(OrderType.BID, e.getValue(), pair, null, null, e.getKey()))
.collect(Collectors.toList());
List<LimitOrder> asks =
ob.getAsks().entrySet().stream()
.map(e -> new LimitOrder(OrderType.ASK, e.getValue(), pair, null, null, e.getKey()))
.collect(Collectors.toList());
return new OrderBook(
Date.from(Instant.ofEpochMilli(ob.getTimestamp())), asks, bids);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.knowm.xchange.bybit.BybitExchange;
import org.knowm.xchange.bybit.dto.BybitCategory;
import org.knowm.xchange.bybit.dto.BybitResult;
import org.knowm.xchange.bybit.dto.marketdata.BybitOrderbook;
import org.knowm.xchange.bybit.dto.marketdata.instruments.BybitInstrumentInfo;
import org.knowm.xchange.bybit.dto.marketdata.instruments.BybitInstrumentsInfo;
import org.knowm.xchange.bybit.dto.marketdata.tickers.BybitTicker;
Expand Down Expand Up @@ -48,4 +49,18 @@ public BybitResult<BybitTickers<BybitTicker>> getTickers(BybitCategory category)
}
return result;
}

public BybitResult<BybitOrderbook> getOrderbook(
BybitCategory category, String symbol, int limit) throws IOException {
BybitResult<BybitOrderbook> result =
bybit.getOrderbook(
category.getValue(),
symbol,
limit > 0 ? String.valueOf(limit) : null);

if (!result.isSuccess()) {
throw BybitAdapters.createBybitExceptionFromResult(result);
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.knowm.xchange.bybit.dto.marketdata.tickers.linear.BybitLinearInverseTicker;
import org.knowm.xchange.bybit.dto.marketdata.tickers.option.BybitOptionTicker;
import org.knowm.xchange.bybit.dto.marketdata.tickers.spot.BybitSpotTicker;
import org.knowm.xchange.bybit.dto.marketdata.BybitOrderbook;

public class BybitMarketDataServiceRawTest extends BaseWiremockTest {

Expand All @@ -42,6 +43,10 @@ private void initInstrumentsInfoStub(String responseBody) throws IOException {
initGetStub("/v5/market/instruments-info", responseBody);
}

private void initOrderbookStub(String responseBody) throws IOException {
initGetStub("/v5/market/orderbook", responseBody);
}

@Test
public void testGetLinearInverseInstrumentsInfo() throws Exception {
initInstrumentsInfoStub("/getInstrumentLinear.json5");
Expand Down Expand Up @@ -257,4 +262,23 @@ public void testGetSpotTicker() throws Exception {
assertThat(actualTicker.getVolume24h()).isEqualTo(new BigDecimal("11801.27771"));
assertThat(actualTicker.getUsdIndexPrice()).isEqualTo(new BigDecimal("20784.12009279"));
}

@Test
public void testGetSpotOrderbook() throws Exception {
initOrderbookStub("/getOrderbookSpot.json5");

BybitOrderbook orderbook =
marketDataServiceRaw.getOrderbook(BybitCategory.SPOT, "BTCUSDT", 100).getResult();

assertThat(orderbook.getSymbol()).isEqualTo("BTCUSDT");
assertThat(orderbook.getTimestamp()).isEqualTo(1716863719031L);
assertThat(orderbook.getUpdateId()).isEqualTo(230704L);
assertThat(orderbook.getCrossSequence()).isEqualTo(1432604333L);
assertThat(orderbook.getBids()).hasSize(2);
assertThat(orderbook.getAsks()).hasSize(2);
assertThat(orderbook.getBids().get(new BigDecimal("65485.47"))).isEqualTo(new BigDecimal("47.081829"));
assertThat(orderbook.getBids().get(new BigDecimal("65484.00"))).isEqualTo(new BigDecimal("10.0"));
assertThat(orderbook.getAsks().get(new BigDecimal("65557.7"))).isEqualTo(new BigDecimal("16.606555"));
assertThat(orderbook.getAsks().get(new BigDecimal("65558.0"))).isEqualTo(new BigDecimal("5.0"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.derivative.FuturesContract;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.service.marketdata.MarketDataService;

Expand Down Expand Up @@ -65,4 +66,17 @@ public void testGetTickerWithSpotArg() throws Exception {
assertThat(ticker.getAskSize()).isEqualTo(new BigDecimal("1.862172"));
assertThat(ticker.getPercentageChange()).isEqualTo(new BigDecimal("0.0068"));
}

@Test
public void testGetOrderBook() throws Exception {
initGetStub("/v5/market/orderbook", "/getOrderbookSpot.json5");

OrderBook orderBook = marketDataService.getOrderBook(CurrencyPair.BTC_USD);

assertThat(orderBook.getBids()).hasSize(2);
assertThat(orderBook.getAsks()).hasSize(2);
assertThat(orderBook.getBids().get(0).getLimitPrice()).isEqualTo(new BigDecimal("65485.47"));
assertThat(orderBook.getBids().get(0).getInstrument()).isEqualTo(CurrencyPair.BTC_USD);
assertThat(orderBook.getAsks().get(0).getLimitPrice()).isEqualTo(new BigDecimal("65557.7"));
}
}
21 changes: 21 additions & 0 deletions xchange-bybit/src/test/resources/getOrderbookSpot.json5
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"retCode": 0,
"retMsg": "OK",
"result": {
"s": "BTCUSDT",
"a": [
["65557.7", "16.606555"],
["65558.0", "5.0"]
],
"b": [
["65485.47", "47.081829"],
["65484.00", "10.0"]
],
"ts": 1716863719031,
"u": 230704,
"seq": 1432604333,
"cts": 1716863718905
},
"retExtInfo": {},
"time": 1716863719382
}
Loading