proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
knowm_XChange
|
XChange/xchange-mercadobitcoin/src/main/java/org/knowm/xchange/mercadobitcoin/service/MercadoBitcoinMarketDataServiceRaw.java
|
MercadoBitcoinMarketDataServiceRaw
|
getMercadoBitcoinTransactions
|
class MercadoBitcoinMarketDataServiceRaw extends MercadoBitcoinBaseService {
private final MercadoBitcoin mercadoBitcoin;
/**
* Constructor
*
* @param exchange
*/
public MercadoBitcoinMarketDataServiceRaw(Exchange exchange) {
super(exchange);
this.mercadoBitcoin =
ExchangeRestProxyBuilder.forInterface(
MercadoBitcoin.class, exchange.getExchangeSpecification())
.build();
}
public MercadoBitcoinOrderBook getMercadoBitcoinOrderBook(CurrencyPair currencyPair)
throws IOException {
MercadoBitcoinUtils.verifyCurrencyPairAvailability(currencyPair);
return mercadoBitcoin.getOrderBook(currencyPair.base.getSymbol());
}
public MercadoBitcoinTicker getMercadoBitcoinTicker(CurrencyPair currencyPair)
throws IOException {
MercadoBitcoinUtils.verifyCurrencyPairAvailability(currencyPair);
return mercadoBitcoin.getTicker(currencyPair.base.getSymbol());
}
public MercadoBitcoinTransaction[] getMercadoBitcoinTransactions(
CurrencyPair currencyPair, Object... args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
MercadoBitcoinUtils.verifyCurrencyPairAvailability(currencyPair);
MercadoBitcoinTransaction[] transactions;
if (args.length == 0) {
// default values: offset=0, limit=100
transactions = mercadoBitcoin.getTransactions(currencyPair.base.getSymbol());
} else if (args.length == 1) {
BigDecimal time = new BigDecimal((Long) args[0]);
transactions =
mercadoBitcoin.getTransactions(currencyPair.base.getSymbol(), time.longValue() / 1000L);
} else if (args.length == 2) {
BigDecimal timeStart = new BigDecimal((Long) args[0]);
BigDecimal timeEnd = new BigDecimal((Long) args[1]);
transactions =
mercadoBitcoin.getTransactions(
currencyPair.base.getSymbol(),
timeStart.longValue() / 1000L,
timeEnd.longValue() / 1000L);
} else {
throw new ExchangeException("Invalid argument length. Must be 0, 1 or 2.");
}
return transactions;
| 317
| 296
| 613
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>
|
knowm_XChange
|
XChange/xchange-mercadobitcoin/src/main/java/org/knowm/xchange/mercadobitcoin/service/MercadoBitcoinTradeServiceRaw.java
|
MercadoBitcoinTradeServiceRaw
|
mercadoBitcoinCancelOrder
|
class MercadoBitcoinTradeServiceRaw extends MercadoBitcoinBaseService {
private static final String GET_ORDER_LIST = "OrderList";
private static final String TRADE = "Trade";
private static final String CANCEL_ORDER = "CancelOrder";
private final MercadoBitcoinAuthenticated mercadoBitcoinAuthenticated;
/**
* Constructor
*
* @param exchange
*/
public MercadoBitcoinTradeServiceRaw(Exchange exchange) {
super(exchange);
this.mercadoBitcoinAuthenticated =
ExchangeRestProxyBuilder.forInterface(
MercadoBitcoinAuthenticated.class, exchange.getExchangeSpecification())
.build();
}
public MercadoBitcoinBaseTradeApiResult<MercadoBitcoinUserOrders> getMercadoBitcoinUserOrders(
@Nonnull String pair,
@Nullable String type,
@Nullable String status,
@Nullable String fromId,
@Nullable String endId,
@Nullable Long since,
@Nullable Long end)
throws IOException {
String method = GET_ORDER_LIST;
long tonce = exchange.getNonceFactory().createValue();
MercadoBitcoinDigest signatureCreator =
MercadoBitcoinDigest.createInstance(
method,
exchange.getExchangeSpecification().getPassword(),
exchange.getExchangeSpecification().getSecretKey(),
tonce);
MercadoBitcoinBaseTradeApiResult<MercadoBitcoinUserOrders> userOrders =
mercadoBitcoinAuthenticated.getOrderList(
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
method,
tonce,
pair,
type,
status,
fromId,
endId,
since,
end);
if (userOrders.getSuccess() == 0) {
throw new ExchangeException("Error getting user orders: " + userOrders.getError());
}
return userOrders;
}
public MercadoBitcoinBaseTradeApiResult<MercadoBitcoinPlaceLimitOrderResult>
mercadoBitcoinPlaceLimitOrder(
@Nonnull String pair,
@Nonnull String type,
@Nonnull BigDecimal volume,
@Nonnull BigDecimal price)
throws IOException {
String method = TRADE;
long tonce = exchange.getNonceFactory().createValue();
MercadoBitcoinDigest signatureCreator =
MercadoBitcoinDigest.createInstance(
method,
exchange.getExchangeSpecification().getPassword(),
exchange.getExchangeSpecification().getSecretKey(),
tonce);
MercadoBitcoinBaseTradeApiResult<MercadoBitcoinPlaceLimitOrderResult> newOrder =
mercadoBitcoinAuthenticated.placeLimitOrder(
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
method,
tonce,
pair,
type,
volume,
price);
if (newOrder.getSuccess() == 0) {
throw new ExchangeException("Error creating a new order: " + newOrder.getError());
}
return newOrder;
}
/**
* @param pair btc_brl or ltc_brl
* @param orderId the order ID
* @return See {@link org.knowm.xchange.mercadobitcoin.dto.trade.MercadoBitcoinCancelOrderResult}
* .
* @throws IOException
*/
public MercadoBitcoinBaseTradeApiResult<MercadoBitcoinCancelOrderResult>
mercadoBitcoinCancelOrder(@Nonnull String pair, @Nonnull String orderId) throws IOException {<FILL_FUNCTION_BODY>}
}
|
String method = CANCEL_ORDER;
long tonce = exchange.getNonceFactory().createValue();
MercadoBitcoinDigest signatureCreator =
MercadoBitcoinDigest.createInstance(
method,
exchange.getExchangeSpecification().getPassword(),
exchange.getExchangeSpecification().getSecretKey(),
tonce);
MercadoBitcoinBaseTradeApiResult<MercadoBitcoinCancelOrderResult> result =
mercadoBitcoinAuthenticated.cancelOrder(
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
method,
tonce,
pair,
orderId);
if (result.getSuccess() == 0) {
throw new ExchangeException("Error canceling a new order: " + result.getError());
}
return result;
| 949
| 211
| 1,160
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>
|
knowm_XChange
|
XChange/xchange-mexc/src/main/java/org/knowm/xchange/mexc/MEXCErrorUtils.java
|
MEXCErrorUtils
|
getErrorMessage
|
class MEXCErrorUtils {
public static Optional<String> getOptionalErrorMessage(int errorCode) {
return Optional.ofNullable(getErrorMessage(errorCode));
}
private static String getErrorMessage(int errorCode) {<FILL_FUNCTION_BODY>}
}
|
switch (errorCode) {
case (400):
return "Invalid parameter";
case (401):
return "Invalid signature, fail to pass the validation";
case (429):
return "Too many requests, rate limit rule is violated";
case (10072):
return "Invalid access key";
case (10073):
return "Invalid request time";
case (30000):
return "Trading is suspended for the requested symbol";
case (30001):
return "Current trading type (bid or ask) is not allowed";
case (30002):
return "Invalid trading amount, smaller than the symbol minimum trading amount";
case (30003):
return "Invalid trading amount, greater than the symbol maximum trading amount";
case (30004):
return "Insufficient balance";
case (30005):
return "Oversell error";
case (30010):
return "Price out of allowed range";
case (30016):
return "Market is closed";
case (30019):
return "Orders count over limit for batch processing";
case (30020):
return "Restricted symbol, API access is not allowed for the time being";
case (30021):
return "Invalid symbol";
default:
return null;
}
| 74
| 365
| 439
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/OkCoinUtils.java
|
OkCoinUtils
|
getErrorMessage
|
class OkCoinUtils {
public static Long toEpoch(Date dateTime, String timeZone) {
// Epoch of midnight in local time zone
Calendar timeOffset = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
timeOffset.set(Calendar.MILLISECOND, 0);
timeOffset.set(Calendar.SECOND, 0);
timeOffset.set(Calendar.MINUTE, 0);
timeOffset.set(Calendar.HOUR_OF_DAY, 0);
long midnightOffSet = timeOffset.getTime().getTime();
long localTimestamp = dateTime.getTime();
return timeOffset == null ? null : midnightOffSet + localTimestamp;
}
public static String getErrorMessage(int errorCode) {<FILL_FUNCTION_BODY>}
}
|
// https://www.okex.com/rest_request.html
switch (errorCode) {
case (1002):
return "The transaction amount exceed the balance";
case (1003):
return "The transaction amount is less than the minimum requirement";
case (1004):
return "The transaction amount is less than 0";
case (1007):
return "No trading market information";
case (1008):
return "No latest market information";
case (1009):
return "No order";
case (1010):
return "Different user of the cancelled order and the original order";
case (10000):
return "Required field can not be null";
case (10001):
return "User request too frequent";
case (10002):
return "System error";
case (10003):
return "Try again later";
case (10004):
return "Not allowed to get resource due to IP constraint";
case (10005):
return "secretKey does not exist";
case (10006):
return "Partner (API key) does not exist";
case (10007):
return "Signature does not match";
case (10008):
return "Illegal parameter";
case (10009):
return "Order does not exist";
case (10010):
return "Insufficient funds";
case (10011):
return "Order quantity is less than minimum quantity allowed";
case (10012):
return "Invalid currency pair";
case (10013):
return "Only support https request";
case (10014):
return "Order price can not be ≤ 0 or ≥ 1,000,000";
case (10015):
return "Order price differs from current market price too much";
case (10016):
return "Insufficient coins balance";
case (10017):
return "API authorization error";
case (10018):
return "borrow amount less than lower limit";
case (10019):
return "loan agreement not checked";
case (10020):
return "rate cannot exceed 1%\n";
case (10021):
return "rate cannot less than 0.01%";
case (10023):
return "fail to get latest ticker";
case (10216):
return "Non-public API";
case (20001):
return "User does not exist";
case (20002):
return "Account frozen";
case (20003):
return "Account frozen due to liquidation";
case (20004):
return "Futures account frozen";
case (20005):
return "User futures account does not exist";
case (20006):
return "Required field missing";
case (20007):
return "Illegal parameter";
case (20008):
return "Futures account balance is too low";
case (20009):
return "Future contract status error";
case (20010):
return "Risk rate ratio does not exist";
case (20011):
return "Risk rate higher than 90% before opening position";
case (20012):
return "Risk rate higher than 90% after opening position";
case (20013):
return "Temporally no counter party price";
case (20014):
return "System error";
case (20015):
return "Order does not exist";
case (20016):
return "Close amount bigger than your open positions";
case (20017):
return "Not authorized/illegal operation";
case (20018):
return "Order price differ more than 5% from the price in the last minute";
case (20019):
return "IP restricted from accessing the resource";
case (20020):
return "secretKey does not exist";
case (20021):
return "Index information does not exist";
case (20022):
return "Wrong API interface (Cross margin mode shall call cross margin API, fixed margin mode shall call fixed margin API)";
case (20023):
return "Account in fixed-margin mode";
case (20024):
return "Signature does not match";
case (20025):
return "Leverage rate error";
case (20026):
return "API Permission Error";
case (20027):
return "no transaction record";
case (20028):
return "no such contract";
default:
return "Unknown error: " + errorCode;
}
| 205
| 1,296
| 1,501
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/OkexAdaptersV3.java
|
OkexAdaptersV3
|
convertDepositStatus
|
class OkexAdaptersV3 {
public static Balance convert(OkexFundingAccountRecord rec) {
return new Balance.Builder()
.currency(Currency.getInstance(rec.getCurrency()))
.available(rec.getAvailable())
.frozen(rec.getBalance().subtract(rec.getAvailable()))
.total(rec.getBalance())
.build();
}
public static Balance convert(OkexSpotAccountRecord rec) {
return new Balance.Builder()
.currency(Currency.getInstance(rec.getCurrency()))
.available(rec.getAvailable())
.frozen(rec.getBalance().subtract(rec.getAvailable()))
.total(rec.getBalance())
.build();
}
public static Balance convert(String currency, FuturesAccount acc) {
return new Balance.Builder()
.currency(Currency.getInstance(currency.toUpperCase()))
.total(acc.getEquity())
.build();
}
public static Balance convert(SwapAccountInfo rec) {
return new Balance.Builder()
.currency(toPair(rec.getInstrumentId()).base)
.total(rec.getEquity())
.build();
}
public static String toSpotInstrument(CurrencyPair pair) {
return pair == null ? null : pair.base.getCurrencyCode() + "-" + pair.counter.getCurrencyCode();
}
/**
* there are different types of instruments: spot (ie 'ETH-BTC'), future (ie 'BCH-USD-190927'),
* swap (ie 'ETH-USD-SWAP')
*
* @param instrument
* @return
*/
public static CurrencyPair toPair(String instrument) {
String[] split = instrument.split("-");
if (split == null || split.length < 2) {
throw new ExchangeException("Not supported instrument: " + instrument);
}
return new CurrencyPair(split[0], split[1]);
}
public static Ticker convert(OkexSpotTicker i) {
return new Ticker.Builder()
.currencyPair(toPair(i.getInstrumentId()))
.last(i.getLast())
.bid(i.getBid())
.ask(i.getAsk())
.volume(i.getBaseVolume24h())
.quoteVolume(i.getQuoteVolume24h())
.timestamp(i.getTimestamp())
.build();
}
public static LimitOrder convert(OkexOpenOrder o) {
return new LimitOrder.Builder(
o.getSide() == Side.sell ? OrderType.ASK : OrderType.BID, toPair(o.getInstrumentId()))
.id(o.getOrderId())
.limitPrice(o.getPrice())
.originalAmount(o.getSize())
.timestamp(o.getCreatedAt())
.build();
}
public static FundingRecord adaptFundingRecord(OkexWithdrawalRecord r) {
return new FundingRecord.Builder()
.setAddress(r.getTo())
.setAmount(r.getAmount())
.setCurrency(Currency.getInstance(r.getCurrency()))
.setDate(r.getTimestamp())
.setInternalId(r.getWithdrawalId())
.setStatus(convertWithdrawalStatus(r.getStatus()))
.setBlockchainTransactionHash(r.getTxid())
.setType(Type.WITHDRAWAL)
.build();
}
/**
* -3:pending cancel; -2: cancelled; -1: failed; 0 :pending; 1 :sending; 2:sent; 3 :email
* confirmation; 4 :manual confirmation; 5:awaiting identity confirmation
*/
private static Status convertWithdrawalStatus(String status) {
switch (status) {
case "-3":
case "-2":
return Status.CANCELLED;
case "-1":
return Status.FAILED;
case "0":
case "1":
case "3":
case "4":
case "5":
return Status.PROCESSING;
case "2":
return Status.COMPLETE;
default:
throw new ExchangeException("Unknown withdrawal status: " + status);
}
}
public static FundingRecord adaptFundingRecord(OkexDepositRecord r) {
return new FundingRecord.Builder()
.setAddress(r.getTo())
.setAmount(r.getAmount())
.setCurrency(Currency.getInstance(r.getCurrency()))
.setDate(r.getTimestamp())
.setStatus(convertDepositStatus(r.getStatus()))
.setBlockchainTransactionHash(r.getTxid())
.setType(Type.DEPOSIT)
.build();
}
/**
* The status of deposits (0: waiting for confirmation; 1: confirmation account; 2: recharge
* success);
*/
private static Status convertDepositStatus(String status) {<FILL_FUNCTION_BODY>}
public static OrderBook convertOrderBook(OkexOrderBook book, CurrencyPair currencyPair) {
List<LimitOrder> asks = toLimitOrderList(book.getAsks(), OrderType.ASK, currencyPair);
List<LimitOrder> bids = toLimitOrderList(book.getBids(), OrderType.BID, currencyPair);
return new OrderBook(null, asks, bids);
}
private static List<LimitOrder> toLimitOrderList(
OkexOrderBookEntry[] levels, OrderType orderType, CurrencyPair currencyPair) {
List<LimitOrder> allLevels = new ArrayList<>();
if (levels != null) {
for (int i = 0; i < levels.length; i++) {
OkexOrderBookEntry ask = levels[i];
allLevels.add(
new LimitOrder(orderType, ask.getVolume(), currencyPair, "0", null, ask.getPrice()));
}
}
return allLevels;
}
}
|
switch (status) {
case "0":
case "1":
case "6":
return Status.PROCESSING;
case "2":
return Status.COMPLETE;
default:
throw new ExchangeException("Unknown deposit status: " + status);
}
| 1,584
| 73
| 1,657
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/OkexDigestV3.java
|
OkexDigestV3
|
digestParams
|
class OkexDigestV3 extends BaseParamsDigest {
private static final String UTF_8 = "UTF-8";
public OkexDigestV3(String secretKey) {
super(secretKey, HMAC_SHA_256);
}
@Override
public String digestParams(RestInvocation ri) {<FILL_FUNCTION_BODY>}
}
|
String timestamp = ri.getHttpHeadersFromParams().get(OkexV3.OK_ACCESS_TIMESTAMP);
String toSign =
timestamp
+ ri.getHttpMethod()
+ ri.getPath()
+ (ri.getQueryString() != null && !ri.getQueryString().isEmpty()
? "?" + ri.getQueryString()
: "")
+ (ri.getRequestBody() == null ? "" : ri.getRequestBody());
byte[] signSHA256;
try {
signSHA256 = getMac().doFinal(toSign.getBytes(UTF_8));
} catch (IllegalStateException | UnsupportedEncodingException e) {
throw new ExchangeException("Could not sign the request", e);
}
return Base64.getEncoder().encodeToString(signSHA256);
| 101
| 216
| 317
|
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/dto/marketdata/OkCoinDepth.java
|
OkCoinDepth
|
toString
|
class OkCoinDepth {
private final BigDecimal[][] asks;
private final BigDecimal[][] bids;
private final Date timestamp;
public OkCoinDepth(
@JsonProperty("asks") final BigDecimal[][] asks,
@JsonProperty("bids") final BigDecimal[][] bids,
@JsonProperty(required = false, value = "timestamp") Date timestamp) {
this.asks = asks;
this.bids = bids;
this.timestamp = timestamp;
}
public BigDecimal[][] getAsks() {
return asks;
}
public BigDecimal[][] getBids() {
return bids;
}
public Date getTimestamp() {
return timestamp;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OkCoinDepth [asks=" + Arrays.toString(asks) + ", bids=" + Arrays.toString(bids) + "]";
| 221
| 43
| 264
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/dto/marketdata/OkCoinTicker.java
|
OkCoinTicker
|
toString
|
class OkCoinTicker {
private final BigDecimal high;
private final BigDecimal low;
private final BigDecimal buy;
private final BigDecimal sell;
private final BigDecimal last;
private final BigDecimal vol;
private final Long contractId;
private final BigDecimal unitAmount;
public OkCoinTicker(
@JsonProperty("high") final BigDecimal high,
@JsonProperty("low") final BigDecimal low,
@JsonProperty("buy") final BigDecimal buy,
@JsonProperty("sell") final BigDecimal sell,
@JsonProperty("last") final BigDecimal last,
@JsonProperty("vol") final BigDecimal vol,
@JsonProperty("contract_id") final Long contractId,
@JsonProperty("unit_amount") final BigDecimal unitAmount) {
this.high = high;
this.low = low;
this.buy = buy;
this.sell = sell;
this.last = last;
this.vol = vol;
this.contractId = contractId;
this.unitAmount = unitAmount;
}
/**
* @return the high
*/
public BigDecimal getHigh() {
return high;
}
/**
* @return the low
*/
public BigDecimal getLow() {
return low;
}
/**
* @return the buy
*/
public BigDecimal getBuy() {
return buy;
}
/**
* @return the sell
*/
public BigDecimal getSell() {
return sell;
}
/**
* @return the last
*/
public BigDecimal getLast() {
return last;
}
/**
* @return the vol
*/
public BigDecimal getVol() {
return vol;
}
public Long getContractId() {
return contractId;
}
public BigDecimal getUnitAmount() {
return unitAmount;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OkCoinTicker{"
+ "high="
+ high
+ ", low="
+ low
+ ", buy="
+ buy
+ ", sell="
+ sell
+ ", last="
+ last
+ ", vol="
+ vol
+ ", contractId="
+ contractId
+ ", unitAmount="
+ unitAmount
+ '}';
| 552
| 111
| 663
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/dto/trade/OkCoinFutureExplosiveDataInfo.java
|
OkCoinFutureExplosiveDataInfo
|
toString
|
class OkCoinFutureExplosiveDataInfo {
private final Integer amount;
private final String createDate;
private final BigDecimal loss;
private final BigDecimal price;
private final Integer type;
public OkCoinFutureExplosiveDataInfo(
@JsonProperty("amount") final Integer amount,
@JsonProperty("create_date") final String createDate,
@JsonProperty("loss") final BigDecimal loss,
@JsonProperty("price") final BigDecimal price,
@JsonProperty("type") final Integer type) {
this.amount = amount;
this.createDate = createDate;
this.loss = loss;
this.price = price;
this.type = type;
}
public Integer getAmount() {
return amount;
}
public String getCreateDate() {
return createDate;
}
public BigDecimal getLoss() {
return loss;
}
public BigDecimal getPrice() {
return price;
}
public Integer getType() {
return type;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OkCoinFutureExplosiveDataInfo{"
+ "amount="
+ amount
+ ", createDate='"
+ createDate
+ '\''
+ ", loss="
+ loss
+ ", price="
+ price
+ ", type="
+ type
+ '}';
| 298
| 85
| 383
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OKCoinBaseTradeService.java
|
OKCoinBaseTradeService
|
returnOrThrow
|
class OKCoinBaseTradeService extends OkCoinBaseService {
protected final OkCoin okCoin;
protected final String apikey;
protected final String secretKey;
/**
* Constructor
*
* @param exchange
*/
protected OKCoinBaseTradeService(Exchange exchange) {
super(exchange);
okCoin =
ExchangeRestProxyBuilder.forInterface(OkCoin.class, exchange.getExchangeSpecification())
.build();
apikey = exchange.getExchangeSpecification().getApiKey();
secretKey = exchange.getExchangeSpecification().getSecretKey();
}
protected OkCoinDigest signatureCreator() {
return new OkCoinDigest(apikey, secretKey);
}
protected static <T extends OkCoinErrorResult> T returnOrThrow(T t) {<FILL_FUNCTION_BODY>}
}
|
if (t.isResult()) {
return t;
} else {
throw new ExchangeException(OkCoinUtils.getErrorMessage(t.getErrorCode()));
}
| 232
| 49
| 281
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>protected final non-sealed boolean useIntl
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinFuturesMarketDataService.java
|
OkCoinFuturesMarketDataService
|
getTicker
|
class OkCoinFuturesMarketDataService extends OkCoinMarketDataServiceRaw
implements MarketDataService {
/** Default contract to use */
private final FuturesContract futuresContract;
/**
* Constructor
*
* @param exchange
*/
public OkCoinFuturesMarketDataService(Exchange exchange, FuturesContract futuresContract) {
super(exchange);
this.futuresContract = futuresContract;
}
@Override
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
if (args != null && args.length > 0) {
return OkCoinAdapters.adaptOrderBook(
getFuturesDepth(currencyPair, (FuturesContract) args[0]), currencyPair);
} else {
return OkCoinAdapters.adaptOrderBook(
getFuturesDepth(currencyPair, futuresContract), currencyPair);
}
}
@Override
public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {
if (args != null && args.length > 0) {
return OkCoinAdapters.adaptTrades(
getFuturesTrades(currencyPair, (FuturesContract) args[0]), currencyPair);
} else {
return OkCoinAdapters.adaptTrades(
getFuturesTrades(currencyPair, futuresContract), currencyPair);
}
}
}
|
if (args != null && args.length > 0) {
return OkCoinAdapters.adaptTicker(
getFuturesTicker(currencyPair, (FuturesContract) args[0]), currencyPair);
} else {
return OkCoinAdapters.adaptTicker(
getFuturesTicker(currencyPair, futuresContract), currencyPair);
}
| 404
| 97
| 501
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getDepth(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getDepth(org.knowm.xchange.currency.CurrencyPair, java.lang.Integer) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getExchangRate_US_CH() throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFutureEstimatedPrice(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureHoldAmount[] getFutureHoldAmount(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Integer, java.lang.Long) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Integer) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturePriceLimit(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getFuturesDepth(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturesIndex(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturesIndex(java.lang.String) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTickerResponse getFuturesTicker(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getFuturesTrades(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Integer) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Long) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Integer, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTickerResponse getTicker(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getTrades(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getTrades(org.knowm.xchange.currency.CurrencyPair, java.lang.Long) throws java.io.IOException<variables>private final non-sealed org.knowm.xchange.okcoin.OkCoin okCoin
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/service/OkCoinMarketDataService.java
|
OkCoinMarketDataService
|
getTrades
|
class OkCoinMarketDataService extends OkCoinMarketDataServiceRaw
implements MarketDataService {
/**
* Constructor
*
* @param exchange
*/
public OkCoinMarketDataService(Exchange exchange) {
super(exchange);
}
@Override
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {
return OkCoinAdapters.adaptTicker(getTicker(currencyPair), currencyPair);
}
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
return OkCoinAdapters.adaptOrderBook(getDepth(currencyPair), currencyPair);
}
@Override
public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
final OkCoinTrade[] trades;
if (args == null || args.length == 0) {
trades = getTrades(currencyPair);
} else {
trades = getTrades(currencyPair, (Long) args[0]);
}
return OkCoinAdapters.adaptTrades(trades, currencyPair);
| 221
| 87
| 308
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getDepth(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getDepth(org.knowm.xchange.currency.CurrencyPair, java.lang.Integer) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getExchangRate_US_CH() throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFutureEstimatedPrice(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureHoldAmount[] getFutureHoldAmount(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Integer, java.lang.Long) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Integer) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureKline> getFutureKline(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, org.knowm.xchange.okcoin.FuturesContract, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturePriceLimit(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinDepth getFuturesDepth(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturesIndex(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinFutureComment getFuturesIndex(java.lang.String) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTickerResponse getFuturesTicker(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getFuturesTrades(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.FuturesContract) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Integer) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Long) throws java.io.IOException,public List<org.knowm.xchange.okcoin.dto.marketdata.OkCoinKline> getKlines(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.okcoin.dto.marketdata.OkCoinKlineType, java.lang.Integer, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTickerResponse getTicker(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getTrades(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.okcoin.dto.marketdata.OkCoinTrade[] getTrades(org.knowm.xchange.currency.CurrencyPair, java.lang.Long) throws java.io.IOException<variables>private final non-sealed org.knowm.xchange.okcoin.OkCoin okCoin
|
knowm_XChange
|
XChange/xchange-okcoin/src/main/java/org/knowm/xchange/okcoin/v3/service/OkexMarketDataService.java
|
OkexMarketDataService
|
getOrderBook
|
class OkexMarketDataService extends OkexMarketDataServiceRaw implements MarketDataService {
public OkexMarketDataService(OkexExchangeV3 exchange) {
super(exchange);
}
@Override
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {
OkexSpotTicker tokenPairInformation =
okex.getSpotTicker(OkexAdaptersV3.toSpotInstrument(currencyPair));
return OkexAdaptersV3.convert(tokenPairInformation);
}
@Override
public List<Ticker> getTickers(Params params) throws IOException {
return okex.getAllSpotTickers().stream()
.map(OkexAdaptersV3::convert)
.collect(Collectors.toList());
}
@Override
public OrderBook getOrderBook(CurrencyPair pair, Object... args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int limitDepth = 50;
if (args != null && args.length == 1) {
Object arg0 = args[0];
if (!(arg0 instanceof Integer)) {
throw new IllegalArgumentException("Argument 0 must be an Integer!");
} else {
limitDepth = (Integer) arg0;
}
}
OkexOrderBook okexOrderbook =
okex.getOrderBook(OkexAdaptersV3.toSpotInstrument(pair), limitDepth);
return OkexAdaptersV3.convertOrderBook(okexOrderbook, pair);
| 257
| 155
| 412
|
<methods>public void <init>(org.knowm.xchange.okcoin.OkexExchangeV3) ,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexFutureInstrument> getAllFutureInstruments() throws java.io.IOException,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexFutureTicker> getAllFutureTickers() throws java.io.IOException,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSpotInstrument> getAllSpotInstruments() throws java.io.IOException,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSpotTicker> getAllSpotTickers() throws java.io.IOException,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSwapInstrument> getAllSwapInstruments() throws java.io.IOException,public List<org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSwapTicker> getAllSwapTickers() throws java.io.IOException,public org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSpotTicker getSpotTicker(java.lang.String) throws java.io.IOException<variables>
|
knowm_XChange
|
XChange/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/OkexResponse.java
|
OkexResponse
|
toString
|
class OkexResponse<V> {
private final String code;
private final String msg;
private final V data;
public OkexResponse(
@JsonProperty("code") String code,
@JsonProperty("msg") String msg,
@JsonProperty("data") V data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public boolean isSuccess() {
return "0".equals(code);
}
public V getData() {
return data;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OkexResponse{" + "code=" + code + ", msg=" + msg + '}';
| 202
| 30
| 232
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okex/src/main/java/org/knowm/xchange/okex/dto/marketdata/OkexPublicOrder.java
|
OkexPublicOrder
|
toString
|
class OkexPublicOrder {
private final BigDecimal price;
private final BigDecimal volume;
private final Integer liquidatedOrders;
private final Integer activeOrders;
public OkexPublicOrder(
BigDecimal price, BigDecimal volume, Integer liquidatedOrders, Integer activeOrders) {
this.price = price;
this.volume = volume;
this.liquidatedOrders = liquidatedOrders;
this.activeOrders = activeOrders;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getVolume() {
return volume;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
static class OkexOrderDeserializer extends JsonDeserializer<OkexPublicOrder> {
@Override
public OkexPublicOrder deserialize(JsonParser jsonParser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node.isArray()) {
BigDecimal price = new BigDecimal(node.path(0).asText());
BigDecimal volume = new BigDecimal(node.path(1).asText());
Integer liquidatedOrders = new Integer(node.path(2).asText());
Integer activeOrders = new Integer(node.path(3).asText());
return new OkexPublicOrder(price, volume, liquidatedOrders, activeOrders);
}
return null;
}
}
}
|
return "OkexPublicOrder{"
+ "price="
+ price
+ ", volume="
+ volume
+ ", liquidatedOrders="
+ liquidatedOrders
+ ", activeOrders="
+ activeOrders
+ '}';
| 418
| 73
| 491
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-okex/src/main/java/org/knowm/xchange/okex/service/OkexAccountService.java
|
OkexAccountService
|
getAccountInfo
|
class OkexAccountService extends OkexAccountServiceRaw implements AccountService {
public OkexAccountService(OkexExchange exchange, ResilienceRegistries resilienceRegistries) {
super(exchange, resilienceRegistries);
}
public AccountInfo getAccountInfo() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String withdrawFunds(WithdrawFundsParams params) throws IOException {
if (params instanceof DefaultWithdrawFundsParams) {
DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params;
String address =
defaultParams.getAddressTag() != null
? defaultParams.getAddress() + ":" + defaultParams.getAddressTag()
: defaultParams.getAddress();
OkexResponse<List<OkexWithdrawalResponse>> okexResponse =
assetWithdrawal(
defaultParams.getCurrency().getCurrencyCode(),
defaultParams.getAmount().toPlainString(),
ON_CHAIN_METHOD,
address,
defaultParams.getCommission() != null
? defaultParams.getCommission().toPlainString()
: null,
null,
null);
if (!okexResponse.isSuccess())
throw new OkexException(okexResponse.getMsg(), Integer.parseInt(okexResponse.getCode()));
return okexResponse.getData().get(0).getWithdrawalId();
}
throw new IllegalStateException("Don't know how to withdraw: " + params);
}
}
|
// null to get assets (with non-zero balance), remaining balance, and available amount in the
// account.
OkexResponse<List<OkexWalletBalance>> tradingBalances = getWalletBalances(null);
OkexResponse<List<OkexAssetBalance>> assetBalances = getAssetBalances(null);
OkexResponse<List<OkexAccountPositionRisk>> positionRis = getAccountPositionRisk();
return new AccountInfo(
OkexAdapters.adaptOkexBalances(tradingBalances.getData()),
OkexAdapters.adaptOkexAssetBalances(assetBalances.getData()),
OkexAdapters.adaptOkexAccountPositionRisk(positionRis.getData()));
| 398
| 195
| 593
|
<methods>public void <init>(org.knowm.xchange.okex.OkexExchange, org.knowm.xchange.client.ResilienceRegistries) ,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexWithdrawalResponse>> assetWithdrawal(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexChangeMarginResponse>> changeMargin(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, boolean, boolean) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexAccountPositionRisk>> getAccountPositionRisk() throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexAssetBalance>> getAssetBalances(List<org.knowm.xchange.currency.Currency>) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexBillDetails>> getBills(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexDepositAddress>> getDepositAddress(java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexAccountConfig>> getOkexAccountConfiguration() throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.PiggyBalance>> getPiggyBalance(java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexWalletBalance>> getSubAccountBalance(java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.subaccount.OkexSubAccountDetails>> getSubAccounts(java.lang.Boolean, java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexTradeFee>> getTradeFee(java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexWalletBalance>> getWalletBalances(List<org.knowm.xchange.currency.Currency>) throws java.io.IOException,public OkexResponse<List<org.knowm.xchange.okex.dto.account.OkexSetLeverageResponse>> setLeverage(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws java.io.IOException<variables>public static final java.lang.String INTERNAL_METHOD,public static final java.lang.String ON_CHAIN_METHOD
|
knowm_XChange
|
XChange/xchange-openexchangerates/src/main/java/org/knowm/xchange/oer/service/OERMarketDataService.java
|
OERMarketDataService
|
getTicker
|
class OERMarketDataService extends OERMarketDataServiceRaw implements MarketDataService {
/**
* Constructor
*
* @param exchange
*/
public OERMarketDataService(Exchange exchange) {
super(exchange);
}
@Override
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
throw new NotAvailableFromExchangeException();
}
@Override
public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {
throw new NotAvailableFromExchangeException();
}
}
|
OERRates rates = getOERTicker(currencyPair);
// Use reflection to get at data.
Method method = null;
try {
method = OERRates.class.getMethod("get" + currencyPair.counter.getCurrencyCode(), null);
} catch (SecurityException | NoSuchMethodException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
}
Double exchangeRate = null;
try {
exchangeRate = (Double) method.invoke(rates, null);
} catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
}
// Adapt to XChange DTOs
return OERAdapters.adaptTicker(currencyPair, exchangeRate);
| 193
| 202
| 395
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.oer.dto.marketdata.OERRates getOERTicker(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException<variables>private final non-sealed org.knowm.xchange.oer.OER openExchangeRates
|
knowm_XChange
|
XChange/xchange-openexchangerates/src/main/java/org/knowm/xchange/oer/service/OERMarketDataServiceRaw.java
|
OERMarketDataServiceRaw
|
getOERTicker
|
class OERMarketDataServiceRaw extends OERBaseService {
private final OER openExchangeRates;
/**
* Constructor
*
* @param exchange
*/
public OERMarketDataServiceRaw(Exchange exchange) {
super(exchange);
this.openExchangeRates =
ExchangeRestProxyBuilder.forInterface(OER.class, exchange.getExchangeSpecification())
.build();
}
public OERRates getOERTicker(CurrencyPair pair) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// Request data
OERTickers oERTickers =
openExchangeRates.getTickers(
exchange.getExchangeSpecification().getApiKey(),
pair.base.toString(),
pair.counter.toString());
if (oERTickers == null) {
throw new ExchangeException("Null response returned from Open Exchange Rates!");
}
return oERTickers.getRates();
| 148
| 107
| 255
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>
|
knowm_XChange
|
XChange/xchange-paribu/src/main/java/org/knowm/xchange/paribu/ParibuAdapters.java
|
ParibuAdapters
|
adaptTicker
|
class ParibuAdapters {
private ParibuAdapters() {}
/**
* Adapts a ParibuTicker to a Ticker Object
*
* @param paribuTicker The exchange specific ticker
* @param currencyPair
* @return The ticker
*/
public static Ticker adaptTicker(ParibuTicker paribuTicker, CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>}
}
|
if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) {
throw new NotAvailableFromExchangeException();
}
BTC_TL btcTL = paribuTicker.getBtcTL();
if (btcTL != null) {
BigDecimal last = btcTL.getLast();
BigDecimal lowestAsk = btcTL.getLowestAsk();
BigDecimal highestBid = btcTL.getHighestBid();
BigDecimal volume = btcTL.getVolume();
BigDecimal high24hr = btcTL.getHigh24hr();
BigDecimal low24hr = btcTL.getLow24hr();
return new Ticker.Builder()
.currencyPair(new CurrencyPair(BTC, Currency.TRY))
.last(last)
.bid(highestBid)
.ask(lowestAsk)
.high(high24hr)
.low(low24hr)
.volume(volume)
.build();
}
return null;
| 114
| 272
| 386
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paribu/src/main/java/org/knowm/xchange/paribu/dto/marketdata/BTC_TL.java
|
BTC_TL
|
toString
|
class BTC_TL {
private final BigDecimal last;
private final BigDecimal lowestAsk;
private final BigDecimal highestBid;
private final BigDecimal percentChange;
private final BigDecimal volume;
private final BigDecimal high24hr;
private final BigDecimal low24hr;
public BTC_TL(
@JsonProperty("last") BigDecimal last,
@JsonProperty("lowestAsk") BigDecimal lowestAsk,
@JsonProperty("highestBid") BigDecimal highestBid,
@JsonProperty("percentChange") BigDecimal percentChange,
@JsonProperty("volume") BigDecimal volume,
@JsonProperty("high24hr") BigDecimal high24hr,
@JsonProperty("low24hr") BigDecimal low24hr) {
this.last = last;
this.lowestAsk = lowestAsk;
this.highestBid = highestBid;
this.percentChange = percentChange;
this.volume = volume;
this.high24hr = high24hr;
this.low24hr = low24hr;
}
public BigDecimal getLast() {
return last;
}
public BigDecimal getLowestAsk() {
return lowestAsk;
}
public BigDecimal getHighestBid() {
return highestBid;
}
public BigDecimal getPercentChange() {
return percentChange;
}
public BigDecimal getVolume() {
return volume;
}
public BigDecimal getHigh24hr() {
return high24hr;
}
public BigDecimal getLow24hr() {
return low24hr;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ParibuTicker {"
+ "last="
+ last
+ ", lowestAsk="
+ lowestAsk
+ ", highestBid="
+ highestBid
+ ", percentChange="
+ percentChange
+ ", volume="
+ volume
+ ", high24hr="
+ high24hr
+ ", low24hr="
+ low24hr
+ '}';
| 476
| 117
| 593
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/dto/account/PaymiumAccountOperations.java
|
PaymiumAccountOperations
|
toString
|
class PaymiumAccountOperations {
@JsonProperty("amount")
protected Double amount;
@JsonProperty("created_at")
protected String createdAt;
@JsonProperty("created_at_int")
protected Integer createdAtInt;
@JsonProperty("currency")
protected String currency;
@JsonProperty("is_trading_account")
protected boolean isTradingAccount;
@JsonProperty("name")
protected String name;
@JsonProperty("uuid")
protected String uuid;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public Integer getCreatedAtInt() {
return createdAtInt;
}
public void setCreatedAtInt(Integer createdAtInt) {
this.createdAtInt = createdAtInt;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public boolean isTradingAccount() {
return isTradingAccount;
}
public void setTradingAccount(boolean tradingAccount) {
isTradingAccount = tradingAccount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
|
return "PaymiumAccountOperations [amount="
+ amount
+ ", createdAt= "
+ createdAt
+ ", currency="
+ currency
+ ", isTradingAccount= "
+ isTradingAccount
+ ", createdAt="
+ createdAt
+ ", currency= "
+ currency
+ ", isTradingAccount="
+ isTradingAccount
+ ", name= "
+ name
+ ", uuid="
+ uuid
+ "]";
| 474
| 133
| 607
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/dto/account/PaymiumBalance.java
|
PaymiumBalance
|
toString
|
class PaymiumBalance {
@JsonProperty("locked_btc")
private BigDecimal lockedBtc;
@JsonProperty("locked_eur")
private BigDecimal lockedEur;
@JsonProperty("balance_btc")
private BigDecimal balanceBtc;
@JsonProperty("balance_eur")
private BigDecimal balanceEur;
@JsonProperty("meta_state")
private String metaState;
@JsonProperty("name")
private String name;
@JsonProperty("locale")
private String locale;
@JsonProperty("channel_d")
private String channelId;
@JsonProperty("email")
private String email;
public BigDecimal getLockedBtc() {
return lockedBtc;
}
public void setLockedBtc(BigDecimal lockedBtc) {
this.lockedBtc = lockedBtc;
}
public BigDecimal getLockedEur() {
return lockedEur;
}
public void setLockedEur(BigDecimal lockedEur) {
this.lockedEur = lockedEur;
}
public BigDecimal getBalanceBtc() {
return balanceBtc;
}
public void setBalanceBtc(BigDecimal balanceBtc) {
this.balanceBtc = balanceBtc;
}
public BigDecimal getBalanceEur() {
return balanceEur;
}
public void setBalanceEur(BigDecimal balanceEur) {
this.balanceEur = balanceEur;
}
public String getMetaState() {
return metaState;
}
public void setMetaState(String metaState) {
this.metaState = metaState;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PaymiumBalance [lockedBtc="
+ lockedBtc
+ ", lockedEur="
+ lockedEur
+ ", balanceBtc="
+ balanceBtc
+ ", balanceEur="
+ balanceEur
+ ", metaState="
+ metaState
+ ", name="
+ name
+ ", locale="
+ locale
+ ", channelId="
+ channelId
+ ", email="
+ email
+ "]";
| 652
| 136
| 788
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/dto/account/PaymiumOrder.java
|
PaymiumOrder
|
toString
|
class PaymiumOrder {
@JsonProperty("account_operations")
private List<PaymiumAccountOperations> accountOperations;
@JsonProperty("amount")
private BigDecimal amount;
@JsonProperty("bitcoin_address")
private String bitcoinAddress;
@JsonProperty("btc_fee")
private BigDecimal btcFee;
@JsonProperty("comment")
private String comment;
@JsonProperty("created_at")
private Date createdAt;
@JsonProperty("currency")
private String currency;
@JsonProperty("currency_amount")
private BigDecimal currencyAmount;
@JsonProperty("currency_fee")
private BigDecimal currencyFee;
@JsonProperty("direction")
private String direction;
@JsonProperty("price")
private BigDecimal price;
@JsonProperty("state")
private String state;
@JsonProperty("traded_btc")
private BigDecimal tradedBtc;
@JsonProperty("traded_currency")
private BigDecimal tradedCurrency;
@JsonProperty("tx_id")
private String txid;
@JsonProperty("type")
private String type;
@JsonProperty("updated_at")
private Date updatedAt;
@JsonProperty("uuid")
private String uuid;
@Override
public String toString() {<FILL_FUNCTION_BODY>}
public List<PaymiumAccountOperations> getAccountOperations() {
return accountOperations;
}
public void setAccountOperations(List<PaymiumAccountOperations> accountOperations) {
this.accountOperations = accountOperations;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getBitcoinAddress() {
return bitcoinAddress;
}
public void setBitcoinAddress(String bitcoinAddress) {
this.bitcoinAddress = bitcoinAddress;
}
public BigDecimal getBtcFee() {
return btcFee;
}
public void setBtcFee(BigDecimal btcFee) {
this.btcFee = btcFee;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public BigDecimal getCurrencyAmount() {
return currencyAmount;
}
public void setCurrencyAmount(BigDecimal currencyAmount) {
this.currencyAmount = currencyAmount;
}
public BigDecimal getCurrencyFee() {
return currencyFee;
}
public void setCurrencyFee(BigDecimal currencyFee) {
this.currencyFee = currencyFee;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public BigDecimal getTradedBtc() {
return tradedBtc;
}
public void setTradedBtc(BigDecimal tradedBtc) {
this.tradedBtc = tradedBtc;
}
public BigDecimal getTradedCurrency() {
return tradedCurrency;
}
public void setTradedCurrency(BigDecimal tradedCurrency) {
this.tradedCurrency = tradedCurrency;
}
public String getTxid() {
return txid;
}
public void setTxid(String txid) {
this.txid = txid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
|
return "PaymiumOrder [accountOperations="
+ accountOperations
+ ", bitcoinAddress= "
+ bitcoinAddress
+ ", btcFee="
+ btcFee
+ ", comment= "
+ comment
+ ", createdAt="
+ createdAt
+ ", currency= "
+ currency
+ ", currencyAmount="
+ currencyAmount
+ ", currencyFee= "
+ currencyFee
+ ", direction="
+ direction
+ ", price= "
+ price
+ ", state="
+ state
+ ", tradedBtc= "
+ tradedBtc
+ ", tradedCurrency="
+ tradedCurrency
+ ", txid= "
+ txid
+ ", type="
+ type
+ ", updatedAt= "
+ updatedAt
+ ", uuid="
+ uuid
+ "]";
| 1,263
| 241
| 1,504
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/dto/marketdata/PaymiumTicker.java
|
PaymiumTicker
|
toString
|
class PaymiumTicker {
private final BigDecimal high;
private final BigDecimal low;
private final BigDecimal volume;
private final BigDecimal bid;
private final BigDecimal ask;
private final BigDecimal midpoint;
private final long at;
private final BigDecimal price;
private final BigDecimal vwap;
private final BigDecimal variation;
private final String currency;
/**
* Constructor
*
* @param high
* @param low
* @param volume
* @param bid
* @param ask
* @param midpoint
* @param at
* @param price
* @param vwap
* @param variation
* @param currency
*/
public PaymiumTicker(
@JsonProperty("high") BigDecimal high,
@JsonProperty("low") BigDecimal low,
@JsonProperty("volume") BigDecimal volume,
@JsonProperty("bid") BigDecimal bid,
@JsonProperty("ask") BigDecimal ask,
@JsonProperty("midpoint") BigDecimal midpoint,
@JsonProperty("at") long at,
@JsonProperty("price") BigDecimal price,
@JsonProperty("vwap") BigDecimal vwap,
@JsonProperty("variation") BigDecimal variation,
@JsonProperty("currency") String currency) {
this.high = high;
this.low = low;
this.volume = volume;
this.bid = bid;
this.ask = ask;
this.midpoint = midpoint;
this.at = at;
this.price = price;
this.vwap = vwap;
this.variation = variation;
this.currency = currency;
}
public BigDecimal getHigh() {
return high;
}
public BigDecimal getLow() {
return low;
}
public BigDecimal getVolume() {
return volume;
}
public BigDecimal getBid() {
return bid;
}
public BigDecimal getAsk() {
return ask;
}
public BigDecimal getMidpoint() {
return midpoint;
}
public long getAt() {
return at;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getVwap() {
return vwap;
}
public BigDecimal getVariation() {
return variation;
}
public String getCurrency() {
return currency;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PaymiumTicker{"
+ "high="
+ high
+ ", low="
+ low
+ ", volume="
+ volume
+ ", bid="
+ bid
+ ", ask="
+ ask
+ ", midpoint="
+ midpoint
+ ", at="
+ at
+ ", price="
+ price
+ ", vwap="
+ vwap
+ ", variation="
+ variation
+ ", currency='"
+ currency
+ '\''
+ '}';
| 700
| 152
| 852
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/service/PaymiumAccountService.java
|
PaymiumAccountService
|
getFundingHistory
|
class PaymiumAccountService extends PaymiumAccountServiceRaw implements AccountService {
/**
* Constructor
*
* @param exchange
*/
public PaymiumAccountService(Exchange exchange) {
super(exchange);
}
@Override
public TradeHistoryParams createFundingHistoryParams() {
return new PaymiumHistoryParams();
}
@Override
public AccountInfo getAccountInfo() throws IOException {
return new AccountInfo(PaymiumAdapters.adaptWallet(getPaymiumBalances()));
}
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException {<FILL_FUNCTION_BODY>}
}
|
List<FundingRecord> res = new ArrayList<>();
Long offset = null;
Integer limit = null;
if (params instanceof TradeHistoryParamOffset) {
final TradeHistoryParamOffset historyParamOffset = (TradeHistoryParamOffset) params;
offset = historyParamOffset.getOffset();
}
if (params instanceof TradeHistoryParamLimit) {
final TradeHistoryParamLimit historyParamLimit = (TradeHistoryParamLimit) params;
limit = historyParamLimit.getLimit();
}
List<PaymiumOrder> orders = getPaymiumFundingOrders(offset, limit);
for (PaymiumOrder order : orders) {
FundingRecord.Type funding = null;
switch (order.getType()) {
case "WireDeposit":
case "BitcoinDeposit":
funding = funding.DEPOSIT;
break;
case "Transfer":
funding = funding.WITHDRAWAL;
break;
}
res.add(
new FundingRecord(
order.getBitcoinAddress(),
order.getUpdatedAt(),
Currency.getInstance(order.getCurrency()),
order.getAmount(),
String.valueOf(order.getUuid()),
order.getUuid(),
funding,
FundingRecord.Status.COMPLETE,
null,
null,
null));
}
return res;
| 183
| 359
| 542
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.paymium.dto.account.PaymiumBalance getPaymiumBalances() throws java.io.IOException,public List<org.knowm.xchange.paymium.dto.account.PaymiumOrder> getPaymiumFundingOrders(java.lang.Long, java.lang.Integer) throws java.io.IOException<variables>protected org.knowm.xchange.paymium.PaymiumAuthenticated paymiumAuthenticated
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/service/PaymiumAccountServiceRaw.java
|
PaymiumAccountServiceRaw
|
getPaymiumFundingOrders
|
class PaymiumAccountServiceRaw extends PaymiumBaseService {
protected PaymiumAuthenticated paymiumAuthenticated;
/**
* Constructor
*
* @param exchange
*/
public PaymiumAccountServiceRaw(Exchange exchange) {
super(exchange);
this.paymiumAuthenticated =
ExchangeRestProxyBuilder.forInterface(
org.knowm.xchange.paymium.PaymiumAuthenticated.class,
exchange.getExchangeSpecification())
.build();
}
public PaymiumBalance getPaymiumBalances() throws IOException {
return paymiumAuthenticated.getBalance(apiKey, signatureCreator, exchange.getNonceFactory());
}
public List<PaymiumOrder> getPaymiumFundingOrders(Long offset, Integer limit) throws IOException {<FILL_FUNCTION_BODY>}
}
|
return paymiumAuthenticated.getOrders(
apiKey,
signatureCreator,
exchange.getNonceFactory(),
offset,
limit,
Arrays.asList("WireDeposit", "BitcoinDeposit", "Transfer"),
null);
| 232
| 74
| 306
|
<methods><variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.paymium.Paymium paymium,protected final non-sealed org.knowm.xchange.paymium.PaymiumAuthenticated paymiumAuthenticated,protected final non-sealed ParamsDigest signatureCreator
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/service/PaymiumDigest.java
|
PaymiumDigest
|
digestParams
|
class PaymiumDigest extends BaseParamsDigest {
/**
* Constructor
*
* @param secretKeyBase64
* @throws IllegalArgumentException if key is invalid (cannot be base-64-decoded or the decoded
* key is invalid).
*/
private PaymiumDigest(String secretKeyBase64) {
super(secretKeyBase64, HMAC_SHA_256);
}
public static PaymiumDigest createInstance(String secretKeyBase64) {
return secretKeyBase64 == null ? null : new PaymiumDigest(secretKeyBase64);
}
@Override
public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>}
}
|
String invocationUrl =
restInvocation.getParamValue(HeaderParam.class, "Api-Nonce").toString()
+ restInvocation.getInvocationUrl();
Mac mac = getMac();
mac.update(invocationUrl.getBytes());
return String.format("%064x", new BigInteger(1, mac.doFinal()));
| 195
| 89
| 284
|
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/service/PaymiumTradeService.java
|
PaymiumTradeService
|
getTradeHistory
|
class PaymiumTradeService extends PaymiumTradeServiceRaw implements TradeService {
/**
* Constructor
*
* @param exchange
*/
public PaymiumTradeService(Exchange exchange) {
super(exchange);
}
@Override
public TradeHistoryParams createTradeHistoryParams() {
return new PaymiumHistoryParams();
}
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {<FILL_FUNCTION_BODY>}
}
|
Long offset = null;
Integer limit = null;
if (params instanceof TradeHistoryParamOffset) {
final TradeHistoryParamOffset historyParamOffset = (TradeHistoryParamOffset) params;
offset = historyParamOffset.getOffset();
}
if (params instanceof TradeHistoryParamLimit) {
final TradeHistoryParamLimit historyParamLimit = (TradeHistoryParamLimit) params;
limit = historyParamLimit.getLimit();
}
List<UserTrade> userTrades = new ArrayList();
List<PaymiumOrder> orders = getPaymiumOrders(offset, limit);
for (PaymiumOrder order : orders) {
Order.OrderType orderType = null;
Currency currencyFee = null;
BigDecimal fee = null;
switch (order.getDirection()) {
case "buy":
orderType = Order.OrderType.ASK;
currencyFee = Currency.BTC;
fee = order.getBtcFee();
break;
case "sell":
orderType = Order.OrderType.BID;
currencyFee = Currency.EUR;
fee = order.getCurrencyFee();
break;
}
UserTrade userTrade =
UserTrade.builder()
.type(orderType)
.originalAmount(order.getTradedCurrency())
.currencyPair(CurrencyPair.BTC_EUR)
.price(order.getPrice())
.id(order.getUuid())
.orderId(order.getUuid())
.feeAmount(fee)
.feeCurrency(currencyFee)
.build();
userTrades.add(userTrade);
}
return new UserTrades(userTrades, Trades.TradeSortType.SortByTimestamp);
| 136
| 460
| 596
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public List<org.knowm.xchange.paymium.dto.account.PaymiumOrder> getPaymiumOrders(java.lang.Long, java.lang.Integer) throws java.io.IOException<variables>protected org.knowm.xchange.paymium.PaymiumAuthenticated paymiumAuthenticated
|
knowm_XChange
|
XChange/xchange-paymium/src/main/java/org/knowm/xchange/paymium/service/PaymiumTradeServiceRaw.java
|
PaymiumTradeServiceRaw
|
getPaymiumOrders
|
class PaymiumTradeServiceRaw extends PaymiumBaseService {
protected PaymiumAuthenticated paymiumAuthenticated;
public PaymiumTradeServiceRaw(Exchange exchange) {
super(exchange);
this.paymiumAuthenticated =
ExchangeRestProxyBuilder.forInterface(
org.knowm.xchange.paymium.PaymiumAuthenticated.class,
exchange.getExchangeSpecification())
.build();
}
public List<PaymiumOrder> getPaymiumOrders(Long offset, Integer limit) throws IOException {<FILL_FUNCTION_BODY>}
}
|
return paymiumAuthenticated.getOrders(
apiKey,
signatureCreator,
exchange.getNonceFactory(),
offset,
limit,
Arrays.asList("LimitOrder"),
null);
| 162
| 60
| 222
|
<methods><variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.paymium.Paymium paymium,protected final non-sealed org.knowm.xchange.paymium.PaymiumAuthenticated paymiumAuthenticated,protected final non-sealed ParamsDigest signatureCreator
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/PoloniexExchange.java
|
PoloniexExchange
|
remoteInit
|
class PoloniexExchange extends BaseExchange implements Exchange {
private final SynchronizedValueFactory<Long> nonceFactory =
new TimestampIncrementingNonceFactory();
@Override
protected void initServices() {
this.marketDataService = new PoloniexMarketDataService(this);
this.accountService = new PoloniexAccountService(this);
this.tradeService =
new PoloniexTradeService(this, (PoloniexMarketDataService) marketDataService);
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass());
exchangeSpecification.setSslUri("https://poloniex.com/");
exchangeSpecification.setHost("poloniex.com");
exchangeSpecification.setPort(80);
exchangeSpecification.setExchangeName("Poloniex");
exchangeSpecification.setExchangeDescription("Poloniex is a bitcoin and altcoin exchange.");
return exchangeSpecification;
}
@Override
public SynchronizedValueFactory<Long> getNonceFactory() {
return nonceFactory;
}
@Override
public void remoteInit() throws IOException {<FILL_FUNCTION_BODY>}
}
|
PoloniexMarketDataServiceRaw poloniexMarketDataServiceRaw =
(PoloniexMarketDataServiceRaw) marketDataService;
Map<String, PoloniexCurrencyInfo> poloniexCurrencyInfoMap =
poloniexMarketDataServiceRaw.getPoloniexCurrencyInfo();
Map<String, PoloniexMarketData> poloniexMarketDataMap =
poloniexMarketDataServiceRaw.getAllPoloniexTickers();
exchangeMetaData =
PoloniexAdapters.adaptToExchangeMetaData(
poloniexCurrencyInfoMap, poloniexMarketDataMap, exchangeMetaData);
| 334
| 180
| 514
|
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/PoloniexUtils.java
|
PoloniexUtils
|
stringToDate
|
class PoloniexUtils {
public static String toPairString(CurrencyPair currencyPair) {
return currencyPair.counter.getCurrencyCode().toUpperCase()
+ "_"
+ currencyPair.base.getCurrencyCode().toUpperCase();
}
public static CurrencyPair toCurrencyPair(String pair) {
String[] currencies = pair.split("_");
return new CurrencyPair(currencies[1], currencies[0]);
}
public static Date stringToDate(String dateString) {<FILL_FUNCTION_BODY>}
public static class TimestampDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
final String millis = p.getText();
try {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(Long.parseLong(millis));
return calendar.getTime();
} catch (Exception e) {
return new Date(0);
}
}
}
}
|
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.parse(dateString);
} catch (ParseException e) {
return new Date(0);
}
| 286
| 85
| 371
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/account/PoloniexBalance.java
|
PoloniexBalance
|
toString
|
class PoloniexBalance {
@JsonProperty("available")
private BigDecimal available;
@JsonProperty("onOrders")
private BigDecimal onOrders;
@JsonProperty("btcValue")
private BigDecimal btcValue;
@JsonProperty("available")
public BigDecimal getAvailable() {
return available;
}
@JsonProperty("available")
public void setAvailable(BigDecimal available) {
this.available = available;
}
@JsonProperty("onOrders")
public BigDecimal getOnOrders() {
return onOrders;
}
@JsonProperty("onOrders")
public void setOnOrders(BigDecimal onOrders) {
this.onOrders = onOrders;
}
@JsonProperty("btcValue")
public BigDecimal getBtcValue() {
return btcValue;
}
@JsonProperty("btcValue")
public void setBtcValue(BigDecimal btcValue) {
this.btcValue = btcValue;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexBalance["
+ "available="
+ available
+ ", onOrders="
+ onOrders
+ ", btcValue="
+ btcValue
+ ']';
| 306
| 61
| 367
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/trade/PoloniexAdjustment.java
|
PoloniexAdjustment
|
toString
|
class PoloniexAdjustment {
private final String currency;
private final BigDecimal amount;
private final Date timestamp;
private final String status;
private final String category;
private final String reason;
private final String adjustmentTitle;
private final String adjustmentShortTitle;
private final String adjustmentDesc;
private final String adjustmentShortDesc;
private final String adjustmentHelp;
public PoloniexAdjustment(
@JsonProperty("currency") String currency,
@JsonProperty("amount") BigDecimal amount,
@JsonProperty("timestamp") long timestamp,
@JsonProperty("status") String status,
@JsonProperty("category") String category,
@JsonProperty("reason") String reason,
@JsonProperty("adjustmentTitle") String adjustmentTitle,
@JsonProperty("adjustmentShortTitle") String adjustmentShortTitle,
@JsonProperty("adjustmentDesc") String adjustmentDesc,
@JsonProperty("adjustmentShortDesc") String adjustmentShortDesc,
@JsonProperty("adjustmentHelp") String adjustmentHelp) {
super();
this.currency = currency;
this.amount = amount;
this.timestamp = new Date(timestamp * 1000);
this.status = status;
this.category = category;
this.reason = reason;
this.adjustmentTitle = adjustmentTitle;
this.adjustmentShortTitle = adjustmentShortTitle;
this.adjustmentDesc = adjustmentDesc;
this.adjustmentShortDesc = adjustmentShortDesc;
this.adjustmentHelp = adjustmentHelp;
}
public String getCurrency() {
return currency;
}
public BigDecimal getAmount() {
return amount;
}
public Date getTimestamp() {
return timestamp;
}
public String getStatus() {
return status;
}
public String getCategory() {
return category;
}
public String getReason() {
return reason;
}
public String getAdjustmentTitle() {
return adjustmentTitle;
}
public String getAdjustmentShortTitle() {
return adjustmentShortTitle;
}
public String getAdjustmentDesc() {
return adjustmentDesc;
}
public String getAdjustmentShortDesc() {
return adjustmentShortDesc;
}
public String getAdjustmentHelp() {
return adjustmentHelp;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexAdjustment{"
+ "currency='"
+ currency
+ '\''
+ ", amount="
+ amount
+ ", timestamp="
+ timestamp
+ ", status='"
+ status
+ '\''
+ ", category='"
+ category
+ '\''
+ ", reason='"
+ reason
+ '\''
+ ", adjustmentTitle='"
+ adjustmentTitle
+ '\''
+ ", adjustmentShortTitle='"
+ adjustmentShortTitle
+ '\''
+ ", adjustmentDesc='"
+ adjustmentDesc
+ '\''
+ ", adjustmentShortDesc='"
+ adjustmentShortDesc
+ '\''
+ ", adjustmentHelp='"
+ adjustmentHelp
+ '\''
+ '}';
| 626
| 201
| 827
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/trade/PoloniexDeposit.java
|
PoloniexDeposit
|
toString
|
class PoloniexDeposit {
private final String currency;
private final String address;
private final BigDecimal amount;
private final int confirmations;
private final String txid;
private final Date timestamp;
private final String status;
private final long depositNumber;
private final String category;
public PoloniexDeposit(
@JsonProperty("currency") String currency,
@JsonProperty("address") String address,
@JsonProperty("amount") BigDecimal amount,
@JsonProperty("confirmations") int confirmations,
@JsonProperty("txid") String txid,
@JsonProperty("timestamp") long timestamp,
@JsonProperty("status") String status,
@JsonProperty("depositNumber") long depositNumber,
@JsonProperty("category") String category) {
super();
this.currency = currency;
this.address = address;
this.amount = amount;
this.confirmations = confirmations;
this.txid = txid;
this.timestamp = new Date(timestamp * 1000);
this.status = status;
this.depositNumber = depositNumber;
this.category = category;
}
public String getCurrency() {
return currency;
}
public String getAddress() {
return address;
}
public BigDecimal getAmount() {
return amount;
}
public int getConfirmations() {
return confirmations;
}
public String getTxid() {
return txid;
}
public Date getTimestamp() {
return timestamp;
}
public String getStatus() {
return status;
}
public long getDepositNumber() {
return depositNumber;
}
public String getCategory() {
return category;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexDeposit [currency="
+ currency
+ ", address="
+ address
+ ", amount="
+ amount
+ ", confirmations="
+ confirmations
+ ", txid="
+ txid
+ ", timestamp="
+ timestamp
+ ", status="
+ status
+ ", depositNumber="
+ depositNumber
+ ", category="
+ category
+ "]";
| 491
| 122
| 613
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/trade/PoloniexMarginPostionResponse.java
|
PoloniexMarginPostionResponse
|
toString
|
class PoloniexMarginPostionResponse {
@JsonProperty("amount")
private BigDecimal amount;
@JsonProperty("total")
private BigDecimal total;
@JsonProperty("basePrice")
private BigDecimal basePrice;
@JsonProperty("liquidationPrice")
private BigDecimal liquidationPrice;
@JsonProperty("pl")
private BigDecimal pl;
@JsonProperty("lendingFees")
private BigDecimal lendingFees;
@JsonProperty("type")
private String type;
@JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getTotal() {
return total;
}
public BigDecimal getBasePrice() {
return basePrice;
}
public BigDecimal getLiquidationPrice() {
return liquidationPrice;
}
public BigDecimal getPl() {
return pl;
}
public BigDecimal getLendingFees() {
return lendingFees;
}
public String getType() {
return type;
}
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexMarginPostionResponse{"
+ "amount="
+ amount
+ ", total="
+ total
+ ", basePrice="
+ basePrice
+ ", liquidationPrice="
+ liquidationPrice
+ ", pl="
+ pl
+ ", lendingFees="
+ lendingFees
+ ", type='"
+ type
+ '\''
+ '}';
| 363
| 117
| 480
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/trade/PoloniexUserTrade.java
|
PoloniexUserTrade
|
toString
|
class PoloniexUserTrade {
@JsonProperty("globalTradeID")
private String globalTradeID;
@JsonProperty("tradeID")
private String tradeID;
@JsonProperty("date")
private String date;
@JsonProperty("rate")
private BigDecimal rate;
@JsonProperty("amount")
private BigDecimal amount;
@JsonProperty("total")
private BigDecimal total;
@JsonProperty("fee")
private BigDecimal fee;
@JsonProperty("orderNumber")
private String orderNumber;
@JsonProperty("type")
private String type;
@JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("globalTradeID")
public String getGlobalTradeID() {
return globalTradeID;
}
@JsonProperty("globalTradeID")
public void setGlobalTradeID(String globalTradeID) {
this.globalTradeID = globalTradeID;
}
@JsonProperty("tradeID")
public String getTradeID() {
return tradeID;
}
@JsonProperty("tradeID")
public void setTradeID(String tradeID) {
this.tradeID = tradeID;
}
@JsonProperty("date")
public String getDate() {
return date;
}
@JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
@JsonProperty("rate")
public BigDecimal getRate() {
return rate;
}
@JsonProperty("rate")
public void setRate(BigDecimal rate) {
this.rate = rate;
}
@JsonProperty("amount")
public BigDecimal getAmount() {
return amount;
}
@JsonProperty("amount")
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
@JsonProperty("total")
public BigDecimal getTotal() {
return total;
}
@JsonProperty("total")
public void setTotal(BigDecimal total) {
this.total = total;
}
@JsonProperty("fee")
public BigDecimal getFee() {
return fee;
}
@JsonProperty("fee")
public void setFee(BigDecimal fee) {
this.fee = fee;
}
@JsonProperty("orderNumber")
public String getOrderNumber() {
return orderNumber;
}
@JsonProperty("orderNumber")
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
@JsonProperty("type")
public String getType() {
return type;
}
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexUserTrade [globalTradeID="
+ globalTradeID
+ ", tradeID= "
+ tradeID
+ ", date="
+ date
+ ", rate="
+ rate
+ ", amount="
+ amount
+ ", total="
+ total
+ ", fee="
+ fee
+ ", orderNumber="
+ orderNumber
+ ", type="
+ type
+ ", additionalProperties="
+ additionalProperties
+ "]";
| 881
| 139
| 1,020
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/dto/trade/PoloniexWithdrawal.java
|
PoloniexWithdrawal
|
toString
|
class PoloniexWithdrawal {
private final long withdrawalNumber;
private final String currency;
private final String address;
private final BigDecimal amount;
private final BigDecimal fee;
private final Date timestamp;
private final String status;
private final String ipAddress;
private final String paymentID;
public PoloniexWithdrawal(
@JsonProperty("withdrawalNumber") long withdrawalNumber,
@JsonProperty("currency") String currency,
@JsonProperty("address") String address,
@JsonProperty("amount") BigDecimal amount,
@JsonProperty("fee") BigDecimal fee,
@JsonProperty("timestamp") long timestamp,
@JsonProperty("status") String status,
@JsonProperty("ipAddress") String ipAddress,
@JsonProperty("paymentID") String paymentID) {
super();
this.withdrawalNumber = withdrawalNumber;
this.currency = currency;
this.address = address;
this.amount = amount;
this.fee = fee;
this.timestamp = new Date(timestamp * 1000);
this.status = status;
this.ipAddress = ipAddress;
this.paymentID = paymentID;
}
public long getWithdrawalNumber() {
return withdrawalNumber;
}
public String getCurrency() {
return currency;
}
public String getAddress() {
return address;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getFee() {
return fee;
}
public Date getTimestamp() {
return timestamp;
}
public String getStatus() {
return status;
}
public String getIpAddress() {
return ipAddress;
}
public String getPaymentID() {
return paymentID;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "PoloniexWithdrawal [withdrawalNumber="
+ withdrawalNumber
+ ", currency="
+ currency
+ ", address="
+ address
+ ", amount="
+ amount
+ ", fee="
+ fee
+ ", timestamp="
+ timestamp
+ ", status="
+ status
+ ", ipAddress="
+ ipAddress
+ ", paymentID="
+ paymentID
+ "]";
| 505
| 125
| 630
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/service/PoloniexAccountServiceRaw.java
|
PoloniexAccountServiceRaw
|
getDepositAddresses
|
class PoloniexAccountServiceRaw extends PoloniexBaseService {
/**
* Constructor
*
* @param exchange
*/
public PoloniexAccountServiceRaw(Exchange exchange) {
super(exchange);
}
public HashMap<String, PoloniexBalance> getExchangeWallet() throws IOException {
return poloniexAuthenticated.returnCompleteBalances(
apiKey, signatureCreator, exchange.getNonceFactory(), null);
}
public HashMap<String, PoloniexBalance> getWallets() throws IOException {
// using account="all" for margin + lending balances
return poloniexAuthenticated.returnCompleteBalances(
apiKey, signatureCreator, exchange.getNonceFactory(), "all");
}
public HashMap<String, PoloniexLoan[]> getLoanInfo() throws IOException {
return poloniexAuthenticated.returnActiveLoans(
apiKey, signatureCreator, exchange.getNonceFactory());
}
public HashMap<String, String> getDepositAddresses() throws IOException {<FILL_FUNCTION_BODY>}
public String getDepositAddress(String currency) throws IOException {
HashMap<String, String> response =
poloniexAuthenticated.returnDepositAddresses(
apiKey, signatureCreator, exchange.getNonceFactory());
if (response.containsKey("error")) {
throw new PoloniexException(response.get("error"));
}
if (response.containsKey(currency)) {
return response.get(currency);
} else {
PoloniexGenerateNewAddressResponse newAddressResponse =
poloniexAuthenticated.generateNewAddress(
apiKey, signatureCreator, exchange.getNonceFactory(), currency);
if (newAddressResponse.success()) {
return newAddressResponse.getAddress();
} else {
throw new PoloniexException("Failed to get Poloniex deposit address for " + currency);
}
}
}
/**
* @param paymentId For XMR withdrawals, you may optionally specify "paymentId".
*/
public String withdraw(
Currency currency, BigDecimal amount, String address, @Nullable String paymentId)
throws IOException {
return poloniexAuthenticated
.withdraw(
apiKey,
signatureCreator,
exchange.getNonceFactory(),
currency.getCurrencyCode(),
amount,
address,
paymentId)
.getResponse();
}
public PoloniexDepositsWithdrawalsResponse returnDepositsWithdrawals(Date start, Date end)
throws IOException {
return poloniexAuthenticated.returnDepositsWithdrawals(
apiKey,
signatureCreator,
exchange.getNonceFactory(),
DateUtils.toUnixTimeNullSafe(start),
DateUtils.toUnixTimeNullSafe(end));
}
public String transfer(
Currency currency, BigDecimal amount, PoloniexWallet fromWallet, PoloniexWallet toWallet)
throws IOException {
return poloniexAuthenticated
.transferBalance(
apiKey,
signatureCreator,
exchange.getNonceFactory(),
currency.getCurrencyCode(),
amount,
fromWallet.name().toLowerCase(),
toWallet.name().toLowerCase())
.getMessage();
}
}
|
HashMap<String, String> response =
poloniexAuthenticated.returnDepositAddresses(
apiKey, signatureCreator, exchange.getNonceFactory());
if (response.containsKey("error")) {
throw new PoloniexException(response.get("error"));
} else {
return response;
}
| 876
| 88
| 964
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed org.knowm.xchange.poloniex.Poloniex poloniex,protected final non-sealed org.knowm.xchange.poloniex.PoloniexAuthenticated poloniexAuthenticated,protected final non-sealed ParamsDigest signatureCreator
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/account/BitcoinAccount.java
|
BitcoinAccount
|
toString
|
class BitcoinAccount {
private final Integer id;
private final BigDecimal balance;
private final String address;
private final String currency;
private final String currencySymbol;
private final String pusherChannel;
private final BigDecimal btcMinimumWithdraw;
private final BigDecimal lowestOfferInterestRate;
private final BigDecimal highestOfferInterestRate;
private final BigDecimal freeBalance;
/**
* Constructor
*
* @param id
* @param balance
* @param address
* @param currency
* @param currencySymbol
* @param pusherChannel
* @param btcMinimumWithdraw
* @param lowestOfferInterestRate
* @param highestOfferInterestRate
* @param freeBalance
*/
public BitcoinAccount(
@JsonProperty("id") Integer id,
@JsonProperty("balance") BigDecimal balance,
@JsonProperty("address") String address,
@JsonProperty("currency") String currency,
@JsonProperty("currency_symbol") String currencySymbol,
@JsonProperty("pusher_channel") String pusherChannel,
@JsonProperty("btc_minimum_withdraw") BigDecimal btcMinimumWithdraw,
@JsonProperty("lowest_offer_interest_rate") BigDecimal lowestOfferInterestRate,
@JsonProperty("highest_offer_interest_rate") BigDecimal highestOfferInterestRate,
@JsonProperty("free_balance") BigDecimal freeBalance) {
this.id = id;
this.balance = balance;
this.address = address;
this.currency = currency;
this.currencySymbol = currencySymbol;
this.pusherChannel = pusherChannel;
this.btcMinimumWithdraw = btcMinimumWithdraw;
this.lowestOfferInterestRate = lowestOfferInterestRate;
this.highestOfferInterestRate = highestOfferInterestRate;
this.freeBalance = freeBalance;
}
public Integer getId() {
return id;
}
public BigDecimal getBalance() {
return balance;
}
public String getAddress() {
return address;
}
public String getCurrency() {
return currency;
}
public String getCurrencySymbol() {
return currencySymbol;
}
public String getPusherChannel() {
return pusherChannel;
}
public BigDecimal getBtcMinimumWithdraw() {
return btcMinimumWithdraw;
}
public BigDecimal getLowestOfferInterestRate() {
return lowestOfferInterestRate;
}
public BigDecimal getHighestOfferInterestRate() {
return highestOfferInterestRate;
}
public BigDecimal getFreeBalance() {
return freeBalance;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "BitcoinAccount [id="
+ id
+ ", balance="
+ balance
+ ", address="
+ address
+ ", currency="
+ currency
+ ", currencySymbol="
+ currencySymbol
+ ", pusherChannel="
+ pusherChannel
+ ", btcMinimumWithdraw="
+ btcMinimumWithdraw
+ ", lowestOfferInterestRate="
+ lowestOfferInterestRate
+ ", highestOfferInterestRate="
+ highestOfferInterestRate
+ ", freeBalance="
+ freeBalance
+ "]";
| 741
| 159
| 900
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/marketdata/QuoineOrderBook.java
|
QuoineOrderBook
|
toString
|
class QuoineOrderBook {
private final List<BigDecimal[]> buyPriceLevels;
private final List<BigDecimal[]> sellPriceLevels;
/**
* Constructor
*
* @param buyPriceLevels
* @param sellPriceLevels
*/
public QuoineOrderBook(
@JsonProperty("buy_price_levels") List<BigDecimal[]> buyPriceLevels,
@JsonProperty("sell_price_levels") List<BigDecimal[]> sellPriceLevels) {
this.buyPriceLevels = buyPriceLevels;
this.sellPriceLevels = sellPriceLevels;
}
public List<BigDecimal[]> getBuyPriceLevels() {
return buyPriceLevels;
}
public List<BigDecimal[]> getSellPriceLevels() {
return sellPriceLevels;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "QuoineOrderBook [buyPriceLevels="
+ buyPriceLevels
+ ", sellPriceLevels="
+ sellPriceLevels
+ "]";
| 257
| 50
| 307
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/trade/QuoineExecution.java
|
QuoineExecution
|
toString
|
class QuoineExecution {
public final String id;
public final BigDecimal quantity;
public final BigDecimal price;
public final String takerSide;
public final String mySide;
public final long createdAt;
public final String pnl;
public final String orderId;
public final String target;
public QuoineExecution(
@JsonProperty("id") String id,
@JsonProperty("quantity") BigDecimal quantity,
@JsonProperty("price") BigDecimal price,
@JsonProperty("taker_side") String takerSide,
@JsonProperty("my_side") String mySide,
@JsonProperty("created_at") long createdAt,
@JsonProperty("pnl") String pnl,
@JsonProperty("order_id") String orderId,
@JsonProperty("target") String target) {
this.id = id;
this.quantity = quantity;
this.price = price;
this.takerSide = takerSide;
this.mySide = mySide;
this.createdAt = createdAt;
this.pnl = pnl;
this.orderId = orderId;
this.target = target;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "QuoineExecution{"
+ "id='"
+ id
+ '\''
+ ", quantity="
+ quantity
+ ", price="
+ price
+ ", takerSide='"
+ takerSide
+ '\''
+ ", mySide='"
+ mySide
+ '\''
+ ", createdAt="
+ createdAt
+ ", pnl='"
+ pnl
+ '\''
+ ", orderId='"
+ orderId
+ '\''
+ ", target='"
+ target
+ '\''
+ '}';
| 325
| 159
| 484
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/trade/QuoineNewOrderRequest.java
|
QuoineNewOrderRequest
|
toString
|
class QuoineNewOrderRequest {
@JsonProperty("order_type")
private final String orderType; // Values: limit, market or market_with_range
@JsonProperty("product_id")
private final int productId;
@JsonProperty("side")
private final String side; // buy or sell
@JsonProperty("quantity")
private final BigDecimal quantity; // Amount of BTC you want to trade.
@JsonProperty("price")
private final BigDecimal price; // Price of BTC you want to trade.
// @JsonProperty("price_range")
// private final boolean priceRange;
public QuoineNewOrderRequest(
String orderType, int productId, String side, BigDecimal quantity, BigDecimal price) {
this.orderType = orderType;
this.productId = productId;
this.side = side;
this.quantity = quantity;
this.price = price;
}
public String getOrderType() {
return orderType;
}
public int getProductId() {
return productId;
}
public String getSide() {
return side;
}
public BigDecimal getQuantity() {
return quantity;
}
public BigDecimal getPrice() {
return price;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "QuoineNewOrderRequest [orderType="
+ orderType
+ ", productId="
+ productId
+ ", side="
+ side
+ ", quantity="
+ quantity
+ ", price="
+ price
+ "]";
| 368
| 75
| 443
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/trade/QuoineOrderDetailsResponse.java
|
QuoineOrderDetailsResponse
|
toString
|
class QuoineOrderDetailsResponse {
private final String id;
private final String orderType;
private final BigDecimal quantity;
private final String currencyPairCode;
private final String side;
private final Integer leverageLevel;
private final String productCode;
private final BigDecimal filledQuantity;
private final BigDecimal price;
private final BigDecimal createdAt;
private final BigDecimal updatedAt;
private final String status;
private final BigDecimal orderFee;
private final Object settings;
private final Execution[] executions;
/**
* Constructor
*
* @param id
* @param orderType
* @param quantity
* @param currencyPairCode
* @param side
* @param leverageLevel
* @param productCode
* @param filledQuantity
* @param price
* @param createdAt
* @param updatedAt
* @param status
* @param orderFee
* @param settings
* @param executions
*/
public QuoineOrderDetailsResponse(
@JsonProperty("id") String id,
@JsonProperty("order_type") String orderType,
@JsonProperty("quantity") BigDecimal quantity,
@JsonProperty("currency_pair_code") String currencyPairCode,
@JsonProperty("side") String side,
@JsonProperty("leverage_level") Integer leverageLevel,
@JsonProperty("product_code") String productCode,
@JsonProperty("filled_quantity") BigDecimal filledQuantity,
@JsonProperty("price") BigDecimal price,
@JsonProperty("created_at") BigDecimal createdAt,
@JsonProperty("updated_at") BigDecimal updatedAt,
@JsonProperty("status") String status,
@JsonProperty("order_fee") BigDecimal orderFee,
@JsonProperty("settings") Object settings,
@JsonProperty("executions") Execution[] executions) {
this.id = id;
this.orderType = orderType;
this.quantity = quantity;
this.currencyPairCode = currencyPairCode;
this.side = side;
this.leverageLevel = leverageLevel;
this.productCode = productCode;
this.filledQuantity = filledQuantity;
this.price = price;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.status = status;
this.orderFee = orderFee;
this.settings = settings;
this.executions = executions;
}
public String getId() {
return id;
}
public String getOrderType() {
return orderType;
}
public BigDecimal getQuantity() {
return quantity;
}
public String getCurrencyPairCode() {
return currencyPairCode;
}
public String getSide() {
return side;
}
public Integer getLeverageLevel() {
return leverageLevel;
}
public String getProductCode() {
return productCode;
}
public BigDecimal getFilledQuantity() {
return filledQuantity;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getCreatedAt() {
return createdAt;
}
public BigDecimal getUpdatedAt() {
return updatedAt;
}
public String getStatus() {
return status;
}
public BigDecimal getOrderFee() {
return orderFee;
}
public Object getSettings() {
return settings;
}
public Execution[] getExecutions() {
return executions;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "OrderDetailsResponse [id="
+ id
+ ", orderType="
+ orderType
+ ", quantity="
+ quantity
+ ", currencyPairCode="
+ currencyPairCode
+ ", side="
+ side
+ ", leverageLevel="
+ leverageLevel
+ ", productCode="
+ productCode
+ ", filledQuantity="
+ filledQuantity
+ ", price="
+ price
+ ", createdAt="
+ createdAt
+ ", updatedAt="
+ updatedAt
+ ", status="
+ status
+ ", orderFee="
+ orderFee
+ ", settings="
+ settings
+ ", executions="
+ Arrays.toString(executions)
+ "]";
| 957
| 208
| 1,165
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/dto/trade/QuoineOrderResponse.java
|
QuoineOrderResponse
|
toString
|
class QuoineOrderResponse {
private final String id;
private final BigDecimal price;
private final String status;
private final BigDecimal quantity;
private final BigDecimal filledQuantity;
private final String productCode;
private final String currencyPairCode;
private final String createdAt;
private final String updatedAt;
private final String side;
private final String orderType;
private final Object notes;
private final boolean success;
/**
* Constructor
*
* @param id
* @param price
* @param status
* @param quantity
* @param filledQuantity
* @param productCode
* @param currencyPairCode
* @param createdAt
* @param side
* @param orderType
* @param notes
* @param success
*/
public QuoineOrderResponse(
@JsonProperty("id") String id,
@JsonProperty("price") BigDecimal price,
@JsonProperty("status") String status,
@JsonProperty("quantity") BigDecimal quantity,
@JsonProperty("filled_quantity") BigDecimal filledQuantity,
@JsonProperty("product_code") String productCode,
@JsonProperty("currency_pair_code") String currencyPairCode,
@JsonProperty("created_at") String createdAt,
@JsonProperty("updated_at") String updatedAt,
@JsonProperty("side") String side,
@JsonProperty("order_type") String orderType,
@JsonProperty("notes") Object notes,
@JsonProperty("success") boolean success) {
this.id = id;
this.price = price;
this.status = status;
this.quantity = quantity;
this.filledQuantity = filledQuantity;
this.productCode = productCode;
this.currencyPairCode = currencyPairCode;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.side = side;
this.orderType = orderType;
this.notes = notes;
this.success = success;
}
public String getId() {
return id;
}
public BigDecimal getPrice() {
return price;
}
public String getStatus() {
return status;
}
public BigDecimal getQuantity() {
return quantity;
}
public BigDecimal getFilledQuantity() {
return filledQuantity;
}
public String getProductCode() {
return productCode;
}
public String getCurrencyPairCode() {
return currencyPairCode;
}
public String getCreatedAt() {
return createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public String getSide() {
return side;
}
public String getOrderType() {
return orderType;
}
public Object getNotes() {
return notes;
}
public boolean isSuccess() {
return success;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "QuoineOrderResponse [id="
+ id
+ ", price="
+ price
+ ", status="
+ status
+ ", quantity="
+ quantity
+ ", filledQuantity="
+ filledQuantity
+ ", productCode="
+ productCode
+ ", currencyPairCode="
+ currencyPairCode
+ ", createdAt="
+ createdAt
+ ", updatedAt="
+ updatedAt
+ ", side="
+ side
+ ", orderType="
+ orderType
+ ", notes="
+ notes
+ ", success="
+ success
+ "]";
| 788
| 174
| 962
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/service/QuoineMarketDataServiceRaw.java
|
QuoineMarketDataServiceRaw
|
getQuoineProducts
|
class QuoineMarketDataServiceRaw extends QuoineBaseService {
/**
* Constructor
*
* @param exchange
*/
public QuoineMarketDataServiceRaw(Exchange exchange) {
super(exchange);
}
public QuoineProduct getQuoineProduct(String currencyPair) throws IOException {
try {
return quoine.getQuoineProduct(currencyPair);
} catch (HttpStatusIOException e) {
throw new ExchangeException(e.getHttpBody(), e);
}
}
public QuoineProduct[] getQuoineProducts() throws IOException {<FILL_FUNCTION_BODY>}
public QuoineOrderBook getOrderBook(int id) throws IOException {
try {
return quoine.getOrderBook(id);
} catch (HttpStatusIOException e) {
throw new ExchangeException(e.getHttpBody(), e);
}
}
}
|
try {
return quoine.getQuoineProducts();
} catch (HttpStatusIOException e) {
throw new ExchangeException(e.getHttpBody(), e);
}
| 242
| 50
| 292
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>protected static final int QUOINE_API_VERSION,protected final java.lang.String contentType,protected org.knowm.xchange.quoine.QuoineAuthenticated quoine,protected final non-sealed java.lang.String secret,protected final non-sealed org.knowm.xchange.quoine.service.QuoineSignatureDigest signatureCreator,protected final non-sealed java.lang.String tokenID
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/service/QuoineSignatureDigest.java
|
QuoineSignatureDigest
|
digestParams
|
class QuoineSignatureDigest implements ParamsDigest {
private final JWTCreator.Builder builder;
private final String tokenID;
private final byte[] userSecret;
private final SynchronizedValueFactory<Long> nonceFactory;
public QuoineSignatureDigest(
String tokenID, String userSecret, SynchronizedValueFactory<Long> nonceFactory) {
this.tokenID = tokenID;
this.userSecret = userSecret.getBytes();
this.nonceFactory = nonceFactory;
this.builder = JWT.create();
}
@Override
public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>}
}
|
String path = "/" + restInvocation.getMethodPath();
String queryString = restInvocation.getQueryString();
if (queryString != null && queryString.length() > 0)
path += "?" + restInvocation.getQueryString();
return builder
.withClaim("path", path)
.withClaim("nonce", String.valueOf(nonceFactory.createValue()))
.withClaim("token_id", tokenID)
.sign(Algorithm.HMAC256(userSecret));
| 180
| 137
| 317
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/service/QuoineTrade.java
|
QuoineTrade
|
toString
|
class QuoineTrade {
public final String id;
public final String currencyPairCode;
public final String status;
public final String side;
public final BigDecimal marginUsed;
public final BigDecimal openQuantity;
public final BigDecimal closeQuantity;
public final BigDecimal quantity;
public final BigDecimal leverageLevel;
public final String productCode;
public final String productId;
public final BigDecimal openPrice;
public final BigDecimal closePrice;
public final String traderId;
public final BigDecimal openPnl;
public final BigDecimal closePnl;
public final BigDecimal pnl;
public final BigDecimal stopLoss;
public final BigDecimal takeProfit;
public final String fundingCurrency;
public final Long createdAt;
public final Long updatedAt;
public final BigDecimal totalInterest;
public QuoineTrade(
@JsonProperty("id") String id,
@JsonProperty("currency_pair_code") String currencyPairCode,
@JsonProperty("status") String status,
@JsonProperty("side") String side,
@JsonProperty("margin_used") BigDecimal marginUsed,
@JsonProperty("open_quantity") BigDecimal openQuantity,
@JsonProperty("close_quantity") BigDecimal closeQuantity,
@JsonProperty("quantity") BigDecimal quantity,
@JsonProperty("leverage_level") BigDecimal leverageLevel,
@JsonProperty("product_code") String productCode,
@JsonProperty("product_id") String productId,
@JsonProperty("open_price") BigDecimal openPrice,
@JsonProperty("close_price") BigDecimal closePrice,
@JsonProperty("trader_id") String traderId,
@JsonProperty("open_pnl") BigDecimal openPnl,
@JsonProperty("close_pnl") BigDecimal closePnl,
@JsonProperty("pnl") BigDecimal pnl,
@JsonProperty("stop_loss") BigDecimal stopLoss,
@JsonProperty("take_profit") BigDecimal takeProfit,
@JsonProperty("funding_currency") String fundingCurrency,
@JsonProperty("created_at") Long createdAt,
@JsonProperty("updated_at") Long updatedAt,
@JsonProperty("total_interest") BigDecimal totalInterest) {
this.id = id;
this.currencyPairCode = currencyPairCode;
this.status = status;
this.side = side;
this.marginUsed = marginUsed;
this.openQuantity = openQuantity;
this.closeQuantity = closeQuantity;
this.quantity = quantity;
this.leverageLevel = leverageLevel;
this.productCode = productCode;
this.productId = productId;
this.openPrice = openPrice;
this.closePrice = closePrice;
this.traderId = traderId;
this.openPnl = openPnl;
this.closePnl = closePnl;
this.pnl = pnl;
this.stopLoss = stopLoss;
this.takeProfit = takeProfit;
this.fundingCurrency = fundingCurrency;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.totalInterest = totalInterest;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "QuoineTrade{"
+ "id='"
+ id
+ '\''
+ ", currencyPairCode='"
+ currencyPairCode
+ '\''
+ ", status='"
+ status
+ '\''
+ ", side='"
+ side
+ '\''
+ ", marginUsed="
+ marginUsed
+ ", openQuantity="
+ openQuantity
+ ", closeQuantity="
+ closeQuantity
+ ", quantity="
+ quantity
+ ", leverageLevel="
+ leverageLevel
+ ", productCode='"
+ productCode
+ '\''
+ ", productId='"
+ productId
+ '\''
+ ", openPrice="
+ openPrice
+ ", closePrice="
+ closePrice
+ ", traderId='"
+ traderId
+ '\''
+ ", openPnl="
+ openPnl
+ ", closePnl="
+ closePnl
+ ", pnl="
+ pnl
+ ", stopLoss="
+ stopLoss
+ ", takeProfit="
+ takeProfit
+ ", fundingCurrency='"
+ fundingCurrency
+ '\''
+ ", createdAt="
+ createdAt
+ ", updatedAt="
+ updatedAt
+ ", totalInterest="
+ totalInterest
+ '}';
| 861
| 368
| 1,229
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-quoine/src/main/java/org/knowm/xchange/quoine/service/QuoineTradeServiceRaw.java
|
QuoineTradeServiceRaw
|
placeMarketOrder
|
class QuoineTradeServiceRaw extends QuoineBaseService {
private boolean useMargin;
private int leverageLevel;
/**
* @param exchange
*/
public QuoineTradeServiceRaw(Exchange exchange, boolean useMargin) {
super(exchange);
this.useMargin = useMargin;
if (useMargin) {
leverageLevel =
Integer.valueOf(
(String)
exchange
.getExchangeSpecification()
.getExchangeSpecificParametersItem("Leverage_Level"));
} else {
leverageLevel = 0;
}
}
public QuoineOrderResponse placeLimitOrder(
CurrencyPair currencyPair, String type, BigDecimal originalAmount, BigDecimal price)
throws IOException {
int productId = productId(currencyPair);
QuoineNewOrderRequest quoineNewOrderRequest =
useMargin
? new QuoineNewMarginOrderRequest(
"limit",
productId,
type,
originalAmount,
price,
leverageLevel,
currencyPair.counter.getCurrencyCode())
: new QuoineNewOrderRequest("limit", productId, type, originalAmount, price);
try {
return quoine.placeOrder(
QUOINE_API_VERSION,
signatureCreator,
contentType,
new QuoineNewOrderRequestWrapper(quoineNewOrderRequest));
} catch (HttpStatusIOException e) {
throw handleHttpError(e);
}
}
public QuoineOrderResponse placeMarketOrder(
CurrencyPair currencyPair, String type, BigDecimal originalAmount) throws IOException {<FILL_FUNCTION_BODY>}
public QuoineOrderResponse cancelQuoineOrder(String orderID) throws IOException {
try {
return quoine.cancelOrder(QUOINE_API_VERSION, signatureCreator, contentType, orderID);
} catch (HttpStatusIOException e) {
throw handleHttpError(e);
}
}
public QuoineOrderDetailsResponse getQuoineOrderDetails(String orderID) throws IOException {
try {
return quoine.orderDetails(QUOINE_API_VERSION, signatureCreator, contentType, orderID);
} catch (HttpStatusIOException e) {
throw handleHttpError(e);
}
}
public QuoineOrdersList listQuoineOrders() throws IOException {
try {
return quoine.listOrders(QUOINE_API_VERSION, signatureCreator, contentType, "live");
} catch (HttpStatusIOException e) {
throw handleHttpError(e);
}
}
public List<QuoineExecution> executions(CurrencyPair currencyPair, Integer limit, Integer page)
throws IOException {
int productId = productId(currencyPair);
QuoineExecutionsResponse response =
quoine.executions(
QUOINE_API_VERSION, signatureCreator, contentType, productId, limit, page, 1);
return response.models;
}
public List<QuoineTrade> trades(Currency fundingCurrency, Integer limit, Integer page)
throws IOException {
QuoineTradesResponse response =
quoine.trades(
QUOINE_API_VERSION,
signatureCreator,
contentType,
fundingCurrency == null ? null : fundingCurrency.getCurrencyCode(),
"null",
limit,
page);
return response.models;
}
public List<QuoineTransaction> transactions(Currency currency, Integer limit, Integer page)
throws IOException {
QuoineTransactionsResponse transactions =
quoine.transactions(
QUOINE_API_VERSION,
signatureCreator,
contentType,
currency == null ? null : currency.getCurrencyCode(),
null,
limit,
page);
return transactions.models;
}
}
|
int productId = productId(currencyPair);
QuoineNewOrderRequest quoineNewOrderRequest =
useMargin
? new QuoineNewMarginOrderRequest(
"market",
productId,
type,
originalAmount,
null,
leverageLevel,
currencyPair.counter.getCurrencyCode())
: new QuoineNewOrderRequest("market", productId, type, originalAmount, null);
try {
return quoine.placeOrder(
QUOINE_API_VERSION,
signatureCreator,
contentType,
new QuoineNewOrderRequestWrapper(quoineNewOrderRequest));
} catch (HttpStatusIOException e) {
throw handleHttpError(e);
}
| 998
| 188
| 1,186
|
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>protected static final int QUOINE_API_VERSION,protected final java.lang.String contentType,protected org.knowm.xchange.quoine.QuoineAuthenticated quoine,protected final non-sealed java.lang.String secret,protected final non-sealed org.knowm.xchange.quoine.service.QuoineSignatureDigest signatureCreator,protected final non-sealed java.lang.String tokenID
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/RippleAmount.java
|
RippleAmount
|
toString
|
class RippleAmount {
@JsonProperty("currency")
private String currency;
@JsonProperty("counterparty")
private String counterparty;
@JsonProperty("value")
private BigDecimal value;
public String getCurrency() {
return currency;
}
public void setCurrency(final String value) {
currency = value;
}
public String getCounterparty() {
return counterparty;
}
public void setCounterparty(final String value) {
counterparty = value;
}
// issuer is the old term for counterparty
// still used in the payment json as of v1.8.1
@JsonProperty("issuer")
public void setIssuer(final String value) {
counterparty = value;
}
@JsonSerialize(using = ToStringSerializer.class)
public BigDecimal getValue() {
return value;
}
public void setValue(final BigDecimal value) {
this.value = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format(
"%s [currency=%s, counterparty=%s, value=%s]",
getClass().getSimpleName(), currency, counterparty, value);
| 288
| 48
| 336
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/account/RippleSettings.java
|
RippleSettings
|
getTransferFeeRate
|
class RippleSettings {
private static final BigDecimal TRANSFER_RATE_DENOMINATOR = BigDecimal.valueOf(1000000000);
private String account;
@JsonProperty("transfer_rate")
private int transferRate;
@JsonProperty("password_spent")
private boolean passwordSpent;
@JsonProperty("require_destination_tag")
private boolean requireDestinationTag;
@JsonProperty("require_authorization")
private boolean requireAuthorization;
@JsonProperty("disallow_xrp")
private boolean disallowXRP;
@JsonProperty("disable_master")
private boolean disableMaster;
@JsonProperty("no_freeze")
private boolean noFreeze;
@JsonProperty("global_freeze")
private boolean globalFreeze;
@JsonProperty("default_ripple")
private boolean defaultRipple;
@JsonProperty("transaction_sequence")
private String transactionSequence;
@JsonProperty("email_hash")
private String emailHash;
@JsonProperty("wallet_locator")
private String walletLocator;
@JsonProperty("wallet_size")
private String walletSize;
@JsonProperty("message_key")
private String messageKey;
private String domain;
private String signers;
public String getAccount() {
return account;
}
public void setAccount(final String account) {
this.account = account;
}
/**
* The raw transfer rate is represented as an integer, the amount that must be sent in order for 1
* billion units to arrive. For example, a 20% transfer fee is represented as the value 120000000.
* The value cannot be less than 1000000000. Less than that would indicate giving away money for
* sending transactions, which is exploitable. You can specify 0 as a shortcut for 1000000000,
* meaning no fee.
*
* @return percentage transfer rate charge
*/
public BigDecimal getTransferFeeRate() {<FILL_FUNCTION_BODY>}
public int getTransferRate() {
return transferRate;
}
public void setTransferRate(final int transferRate) {
this.transferRate = transferRate;
}
public boolean isPasswordSpent() {
return passwordSpent;
}
public void setPasswordSpent(final boolean passwordSpent) {
this.passwordSpent = passwordSpent;
}
public boolean isRequireDestinationTag() {
return requireDestinationTag;
}
public void setRequireDestinationTag(final boolean requireDestinationTag) {
this.requireDestinationTag = requireDestinationTag;
}
public boolean isRequireAuthorization() {
return requireAuthorization;
}
public void setRequireAuthorization(final boolean requireAuthorization) {
this.requireAuthorization = requireAuthorization;
}
public boolean isDisallowXRP() {
return disallowXRP;
}
public void setDisallowXRP(final boolean disallowXRP) {
this.disallowXRP = disallowXRP;
}
public boolean isDisableMaster() {
return disableMaster;
}
public void setDisableMaster(final boolean disallowMaster) {
this.disableMaster = disallowMaster;
}
public boolean isNoFreeze() {
return noFreeze;
}
public void setNoFreeze(final boolean noFreeze) {
this.noFreeze = noFreeze;
}
public boolean isGlobalFreeze() {
return globalFreeze;
}
public void setGlobalFreeze(final boolean globalFreeze) {
this.globalFreeze = globalFreeze;
}
public boolean isDefaultRipple() {
return defaultRipple;
}
public void setDefaultRipple(final boolean defaultRipple) {
this.defaultRipple = defaultRipple;
}
public String getTransactionSequence() {
return transactionSequence;
}
public void setTransactionSequence(final String transactionSequence) {
this.transactionSequence = transactionSequence;
}
public String getEmailHash() {
return emailHash;
}
public void setEmailHash(final String emailHash) {
this.emailHash = emailHash;
}
public String getWalletLocator() {
return walletLocator;
}
public void setWalletLocator(final String walletLocator) {
this.walletLocator = walletLocator;
}
public String getWalletSize() {
return walletSize;
}
public void setWalletSize(final String walletSize) {
this.walletSize = walletSize;
}
public String getMessageKey() {
return messageKey;
}
public void setMessageKey(final String messageKey) {
this.messageKey = messageKey;
}
public String getDomain() {
return domain;
}
public void setDomain(final String domain) {
this.domain = domain;
}
public String getSigners() {
return signers;
}
public void setSigners(final String signers) {
this.signers = signers;
}
@Override
public String toString() {
return String.format("%s [account=%s]", getClass().getSimpleName(), account);
}
}
|
if (transferRate == 0) {
return BigDecimal.ZERO;
} else {
return BigDecimal.valueOf(transferRate)
.divide(TRANSFER_RATE_DENOMINATOR)
.subtract(BigDecimal.ONE);
}
| 1,428
| 79
| 1,507
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/marketdata/RippleOrder.java
|
RippleOrder
|
toString
|
class RippleOrder {
@JsonProperty("price")
private RippleAmount price;
@JsonProperty("taker_gets_funded")
private RippleAmount takerGetsFunded;
@JsonProperty("taker_gets_total")
private RippleAmount takerGetsTotal;
@JsonProperty("taker_pays_funded")
private RippleAmount takerPaysFunded;
@JsonProperty("taker_pays_total")
private RippleAmount takerPaysTotal;
@JsonProperty("order_maker")
private String orderMaker;
@JsonProperty("sequence")
private Integer sequence;
@JsonProperty("passive")
private Boolean passive;
@JsonProperty("sell")
private Boolean sell;
public RippleAmount getPrice() {
return price;
}
public void setPrice(final RippleAmount value) {
price = value;
}
public RippleAmount getTakerGetsFunded() {
return takerGetsFunded;
}
public void setTakerGetsFunded(final RippleAmount value) {
takerGetsFunded = value;
}
public RippleAmount getTakerGetsTotal() {
return takerGetsTotal;
}
public void setTakerGetsTotal(final RippleAmount value) {
takerGetsTotal = value;
}
public RippleAmount getTakerPaysFunded() {
return takerPaysFunded;
}
public void setTakerPaysFunded(final RippleAmount value) {
takerPaysFunded = value;
}
public RippleAmount getTakerPaysTotal() {
return takerPaysTotal;
}
public void setTakerPaysTotal(final RippleAmount value) {
takerPaysTotal = value;
}
public String getOrderMaker() {
return orderMaker;
}
public void setOrderMaker(final String value) {
orderMaker = value;
}
public Integer getSequence() {
return sequence;
}
public void setSequence(final Integer value) {
sequence = value;
}
public Boolean getPassive() {
return passive;
}
public void setPassive(final Boolean value) {
passive = value;
}
public Boolean getSell() {
return sell;
}
public void setSell(final Boolean value) {
sell = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format(
"Order [order_maker=%s, sequence=%d, passive=%b, sell=%s, price=%s, taker_gets_funded=%s, taker_gets_total=%s, taker_pays_funded=%s, taker_pays_total=%s]",
orderMaker,
sequence,
passive,
sell,
price,
takerGetsFunded,
takerGetsTotal,
takerPaysFunded,
takerPaysTotal);
| 691
| 145
| 836
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/marketdata/RippleOrderBook.java
|
RippleOrderBook
|
toString
|
class RippleOrderBook extends RippleCommon {
@JsonProperty("order_book")
private String orderBook;
@JsonProperty("bids")
private List<RippleOrder> bids = new ArrayList<>();
@JsonProperty("asks")
private List<RippleOrder> asks = new ArrayList<>();
public String getOrderBook() {
return orderBook;
}
public void setOrderBook(final String orderBook) {
this.orderBook = orderBook;
}
public List<RippleOrder> getBids() {
return bids;
}
public void setBids(final List<RippleOrder> bids) {
this.bids = bids;
}
public List<RippleOrder> getAsks() {
return asks;
}
public void setAsks(final List<RippleOrder> asks) {
this.asks = asks;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format(
"OrderBook [ledger=%s, validated=%b, success=%b, order_book=%s, bids=%s, asks=%s]",
ledger, validated, success, orderBook, bids, asks);
| 269
| 70
| 339
|
<methods>public non-sealed void <init>() ,public final java.lang.String getHash() ,public final long getLedger() ,public final java.lang.String getState() ,public final java.lang.Boolean isSuccess() ,public final java.lang.Boolean isValidated() ,public final void setHash(java.lang.String) ,public final void setLedger(long) ,public final void setState(java.lang.String) ,public final void setSuccess(java.lang.Boolean) ,public final void setValidated(java.lang.Boolean) <variables>protected java.lang.String hash,protected long ledger,protected java.lang.String state,protected java.lang.Boolean success,protected java.lang.Boolean validated
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/trade/RippleAccountOrders.java
|
RippleAccountOrders
|
toString
|
class RippleAccountOrders extends RippleCommon {
@JsonProperty("orders")
private List<RippleAccountOrdersBody> orders;
public List<RippleAccountOrdersBody> getOrders() {
return orders;
}
public void setOrder(final List<RippleAccountOrdersBody> value) {
orders = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format(
"%s [success=%b, validated=%b, ledger=%s, order=%s]",
getClass().getSimpleName(), success, validated, ledger, orders);
| 120
| 57
| 177
|
<methods>public non-sealed void <init>() ,public final java.lang.String getHash() ,public final long getLedger() ,public final java.lang.String getState() ,public final java.lang.Boolean isSuccess() ,public final java.lang.Boolean isValidated() ,public final void setHash(java.lang.String) ,public final void setLedger(long) ,public final void setState(java.lang.String) ,public final void setSuccess(java.lang.Boolean) ,public final void setValidated(java.lang.Boolean) <variables>protected java.lang.String hash,protected long ledger,protected java.lang.String state,protected java.lang.Boolean success,protected java.lang.Boolean validated
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/trade/RippleOrderEntryRequestBody.java
|
RippleOrderEntryRequestBody
|
toString
|
class RippleOrderEntryRequestBody {
@JsonProperty("type")
private String type;
@JsonProperty("taker_pays")
private RippleAmount takerPays = new RippleAmount();
@JsonProperty("taker_gets")
private RippleAmount takerGets = new RippleAmount();
public String getType() {
return type;
}
public void setType(final String value) {
type = value;
}
public RippleAmount getTakerPays() {
return takerPays;
}
public void setTakerPays(final RippleAmount value) {
takerPays = value;
}
public RippleAmount getTakerGets() {
return takerGets;
}
public void setTakerGetsTotal(final RippleAmount value) {
takerGets = value;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return String.format(
"%s [type=%s, taker_pays=%s, taker_gets=%s]",
getClass().getSimpleName(), type, takerPays, takerGets);
| 258
| 59
| 317
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/dto/trade/RippleUserTrade.java
|
Builder
|
build
|
class Builder extends UserTrade.Builder {
private String baseCounterparty = "";
private String counterCounterparty = "";
private BigDecimal baseTransferFee = BigDecimal.ZERO;
private BigDecimal counterTransferFee = BigDecimal.ZERO;
public static Builder from(final RippleUserTrade trade) {
final Builder builder =
new Builder()
.baseCounterparty(trade.getBaseCounterparty())
.counterCounterparty(trade.getCounterCounterparty());
builder
.orderId(trade.getOrderId())
.feeAmount(trade.getFeeAmount())
.feeCurrency(trade.getFeeCurrency());
builder
.type(trade.getType())
.originalAmount(trade.getOriginalAmount())
.currencyPair(trade.getCurrencyPair())
.price(trade.getPrice())
.timestamp(trade.getTimestamp())
.id(trade.getId());
return builder;
}
public Builder baseCounterparty(final String value) {
baseCounterparty = value;
return this;
}
public Builder counterCounterparty(final String value) {
counterCounterparty = value;
return this;
}
public Builder baseTransferFee(final BigDecimal value) {
baseTransferFee = value;
return this;
}
public Builder counterTransferFee(final BigDecimal value) {
counterTransferFee = value;
return this;
}
@Override
public RippleUserTrade build() {<FILL_FUNCTION_BODY>}
}
|
final RippleUserTrade trade =
new RippleUserTrade(
type,
originalAmount,
(CurrencyPair) instrument,
price,
timestamp,
id,
orderId,
feeAmount,
feeCurrency,
baseCounterparty,
counterCounterparty,
baseTransferFee,
counterTransferFee);
return trade;
| 420
| 101
| 521
|
<methods>public void <init>(org.knowm.xchange.dto.Order.OrderType, java.math.BigDecimal, org.knowm.xchange.instrument.Instrument, java.math.BigDecimal, java.util.Date, java.lang.String, java.lang.String, java.math.BigDecimal, org.knowm.xchange.currency.Currency, java.lang.String) ,public static org.knowm.xchange.dto.trade.UserTrade.Builder builder() ,public boolean equals(java.lang.Object) ,public java.math.BigDecimal getFeeAmount() ,public org.knowm.xchange.currency.Currency getFeeCurrency() ,public java.lang.String getOrderId() ,public java.lang.String getOrderUserReference() ,public int hashCode() ,public java.lang.String toString() <variables>private final non-sealed java.math.BigDecimal feeAmount,private final non-sealed org.knowm.xchange.currency.Currency feeCurrency,private final non-sealed java.lang.String orderId,private final non-sealed java.lang.String orderUserReference,private static final long serialVersionUID
|
knowm_XChange
|
XChange/xchange-ripple/src/main/java/org/knowm/xchange/ripple/service/RippleTradeService.java
|
RippleTradeService
|
getTradeHistory
|
class RippleTradeService extends RippleTradeServiceRaw implements TradeService {
private final RippleExchange ripple;
/** Empty placeholder trade history parameter object. */
private final RippleTradeHistoryParams defaultTradeHistoryParams = createTradeHistoryParams();
public RippleTradeService(final RippleExchange exchange) {
super(exchange);
ripple = exchange;
}
/**
* The additional data map of an order will be populated with {@link
* RippleExchange.DATA_BASE_COUNTERPARTY} if the base currency is not XRP, similarly if the
* counter currency is not XRP then {@link RippleExchange.DATA_COUNTER_COUNTERPARTY} will be
* populated.
*/
@Override
public OpenOrders getOpenOrders() throws IOException {
return getOpenOrders(createOpenOrdersParams());
}
@Override
public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException {
return RippleAdapters.adaptOpenOrders(getOpenAccountOrders(), ripple.getRoundingScale());
}
/**
* @param order this should be a RippleLimitOrder object with the base and counter counterparties
* populated for any currency other than XRP.
*/
@Override
public String placeLimitOrder(final LimitOrder order) throws IOException {
if (order instanceof RippleLimitOrder) {
return placeOrder((RippleLimitOrder) order, ripple.validateOrderRequests());
} else {
throw new IllegalArgumentException("order must be of type: " + RippleLimitOrder.class);
}
}
@Override
public boolean cancelOrder(final String orderId) throws IOException {
return cancelOrder(orderId, ripple.validateOrderRequests());
}
@Override
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException {
if (orderParams instanceof CancelOrderByIdParams) {
return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId());
} else {
return false;
}
}
/**
* Ripple trade history is a request intensive process. The REST API does not provide a simple
* single trade history query. Trades are retrieved by querying account notifications and for
* those of type order details of the hash are then queried. These order detail queries could be
* order entry, cancel or execution, it is not possible to tell from the notification. Therefore
* if an account is entering many orders but executing few of them, this trade history query will
* result in many API calls without returning any trade history. In order to reduce the time and
* resources used in these repeated calls In order to reduce the number of API calls a number of
* different methods can be used:
*
* <ul>
* <li><b>RippleTradeHistoryHashLimit</b> set the to the last known trade, this query will then
* terminate once it has been found.
* <li><b>RippleTradeHistoryCount</b> set the to restrict the number of trades to return, the
* default is {@link RippleTradeHistoryCount#DEFAULT_TRADE_COUNT_LIMIT}.
* <li><b>RippleTradeHistoryCount</b> set the to restrict the number of API calls that will be
* made during a single trade history query, the default is {@link
* RippleTradeHistoryCount#DEFAULT_API_CALL_COUNT}.
* <li><b>TradeHistoryParamsTimeSpan</b> set the {@link
* TradeHistoryParamsTimeSpan#setStartTime(java.util.Date)} to limit the number of trades
* searched for to those done since the given start time. TradeHistoryParamsTimeSpan
* </ul>
*
* @param params Can optionally implement {@RippleTradeHistoryAccount},
* {@RippleTradeHistoryCount}, {@RippleTradeHistoryHashLimit},
* {@RippleTradeHistoryPreferredCurrencies}, {@link TradeHistoryParamPaging},
* {@TradeHistoryParamCurrencyPair}, {@link TradeHistoryParamsTimeSpan}. All other
* TradeHistoryParams types will be ignored.
*/
@Override
public UserTrades getTradeHistory(final TradeHistoryParams params) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public RippleTradeHistoryParams createTradeHistoryParams() {
final RippleTradeHistoryParams params = new RippleTradeHistoryParams();
params.setAccount(exchange.getExchangeSpecification().getApiKey());
return params;
}
@Override
public OpenOrdersParams createOpenOrdersParams() {
return null;
}
}
|
if (params instanceof RippleTradeHistoryCount) {
final RippleTradeHistoryCount rippleParams = (RippleTradeHistoryCount) params;
rippleParams.resetApiCallCount();
rippleParams.resetTradeCount();
}
final String account;
if (params instanceof RippleTradeHistoryAccount) {
final RippleTradeHistoryAccount rippleAccount = (RippleTradeHistoryAccount) params;
if (rippleAccount.getAccount() != null) {
account = rippleAccount.getAccount();
} else {
account = exchange.getExchangeSpecification().getApiKey();
}
} else {
account = defaultTradeHistoryParams.getAccount();
}
final List<IRippleTradeTransaction> trades = getTradesForAccount(params, account);
return RippleAdapters.adaptTrades(
trades,
params,
(RippleAccountService) exchange.getAccountService(),
ripple.getRoundingScale());
| 1,183
| 254
| 1,437
|
<methods>public void <init>(org.knowm.xchange.Exchange) ,public boolean cancelOrder(java.lang.String, boolean) throws java.io.IOException,public void clearOrderDetailsStore() ,public java.math.BigDecimal getExpectedBaseTransferFee(org.knowm.xchange.ripple.dto.trade.RippleLimitOrder) throws java.io.IOException,public java.math.BigDecimal getExpectedCounterTransferFee(org.knowm.xchange.ripple.dto.trade.RippleLimitOrder) throws java.io.IOException,public static java.math.BigDecimal getExpectedTransferFee(org.knowm.xchange.ripple.dto.account.ITransferFeeSource, java.lang.String, java.lang.String, java.math.BigDecimal, org.knowm.xchange.dto.Order.OrderType) throws java.io.IOException,public org.knowm.xchange.ripple.dto.trade.RippleNotifications getNotifications(java.lang.String, java.lang.Boolean, java.lang.Boolean, java.lang.Integer, java.lang.Integer, java.lang.Long, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.ripple.dto.trade.RippleAccountOrders getOpenAccountOrders() throws java.io.IOException,public org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction getTrade(java.lang.String, org.knowm.xchange.ripple.dto.trade.RippleNotifications.RippleNotification) throws java.io.IOException,public List<org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction> getTradesForAccount(org.knowm.xchange.service.trade.params.TradeHistoryParams, java.lang.String) throws java.io.IOException,public java.math.BigDecimal getTransactionFee() ,public java.lang.String placeOrder(org.knowm.xchange.ripple.dto.trade.RippleLimitOrder, boolean) throws java.io.IOException<variables>private static final java.lang.Boolean EARLIEST_FIRST,private static final java.lang.Long END_LEDGER,private static final java.lang.Boolean EXCLUDE_FAILED,private static final java.lang.Long START_LEDGER,private final Logger logger,private final Map<java.lang.String,Map<java.lang.String,org.knowm.xchange.ripple.dto.trade.IRippleTradeTransaction>> rawTradeStore
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/SerumAdapters.java
|
SerumAdapters
|
loadMarkets
|
class SerumAdapters {
private static final Map<CurrencyPair, Market> pairToMarket = new ConcurrentHashMap<>();
/**
* Serum represents markets as individual Solana addresses. As part of starting up the the
* scaffold for Serum we load all the "markets" from the REST api and associate currency pairs to
* their addresses and metadata.
*
* <p>The markets file maintained in XChange should mirror the one found:
* https://github.com/project-serum/serum-ts/blob/master/packages/serum/src/markets.json
*
* @param raw service to use to query for data
*/
public static void loadMarkets(final SerumMarketDataServiceRaw raw) throws Exception {<FILL_FUNCTION_BODY>}
/**
* Extracts the address associated to a currency pair
*
* @param pair to query address for
* @return address as string
*/
public static String toSolanaAddress(final CurrencyPair pair) {
return pairToMarket.get(pair).decoded.getOwnAddress().getKeyString();
}
/**
* Extracts the address associated to a currency pair's specific data type. Serum manages the
* different parts of an order's lifecycle by using different addresses. e.g.
*
* <p>request queue (submitted orders) event queue (fills) bids (orderbook bids) asks (orderbook
* asks)
*
* @param pair to query address for
* @return address as string
*/
public static String getSolanaDataTypeAddress(final CurrencyPair pair, final String dataType) {
final Market m = pairToMarket.get(pair);
switch (dataType) {
case "bids":
return m.decoded.getBids().getKeyString();
case "asks":
return m.decoded.getAsks().getKeyString();
case "eventQueue":
return m.decoded.getEventQueue().getKeyString();
case "requestQueue":
return m.decoded.getRequestQueue().getKeyString();
default:
throw new IllegalArgumentException(
String.format("Market Data Type %s not valid", dataType));
}
}
public static Market getMarket(final CurrencyPair pair) {
return pairToMarket.get(pair);
}
}
|
final String text =
new String(
Files.readAllBytes(
Paths.get(SerumAdapters.class.getResource("/markets.json").toURI())));
final MarketMeta[] marketMetas = new ObjectMapper().readValue(text, MarketMeta[].class);
for (MarketMeta meta : marketMetas) {
final Market m =
WrapperFuncs.runUntilSuccess(() -> raw.load(meta.address, null, meta.programId), 5000, 3);
pairToMarket.put(new CurrencyPair(meta.name), m);
}
| 606
| 156
| 762
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/SerumExchange.java
|
SerumExchange
|
remoteInit
|
class SerumExchange extends BaseExchange implements Exchange {
protected final Logger logger = LoggerFactory.getLogger(SerumExchange.class);
@Override
protected void initServices() {
this.marketDataService = new SerumMarketDataService(this);
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass());
exchangeSpecification.setSslUri(Solana.MAINNET.restUrl());
exchangeSpecification.setHost("projectserum.com");
exchangeSpecification.setPort(80);
exchangeSpecification.setExchangeName("Serum");
exchangeSpecification.setExchangeDescription(
"Serum is a decentralized cryptocurrency exchange built on Solana.");
return exchangeSpecification;
}
@Override
public void remoteInit() {<FILL_FUNCTION_BODY>}
}
|
try {
SerumAdapters.loadMarkets((SerumMarketDataServiceRaw) this.marketDataService);
} catch (Exception e) {
logger.error("Unable to load markets", e);
}
| 239
| 59
| 298
|
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.service.account.AccountService getAccountService() ,public List<org.knowm.xchange.instrument.Instrument> getExchangeInstruments() ,public org.knowm.xchange.dto.meta.ExchangeMetaData getExchangeMetaData() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public org.knowm.xchange.service.marketdata.MarketDataService getMarketDataService() ,public java.lang.String getMetaDataFileName(org.knowm.xchange.ExchangeSpecification) ,public SynchronizedValueFactory<java.lang.Long> getNonceFactory() ,public org.knowm.xchange.service.trade.TradeService getTradeService() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException,public java.lang.String toString() <variables>protected org.knowm.xchange.service.account.AccountService accountService,protected org.knowm.xchange.dto.meta.ExchangeMetaData exchangeMetaData,protected org.knowm.xchange.ExchangeSpecification exchangeSpecification,protected final Logger logger,protected org.knowm.xchange.service.marketdata.MarketDataService marketDataService,private final SynchronizedValueFactory<java.lang.Long> nonceFactory,protected org.knowm.xchange.service.trade.TradeService tradeService
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/core/WrapperFuncs.java
|
WrapperFuncs
|
runUntilSuccess
|
class WrapperFuncs {
protected static final Logger logger = LoggerFactory.getLogger(WrapperFuncs.class);
/**
* Method is a bit of a hack, we simply keep trying to process some function until we succeed. Can
* optionally be configured to have a maximum number of retry attempts.
*
* @param callback to attempt
* @param retryInterval how often we should retry
* @return a value if expected
*/
public static <T> T runUntilSuccess(
final Callback<T> callback, int retryInterval, int retryMaximum) {<FILL_FUNCTION_BODY>}
public interface Callback<T> {
public T callback() throws Exception;
}
}
|
int retries = 0;
while (true) {
try {
return callback.callback();
} catch (Exception e) {
try {
Thread.sleep(retryInterval);
} catch (InterruptedException e1) {
logger.error("Interrupted exception: {}", e.getMessage());
}
logger.debug("Issue processing: {} exception {}", e.getMessage(), e.getClass());
retries++;
if (retries > retryMaximum) {
logger.warn("Exceeded maximum retry attempts");
logger.error("Issue processing: {} exception {}", e.getMessage(), e.getClass());
return null;
}
}
}
| 185
| 176
| 361
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/structures/EventFlagsLayout.java
|
EventFlagsLayout
|
decode
|
class EventFlagsLayout extends Struct {
@Bin(order = 1, name = "bytes", type = BinType.BYTE_ARRAY)
byte[] bytes;
/** There is probably a cleaner way to do this but making it work for now */
public EventFlags decode() {<FILL_FUNCTION_BODY>}
public static class EventFlags {
public boolean fill;
public boolean out;
public boolean bid;
public boolean maker;
EventFlags(boolean fill, boolean out, boolean bid, boolean maker) {
this.fill = fill;
this.out = out;
this.bid = bid;
this.maker = maker;
}
}
}
|
final byte[] copy = new byte[8];
System.arraycopy(bytes, 0, copy, 0, bytes.length);
boolean[] results = booleanFlagsDecoder(copy, 4);
return new EventFlags(results[0], results[1], results[2], results[3]);
| 176
| 75
| 251
|
<methods>public void <init>() ,public void <init>(int) ,public boolean[] booleanFlagsDecoder(byte[], int) ,public static long decodeLong(byte[]) ,public int fixBitwiseResult(int) <variables>public int valueMask
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/structures/EventQueueLayout.java
|
EventNode
|
getUnsignedInt
|
class EventNode {
public final EventFlags eventFlags;
public final long openOrdersSlot;
public final long feeTier;
public final long nativeQuantityReleased; // amount the user received (nativeQuantityUnlocked)
public final long nativeQuantityPaid; // amount the user paid (nativeQuantityStillLocked)
public final long nativeFeeOrRebate;
public final String orderId;
public final byte[] orderIdBytes;
public final PublicKey openOrders;
public final long clientOrderId;
public EventNode(
final EventFlags eventFlags,
long openOrdersSlot,
long feeTier,
long nativeQuantityReleased,
long nativeQuantityPaid,
long nativeFeeOrRebate,
final String orderId,
final byte[] orderIdBytes,
final PublicKey openOrders,
long clientOrderId) {
this.eventFlags = eventFlags;
this.openOrdersSlot = openOrdersSlot;
this.feeTier = feeTier;
this.nativeQuantityReleased = nativeQuantityReleased;
this.nativeQuantityPaid = nativeQuantityPaid;
this.nativeFeeOrRebate = nativeFeeOrRebate;
this.orderId = orderId;
this.orderIdBytes = orderIdBytes;
this.openOrders = openOrders;
this.clientOrderId = clientOrderId;
}
}
public static long getUnsignedInt(byte[] data) {<FILL_FUNCTION_BODY>
|
ByteBuffer bb = ByteBuffer.wrap(data);
bb.order(ByteOrder.LITTLE_ENDIAN);
return bb.getInt() & 0xffffffffL;
| 402
| 52
| 454
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-serum/src/main/java/com/knowm/xchange/serum/structures/MarketLayout.java
|
MarketLayout
|
getLayout
|
class MarketLayout extends Struct {
public static StructDecoder<MarketStat> getLayout(final PublicKey programId) {<FILL_FUNCTION_BODY>}
}
|
if (getLayoutVersion(programId) == 1) {
return MarketStatLayoutV1.DECODER;
}
return MarketStatLayoutV2.DECODER;
| 44
| 47
| 91
|
<methods>public void <init>() ,public void <init>(int) ,public boolean[] booleanFlagsDecoder(byte[], int) ,public static long decodeLong(byte[]) ,public int fixBitwiseResult(int) <variables>public int valueMask
|
knowm_XChange
|
XChange/xchange-simulated/src/main/java/org/knowm/xchange/simulated/Account.java
|
Account
|
reserve
|
class Account {
private final ConcurrentMap<Currency, AtomicReference<Balance>> balances =
new ConcurrentHashMap<>();
void initialize(Iterable<Currency> currencies) {
currencies.forEach(
currency -> balances.put(currency, new AtomicReference<>(new Balance(currency, ZERO))));
}
public Collection<Balance> balances() {
return Collections2.transform(balances.values(), AtomicReference::get);
}
public void checkBalance(LimitOrder order) {
checkBalance(order, order.getOriginalAmount().multiply(order.getLimitPrice()));
}
public void checkBalance(Order order, BigDecimal bidAmount) {
switch (order.getType()) {
case ASK:
BigDecimal askAmount = order.getRemainingAmount();
Balance askBalance =
balances.computeIfAbsent(order.getCurrencyPair().base, this::defaultBalance).get();
checkBalance(order, askAmount, askBalance);
break;
case BID:
Balance bidBalance =
balances.computeIfAbsent(order.getCurrencyPair().counter, this::defaultBalance).get();
checkBalance(order, bidAmount, bidBalance);
break;
default:
throw new NotAvailableFromExchangeException(
"Order type " + order.getType() + " not supported");
}
}
private void checkBalance(Order order, BigDecimal amount, Balance balance) {
if (balance.getAvailable().compareTo(amount) < 0) {
throw new FundsExceededException(
"Insufficient balance: "
+ amount.toPlainString()
+ order.getCurrencyPair().base
+ " required but only "
+ balance.getAvailable()
+ " available");
}
}
public void reserve(LimitOrder order) {
reserve(order, false);
}
public void release(LimitOrder order) {
reserve(order, true);
}
private AtomicReference<Balance> defaultBalance(Currency currency) {
return new AtomicReference<>(new Balance(currency, ZERO));
}
private void reserve(LimitOrder order, boolean negate) {<FILL_FUNCTION_BODY>}
public void fill(UserTrade userTrade, boolean reserved) {
BigDecimal counterAmount = userTrade.getOriginalAmount().multiply(userTrade.getPrice());
switch (userTrade.getType()) {
case ASK:
balance(userTrade.getCurrencyPair().base)
.updateAndGet(
b ->
Balance.Builder.from(b)
.available(
reserved
? b.getAvailable()
: b.getAvailable().subtract(userTrade.getOriginalAmount()))
.frozen(
reserved
? b.getFrozen().subtract(userTrade.getOriginalAmount())
: b.getFrozen())
.total(b.getTotal().subtract(userTrade.getOriginalAmount()))
.build());
balance(userTrade.getCurrencyPair().counter)
.updateAndGet(
b ->
Balance.Builder.from(b)
.total(b.getTotal().add(counterAmount))
.available(b.getAvailable().add(counterAmount))
.build());
break;
case BID:
balance(userTrade.getCurrencyPair().base)
.updateAndGet(
b ->
Balance.Builder.from(b)
.total(b.getTotal().add(userTrade.getOriginalAmount()))
.available(b.getAvailable().add(userTrade.getOriginalAmount()))
.build());
balance(userTrade.getCurrencyPair().counter)
.updateAndGet(
b ->
Balance.Builder.from(b)
.available(
reserved ? b.getAvailable() : b.getAvailable().subtract(counterAmount))
.frozen(reserved ? b.getFrozen().subtract(counterAmount) : b.getFrozen())
.total(b.getTotal().subtract(counterAmount))
.build());
break;
default:
throw new NotAvailableFromExchangeException(
"Order type " + userTrade.getType() + " not supported");
}
}
private AtomicReference<Balance> balance(Currency currency) {
return balances.computeIfAbsent(currency, this::defaultBalance);
}
public void deposit(Currency currency, BigDecimal amount) {
balance(currency)
.updateAndGet(
b ->
Balance.Builder.from(b)
.total(b.getTotal().add(amount))
.available(b.getAvailable().add(amount))
.build());
}
}
|
switch (order.getType()) {
case ASK:
BigDecimal askAmount =
negate ? order.getRemainingAmount().negate() : order.getRemainingAmount();
balance(order.getCurrencyPair().base)
.updateAndGet(
b -> {
if (b.getAvailable().compareTo(askAmount) < 0) {
throw new ExchangeException(
"Insufficient balance: "
+ askAmount.toPlainString()
+ order.getCurrencyPair().base
+ " required but only "
+ b.getAvailable()
+ " available");
}
return Balance.Builder.from(b)
.available(b.getAvailable().subtract(askAmount))
.frozen(b.getFrozen().add(askAmount))
.build();
});
break;
case BID:
BigDecimal bid = order.getRemainingAmount().multiply(order.getLimitPrice());
BigDecimal bidAmount = negate ? bid.negate() : bid;
balance(order.getCurrencyPair().counter)
.updateAndGet(
b -> {
if (b.getAvailable().compareTo(bidAmount) < 0) {
throw new ExchangeException(
"Insufficient balance: "
+ bidAmount.toPlainString()
+ order.getCurrencyPair().counter
+ " required but only "
+ b.getAvailable()
+ " available");
}
return Balance.Builder.from(b)
.available(b.getAvailable().subtract(bidAmount))
.frozen(b.getFrozen().add(bidAmount))
.build();
});
break;
default:
throw new NotAvailableFromExchangeException(
"Order type " + order.getType() + " not supported");
}
| 1,254
| 468
| 1,722
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/BinanceUsStreamingExchange.java
|
BinanceUsStreamingExchange
|
getDefaultExchangeSpecification
|
class BinanceUsStreamingExchange extends BinanceStreamingExchange {
private static final Logger LOG = LoggerFactory.getLogger(BinanceStreamingExchange.class);
private static final String API_BASE_URI = "wss://stream.binance.us:9443/";
@Override
protected String getStreamingBaseUri() {
return API_BASE_URI;
}
// This is needed since BinanceStreamingExchange extends BinanceExchange which has the spec
// configured for binance.com
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {<FILL_FUNCTION_BODY>}
}
|
ExchangeSpecification spec = new ExchangeSpecification(this.getClass());
spec.setSslUri("https://api.binance.us");
spec.setHost("www.binance.us");
spec.setPort(80);
spec.setExchangeName("Binance US");
spec.setExchangeDescription("Binance US Exchange.");
AuthUtils.setApiAndSecretKey(spec, "binanceus");
return spec;
| 168
| 115
| 283
|
<methods>public non-sealed void <init>() ,public java.lang.String buildSubscriptionStreams(info.bitrich.xchangestream.core.ProductSubscription) ,public transient Completable connect(info.bitrich.xchangestream.binance.KlineSubscription, info.bitrich.xchangestream.core.ProductSubscription[]) ,public transient Completable connect(info.bitrich.xchangestream.core.ProductSubscription[]) ,public Observable<info.bitrich.xchangestream.service.netty.ConnectionStateModel.State> connectionStateObservable() ,public Observable<java.lang.Object> connectionSuccess() ,public void disableLiveSubscription() ,public Completable disconnect() ,public void enableLiveSubscription() ,public info.bitrich.xchangestream.binance.BinanceStreamingAccountService getStreamingAccountService() ,public info.bitrich.xchangestream.binance.BinanceStreamingMarketDataService getStreamingMarketDataService() ,public info.bitrich.xchangestream.binance.BinanceStreamingTradeService getStreamingTradeService() ,public boolean isAlive() ,public Observable<java.lang.Throwable> reconnectFailure() ,public void setChannelInactiveHandler(info.bitrich.xchangestream.service.netty.WebSocketClientHandler.WebSocketMessageHandler) ,public void useCompressedMessages(boolean) <variables>public static final java.lang.String FETCH_ORDER_BOOK_LIMIT,private static final Logger LOG,public static final java.lang.String USE_HIGHER_UPDATE_FREQUENCY,public static final java.lang.String USE_REALTIME_BOOK_TICKER,private static final java.lang.String WS_API_BASE_URI,private static final java.lang.String WS_SANDBOX_API_BASE_URI,private int oderBookFetchLimitParameter,private java.lang.Runnable onApiCall,private java.lang.String orderBookUpdateFrequencyParameter,private boolean realtimeOrderBookTicker,private info.bitrich.xchangestream.binance.BinanceStreamingAccountService streamingAccountService,private info.bitrich.xchangestream.binance.BinanceStreamingMarketDataService streamingMarketDataService,private info.bitrich.xchangestream.binance.BinanceStreamingService streamingService,private info.bitrich.xchangestream.binance.BinanceStreamingTradeService streamingTradeService,private info.bitrich.xchangestream.binance.BinanceUserDataChannel userDataChannel,private info.bitrich.xchangestream.binance.BinanceUserDataStreamingService userDataStreamingService
|
knowm_XChange
|
XChange/xchange-stream-binance/src/main/java/info/bitrich/xchangestream/binance/dto/KlineBinanceWebSocketTransaction.java
|
KlineBinanceWebSocketTransaction
|
getParameters
|
class KlineBinanceWebSocketTransaction extends BaseBinanceWebSocketTransaction {
private final String symbol;
private final Map<String, Object> kline;
private final KlineInterval klineInterval;
public KlineBinanceWebSocketTransaction(
@JsonProperty("e") String eventType,
@JsonProperty("E") String eventTime,
@JsonProperty("s") String symbol,
@JsonProperty("k") Map<String, Object> kline) {
super(eventType, eventTime);
this.symbol = symbol;
this.kline = kline;
this.klineInterval =
Arrays.stream(KlineInterval.values())
.filter(i -> i.code().equals(kline.get("i")))
.collect(singletonCollector());
}
private static Object[] getParameters(Map<String, Object> kline) {<FILL_FUNCTION_BODY>}
public BinanceKline toBinanceKline(boolean isFuture) {
return new BinanceKline(
BinanceAdapters.adaptSymbol(symbol, isFuture), klineInterval, getParameters(kline));
}
}
|
Object[] parameters = new Object[12];
parameters[0] = kline.get("t");
parameters[1] = kline.get("o");
parameters[2] = kline.get("h");
parameters[3] = kline.get("l");
parameters[4] = kline.get("c");
parameters[5] = kline.get("v");
parameters[6] = kline.get("T");
parameters[7] = kline.get("q");
parameters[8] = kline.get("n");
parameters[9] = kline.get("V");
parameters[10] = kline.get("Q");
parameters[11] = kline.get("x");
return parameters;
| 296
| 190
| 486
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public java.util.Date getEventTime() ,public info.bitrich.xchangestream.binance.dto.BaseBinanceWebSocketTransaction.BinanceWebSocketTypes getEventType() <variables>protected final non-sealed java.util.Date eventTime,protected final non-sealed info.bitrich.xchangestream.binance.dto.BaseBinanceWebSocketTransaction.BinanceWebSocketTypes eventType
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/BitfinexStreamingMarketDataService.java
|
BitfinexStreamingMarketDataService
|
getOrderBook
|
class BitfinexStreamingMarketDataService implements StreamingMarketDataService {
private final BitfinexStreamingService service;
private final Map<CurrencyPair, BitfinexOrderbook> orderbooks = new HashMap<>();
public BitfinexStreamingMarketDataService(BitfinexStreamingService service) {
this.service = service;
}
private String pairToSymbol(CurrencyPair currencyPair) {
return (currencyPair.counter == Currency.USDT)
? ("t" + currencyPair.base.getCurrencyCode() + "UST")
: ("t" + currencyPair.base.getCurrencyCode() + currencyPair.counter.getCurrencyCode());
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
String channelName = "ticker";
String pair = pairToSymbol(currencyPair);
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
Observable<BitfinexWebSocketTickerTransaction> subscribedChannel =
service
.subscribeChannel(channelName, new Object[] {pair})
.map(s -> mapper.treeToValue(s, BitfinexWebSocketTickerTransaction.class));
return subscribedChannel.map(s -> adaptTicker(s.toBitfinexTicker(), currencyPair));
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
String channelName = "trades";
final String tradeType = args.length > 0 ? args[0].toString() : "te";
String pair = pairToSymbol(currencyPair);
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
Observable<BitfinexWebSocketTradesTransaction> subscribedChannel =
service
.subscribeChannel(channelName, new Object[] {pair})
.filter(s -> s.get(1).asText().equals(tradeType))
.map(
s -> {
if (s.get(1).asText().equals("te") || s.get(1).asText().equals("tu")) {
return mapper.treeToValue(s, BitfinexWebsocketUpdateTrade.class);
} else return mapper.treeToValue(s, BitfinexWebSocketSnapshotTrades.class);
});
return subscribedChannel.flatMapIterable(
s -> {
Trades adaptedTrades = adaptTrades(s.toBitfinexTrades(), currencyPair);
return adaptedTrades.getTrades();
});
}
}
|
String channelName = "book";
final String depth = args.length > 0 ? args[0].toString() : "100";
String pair = pairToSymbol(currencyPair);
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
Observable<BitfinexWebSocketOrderbookTransaction> subscribedChannel =
service
.subscribeChannel(channelName, new Object[] {pair, "P0", depth})
.map(
s -> {
if (s.get(1).get(0).isArray())
return mapper.treeToValue(s, BitfinexWebSocketSnapshotOrderbook.class);
else return mapper.treeToValue(s, BitfinexWebSocketUpdateOrderbook.class);
});
return subscribedChannel.map(
s -> {
BitfinexOrderbook bitfinexOrderbook =
s.toBitfinexOrderBook(orderbooks.getOrDefault(currencyPair, null));
orderbooks.put(currencyPair, bitfinexOrderbook);
return adaptOrderBook(bitfinexOrderbook.toBitfinexDepth(), currencyPair);
});
| 704
| 289
| 993
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketAuthPreTrade.java
|
BitfinexWebSocketAuthPreTrade
|
toString
|
class BitfinexWebSocketAuthPreTrade {
private final long id;
private final String pair;
private final long mtsCreate;
private final long orderId;
private final BigDecimal execAmount;
private final BigDecimal execPrice;
private final String orderType;
private final BigDecimal orderPrice;
private final long maker;
public BitfinexWebSocketAuthPreTrade(
long id,
String pair,
long mtsCreate,
long orderId,
BigDecimal execAmount,
BigDecimal execPrice,
String orderType,
BigDecimal orderPrice,
long maker) {
this.id = id;
this.pair = pair;
this.mtsCreate = mtsCreate;
this.orderId = orderId;
this.execAmount = execAmount;
this.execPrice = execPrice;
this.orderType = orderType;
this.orderPrice = orderPrice;
this.maker = maker;
}
public long getId() {
return id;
}
public String getPair() {
return pair;
}
public long getMtsCreate() {
return mtsCreate;
}
public long getOrderId() {
return orderId;
}
public BigDecimal getExecAmount() {
return execAmount;
}
public BigDecimal getExecPrice() {
return execPrice;
}
public String getOrderType() {
return orderType;
}
public BigDecimal getOrderPrice() {
return orderPrice;
}
public long getMaker() {
return maker;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BitfinexWebSocketAuthPreTrade)) return false;
BitfinexWebSocketAuthPreTrade that = (BitfinexWebSocketAuthPreTrade) o;
return getId() == that.getId()
&& getMtsCreate() == that.getMtsCreate()
&& getOrderId() == that.getOrderId()
&& getMaker() == that.getMaker()
&& Objects.equals(getPair(), that.getPair())
&& Objects.equals(getExecAmount(), that.getExecAmount())
&& Objects.equals(getExecPrice(), that.getExecPrice())
&& Objects.equals(getOrderType(), that.getOrderType())
&& Objects.equals(getOrderPrice(), that.getOrderPrice());
}
@Override
public int hashCode() {
return Objects.hash(
getId(),
getPair(),
getMtsCreate(),
getOrderId(),
getExecAmount(),
getExecPrice(),
getOrderType(),
getOrderPrice(),
getMaker());
}
}
|
return "BitfinexWebSocketAuthPreTrade{"
+ "id="
+ id
+ ", pair='"
+ pair
+ '\''
+ ", mtsCreate="
+ mtsCreate
+ ", orderId="
+ orderId
+ ", execAmount="
+ execAmount
+ ", execPrice="
+ execPrice
+ ", orderType='"
+ orderType
+ '\''
+ ", orderPrice="
+ orderPrice
+ ", maker="
+ maker
+ '}';
| 751
| 147
| 898
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketAuthTrade.java
|
BitfinexWebSocketAuthTrade
|
toString
|
class BitfinexWebSocketAuthTrade extends BitfinexWebSocketAuthPreTrade {
private final BigDecimal fee;
private final String feeCurrency;
public BitfinexWebSocketAuthTrade(
long id,
String pair,
long mtsCreate,
long orderId,
BigDecimal execAmount,
BigDecimal execPrice,
String orderType,
BigDecimal orderPrice,
long maker,
BigDecimal fee,
String feeCurrency) {
super(id, pair, mtsCreate, orderId, execAmount, execPrice, orderType, orderPrice, maker);
this.fee = fee;
this.feeCurrency = feeCurrency;
}
public BigDecimal getFee() {
return fee;
}
public String getFeeCurrency() {
return feeCurrency;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BitfinexWebSocketAuthTrade)) return false;
if (!super.equals(o)) return false;
BitfinexWebSocketAuthTrade that = (BitfinexWebSocketAuthTrade) o;
return Objects.equals(fee, that.fee) && Objects.equals(feeCurrency, that.feeCurrency);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), fee, feeCurrency);
}
}
|
return "BitfinexWebSocketAuthenticatedTrade{"
+ "id="
+ getId()
+ ", pair='"
+ getPair()
+ '\''
+ ", mtsCreate="
+ getMtsCreate()
+ ", orderId="
+ getOrderId()
+ ", execAmount="
+ getExecAmount()
+ ", execPrice="
+ getExecPrice()
+ ", orderType='"
+ getOrderType()
+ '\''
+ ", orderPrice="
+ getOrderPrice()
+ ", maker="
+ getMtsCreate()
+ ", fee="
+ fee
+ ", feeCurrency='"
+ feeCurrency
+ '\''
+ '}';
| 408
| 199
| 607
|
<methods>public void <init>(long, java.lang.String, long, long, java.math.BigDecimal, java.math.BigDecimal, java.lang.String, java.math.BigDecimal, long) ,public boolean equals(java.lang.Object) ,public java.math.BigDecimal getExecAmount() ,public java.math.BigDecimal getExecPrice() ,public long getId() ,public long getMaker() ,public long getMtsCreate() ,public long getOrderId() ,public java.math.BigDecimal getOrderPrice() ,public java.lang.String getOrderType() ,public java.lang.String getPair() ,public int hashCode() ,public java.lang.String toString() <variables>private final non-sealed java.math.BigDecimal execAmount,private final non-sealed java.math.BigDecimal execPrice,private final non-sealed long id,private final non-sealed long maker,private final non-sealed long mtsCreate,private final non-sealed long orderId,private final non-sealed java.math.BigDecimal orderPrice,private final non-sealed java.lang.String orderType,private final non-sealed java.lang.String pair
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketSnapshotTrades.java
|
BitfinexWebSocketSnapshotTrades
|
toBitfinexTrades
|
class BitfinexWebSocketSnapshotTrades extends BitfinexWebSocketTradesTransaction {
public BitfinexWebSocketTrade[] trades;
public BitfinexWebSocketSnapshotTrades() {}
public BitfinexWebSocketSnapshotTrades(String channelId, BitfinexWebSocketTrade[] trades) {
super(channelId);
this.trades = trades;
}
public BitfinexWebSocketTrade[] getTrades() {
return trades;
}
public BitfinexTrade[] toBitfinexTrades() {<FILL_FUNCTION_BODY>}
}
|
List<BitfinexTrade> bitfinexTrades = new ArrayList<>(getTrades().length);
for (BitfinexWebSocketTrade websocketTrade : trades) {
bitfinexTrades.add(websocketTrade.toBitfinexTrade());
}
return bitfinexTrades.toArray(new BitfinexTrade[bitfinexTrades.size()]);
| 160
| 111
| 271
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public java.lang.String getChannelId() ,public abstract org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade[] toBitfinexTrades() <variables>public java.lang.String channelId
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketTickerTransaction.java
|
BitfinexWebSocketTickerTransaction
|
toBitfinexTicker
|
class BitfinexWebSocketTickerTransaction {
public String channelId;
public String[] tickerArr;
public BitfinexWebSocketTickerTransaction() {}
public BitfinexWebSocketTickerTransaction(String channelId, String[] tickerArr) {
this.channelId = channelId;
this.tickerArr = tickerArr;
}
public String getChannelId() {
return channelId;
}
public BitfinexTicker toBitfinexTicker() {<FILL_FUNCTION_BODY>}
}
|
BigDecimal bid = new BigDecimal(tickerArr[0]);
BigDecimal bidSize = new BigDecimal(tickerArr[1]);
BigDecimal ask = new BigDecimal(tickerArr[2]);
BigDecimal askSize = new BigDecimal(tickerArr[3]);
BigDecimal mid = ask.subtract(bid);
BigDecimal low = new BigDecimal(tickerArr[9]);
BigDecimal high = new BigDecimal(tickerArr[8]);
BigDecimal last = new BigDecimal(tickerArr[6]);
// Xchange-bitfinex adapter expects the timestamp to be seconds since Epoch.
double timestamp = System.currentTimeMillis() / 1000;
BigDecimal volume = new BigDecimal(tickerArr[7]);
return new BitfinexTicker(mid, bid, bidSize, ask, askSize, low, high, last, timestamp, volume);
| 150
| 246
| 396
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitfinex/src/main/java/info/bitrich/xchangestream/bitfinex/dto/BitfinexWebSocketTrade.java
|
BitfinexWebSocketTrade
|
toBitfinexTrade
|
class BitfinexWebSocketTrade {
public long tradeId;
public long timestamp;
public BigDecimal amount;
public BigDecimal price;
public BitfinexWebSocketTrade() {}
public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
this.tradeId = tradeId;
this.timestamp = timestamp;
this.amount = amount;
this.price = price;
}
public long getTradeId() {
return tradeId;
}
public long getTimestamp() {
return timestamp;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getPrice() {
return price;
}
public BitfinexTrade toBitfinexTrade() {<FILL_FUNCTION_BODY>}
}
|
String type;
if (amount.compareTo(BigDecimal.ZERO) < 0) {
type = "sell";
} else {
type = "buy";
}
return new BitfinexTrade(price, amount.abs(), timestamp / 1000, "bitfinex", tradeId, type);
| 231
| 89
| 320
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitflyer/src/main/java/info/bitrich/xchangestream/bitflyer/dto/BitflyerMarketEvent.java
|
BitflyerMarketEvent
|
getDate
|
class BitflyerMarketEvent {
protected final String timestamp;
BitflyerMarketEvent(String timestamp) {
this.timestamp = timestamp;
}
public String getTimestamp() {
return timestamp;
}
public Date getDate() {<FILL_FUNCTION_BODY>}
}
|
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(timestamp.substring(0, 23));
} catch (ParseException e) {
e.printStackTrace();
}
return date;
| 81
| 96
| 177
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitflyer/src/main/java/info/bitrich/xchangestream/bitflyer/dto/BitflyerPubNubTickerTransaction.java
|
BitflyerPubNubTickerTransaction
|
toBitflyerTicker
|
class BitflyerPubNubTickerTransaction {
private final String productCode;
private final String timestamp;
private final String tickId;
private final BigDecimal bestBid;
private final BigDecimal bestAsk;
private final BigDecimal bestBidSize;
private final BigDecimal bestAskSize;
private final BigDecimal totalBidDepth;
private final BigDecimal totalAskDepth;
private final String ltp;
private final BigDecimal volume;
private final BigDecimal volumeByProduct;
public BitflyerPubNubTickerTransaction(
@JsonProperty("product_code") String productCode,
@JsonProperty("timestamp") String timestamp,
@JsonProperty("tick_id") String tickId,
@JsonProperty("best_bid") BigDecimal bestBid,
@JsonProperty("best_ask") BigDecimal bestAsk,
@JsonProperty("best_bid_size") BigDecimal bestBidSize,
@JsonProperty("best_ask_size") BigDecimal bestAskSize,
@JsonProperty("total_bid_depth") BigDecimal totalBidDepth,
@JsonProperty("total_ask_depth") BigDecimal totalAskDepth,
@JsonProperty("ltp") String ltp,
@JsonProperty("volume") BigDecimal volume,
@JsonProperty("volume_by_product") BigDecimal volumeByProduct) {
this.productCode = productCode;
this.timestamp = timestamp;
this.tickId = tickId;
this.bestBid = bestBid;
this.bestAsk = bestAsk;
this.bestBidSize = bestBidSize;
this.bestAskSize = bestAskSize;
this.totalBidDepth = totalBidDepth;
this.totalAskDepth = totalAskDepth;
this.ltp = ltp;
this.volume = volume;
this.volumeByProduct = volumeByProduct;
}
public BitflyerTicker toBitflyerTicker() {<FILL_FUNCTION_BODY>}
public String getProductCode() {
return productCode;
}
public String getTimestamp() {
return timestamp;
}
public String getTickId() {
return tickId;
}
public BigDecimal getBestBid() {
return bestBid;
}
public BigDecimal getBestAsk() {
return bestAsk;
}
public BigDecimal getBestBidSize() {
return bestBidSize;
}
public BigDecimal getBestAskSize() {
return bestAskSize;
}
public BigDecimal getTotalBidDepth() {
return totalBidDepth;
}
public BigDecimal getTotalAskDepth() {
return totalAskDepth;
}
public String getLtp() {
return ltp;
}
public BigDecimal getVolume() {
return volume;
}
public BigDecimal getVolumeByProduct() {
return volumeByProduct;
}
}
|
return new BitflyerTicker(
productCode,
timestamp,
tickId,
bestBid,
bestAsk,
bestBidSize,
bestAskSize,
totalBidDepth,
totalAskDepth,
ltp,
volume,
volumeByProduct);
| 783
| 82
| 865
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitflyer/src/main/java/info/bitrich/xchangestream/bitflyer/dto/BitflyerTicker.java
|
BitflyerTicker
|
getCurrencyPair
|
class BitflyerTicker extends BitflyerMarketEvent {
private final String productCode;
private final String tickId;
private final BigDecimal bestBid;
private final BigDecimal bestAsk;
private final BigDecimal bestBidSize;
private final BigDecimal bestAskSize;
private final BigDecimal totalBidDepth;
private final BigDecimal totalAskDepth;
private final String ltp;
private final BigDecimal volume;
private final BigDecimal volumeByProduct;
public BitflyerTicker(
@JsonProperty("product_code") String productCode,
@JsonProperty("timestamp") String timestamp,
@JsonProperty("tick_id") String tickId,
@JsonProperty("best_bid") BigDecimal bestBid,
@JsonProperty("best_ask") BigDecimal bestAsk,
@JsonProperty("best_bid_size") BigDecimal bestBidSize,
@JsonProperty("best_ask_size") BigDecimal bestAskSize,
@JsonProperty("total_bid_depth") BigDecimal totalBidDepth,
@JsonProperty("total_ask_depth") BigDecimal totalAskDepth,
@JsonProperty("ltp") String ltp,
@JsonProperty("volume") BigDecimal volume,
@JsonProperty("volume_by_product") BigDecimal volumeByProduct) {
super(timestamp);
this.productCode = productCode;
this.tickId = tickId;
this.bestBid = bestBid;
this.bestAsk = bestAsk;
this.bestBidSize = bestBidSize;
this.bestAskSize = bestAskSize;
this.totalBidDepth = totalBidDepth;
this.totalAskDepth = totalAskDepth;
this.ltp = ltp;
this.volume = volume;
this.volumeByProduct = volumeByProduct;
}
public String getProductCode() {
return productCode;
}
public String getTickId() {
return tickId;
}
public BigDecimal getBestBid() {
return bestBid;
}
public BigDecimal getBestAsk() {
return bestAsk;
}
public BigDecimal getBestBidSize() {
return bestBidSize;
}
public BigDecimal getBestAskSize() {
return bestAskSize;
}
public BigDecimal getTotalBidDepth() {
return totalBidDepth;
}
public BigDecimal getTotalAskDepth() {
return totalAskDepth;
}
public String getLtp() {
return ltp;
}
public BigDecimal getVolume() {
return volume;
}
public BigDecimal getVolumeByProduct() {
return volumeByProduct;
}
public CurrencyPair getCurrencyPair() {<FILL_FUNCTION_BODY>}
public Ticker toTicker() {
return new Ticker.Builder()
.ask(bestAsk)
.bid(bestBid)
.volume(volume)
.timestamp(getDate())
.currencyPair(getCurrencyPair())
.build();
}
}
|
String[] currencies = productCode.split("_");
String base = currencies[0];
String counter = currencies[1];
return new CurrencyPair(new Currency(base), new Currency(counter));
| 824
| 60
| 884
|
<methods>public java.util.Date getDate() ,public java.lang.String getTimestamp() <variables>protected final non-sealed java.lang.String timestamp
|
knowm_XChange
|
XChange/xchange-stream-bitmex/src/main/java/info/bitrich/xchangestream/bitmex/dto/BitmexOrder.java
|
BitmexOrder
|
toOrder
|
class BitmexOrder extends BitmexMarketDataEvent {
public enum OrderStatus {
NEW,
PARTIALLYFILLED,
FILLED,
TBD,
CANCELED,
REJECTED,
UNKNOW
}
private String orderID;
private int account;
private String side;
private BigDecimal price;
private BigDecimal avgPx;
private String ordType;
private OrderStatus ordStatus;
private String clOrdID;
private BigDecimal orderQty;
private BigDecimal cumQty;
public boolean isNotWorkingIndicator() {
return !workingIndicator;
}
private boolean workingIndicator;
@JsonCreator
public BitmexOrder(
@JsonProperty("symbol") String symbol,
@JsonProperty("timestamp") String timestamp,
@JsonProperty("orderID") String orderID,
@JsonProperty("account") int account,
@JsonProperty("side") String side,
@JsonProperty("price") BigDecimal price,
@JsonProperty("avgPx") BigDecimal avgPx,
@JsonProperty("ordType") String ordType,
@JsonProperty("ordStatus") String ordStatus,
@JsonProperty("clOrdID") String clOrdID,
@JsonProperty("orderQty") BigDecimal orderQty,
@JsonProperty("cumQty") BigDecimal cumQty,
@JsonProperty("workingIndicator") boolean workingIndicator) {
super(symbol, timestamp);
this.orderID = orderID;
this.account = account;
this.side = side;
this.price = price;
this.avgPx = avgPx;
this.ordType = ordType;
try {
this.ordStatus = OrderStatus.valueOf(ordStatus.toUpperCase());
} catch (Exception e) {
this.ordStatus = OrderStatus.UNKNOW;
}
this.clOrdID = clOrdID;
this.orderQty = orderQty;
this.cumQty = cumQty;
this.workingIndicator = workingIndicator;
}
public Order toOrder() {<FILL_FUNCTION_BODY>}
public String getOrderID() {
return orderID;
}
public int getAccount() {
return account;
}
public String getSide() {
return side;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getAvgPx() {
return avgPx;
}
public String getOrdType() {
return ordType;
}
public OrderStatus getOrdStatus() {
return ordStatus;
}
public String getClOrdID() {
return clOrdID;
}
public BigDecimal getOrderQty() {
return orderQty;
}
public BigDecimal getCumQty() {
return cumQty;
}
public boolean isWorkingIndicator() {
return workingIndicator;
}
}
|
Order.Builder order;
if (ordType.equals("Market")) {
order =
new MarketOrder.Builder(
side.equals("Buy") ? Order.OrderType.BID : Order.OrderType.ASK,
new CurrencyPair(symbol.substring(0, 3), symbol.substring(3, symbol.length())));
} else {
order =
new LimitOrder.Builder(
side.equals("Buy") ? Order.OrderType.BID : Order.OrderType.ASK,
new CurrencyPair(symbol.substring(0, 3), symbol.substring(3, symbol.length())));
}
order.id(orderID).averagePrice(avgPx).originalAmount(orderQty).cumulativeAmount(cumQty);
switch (ordStatus) {
case NEW:
order.orderStatus(Order.OrderStatus.NEW);
break;
case PARTIALLYFILLED:
order.orderStatus(Order.OrderStatus.PARTIALLY_FILLED);
break;
case FILLED:
order.orderStatus(Order.OrderStatus.FILLED);
break;
case TBD:
order.orderStatus(Order.OrderStatus.PENDING_CANCEL);
break;
case CANCELED:
order.orderStatus(Order.OrderStatus.CANCELED);
break;
case REJECTED:
order.orderStatus(Order.OrderStatus.REJECTED);
default:
order.orderStatus(Order.OrderStatus.UNKNOWN);
break;
}
if (ordType.equals("Market")) {
return ((MarketOrder.Builder) order).build();
} else {
return ((LimitOrder.Builder) order).build();
}
| 826
| 448
| 1,274
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public org.knowm.xchange.currency.CurrencyPair getCurrencyPair() ,public java.util.Date getDate() ,public java.lang.String getSymbol() ,public java.lang.String getTimestamp() <variables>public static final java.lang.String BITMEX_TIMESTAMP_FORMAT,protected java.lang.String symbol,protected java.lang.String timestamp
|
knowm_XChange
|
XChange/xchange-stream-bitstamp/src/main/java/info/bitrich/xchangestream/bitstamp/v2/BitstampStreamingMarketDataService.java
|
BitstampStreamingMarketDataService
|
mapOrderBookToTicker
|
class BitstampStreamingMarketDataService implements StreamingMarketDataService {
private final BitstampStreamingService service;
public BitstampStreamingMarketDataService(BitstampStreamingService service) {
this.service = service;
}
public Observable<OrderBook> getFullOrderBook(CurrencyPair currencyPair, Object... args) {
return getOrderBook("diff_order_book", currencyPair, args);
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {
return getOrderBook("order_book", currencyPair, args);
}
private Observable<OrderBook> getOrderBook(
String channelPrefix, CurrencyPair currencyPair, Object... args) {
String channelName = channelPrefix + getChannelPostfix(currencyPair);
return service
.subscribeChannel(channelName, BitstampStreamingService.EVENT_ORDERBOOK)
.map(
s -> {
ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
BitstampOrderBook orderBook =
mapper.treeToValue(s.get("data"), BitstampOrderBook.class);
return BitstampAdapters.adaptOrderBook(orderBook, currencyPair);
});
}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
return getOrderBook(currencyPair, args)
.map(orderBook -> mapOrderBookToTicker(currencyPair, orderBook));
}
private Ticker mapOrderBookToTicker(CurrencyPair currencyPair, OrderBook orderBook) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
String channelName = "live_trades" + getChannelPostfix(currencyPair);
return service
.subscribeChannel(channelName, BitstampStreamingService.EVENT_TRADE)
.map(
s -> {
ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
BitstampWebSocketTransaction transactions =
mapper.treeToValue(s.get("data"), BitstampWebSocketTransaction.class);
return BitstampAdapters.adaptTrade(transactions, currencyPair, 1);
});
}
private String getChannelPostfix(CurrencyPair currencyPair) {
return "_"
+ currencyPair.base.toString().toLowerCase()
+ currencyPair.counter.toString().toLowerCase();
}
}
|
final LimitOrder ask = orderBook.getAsks().get(0);
final LimitOrder bid = orderBook.getBids().get(0);
return new Ticker.Builder()
.instrument(currencyPair)
.bid(bid.getLimitPrice())
.bidSize(bid.getOriginalAmount())
.ask(ask.getLimitPrice())
.askSize(ask.getOriginalAmount())
.timestamp(orderBook.getTimeStamp())
.build();
| 648
| 124
| 772
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bitstamp/src/main/java/info/bitrich/xchangestream/bitstamp/v2/BitstampStreamingService.java
|
BitstampStreamingService
|
handleMessage
|
class BitstampStreamingService extends JsonNettyStreamingService {
private static final Logger LOG = LoggerFactory.getLogger(BitstampStreamingService.class);
private static final String JSON_CHANNEL = "channel";
private static final String JSON_EVENT = "event";
public static final String EVENT_ORDERBOOK = "data";
public static final String EVENT_TRADE = "trade";
private static final String EVENT_SUBSCRIPTION_SUCCEEDED = "bts:subscription_succeeded";
private static final String EVENT_UNSUBSCRIPTION_SUCCEEDED = "bts:unsubscription_succeeded";
public BitstampStreamingService(String apiUrl) {
super(apiUrl, Integer.MAX_VALUE);
}
public BitstampStreamingService(
String apiUrl,
int maxFramePayloadLength,
Duration connectionTimeout,
Duration retryDuration,
int idleTimeoutSeconds) {
super(apiUrl, maxFramePayloadLength, connectionTimeout, retryDuration, idleTimeoutSeconds);
}
@Override
protected WebSocketClientExtensionHandler getWebSocketClientExtensionHandler() {
return null;
}
@Override
protected String getChannelNameFromMessage(JsonNode message) throws IOException {
JsonNode jsonNode = message.get(JSON_CHANNEL);
if (jsonNode != null) {
return jsonNode.asText();
}
throw new IOException("Channel name can't be evaluated from message");
}
@Override
protected void handleMessage(JsonNode message) {<FILL_FUNCTION_BODY>}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
BitstampWebSocketSubscriptionMessage subscribeMessage =
generateSubscribeMessage(channelName, "bts:subscribe");
return objectMapper.writeValueAsString(subscribeMessage);
}
@Override
public String getUnsubscribeMessage(String channelName, Object... args) throws IOException {
BitstampWebSocketSubscriptionMessage subscribeMessage =
generateSubscribeMessage(channelName, "bts:unsubscribe");
return objectMapper.writeValueAsString(subscribeMessage);
}
private BitstampWebSocketSubscriptionMessage generateSubscribeMessage(
String channelName, String channel) {
return new BitstampWebSocketSubscriptionMessage(
channel, new BitstampWebSocketData(channelName));
}
}
|
JsonNode channelJsonNode = message.get(JSON_CHANNEL);
JsonNode eventJsonNode = message.get(JSON_EVENT);
if (channelJsonNode == null || eventJsonNode == null) {
LOG.error(
"Received JSON message does not contain {} and {} fields. Skipped...",
JSON_CHANNEL,
JSON_EVENT);
return;
}
String channel = channelJsonNode.asText();
String event = eventJsonNode.asText();
switch (event) {
case EVENT_ORDERBOOK:
case EVENT_TRADE:
if (!channels.containsKey(channel)) {
LOG.warn(
"The message has been received from disconnected channel '{}'. Skipped.", channel);
return;
}
super.handleMessage(message);
break;
case EVENT_SUBSCRIPTION_SUCCEEDED:
LOG.info("Channel {} has been successfully subscribed", channel);
break;
case EVENT_UNSUBSCRIPTION_SUCCEEDED:
LOG.info("Channel {} has been successfully unsubscribed", channel);
break;
default:
LOG.warn("Unsupported event type {} in message {}", event, message.toString());
}
| 622
| 317
| 939
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingExchange.java
|
BTCMarketsStreamingExchange
|
createStreamingService
|
class BTCMarketsStreamingExchange extends BTCMarketsExchange implements StreamingExchange {
private static final String API_URI = "wss://socket.btcmarkets.net/v2";
private BTCMarketsStreamingService streamingService;
private BTCMarketsStreamingMarketDataService streamingMarketDataService;
@Override
protected void initServices() {
super.initServices();
this.streamingService = createStreamingService();
this.streamingMarketDataService = new BTCMarketsStreamingMarketDataService(streamingService);
}
private BTCMarketsStreamingService createStreamingService() {<FILL_FUNCTION_BODY>}
@Override
public Completable connect(ProductSubscription... args) {
return streamingService.connect();
}
@Override
public Completable disconnect() {
return streamingService.disconnect();
}
@Override
public boolean isAlive() {
return streamingService.isSocketOpen();
}
@Override
public Observable<Throwable> reconnectFailure() {
return streamingService.subscribeReconnectFailure();
}
@Override
public Observable<Object> connectionSuccess() {
return streamingService.subscribeConnectionSuccess();
}
@Override
public Observable<State> connectionStateObservable() {
return streamingService.subscribeConnectionState();
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification spec = super.getDefaultExchangeSpecification();
spec.setShouldLoadRemoteMetaData(false);
return spec;
}
@Override
public StreamingMarketDataService getStreamingMarketDataService() {
return streamingMarketDataService;
}
@Override
public void useCompressedMessages(boolean compressedMessages) {
streamingService.useCompressedMessages(compressedMessages);
}
}
|
BTCMarketsStreamingService streamingService = new BTCMarketsStreamingService(API_URI);
applyStreamingSpecification(getExchangeSpecification(), streamingService);
return streamingService;
| 482
| 51
| 533
|
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.ExchangeSpecification getDefaultExchangeSpecification() <variables>
|
knowm_XChange
|
XChange/xchange-stream-btcmarkets/src/main/java/info/bitrich/xchangestream/btcmarkets/BTCMarketsStreamingMarketDataService.java
|
BTCMarketsStreamingMarketDataService
|
getTicker
|
class BTCMarketsStreamingMarketDataService implements StreamingMarketDataService {
private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
private final BTCMarketsStreamingService service;
public BTCMarketsStreamingMarketDataService(BTCMarketsStreamingService service) {
this.service = service;
}
private OrderBook handleOrderbookMessage(BTCMarketsWebSocketOrderbookMessage message)
throws InvalidFormatException {
return BTCMarketsStreamingAdapters.adaptOrderbookMessageToOrderbook(message);
}
private Ticker handleTickerMessage(BTCMarketsWebSocketTickerMessage message)
throws InvalidFormatException {
return BTCMarketsStreamingAdapters.adaptTickerMessageToTicker(message);
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {
final String marketId = BTCMarketsStreamingAdapters.adaptCurrencyPairToMarketId(currencyPair);
return service
.subscribeChannel(CHANNEL_ORDERBOOK, marketId)
.map(node -> mapper.treeToValue(node, BTCMarketsWebSocketOrderbookMessage.class))
.filter(orderEvent -> marketId.equals(orderEvent.marketId))
.map(this::handleOrderbookMessage);
}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
final String marketId = BTCMarketsStreamingAdapters.adaptCurrencyPairToMarketId(currencyPair);
return service
.subscribeChannel(CHANNEL_TRADE, marketId)
.map(node -> mapper.treeToValue(node, BTCMarketsWebSocketTradeMessage.class))
.filter(event -> marketId.equals(event.getMarketId()))
.map(this::handleTradeMessage);
}
private Trade handleTradeMessage(BTCMarketsWebSocketTradeMessage message)
throws InvalidFormatException {
return BTCMarketsStreamingAdapters.adaptTradeMessageToTrade(message);
}
}
|
final String marketId = BTCMarketsStreamingAdapters.adaptCurrencyPairToMarketId(currencyPair);
return service
.subscribeChannel(CHANNEL_TICKER, marketId)
.map(node -> mapper.treeToValue(node, BTCMarketsWebSocketTickerMessage.class))
.filter(tickerEvent -> marketId.equals(tickerEvent.getMarketId()))
.map(this::handleTickerMessage);
| 585
| 119
| 704
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingExchange.java
|
BybitStreamingExchange
|
getApiUrl
|
class BybitStreamingExchange extends BybitExchange implements StreamingExchange {
private final Logger LOG = LoggerFactory.getLogger(BybitStreamingExchange.class);
//https://bybit-exchange.github.io/docs/v5/ws/connect
public static final String URI = "wss://stream.bybit.com/v5/public";
public static final String TESTNET_URI = "wss://stream-testnet.bybit.com/v5/public";
public static final String AUTH_URI = "wss://stream.bybit.com/v5/private";
public static final String TESTNET_AUTH_URI = "wss://stream-testnet.bybit.com/v5/private";
//spot, linear, inverse or option
public static final String EXCHANGE_TYPE = "EXCHANGE_TYPE";
private BybitStreamingService streamingService;
private BybitStreamingMarketDataService streamingMarketDataService;
@Override
protected void initServices() {
super.initServices();
this.streamingService = new BybitStreamingService(getApiUrl(),
exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE));
this.streamingMarketDataService = new BybitStreamingMarketDataService(streamingService);
}
private String getApiUrl() {<FILL_FUNCTION_BODY>}
@Override
public Completable connect(ProductSubscription... args) {
LOG.info("Connect to BybitStream");
return streamingService.connect();
}
@Override
public Completable disconnect() {
streamingService.pingPongDisconnectIfConnected();
return streamingService.disconnect();
}
@Override
public boolean isAlive() {
return streamingService != null && streamingService.isSocketOpen();
}
@Override
public void useCompressedMessages(boolean compressedMessages) {
streamingService.useCompressedMessages(compressedMessages);
}
@Override
public BybitStreamingMarketDataService getStreamingMarketDataService() {
return streamingMarketDataService;
}
}
|
String apiUrl = null;
if (exchangeSpecification.getApiKey() == null) {
if (Boolean.TRUE.equals(
exchangeSpecification.getExchangeSpecificParametersItem(USE_SANDBOX))) {
apiUrl = TESTNET_URI;
} else {
apiUrl = URI;
}
apiUrl += "/" + exchangeSpecification.getExchangeSpecificParametersItem(EXCHANGE_TYPE);
}
// TODO auth
return apiUrl;
| 542
| 126
| 668
|
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.ExchangeSpecification getDefaultExchangeSpecification() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException<variables>private static final java.lang.String BASE_URL,private static final java.lang.String DEMO_URL,public static final java.lang.String SPECIFIC_PARAM_ACCOUNT_TYPE
|
knowm_XChange
|
XChange/xchange-stream-bybit/src/main/java/info/bitrich/xchangestream/bybit/BybitStreamingService.java
|
BybitStreamingService
|
messageHandler
|
class BybitStreamingService extends JsonNettyStreamingService {
private final Logger LOG = LoggerFactory.getLogger(BybitStreamingService.class);
public final String exchange_type;
private final Observable<Long> pingPongSrc = Observable.interval(15, 20, TimeUnit.SECONDS);
private Disposable pingPongSubscription;
public BybitStreamingService(String apiUrl, Object exchange_type) {
super(apiUrl);
this.exchange_type = (String) exchange_type;
// this.setEnableLoggingHandler(true);
}
@Override
public Completable connect() {
Completable conn = super.connect();
return conn.andThen(
(CompletableSource)
(completable) -> {
pingPongDisconnectIfConnected();
pingPongSubscription = pingPongSrc.subscribe(
o -> this.sendMessage("{\"op\":\"ping\"}"));
completable.onComplete();
});
}
@Override
protected String getChannelNameFromMessage(JsonNode message) {
if (message.has("topic")) {
return message.get("topic").asText();
}
return "";
}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
LOG.info(" getSubscribeMessage {}", channelName);
return objectMapper.writeValueAsString(
new BybitSubscribeMessage("subscribe", Collections.singletonList(channelName)));
}
@Override
public String getUnsubscribeMessage(String channelName, Object... args) throws IOException {
LOG.info(" getUnsubscribeMessage {}", channelName);
return objectMapper.writeValueAsString(
new BybitSubscribeMessage("unsubscribe", Collections.singletonList(channelName)));
}
@Override
public void messageHandler(String message) {<FILL_FUNCTION_BODY>}
public void pingPongDisconnectIfConnected() {
if (pingPongSubscription != null && !pingPongSubscription.isDisposed()) {
pingPongSubscription.dispose();
}
}
@Override
protected WebSocketClientExtensionHandler getWebSocketClientExtensionHandler() {
return WebSocketClientCompressionAllowClientNoContextAndServerNoContextHandler.INSTANCE;
}
}
|
LOG.debug("Received message: {}", message);
JsonNode jsonNode;
try {
jsonNode = objectMapper.readTree(message);
} catch (IOException e) {
LOG.error("Error parsing incoming message to JSON: {}", message);
return;
}
String op = "";
boolean success = false;
if (jsonNode.has("op")) {
op = jsonNode.get("op").asText();
}
if (jsonNode.has("success")) {
success = jsonNode.get("success").asBoolean();
}
if (success) {
switch (op) {
case "pong":
case "subscribe":
case "unsubscribe": {
break;
}
}
return;
}
handleMessage(jsonNode);
| 597
| 206
| 803
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/CexioStreamingRawService.java
|
AuthCompletable
|
auth
|
class AuthCompletable implements CompletableOnSubscribe {
private CompletableEmitter completableEmitter;
@Override
public void subscribe(CompletableEmitter e) throws Exception {
this.completableEmitter = e;
}
public void SignalAuthComplete() {
completableEmitter.onComplete();
}
public void SignalError(String error) {
completableEmitter.onError(new IllegalStateException(error));
}
}
@Override
public Completable connect() {
synchronized (authCompletable) {
Completable parentCompletable = super.connect();
parentCompletable.blockingAwait();
return Completable.create(authCompletable);
}
}
@Override
protected void handleMessage(JsonNode message) {
LOG.debug("Receiving message: {}", message);
JsonNode cexioMessage = message.get("e");
try {
if (cexioMessage != null) {
switch (cexioMessage.textValue()) {
case CONNECTED:
auth();
break;
case AUTH:
CexioWebSocketAuthResponse response =
deserialize(message, CexioWebSocketAuthResponse.class);
if (response != null) {
if (response.isSuccess()) {
synchronized (authCompletable) {
authCompletable.SignalAuthComplete();
}
} else {
String authErrorString =
new String("Authentication error: " + response.getData().getError());
LOG.error(authErrorString);
synchronized (authCompletable) {
authCompletable.SignalError(authErrorString);
}
}
}
break;
case PING:
pong();
break;
case ORDER:
try {
CexioWebSocketOrderMessage cexioOrder =
deserialize(message, CexioWebSocketOrderMessage.class);
Order order = CexioAdapters.adaptOrder(cexioOrder.getData());
LOG.debug(String.format("Order is updated: %s", order));
subjectOrder.onNext(order);
} catch (Exception e) {
LOG.error("Order parsing error: {}", e.getMessage(), e);
subjectOrder.onError(e);
}
break;
case TRANSACTION:
try {
CexioWebSocketTransactionMessage transaction =
deserialize(message, CexioWebSocketTransactionMessage.class);
LOG.debug(String.format("New transaction: %s", transaction.getData()));
subjectTransaction.onNext(transaction.getData());
} catch (Exception e) {
LOG.error("Transaction parsing error: {}", e.getMessage(), e);
subjectTransaction.onError(e);
}
break;
case ORDERBOOK:
JsonNode okNode = message.get("ok");
if (okNode.textValue().compareTo("ok") != 0) {
String errorString =
"Error response for order book subscription: %s" + message.toString();
LOG.error(errorString);
subjectOrder.onError(new IllegalArgumentException(errorString));
} else {
super.handleMessage(message);
}
break;
case ORDERBOOK_UPDATE:
super.handleMessage(message);
break;
}
}
} catch (JsonProcessingException e) {
LOG.error("Json parsing error: {}", e.getMessage());
}
}
private void auth() {<FILL_FUNCTION_BODY>
|
if (apiSecret == null || apiKey == null) {
throw new IllegalStateException("API keys must be provided to use cexio streaming exchange");
}
long timestamp = System.currentTimeMillis() / 1000;
CexioDigest cexioDigest = CexioDigest.createInstance(apiSecret);
String signature = cexioDigest.createSignature(timestamp, apiKey);
CexioWebSocketAuthMessage message =
new CexioWebSocketAuthMessage(new CexioWebSocketAuth(apiKey, signature, timestamp));
sendMessage(message);
| 902
| 149
| 1,051
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/dto/CexioWebSocketOrderMessage.java
|
CexioWebSocketOrderMessage
|
toString
|
class CexioWebSocketOrderMessage {
private final String e;
private final CexioWebSocketOrder data;
public CexioWebSocketOrderMessage(
@JsonProperty("e") String e, @JsonProperty("data") CexioWebSocketOrder data) {
this.e = e;
this.data = data;
}
public String getE() {
return e;
}
public CexioWebSocketOrder getData() {
return data;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "CexioWebSocketOrderMessage {" + "e='" + e + '\'' + ", data=" + data + '}';
| 153
| 36
| 189
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/dto/CexioWebSocketPair.java
|
CexioWebSocketPair
|
toString
|
class CexioWebSocketPair {
private final String symbol1;
private final String symbol2;
public CexioWebSocketPair(
@JsonProperty("symbol1") String symbol1, @JsonProperty("symbol2") String symbol2) {
this.symbol1 = symbol1;
this.symbol2 = symbol2;
}
public String getSymbol1() {
return symbol1;
}
public String getSymbol2() {
return symbol2;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "CexioWebSocketPair{"
+ "symbol1='"
+ symbol1
+ '\''
+ ", symbol2='"
+ symbol2
+ '\''
+ '}';
| 150
| 56
| 206
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-cexio/src/main/java/info/bitrich/xchangestream/cexio/dto/CexioWebSocketPongMessage.java
|
CexioWebSocketPongMessage
|
toString
|
class CexioWebSocketPongMessage {
@JsonProperty("e")
private final String e = CexioStreamingRawService.PONG;
public CexioWebSocketPongMessage() {}
public String getE() {
return e;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "CexioWebSocketPongMessage{" + "e='" + e + '\'' + '}';
| 96
| 30
| 126
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingMarketDataService.java
|
CoinjarStreamingMarketDataService
|
handleOrderbookEvent
|
class CoinjarStreamingMarketDataService implements StreamingMarketDataService {
private static final Logger logger =
LoggerFactory.getLogger(CoinjarStreamingMarketDataService.class);
private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
private final CoinjarStreamingService service;
public CoinjarStreamingMarketDataService(CoinjarStreamingService service) {
this.service = service;
}
private static void updateOrderbook(Map<BigDecimal, LimitOrder> book, List<LimitOrder> orders) {
orders.forEach(
order -> {
if (order.getOriginalAmount().compareTo(BigDecimal.ZERO) > 0) {
book.put(order.getLimitPrice(), order);
} else {
book.remove(order.getLimitPrice());
}
});
}
private static OrderBook handleOrderbookEvent(
CoinjarWebSocketBookEvent event,
Map<BigDecimal, LimitOrder> bids,
Map<BigDecimal, LimitOrder> asks) {<FILL_FUNCTION_BODY>}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {
final SortedMap<BigDecimal, LimitOrder> bids =
Maps.newTreeMap((o1, o2) -> Math.negateExact(o1.compareTo(o2)));
final SortedMap<BigDecimal, LimitOrder> asks = Maps.newTreeMap(BigDecimal::compareTo);
String channelName = CoinjarStreamingAdapters.adaptCurrencyPairToBookTopic(currencyPair);
return service
.subscribeChannel(channelName)
.doOnError(
throwable -> {
logger.warn(
"encoutered error while subscribing to channel " + channelName, throwable);
})
.map(
node -> {
CoinjarWebSocketBookEvent orderEvent =
mapper.treeToValue(node, CoinjarWebSocketBookEvent.class);
return handleOrderbookEvent(orderEvent, bids, asks);
})
.filter(orderbook -> !orderbook.getBids().isEmpty() && !orderbook.getAsks().isEmpty());
}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
throw new NotYetImplementedForExchangeException();
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
throw new NotYetImplementedForExchangeException();
}
}
|
final CurrencyPair pairFromEvent =
CoinjarStreamingAdapters.adaptTopicToCurrencyPair(event.topic);
switch (event.event) {
case CoinjarWebSocketBookEvent.UPDATE:
case CoinjarWebSocketBookEvent.INIT:
updateOrderbook(
bids,
CoinjarStreamingAdapters.toLimitOrders(
event.payload.bids, pairFromEvent, Order.OrderType.BID));
updateOrderbook(
asks,
CoinjarStreamingAdapters.toLimitOrders(
event.payload.asks, pairFromEvent, Order.OrderType.ASK));
break;
}
return new OrderBook(
null, Lists.newArrayList(asks.values()), Lists.newArrayList(bids.values()));
| 673
| 206
| 879
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-coinjar/src/main/java/info/bitrich/xchangestream/coinjar/CoinjarStreamingTradeService.java
|
CoinjarStreamingTradeService
|
getUserTrades
|
class CoinjarStreamingTradeService implements StreamingTradeService {
private static final Logger logger = LoggerFactory.getLogger(CoinjarStreamingTradeService.class);
private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
private final CoinjarStreamingService service;
private final String userTradeChannel = "private";
public CoinjarStreamingTradeService(CoinjarStreamingService service) {
this.service = service;
}
@Override
public Observable<UserTrade> getUserTrades(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Order> getOrderChanges(CurrencyPair currencyPair, Object... args) {
return service
.subscribeChannel(userTradeChannel)
.filter(node -> node.get("event").textValue().equals("private:order"))
.map(
node -> {
return mapper.treeToValue(node, CoinjarWebSocketOrderEvent.class);
})
.map(CoinjarStreamingAdapters::adaptOrder)
.filter(order -> currencyPair == null || currencyPair == order.getInstrument());
}
}
|
return service
.subscribeChannel(userTradeChannel)
.filter(node -> node.get("event").textValue().equals("private:fill"))
.map(
node -> {
return mapper.treeToValue(node, CoinjarWebSocketUserTradeEvent.class);
})
.map(CoinjarStreamingAdapters::adaptUserTrade)
.filter(userTrade -> currencyPair == null || currencyPair == userTrade.getInstrument());
| 315
| 124
| 439
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-coinmate/src/main/java/info/bitrich/xchangestream/coinmate/v2/CoinmateStreamingExchange.java
|
CoinmateStreamingExchange
|
createExchange
|
class CoinmateStreamingExchange extends CoinmateExchange implements StreamingExchange {
private static final String API_BASE = "wss://coinmate.io/api/websocket";
private CoinmateStreamingService streamingService;
private CoinmateStreamingMarketDataService streamingMarketDataService;
private CoinmateStreamingAccountService streamingAccountService;
private CoinmateStreamingTradeService streamingTradeService;
public CoinmateStreamingExchange() {}
private void createExchange() {<FILL_FUNCTION_BODY>}
@Override
protected void initServices() {
super.initServices();
createExchange();
streamingMarketDataService = new CoinmateStreamingMarketDataService(streamingService);
streamingAccountService = new CoinmateStreamingAccountService(streamingService);
streamingTradeService = new CoinmateStreamingTradeService(streamingService);
}
@Override
public Completable connect(ProductSubscription... args) {
return streamingService.connect();
}
@Override
public Completable disconnect() {
return streamingService.disconnect();
}
@Override
public StreamingMarketDataService getStreamingMarketDataService() {
return streamingMarketDataService;
}
@Override
public StreamingTradeService getStreamingTradeService() {
return streamingTradeService;
}
@Override
public StreamingAccountService getStreamingAccountService() {
return streamingAccountService;
}
@Override
public boolean isAlive() {
return streamingService.isSocketOpen();
}
@Override
public void useCompressedMessages(boolean compressedMessages) {}
}
|
AuthParams authParams;
if (exchangeSpecification.getApiKey() != null) {
authParams =
new AuthParams(
exchangeSpecification.getSecretKey(),
exchangeSpecification.getApiKey(),
exchangeSpecification.getUserName(),
getNonceFactory());
} else {
authParams = null;
}
streamingService = new CoinmateStreamingService(API_BASE, authParams);
applyStreamingSpecification(getExchangeSpecification(), streamingService);
| 433
| 129
| 562
|
<methods>public non-sealed void <init>() ,public org.knowm.xchange.ExchangeSpecification getDefaultExchangeSpecification() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException<variables>
|
knowm_XChange
|
XChange/xchange-stream-coinmate/src/main/java/info/bitrich/xchangestream/coinmate/v2/CoinmateStreamingMarketDataService.java
|
CoinmateStreamingMarketDataService
|
getOrderBook
|
class CoinmateStreamingMarketDataService implements StreamingMarketDataService {
private final CoinmateStreamingService coinmateStreamingService;
CoinmateStreamingMarketDataService(CoinmateStreamingService coinmateStreamingService) {
this.coinmateStreamingService = coinmateStreamingService;
}
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
String channelName = "statistics-" + CoinmateStreamingAdapter.getChannelPostfix(currencyPair);
ObjectReader reader =
StreamingObjectMapperHelper.getObjectMapper().readerFor(CoinmateTradeStatistics.class);
return coinmateStreamingService
.subscribeChannel(channelName)
.map(
s -> {
CoinmateTradeStatistics tradeStatistics = reader.readValue(s.get("payload"));
return CoinmateAdapters.adaptTradeStatistics(tradeStatistics, currencyPair);
});
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
String channelName = "trades-" + CoinmateStreamingAdapter.getChannelPostfix(currencyPair);
ObjectReader reader =
StreamingObjectMapperHelper.getObjectMapper()
.readerFor(new TypeReference<List<CoinmateWebSocketTrade>>() {});
return coinmateStreamingService
.subscribeChannel(channelName)
.map(s -> reader.<List<CoinmateWebSocketTrade>>readValue(s.get("payload")))
.flatMapIterable(coinmateWebSocketTrades -> coinmateWebSocketTrades)
.map(
coinmateWebSocketTrade ->
CoinmateStreamingAdapter.adaptTrade(coinmateWebSocketTrade, currencyPair));
}
}
|
String channelName = "order_book-" + CoinmateStreamingAdapter.getChannelPostfix(currencyPair);
ObjectReader reader =
StreamingObjectMapperHelper.getObjectMapper().readerFor(CoinmateOrderBookData.class);
return coinmateStreamingService
.subscribeChannel(channelName)
.map(
s -> {
CoinmateOrderBookData orderBookData = reader.readValue(s.get("payload"));
CoinmateOrderBook coinmateOrderBook =
new CoinmateOrderBook(false, null, orderBookData);
return CoinmateAdapters.adaptOrderBook(coinmateOrderBook, currencyPair);
});
| 504
| 169
| 673
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-coinmate/src/main/java/info/bitrich/xchangestream/coinmate/v2/CoinmateStreamingService.java
|
CoinmateStreamingService
|
getChannelNameFromMessage
|
class CoinmateStreamingService extends JsonNettyStreamingService {
private static final Logger LOG = LoggerFactory.getLogger(CoinmateStreamingService.class);
private final AuthParams authParams;
CoinmateStreamingService(String url, AuthParams authParams) {
super(url);
this.authParams = authParams;
}
@Override
protected String getChannelNameFromMessage(JsonNode message) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
if (args.length > 0 && args[0].equals(true)) {
return objectMapper.writeValueAsString(generateAuthenticatedSubscribeMessage(channelName));
} else {
return objectMapper.writeValueAsString(generateSubscribeMessage(channelName));
}
}
@Override
public String getUnsubscribeMessage(String channelName, Object... args) throws IOException {
return objectMapper.writeValueAsString(generateUnsubscribeMessage(channelName));
}
@Override
protected void handleIdle(ChannelHandlerContext ctx) {
// the default zero frame is not handled by Coinmate API, use ping message instead
try {
ctx.writeAndFlush(
new TextWebSocketFrame(objectMapper.writeValueAsString(new CoinmatePingMessage())));
} catch (JsonProcessingException e) {
LOG.error("Failed to write ping message.");
}
}
private CoinmateSubscribeMessage generateSubscribeMessage(String channelName) {
return new CoinmateSubscribeMessage(channelName);
}
private CoinmateAuthenticedSubscribeMessage generateAuthenticatedSubscribeMessage(
String channelName) {
return new CoinmateAuthenticedSubscribeMessage(channelName, authParams);
}
private CoinmateUnsubscribeMessage generateUnsubscribeMessage(String channelName) {
return new CoinmateUnsubscribeMessage(channelName);
}
/**
* @return Client ID needed for private channel
*/
String getUserId() {
return authParams.getUserId();
}
}
|
String event = message.get("event").asText();
if (!"data".equals(event)) {
return null;
}
return message.get("channel").asText();
| 540
| 49
| 589
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-coinmate/src/main/java/info/bitrich/xchangestream/coinmate/v2/dto/CoinmateWebsocketBalance.java
|
CoinmateWebsocketBalance
|
toString
|
class CoinmateWebsocketBalance {
@JsonProperty("balance")
private final BigDecimal balance;
@JsonProperty("reserved")
private final BigDecimal reserved;
@JsonCreator
public CoinmateWebsocketBalance(
@JsonProperty("balance") BigDecimal balance, @JsonProperty("reserved") BigDecimal reserved) {
this.balance = balance;
this.reserved = reserved;
}
public BigDecimal getBalance() {
return this.balance;
}
public BigDecimal getReserved() {
return this.reserved;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "CoinmateWebsocketBalance{" + "balance=" + balance + ", reserved=" + reserved + '}';
| 185
| 34
| 219
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/dto/v1/dydxInitialOrderBookMessage.java
|
Order
|
toOrderBook
|
class Order {
@JsonProperty("id")
private String id;
@JsonProperty("uuid")
private String uuid;
@JsonProperty("price")
private String price;
@JsonProperty("amount")
private String amount;
}
public OrderBook toOrderBook(
SortedMap<BigDecimal, BigDecimal> bids,
SortedMap<BigDecimal, BigDecimal> asks,
Map<String, String> bidIds,
Map<String, String> askIds,
int maxDepth,
CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>
|
String[][] bidsData = null;
String[][] asksData = null;
if (this.contents.getBids() != null) {
bidsData =
Arrays.stream(this.contents.getBids())
.map(
b -> {
bidIds.put(b.id, b.price);
return new String[] {b.price, b.amount};
})
.toArray(String[][]::new);
}
if (this.contents.getAsks() != null) {
asksData =
Arrays.stream(this.contents.getAsks())
.map(
a -> {
askIds.put(a.id, a.price);
return new String[] {a.price, a.amount};
})
.toArray(String[][]::new);
}
List<LimitOrder> dydxBids =
dydxOrderBookChanges(
org.knowm.xchange.dto.Order.OrderType.BID,
currencyPair,
bidsData,
bids,
maxDepth,
true);
List<LimitOrder> dydxAsks =
dydxOrderBookChanges(
org.knowm.xchange.dto.Order.OrderType.ASK,
currencyPair,
asksData,
asks,
maxDepth,
true);
return new OrderBook(null, dydxBids, dydxAsks, false);
| 158
| 379
| 537
|
<methods>public non-sealed void <init>() <variables>private java.lang.String channel,private java.lang.String connectionId,private java.lang.String id,private java.lang.String messageId,private java.lang.String type
|
knowm_XChange
|
XChange/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/dto/v3/dydxInitialOrderBookMessage.java
|
Order
|
toOrderBook
|
class Order {
@JsonProperty("price")
private String price;
@JsonProperty("size")
private String size;
}
public OrderBook toOrderBook(
SortedMap<BigDecimal, BigDecimal> bids,
SortedMap<BigDecimal, BigDecimal> asks,
int maxDepth,
CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>
|
String[][] bidsData = null;
String[][] asksData = null;
if (this.contents.getBids() != null) {
bidsData =
Arrays.stream(this.contents.getBids())
.map(b -> new String[] {b.price, b.size})
.toArray(String[][]::new);
}
if (this.contents.getAsks() != null) {
asksData =
Arrays.stream(this.contents.getAsks())
.map(a -> new String[] {a.price, a.size})
.toArray(String[][]::new);
}
List<LimitOrder> dydxBids =
dydxOrderBookChanges(
org.knowm.xchange.dto.Order.OrderType.BID,
currencyPair,
bidsData,
bids,
maxDepth,
false);
List<LimitOrder> dydxAsks =
dydxOrderBookChanges(
org.knowm.xchange.dto.Order.OrderType.ASK,
currencyPair,
asksData,
asks,
maxDepth,
false);
return new OrderBook(null, dydxBids, dydxAsks, false);
| 105
| 331
| 436
|
<methods>public non-sealed void <init>() <variables>private java.lang.String channel,private java.lang.String connectionId,private java.lang.String id,private java.lang.String messageId,private java.lang.String type
|
knowm_XChange
|
XChange/xchange-stream-dydx/src/main/java/info/bitrich/xchangestream/dydx/dydxStreamingService.java
|
dydxStreamingService
|
handleOrderbookMessage
|
class dydxStreamingService extends JsonNettyStreamingService {
private static final Logger LOG = LoggerFactory.getLogger(dydxStreamingService.class);
private static final String SUBSCRIBE = "subscribe";
private static final String UNSUBSCRIBE = "unsubscribe";
private static final String CHANNEL = "channel";
private static final String ID = "id";
public static final String SUBSCRIBED = "subscribed";
public static final String CHANNEL_DATA = "channel_data";
public static final String V3_ORDERBOOK = "v3_orderbook";
public static final String V3_TRADES = "v3_trades";
public static final String V3_ACCOUNTS = "v3_accounts";
public static final String V3_MARKETS = "v3_markets";
public static final String V1_ORDERBOOK = "orderbook";
public static final String V1_TRADES = "trades";
public static final String V1_ACCOUNTS = "accounts";
public static final String V1_MARKETS = "markets";
public static final String ORDERBOOK = "orderbook";
private final String apiUri;
private ProductSubscription productSubscription;
private final Map<String, Observable<JsonNode>> subscriptions = new ConcurrentHashMap<>();
public dydxStreamingService(String apiUri) {
super(apiUri, Integer.MAX_VALUE);
this.apiUri = apiUri;
}
@Override
protected String getChannelNameFromMessage(JsonNode message) {
return message.has(CHANNEL) && message.has(ID)
? String.format("%s-%s", message.get(CHANNEL).asText(), message.get(ID).asText())
: "";
}
public ProductSubscription getProduct() {
return productSubscription;
}
public void subscribeMultipleCurrencyPairs(ProductSubscription... products) {
this.productSubscription = products[0];
}
/**
* Creates an observable of a channel using the baseChannelName and currencyPair. For example,
* subscribing to the trades channel for WETH/USDC will create a new channel "trades-WETH-USDC".
*
* @param currencyPair any currency pair supported by dydx
* @param baseChannelName e.g. "orderbook", "v3_orderbook", etc.
* @return
*/
public Observable<dydxWebSocketTransaction> getRawWebsocketTransactions(
CurrencyPair currencyPair, String baseChannelName) {
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
String currencyPairChannelName =
String.format("%s-%s", baseChannelName, currencyPair.toString().replace('/', '-'));
return subscribeChannel(currencyPairChannelName, currencyPair)
.map(
msg -> {
switch (baseChannelName) {
case V1_ORDERBOOK:
case V3_ORDERBOOK:
return handleOrderbookMessage(currencyPairChannelName, objectMapper, msg);
}
return mapper.treeToValue(msg, dydxWebSocketTransaction.class);
})
.filter(t -> currencyPair.equals(new CurrencyPair(t.getId())))
.filter(t -> baseChannelName.equals(t.getChannel()));
}
private dydxWebSocketTransaction handleOrderbookMessage(
String orderBookChannel, ObjectMapper mapper, JsonNode msg) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public Observable<JsonNode> subscribeChannel(String channelName, Object... args) {
if (!channels.containsKey(channelName) && !subscriptions.containsKey(channelName)) {
subscriptions.put(channelName, super.subscribeChannel(channelName, args));
}
return subscriptions.get(channelName);
}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
final CurrencyPair currencyPair =
(args.length > 0 && args[0] instanceof CurrencyPair) ? ((CurrencyPair) args[0]) : null;
if (channelName.contains(ORDERBOOK)) {
if (productSubscription != null && productSubscription.getOrderBook() != null) {
return objectMapper.writeValueAsString(
new dydxWebSocketSubscriptionMessage(
SUBSCRIBE,
channelName.contains(V3_ORDERBOOK) ? V3_ORDERBOOK : ORDERBOOK,
currencyPair.toString().replace('/', '-')));
}
}
return null;
}
@Override
public String getUnsubscribeMessage(String channelName, Object... args) throws IOException {
return null;
}
}
|
if (orderBookChannel.contains(V3_ORDERBOOK)) {
switch (msg.get("type").asText()) {
case SUBSCRIBED:
return mapper.treeToValue(msg, dydxInitialOrderBookMessage.class);
case CHANNEL_DATA:
return mapper.treeToValue(msg, dydxUpdateOrderBookMessage.class);
}
}
if (orderBookChannel.contains(V1_ORDERBOOK)) {
switch (msg.get("type").asText()) {
case SUBSCRIBED:
return mapper.treeToValue(
msg, info.bitrich.xchangestream.dydx.dto.v1.dydxInitialOrderBookMessage.class);
case CHANNEL_DATA:
return mapper.treeToValue(
msg, info.bitrich.xchangestream.dydx.dto.v1.dydxUpdateOrderBookMessage.class);
}
}
return mapper.treeToValue(msg, dydxWebSocketTransaction.class);
| 1,225
| 272
| 1,497
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAdapters.java
|
GateioStreamingAdapters
|
toOrderBook
|
class GateioStreamingAdapters {
public Ticker toTicker(GateioTickerNotification notification) {
TickerPayload tickerPayload = notification.getResult();
return new Ticker.Builder()
.timestamp(Date.from(notification.getTimeMs()))
.instrument(tickerPayload.getCurrencyPair())
.last(tickerPayload.getLastPrice())
.ask(tickerPayload.getLowestAsk())
.bid(tickerPayload.getHighestBid())
.percentageChange(tickerPayload.getChangePercent24h())
.volume(tickerPayload.getBaseVolume())
.quoteVolume(tickerPayload.getQuoteVolume())
.high(tickerPayload.getHighPrice24h())
.low(tickerPayload.getLowPrice24h())
.build();
}
public Trade toTrade(GateioTradeNotification notification) {
TradePayload tradePayload = notification.getResult();
return new Trade.Builder()
.type(tradePayload.getSide())
.originalAmount(tradePayload.getAmount())
.instrument(tradePayload.getCurrencyPair())
.price(tradePayload.getPrice())
.timestamp(Date.from(tradePayload.getTimeMs()))
.id(String.valueOf(tradePayload.getId()))
.build();
}
public UserTrade toUserTrade(GateioSingleUserTradeNotification notification) {
UserTradePayload userTradePayload = notification.getResult();
return new UserTrade.Builder()
.type(userTradePayload.getSide())
.originalAmount(userTradePayload.getAmount())
.instrument(userTradePayload.getCurrencyPair())
.price(userTradePayload.getPrice())
.timestamp(Date.from(userTradePayload.getTimeMs()))
.id(String.valueOf(userTradePayload.getId()))
.orderId(String.valueOf(userTradePayload.getOrderId()))
.feeAmount(userTradePayload.getFee())
.feeCurrency(userTradePayload.getFeeCurrency())
.orderUserReference(userTradePayload.getRemark())
.build();
}
public Balance toBalance(GateioSingleSpotBalanceNotification notification) {
BalancePayload balancePayload = notification.getResult();
return new Balance.Builder()
.currency(balancePayload.getCurrency())
.total(balancePayload.getTotal())
.available(balancePayload.getAvailable())
.frozen(balancePayload.getFreeze())
.timestamp(Date.from(balancePayload.getTimeMs()))
.build();
}
public OrderBook toOrderBook(GateioOrderBookNotification notification) {<FILL_FUNCTION_BODY>}
}
|
OrderBookPayload orderBookPayload = notification.getResult();
Stream<LimitOrder> asks = orderBookPayload.getAsks().stream()
.map(priceSizeEntry -> new LimitOrder(OrderType.ASK, priceSizeEntry.getSize(), orderBookPayload.getCurrencyPair(), null, null, priceSizeEntry.getPrice()));
Stream<LimitOrder> bids = orderBookPayload.getAsks().stream()
.map(priceSizeEntry -> new LimitOrder(OrderType.BID, priceSizeEntry.getSize(), orderBookPayload.getCurrencyPair(), null, null, priceSizeEntry.getPrice()));
return new OrderBook(Date.from(orderBookPayload.getTimestamp()), asks, bids);
| 762
| 184
| 946
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingAuthHelper.java
|
GateioStreamingAuthHelper
|
sign
|
class GateioStreamingAuthHelper {
private final GateioV4Digest gateioV4Digest;
public GateioStreamingAuthHelper(String apiSecret) {
gateioV4Digest = GateioV4Digest.createInstance(apiSecret);
}
/**
* Generates signature based on payload
*/
public String sign(String channel, String event, String timestamp) {<FILL_FUNCTION_BODY>}
}
|
Mac mac = gateioV4Digest.getMac();
String payloadToSign = String.format("channel=%s&event=%s&time=%s", channel, event, timestamp);
mac.update(payloadToSign.getBytes(StandardCharsets.UTF_8));
return DigestUtils.bytesToHex(mac.doFinal());
| 116
| 91
| 207
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-gateio/src/main/java/info/bitrich/xchangestream/gateio/GateioStreamingMarketDataService.java
|
GateioStreamingMarketDataService
|
getOrderBook
|
class GateioStreamingMarketDataService implements StreamingMarketDataService {
public static final int MAX_DEPTH_DEFAULT = 5;
public static final int UPDATE_INTERVAL_DEFAULT = 100;
private final GateioStreamingService service;
public GateioStreamingMarketDataService(GateioStreamingService service) {
this.service = service;
}
/**
* Uses the limited-level snapshot method:
* https://www.gate.io/docs/apiv4/ws/index.html#limited-level-full-order-book-snapshot
*
* @param currencyPair Currency pair of the order book
* @param args Order book level: {@link Integer}, update speed: {@link Duration}
*/
@Override
public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) {
return service
.subscribeChannel(Config.SPOT_TICKERS_CHANNEL, currencyPair)
.map(GateioTickerNotification.class::cast)
.map(GateioStreamingAdapters::toTicker);
}
@Override
public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {
return service
.subscribeChannel(Config.SPOT_TRADES_CHANNEL, currencyPair)
.map(GateioTradeNotification.class::cast)
.map(GateioStreamingAdapters::toTrade);
}
}
|
Integer orderBookLevel = (Integer) ArrayUtils.get(args, 0, MAX_DEPTH_DEFAULT);
Duration updateSpeed = (Duration) ArrayUtils.get(args, 1, UPDATE_INTERVAL_DEFAULT);
return service
.subscribeChannel(Config.SPOT_ORDERBOOK_CHANNEL, new Object[]{currencyPair, orderBookLevel, updateSpeed})
.map(GateioOrderBookNotification.class::cast)
.map(GateioStreamingAdapters::toOrderBook);
| 422
| 129
| 551
|
<no_super_class>
|
knowm_XChange
|
XChange/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingExchange.java
|
GeminiStreamingExchange
|
connect
|
class GeminiStreamingExchange extends GeminiExchange implements StreamingExchange {
private static final String API_V2_URI = "wss://api.gemini.com/v2/marketdata/";
private GeminiStreamingService streamingService;
private GeminiStreamingMarketDataService streamingMarketDataService;
public GeminiStreamingExchange() {}
@Override
protected void initServices() {
super.initServices();
}
@Override
public Completable connect(ProductSubscription... args) {<FILL_FUNCTION_BODY>}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification spec = super.getDefaultExchangeSpecification();
spec.setShouldLoadRemoteMetaData(false);
return spec;
}
@Override
public Completable disconnect() {
GeminiStreamingService service = streamingService;
streamingService = null;
streamingMarketDataService = null;
return service.disconnect();
}
@Override
public StreamingMarketDataService getStreamingMarketDataService() {
return streamingMarketDataService;
}
@Override
public Observable<State> connectionStateObservable() {
return streamingService.subscribeConnectionState();
}
@Override
public boolean isAlive() {
return streamingService != null && streamingService.isSocketOpen();
}
@Override
public void useCompressedMessages(boolean compressedMessages) {
throw new NotYetImplementedForExchangeException();
}
}
|
if (args == null || args.length == 0)
throw new UnsupportedOperationException("The ProductSubscription must be defined!");
ExchangeSpecification exchangeSpec = getExchangeSpecification();
this.streamingService = new GeminiStreamingService(API_V2_URI);
applyStreamingSpecification(exchangeSpec, this.streamingService);
this.streamingMarketDataService = new GeminiStreamingMarketDataService(streamingService);
streamingService.subscribeMultipleCurrencyPairs(args);
return streamingService.connect();
| 400
| 141
| 541
|
<methods>public non-sealed void <init>() ,public void applySpecification(org.knowm.xchange.ExchangeSpecification) ,public org.knowm.xchange.ExchangeSpecification getDefaultExchangeSpecification() ,public org.knowm.xchange.ExchangeSpecification getExchangeSpecification() ,public void remoteInit() throws java.io.IOException, org.knowm.xchange.exceptions.ExchangeException<variables>
|
knowm_XChange
|
XChange/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingService.java
|
GeminiStreamingService
|
subscribeChannel
|
class GeminiStreamingService extends JsonNettyStreamingService {
private static final Logger LOG = LoggerFactory.getLogger(GeminiStreamingService.class);
private static final String SHARE_CHANNEL_NAME = "ALL";
private static final String SUBSCRIBE = "subscribe";
private static final String UNSUBSCRIBE = "unsubscribe";
private final Map<String, Observable<JsonNode>> subscriptions = new ConcurrentHashMap<>();
private ProductSubscription product = null;
public GeminiStreamingService(String baseUri) {
super(baseUri, Integer.MAX_VALUE);
}
public ProductSubscription getProduct() {
return this.product;
}
public Observable<GeminiWebSocketTransaction> getRawWebSocketTransactions(
CurrencyPair currencyPair, boolean filterChannelName) {
String channelName = currencyPair.base.toString() + currencyPair.counter.toString();
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper();
return subscribeChannel(channelName)
.map(s -> mapper.treeToValue(s, GeminiWebSocketTransaction.class))
.filter(t -> channelName.equals(t.getSymbol()))
.filter(t -> !StringUtil.isNullOrEmpty(t.getType()));
}
public void subscribeMultipleCurrencyPairs(ProductSubscription... products) {
this.product = products[0];
}
@Override
public Observable<JsonNode> subscribeChannel(String channelName, Object... args) {<FILL_FUNCTION_BODY>}
@Override
public boolean processArrayMessageSeparately() {
return false;
}
@Override
protected String getChannelNameFromMessage(JsonNode message) throws IOException {
return SHARE_CHANNEL_NAME;
}
@Override
public String getSubscribeMessage(String channelName, Object... args) throws IOException {
return objectMapper.writeValueAsString(
new GeminiWebSocketSubscriptionMessage(SUBSCRIBE, product));
}
@Override
public String getUnsubscribeMessage(String channelName, Object... args) throws IOException {
return objectMapper.writeValueAsString(
new GeminiWebSocketSubscriptionMessage(UNSUBSCRIBE, product));
}
}
|
channelName = SHARE_CHANNEL_NAME;
if (!channels.containsKey(channelName) && !subscriptions.containsKey(channelName)) {
subscriptions.put(channelName, super.subscribeChannel(channelName, args));
}
return subscriptions.get(channelName);
| 584
| 79
| 663
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
|
knowm_XChange
|
XChange/xchange-stream-gemini-v2/src/main/java/info/bitrich/xchangestream/gemini/dto/GeminiWebSocketTransaction.java
|
GeminiWebSocketTransaction
|
toOrderBook
|
class GeminiWebSocketTransaction {
private String type;
private String symbol;
private String[][] changes;
private JsonNode trades;
private JsonNode auctionEvents;
public GeminiWebSocketTransaction(
@JsonProperty("type") String type,
@JsonProperty("symbol") String symbol,
@JsonProperty("changes") String[][] changes,
@JsonProperty("trades") JsonNode trades,
@JsonProperty("auction_events") JsonNode auctionEvents) {
this.type = type;
this.symbol = symbol;
this.changes = changes;
this.trades = trades;
this.auctionEvents = auctionEvents;
}
public String getType() {
return type;
}
public String getSymbol() {
return symbol;
}
public String[][] getChanges() {
return changes;
}
public JsonNode getTrades() {
return trades;
}
public JsonNode getAuctionEvents() {
return auctionEvents;
}
private List<LimitOrder> geminiOrderBookChanges(
String side,
Order.OrderType orderType,
CurrencyPair currencyPair,
String[][] changes,
SortedMap<BigDecimal, BigDecimal> sideEntries,
int maxDepth) {
if (changes.length == 0) {
return Collections.emptyList();
}
if (sideEntries == null) {
return Collections.emptyList();
}
for (String[] level : changes) {
if (level.length == 3 && !level[0].equals(side)) {
continue;
}
BigDecimal price = new BigDecimal(level[level.length - 2]);
BigDecimal volume = new BigDecimal(level[level.length - 1]);
sideEntries.put(price, volume);
}
Stream<Map.Entry<BigDecimal, BigDecimal>> stream =
sideEntries.entrySet().stream()
.filter(level -> level.getValue().compareTo(BigDecimal.ZERO) != 0);
if (maxDepth != 0) {
stream = stream.limit(maxDepth);
}
return stream
.map(
level ->
new LimitOrder(
orderType, level.getValue(), currencyPair, "0", null, level.getKey()))
.collect(Collectors.toList());
}
public OrderBook toOrderBook(
SortedMap<BigDecimal, BigDecimal> bids,
SortedMap<BigDecimal, BigDecimal> asks,
int maxDepth,
CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>}
}
|
// For efficiency, we go straight to XChange format
List<LimitOrder> orderBookBids =
geminiOrderBookChanges(
"buy",
Order.OrderType.BID,
currencyPair,
changes != null ? changes : null,
bids,
maxDepth);
List<LimitOrder> orderBookAsks =
geminiOrderBookChanges(
"sell",
Order.OrderType.ASK,
currencyPair,
changes != null ? changes : null,
asks,
maxDepth);
return new OrderBook(null, orderBookAsks, orderBookBids, false);
| 686
| 161
| 847
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.