Skip to content

Commit

Permalink
#137 : Enabled balance info test + try-mode adapter code polish
Browse files Browse the repository at this point in the history
  • Loading branch information
gazbert committed Apr 2, 2022
1 parent 9b935eb commit 6620753
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public MarketOrderBook getMarketOrders(String marketId)
public List<OpenOrder> getYourOpenOrders(String marketId)
throws ExchangeNetworkException, TradingApiException {
checkOpenOrderExecution(marketId);
LinkedList<OpenOrder> result = new LinkedList<>();
final List<OpenOrder> result = new LinkedList<>();
if (currentOpenOrder != null) {
result.add(currentOpenOrder);
LOG.info(() -> "getYourOpenOrders: Found an open DUMMY order: " + currentOpenOrder);
Expand All @@ -128,9 +128,9 @@ public String createOrder(
throw new TradingApiException(
"Can only record/execute one order at a time. Wait for the open order to fulfill");
}
String newOrderId = "DUMMY_" + orderType + "_ORDER_ID_" + System.currentTimeMillis();
Date creationDate = new Date();
BigDecimal total = price.multiply(quantity);
final String newOrderId = "DUMMY_" + orderType + "_ORDER_ID_" + System.currentTimeMillis();
final Date creationDate = new Date();
final BigDecimal total = price.multiply(quantity);
currentOpenOrder =
new OpenOrderImpl(
newOrderId, creationDate, marketId, orderType, price, quantity, quantity, total);
Expand Down Expand Up @@ -169,11 +169,11 @@ public BigDecimal getLatestMarketPrice(String marketId)
}

@Override
public BalanceInfo getBalanceInfo() throws ExchangeNetworkException, TradingApiException {
HashMap<String, BigDecimal> availableBalances = new HashMap<>();
public BalanceInfo getBalanceInfo() {
final HashMap<String, BigDecimal> availableBalances = new HashMap<>();
availableBalances.put(simulatedBaseCurrency, baseCurrencyBalance);
availableBalances.put(simulatedCounterCurrency, counterCurrencyBalance);
BalanceInfoImpl currentBalance = new BalanceInfoImpl(availableBalances, new HashMap<>());
final BalanceInfo currentBalance = new BalanceInfoImpl(availableBalances, new HashMap<>());
LOG.info(() -> "Return the following simulated balances: " + currentBalance);
return currentBalance;
}
Expand Down Expand Up @@ -296,15 +296,16 @@ private void checkOpenOrderExecution(String marketId)

private void checkOpenSellOrderExecution(String marketId)
throws TradingApiException, ExchangeNetworkException {
BigDecimal currentBidPrice = getTicker(marketId).getBid();
final BigDecimal currentBidPrice = getTicker(marketId).getBid();
if (currentBidPrice.compareTo(currentOpenOrder.getPrice()) >= 0) {
LOG.info(
"SELL: the market's bid price moved above the limit price "
+ "--> record sell order execution with the current bid price");
BigDecimal orderPrice = currentOpenOrder.getOriginalQuantity().multiply(currentBidPrice);
BigDecimal buyFees =
final BigDecimal orderPrice =
currentOpenOrder.getOriginalQuantity().multiply(currentBidPrice);
final BigDecimal buyFees =
getPercentageOfSellOrderTakenForExchangeFee(marketId).multiply(orderPrice);
BigDecimal netOrderPrice = orderPrice.subtract(buyFees);
final BigDecimal netOrderPrice = orderPrice.subtract(buyFees);
counterCurrencyBalance = counterCurrencyBalance.add(netOrderPrice);
baseCurrencyBalance = baseCurrencyBalance.subtract(currentOpenOrder.getOriginalQuantity());
currentOpenOrder = null;
Expand All @@ -313,15 +314,16 @@ private void checkOpenSellOrderExecution(String marketId)

private void checkOpenBuyOrderExecution(String marketId)
throws TradingApiException, ExchangeNetworkException {
BigDecimal currentAskPrice = getTicker(marketId).getAsk();
final BigDecimal currentAskPrice = getTicker(marketId).getAsk();
if (currentAskPrice.compareTo(currentOpenOrder.getPrice()) <= 0) {
LOG.info(
"BUY: the market's current ask price moved below the limit price "
+ "--> record buy order execution with the current ask price");
BigDecimal orderPrice = currentOpenOrder.getOriginalQuantity().multiply(currentAskPrice);
BigDecimal buyFees =
final BigDecimal orderPrice =
currentOpenOrder.getOriginalQuantity().multiply(currentAskPrice);
final BigDecimal buyFees =
getPercentageOfBuyOrderTakenForExchangeFee(marketId).multiply(orderPrice);
BigDecimal netOrderPrice = orderPrice.add(buyFees);
final BigDecimal netOrderPrice = orderPrice.add(buyFees);
counterCurrencyBalance = counterCurrencyBalance.subtract(netOrderPrice);
baseCurrencyBalance = baseCurrencyBalance.add(currentOpenOrder.getOriginalQuantity());
currentOpenOrder = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,6 @@ public class TestTryModeExchangeAdapter extends AbstractExchangeAdapter {
"./src/test/exchange-data/bitstamp/order_book.json";
private static final String OPEN_ORDERS_JSON_RESPONSE =
"./src/test/exchange-data/bitstamp/open_orders.json";
private static final String BALANCE_JSON_RESPONSE =
"./src/test/exchange-data/bitstamp/balance.json";
private static final String TICKER_JSON_RESPONSE =
"./src/test/exchange-data/bitstamp/ticker.json";
private static final String BUY_JSON_RESPONSE = "./src/test/exchange-data/bitstamp/buy.json";
Expand All @@ -97,18 +95,14 @@ public class TestTryModeExchangeAdapter extends AbstractExchangeAdapter {

private static final String ORDER_BOOK = "order_book/";
private static final String OPEN_ORDERS = "open_orders/";
private static final String BALANCE = "balance";
private static final String TICKER = "ticker/";
private static final String BUY = "buy/";
private static final String SELL = "sell/";
private static final String CANCEL_ORDER = "cancel_order";

private static final String BASE_CURRENCY = "BTC";
private static final String BASE_CURRENCY_STARTING_BALANCE = "1.0";
private static final String COUNTER_CURRENCY = "USD";
private static final String COUNTER_CURRENCY_STARTING_BALANCE = "100.0";
private static final String DELEGATE_ADAPTER =
"com.gazbert.bxbot.exchanges.BitstampExchangeAdapter";
// --------------------------------------------------------------------------
// Canned test data
// --------------------------------------------------------------------------

private static final String MARKET_ID = "btcusd";
private static final BigDecimal BUY_ORDER_PRICE = new BigDecimal("200.18");
Expand All @@ -132,11 +126,16 @@ public class TestTryModeExchangeAdapter extends AbstractExchangeAdapter {
private static final BigDecimal VWAP = new BigDecimal("17756.56");
private static final Long TIMESTAMP = 1513439945L;

// --------------------------------------------------------------------------
// Mocked API Ops
// --------------------------------------------------------------------------

private static final String MOCKED_GET_PERCENTAGE_OF_SELL_ORDER_TAKEN_FOR_EXCHANGE_FEE =
"getPercentageOfSellOrderTakenForExchangeFee";
private static final String MOCKED_GET_PERCENTAGE_OF_BUY_ORDER_TAKEN_FOR_EXCHANGE_FEE =
"getPercentageOfBuyOrderTakenForExchangeFee";
private static final String MOCKED_GET_TICKER_METHOD = "getTicker";
private static final String MOCKED_GET_BALANCE_INFO = "getBalanceInfo";
private static final String MOCKED_CREATE_DELEGATE_EXCHANGE_ADAPTER =
"createDelegateExchangeAdapter";
private static final String MOCKED_CREATE_REQUEST_PARAM_MAP_METHOD = "createRequestParamMap";
Expand All @@ -145,6 +144,18 @@ public class TestTryModeExchangeAdapter extends AbstractExchangeAdapter {
private static final String MOCKED_SEND_PUBLIC_REQUEST_TO_EXCHANGE_METHOD =
"sendPublicRequestToExchange";

// --------------------------------------------------------------------------
// Delegate Exchange Adapter config
// --------------------------------------------------------------------------

private static final String DELEGATE_ADAPTER =
"com.gazbert.bxbot.exchanges.BitstampExchangeAdapter";

private static final String BASE_CURRENCY = "BTC";
private static final String BASE_CURRENCY_STARTING_BALANCE = "1.0";
private static final String COUNTER_CURRENCY = "USD";
private static final String COUNTER_CURRENCY_STARTING_BALANCE = "100.0";

private static final String CLIENT_ID = "clientId123";
private static final String KEY = "key123";
private static final String SECRET = "notGonnaTellYa";
Expand All @@ -162,6 +173,7 @@ public class TestTryModeExchangeAdapter extends AbstractExchangeAdapter {
private AuthenticationConfig authenticationConfig;
private NetworkConfig networkConfig;


/** Create some exchange config - the TradingEngine would normally do this. */
@Before
public void setupForEachTest() {
Expand Down Expand Up @@ -699,92 +711,38 @@ exchangeAdapter, MOCKED_SEND_PUBLIC_REQUEST_TO_EXCHANGE_METHOD, eq(TICKER + MARK
// Get Balance Info tests
// --------------------------------------------------------------------------

@Ignore("TODO: Enable test")
@Test
public void testGettingBalanceInfoSuccessfully() throws Exception {
final byte[] encoded = Files.readAllBytes(Paths.get(BALANCE_JSON_RESPONSE));
final ExchangeHttpResponse exchangeResponse =
new ExchangeHttpResponse(200, "OK", new String(encoded, StandardCharsets.UTF_8));

final BitstampExchangeAdapter exchangeAdapter =
final BitstampExchangeAdapter delegateExchangeAdapter =
PowerMock.createPartialMockAndInvokeDefaultConstructor(
BitstampExchangeAdapter.class, MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD);
PowerMock.expectPrivate(
exchangeAdapter,
MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD,
eq(BALANCE),
eq(null))
.andReturn(exchangeResponse);

PowerMock.replayAll();
exchangeAdapter.init(exchangeConfig);

final BalanceInfo balanceInfo = exchangeAdapter.getBalanceInfo();

assertEquals(
0, balanceInfo.getBalancesAvailable().get("BTC").compareTo(new BigDecimal("0.00760854")));
assertEquals(
0, balanceInfo.getBalancesAvailable().get("USD").compareTo(new BigDecimal("57.03")));
assertEquals(
0, balanceInfo.getBalancesAvailable().get("EUR").compareTo(new BigDecimal("16.01")));
assertEquals(
0, balanceInfo.getBalancesAvailable().get("LTC").compareTo(new BigDecimal("50.01")));
assertEquals(
0, balanceInfo.getBalancesAvailable().get("XRP").compareTo(new BigDecimal("10.01")));

assertEquals(
0, balanceInfo.getBalancesOnHold().get("BTC").compareTo(new BigDecimal("0.01918917")));
assertEquals(0, balanceInfo.getBalancesOnHold().get("USD").compareTo(new BigDecimal("62.23")));
assertEquals(0, balanceInfo.getBalancesOnHold().get("EUR").compareTo(new BigDecimal("12.01")));
assertEquals(0, balanceInfo.getBalancesOnHold().get("LTC").compareTo(new BigDecimal("40.01")));
assertEquals(0, balanceInfo.getBalancesOnHold().get("XRP").compareTo(new BigDecimal("5.01")));
BitstampExchangeAdapter.class, MOCKED_GET_BALANCE_INFO);

PowerMock.verifyAll();
}

@Ignore("TODO: Enable test")
@Test(expected = ExchangeNetworkException.class)
public void testGettingBalanceInfoHandlesExchangeNetworkException() throws Exception {
final BitstampExchangeAdapter exchangeAdapter =
final TryModeExchangeAdapter tryModeExchangeAdapter =
PowerMock.createPartialMockAndInvokeDefaultConstructor(
BitstampExchangeAdapter.class, MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD);
PowerMock.expectPrivate(
exchangeAdapter,
MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD,
eq(BALANCE),
eq(null))
.andThrow(new ExchangeNetworkException("You mean we're going into the black hole?"));
TryModeExchangeAdapter.class, MOCKED_CREATE_DELEGATE_EXCHANGE_ADAPTER);

PowerMock.replayAll();
exchangeAdapter.init(exchangeConfig);
PowerMock.expectPrivate(tryModeExchangeAdapter, MOCKED_CREATE_DELEGATE_EXCHANGE_ADAPTER)
.andReturn(delegateExchangeAdapter);

exchangeAdapter.getBalanceInfo();
PowerMock.verifyAll();
}
PowerMock.replayAll();

@Ignore("TODO: Enable test")
@Test(expected = TradingApiException.class)
public void testGettingBalanceInfoHandlesUnexpectedException() throws Exception {
final BitstampExchangeAdapter exchangeAdapter =
PowerMock.createPartialMockAndInvokeDefaultConstructor(
BitstampExchangeAdapter.class, MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD);
PowerMock.expectPrivate(
exchangeAdapter,
MOCKED_SEND_AUTHENTICATED_REQUEST_TO_EXCHANGE_METHOD,
eq(BALANCE),
eq(null))
.andThrow(
new IllegalStateException(
"2130; day 547. Unscheduled course correction"
+ " due at 2200. Pre-correction check: rotation axis plus three degrees."
+ " Nitrous oxide pressure: 4100 rising to 5,000. Quad jet C and D on "
+ "preselect. Rotor ignition sequence beginning in 3-0. Thruster line "
+ "reactors on standby."));
tryModeExchangeAdapter.init(exchangeConfig);
final BalanceInfo balanceInfo = tryModeExchangeAdapter.getBalanceInfo();

PowerMock.replayAll();
exchangeAdapter.init(exchangeConfig);
assertEquals(
0,
balanceInfo
.getBalancesAvailable()
.get(BASE_CURRENCY)
.compareTo(new BigDecimal(BASE_CURRENCY_STARTING_BALANCE)));
assertEquals(
0,
balanceInfo
.getBalancesAvailable()
.get(COUNTER_CURRENCY)
.compareTo(new BigDecimal(COUNTER_CURRENCY_STARTING_BALANCE)));

exchangeAdapter.getBalanceInfo();
PowerMock.verifyAll();
}

Expand Down

0 comments on commit 6620753

Please sign in to comment.