Skip to content

Commit

Permalink
add all bybit parameters to PositionChanges subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
rizer1980 committed Oct 8, 2024
1 parent e5cfa8d commit 7e3b3f2
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,37 @@
import java.math.BigDecimal;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.knowm.xchange.bybit.dto.BybitCategory;
import org.knowm.xchange.dto.account.OpenPosition;
import org.knowm.xchange.instrument.Instrument;

@Getter
@Setter
@ToString
public class BybitComplexPositionChanges extends OpenPosition {
private int positionIdx;
private int tradeMode;
private int riskId;
private String riskLimitValue;
private BigDecimal markPrice;
private BigDecimal positionBalance;
private int autoAddMargin;
private BigDecimal positionMM;
private BigDecimal positionIM;
private BigDecimal bustPrice;
private BigDecimal positionValue;
private BigDecimal leverage;
private BigDecimal takeProfit;
private BigDecimal stopLoss;
private BigDecimal stopLoss;
private BigDecimal trailingStop;
private BigDecimal curRealisedPnl;
private BigDecimal sessionAvgPrice; //USDC contract session avg price
private String positionStatus;
private int adlRankIndicator;
private boolean isReduceOnly;
private String mmrSysUpdatedTime;
private String leverageSysUpdatedTime;
private long createdTime;
private long updatedTime;
private long seq;
Expand Down Expand Up @@ -53,5 +72,40 @@ public BybitComplexPositionChanges(BybitComplexPositionChanges changes) {
this.updatedTime = changes.updatedTime;
this.seq = changes.seq;
}

public BybitComplexPositionChanges(Instrument instrument, Type type, BigDecimal size,
BigDecimal price, BigDecimal liquidationPrice, BigDecimal unRealisedPnl, int positionIdx,
int tradeMode, int riskId, String riskLimitValue, BigDecimal markPrice,
BigDecimal positionBalance, int autoAddMargin, BigDecimal positionMM, BigDecimal positionIM,
BigDecimal bustPrice, BigDecimal positionValue, BigDecimal leverage,
BigDecimal takeProfit, BigDecimal stopLoss, BigDecimal trailingStop, BigDecimal curRealisedPnl,
BigDecimal sessionAvgPrice, String positionStatus, int adlRankIndicator, boolean isReduceOnly,
String mmrSysUpdatedTime, String leverageSysUpdatedTime, long createdTime, long updatedTime,
long seq) {
super(instrument, type, size, price, liquidationPrice, unRealisedPnl);
this.positionIdx = positionIdx;
this.tradeMode = tradeMode;
this.riskId = riskId;
this.riskLimitValue = riskLimitValue;
this.markPrice = markPrice;
this.positionBalance = positionBalance;
this.autoAddMargin = autoAddMargin;
this.positionMM = positionMM;
this.positionIM = positionIM;
this.bustPrice = bustPrice;
this.positionValue = positionValue;
this.leverage = leverage;
this.takeProfit = takeProfit;
this.stopLoss = stopLoss;
this.trailingStop = trailingStop;
this.curRealisedPnl = curRealisedPnl;
this.sessionAvgPrice = sessionAvgPrice;
this.positionStatus = positionStatus;
this.adlRankIndicator = adlRankIndicator;
this.isReduceOnly = isReduceOnly;
this.mmrSysUpdatedTime = mmrSysUpdatedTime;
this.leverageSysUpdatedTime = leverageSysUpdatedTime;
this.createdTime = createdTime;
this.updatedTime = updatedTime;
this.seq = seq;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,55 +10,55 @@
@Getter
public class BybitPositionChangesResponse {

String id;
String topic;
long creationTime;
List<BybitPositionChanges> data = new ArrayList<>();
private String id;
private String topic;
private long creationTime;
private List<BybitPositionChanges> data = new ArrayList<>();

@Getter
public static class BybitPositionChanges {

BybitCategory category;
String symbol;
String side;
String size;
int positionIdx;
String tradeMode;
String positionValue;
int riskId;
String riskLimitValue;
String entryPrice;
String markPrice;
String leverage;
String positionBalance;
int autoAddMargin;
String positionMM;
String positionIM;
String liqPrice;
String bustPrice;
String tpslMode;
String takeProfit;
String stopLoss;
String trailingStop;
String unrealisedPnl;
String curRealisedPnl;
String sessionAvgPrice;
String delta;
String gamma;
String vega;
String theta;
String cumRealisedPnl;
String positionStatus;
int adlRankIndicator;
boolean isReduceOnly;
private BybitCategory category;
private String symbol;
private String side;
private String size;
private int positionIdx;
private int tradeMode;
private String positionValue;
private int riskId;
private String riskLimitValue;
private String entryPrice;
private String markPrice;
private String leverage;
private String positionBalance;
private int autoAddMargin;
private String positionMM;
private String positionIM;
private String liqPrice;
private String bustPrice;
private String tpslMode;
private String takeProfit;
private String stopLoss;
private String trailingStop;
private String unrealisedPnl;
private String curRealisedPnl;
private String sessionAvgPrice;
private String delta;
private String gamma;
private String vega;
private String theta;
private String cumRealisedPnl;
private String positionStatus;
private int adlRankIndicator;
private boolean isReduceOnly;

String mmrSysUpdatedTime;
private String mmrSysUpdatedTime;

String leverageSysUpdatedTime;
private String leverageSysUpdatedTime;

String createdTime;
String updatedTime;
long seq;
private String createdTime;
private String updatedTime;
private long seq;

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,32 @@ public static List<BybitComplexPositionChanges> adaptComplexPositionChanges(
if (!position.getLiqPrice().isEmpty()) {
liqPrice = new BigDecimal(position.getLiqPrice());
}
BigDecimal bustPrice = null;
if(!position.getBustPrice().isEmpty()) {
bustPrice = new BigDecimal(position.getBustPrice());
}
BigDecimal sessionAvgPrice = null;
if (!position.getSessionAvgPrice().isEmpty()) {
sessionAvgPrice = new BigDecimal(position.getSessionAvgPrice());
}
BybitComplexPositionChanges positionChanges = new BybitComplexPositionChanges(
guessSymbol(position.getSymbol(),
position.getCategory()), type, new BigDecimal(position.getSize()), liqPrice,
new BigDecimal(position.getUnrealisedPnl()),
new BigDecimal(position.getPositionValue()), new BigDecimal(position.getEntryPrice()),
position.getCategory()), type, new BigDecimal(position.getSize()),
new BigDecimal(position.getEntryPrice()), liqPrice,
new BigDecimal(position.getUnrealisedPnl()), position.getPositionIdx(),
position.getTradeMode(), position.getRiskId(), position.getRiskLimitValue(),
new BigDecimal(position.getMarkPrice()),
new BigDecimal(position.getPositionBalance()), position.getAutoAddMargin(),
new BigDecimal(position.getPositionMM()),
new BigDecimal(position.getPositionIM()),
bustPrice, new BigDecimal(position.getPositionValue()),
new BigDecimal(position.getLeverage()),
new BigDecimal(position.getTakeProfit()), new BigDecimal(position.getStopLoss()),
new BigDecimal(position.getTrailingStop()),
new BigDecimal(position.getCurRealisedPnl()),
sessionAvgPrice, position.getPositionStatus(),
position.getAdlRankIndicator(), position.isReduceOnly(),
position.getMmrSysUpdatedTime(), position.getLeverageSysUpdatedTime(),
Long.parseLong(position.getCreatedTime()), Long.parseLong(position.getUpdatedTime()),
position.getSeq());
result.add(positionChanges);
Expand All @@ -160,9 +178,11 @@ public static List<BybitComplexOrderChanges> adaptComplexOrdersChanges(
List<BybitComplexOrderChanges> result = new ArrayList<>();
for (BybitOrderChanges change : data) {
Order.OrderType orderType = getOrderType(change.getSide());
BigDecimal avgPrice = change.getAvgPrice().isEmpty() ? null : new BigDecimal(change.getAvgPrice());
BigDecimal avgPrice =
change.getAvgPrice().isEmpty() ? null : new BigDecimal(change.getAvgPrice());
BybitComplexOrderChanges orderChanges = new BybitComplexOrderChanges(orderType,
new BigDecimal(change.getQty()), guessSymbol(change.getSymbol(),change.getCategory()), change.getOrderId(),
new BigDecimal(change.getQty()), guessSymbol(change.getSymbol(), change.getCategory()),
change.getOrderId(),
new Date(Long.parseLong(change.getCreatedTime())), avgPrice,
new BigDecimal(change.getCumExecQty()), new BigDecimal(change.getCumExecFee()),
adaptBybitOrderStatus(change.getOrderStatus()), change.getOrderLinkId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.instrument.Instrument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class BybitStreamExample {

private static final Logger log = LoggerFactory.getLogger(BybitStreamExample.class);

public static void main(String[] args) {
Expand Down Expand Up @@ -63,41 +65,53 @@ private static void auth() throws IOException, InterruptedException {
exchangeSpecification);
exchange.connect().blockingAwait();
Ticker ticker = (exchange.getMarketDataService().getTicker(DOGE_PERP));
BigDecimal amount = exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getMinimumAmount();
if(amount.multiply(ticker.getLast()).compareTo(new BigDecimal("5.0")) <= 0) {
amount = new BigDecimal("5").divide(ticker.getAsk(), exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getVolumeScale(), UP);
BigDecimal amount = exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP)
.getMinimumAmount();
if (amount.multiply(ticker.getLast()).compareTo(new BigDecimal("5.0")) <= 0) {
amount = new BigDecimal("5").divide(ticker.getAsk(),
exchange.getExchangeMetaData().getInstruments().get(DOGE_PERP).getVolumeScale(), UP);
}
LimitOrder limitOrder = new LimitOrder(OrderType.BID,amount, DOGE_PERP, "", new Date(), ticker.getAsk());
LimitOrder limitOrder = new LimitOrder(OrderType.BID, amount, DOGE_PERP, "", new Date(),
ticker.getAsk());
MarketOrder marketOrder = new MarketOrder(OrderType.BID, amount, DOGE_PERP);
Thread.sleep(2000L);
AtomicReference<Order> order = new AtomicReference<>();
Disposable disposableOrderChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getOrderChanges(BybitCategory.LINEAR)
Disposable disposableOrderChanges = ((BybitStreamingTradeService) exchange.getStreamingTradeService()).getOrderChanges(
BybitCategory.LINEAR)
.doOnError(
error -> log.error("OrderChanges error {}",error.getMessage()))
.subscribe( c -> {
error -> log.error("OrderChanges error {}", error.getMessage()))
.subscribe(c -> {
log.info("Order Changes {}", c);
order.set(c);
},
throwable -> log.error("OrderChanges throwable,{}",throwable.getMessage()));
throwable -> log.error("OrderChanges throwable,{}", throwable.getMessage()));
// Disposable disposablePositionChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getPositionChanges(BybitCategory.LINEAR)
// .doOnError(
// error -> log.error("PositionChanges error {}",error.getMessage()))
// .subscribe( p -> log.info("PositionChanges Changes {}", p),
// throwable -> log.error("Position throwable,{}",throwable.getMessage()));

Disposable disposableComplexPositionChanges = ((BybitStreamingTradeService)exchange.getStreamingTradeService()).getBybitPositionChanges(BybitCategory.LINEAR)
Disposable disposableByBitPositionChanges = ((BybitStreamingTradeService) exchange.getStreamingTradeService()).getBybitPositionChanges(
BybitCategory.LINEAR)
.doOnError(
error -> log.error("PositionChanges error {}",error,error))
.subscribe(p -> log.info("PositionChanges Changes {}", p),
throwable -> log.error("Position throwable,{}",throwable ,throwable));
Disposable disposableComplexPositionChanges = ((BybitStreamingTradeService) exchange.getStreamingTradeService()).getBybitPositionChanges(
BybitCategory.LINEAR)
.doOnError(
error -> log.error("ComplexPositionChanges error {}",error.getMessage()))
.subscribe( p -> log.info("ComplexPositionChanges Changes {}", p),
throwable -> log.error("ComplexPosition throwable,{}",throwable.getMessage()));
error -> log.error("ComplexPositionChanges error {}", error.getMessage()))
.subscribe(p -> log.info("ComplexPositionChanges Changes {}", p),
throwable -> log.error("ComplexPosition throwable,{}", throwable.getMessage()));

Thread.sleep(3000L);
exchange.getTradeService().placeLimitOrder(limitOrder);
exchange.getTradeService().placeMarketOrder(marketOrder);
Thread.sleep(30000L);
disposableOrderChanges.dispose();
// disposablePositionChanges.dispose();
disposableByBitPositionChanges.dispose();
disposableComplexPositionChanges.dispose();
exchange.disconnect().blockingAwait();
}
}

public static void spot() throws IOException {
ExchangeSpecification exchangeSpecification =
Expand Down

0 comments on commit 7e3b3f2

Please sign in to comment.