Search in sources :

Example 21 with APIException

use of com.github.jnidzwetzki.bitfinex.v2.entity.APIException in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class OrderManager method placeOrderAndWaitUntilActive.

/**
 * Place an order and retry if Exception occur
 * @param order - new BitfinexOrder to place
 * @throws APIException
 * @throws InterruptedException
 */
public void placeOrderAndWaitUntilActive(final BitfinexOrder order) throws APIException, InterruptedException {
    final ConnectionCapabilities capabilities = bitfinexApiBroker.getCapabilities();
    if (!capabilities.isHavingOrdersWriteCapability()) {
        throw new APIException("Unable to wait for order " + order + " connection has not enough capabilities: " + capabilities);
    }
    order.setApikey(bitfinexApiBroker.getApiKey());
    final Callable<Boolean> orderCallable = () -> placeOrderOrderOnAPI(order);
    // Bitfinex does not implement a happens-before relationship. Sometimes
    // canceling a stop-loss order and placing a new stop-loss order results
    // in an 'ERROR, reason is Invalid order: not enough exchange balance'
    // error for some seconds. The retryer tries to place the order up to
    // three times
    final Retryer<Boolean> retryer = new Retryer<>(ORDER_RETRIES, RETRY_DELAY_IN_MS, orderCallable);
    retryer.execute();
    if (retryer.getNeededExecutions() > 1) {
        logger.info("Nedded {} executions for placing the order", retryer.getNeededExecutions());
    }
    if (!retryer.isSuccessfully()) {
        final Exception lastException = retryer.getLastException();
        if (lastException == null) {
            throw new APIException("Unable to execute order");
        } else {
            throw new APIException(lastException);
        }
    }
}
Also used : APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) ConnectionCapabilities(com.github.jnidzwetzki.bitfinex.v2.entity.ConnectionCapabilities) Retryer(org.bboxdb.commons.Retryer) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException)

Example 22 with APIException

use of com.github.jnidzwetzki.bitfinex.v2.entity.APIException in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class OrderManager method placeOrder.

/**
 * Place a new order
 * @throws APIException
 */
public void placeOrder(final BitfinexOrder order) throws APIException {
    final ConnectionCapabilities capabilities = bitfinexApiBroker.getCapabilities();
    if (!capabilities.isHavingOrdersWriteCapability()) {
        throw new APIException("Unable to place order " + order + " connection has not enough capabilities: " + capabilities);
    }
    logger.info("Executing new order {}", order);
    final OrderCommand orderCommand = new OrderCommand(order);
    bitfinexApiBroker.sendCommand(orderCommand);
}
Also used : APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) CancelOrderCommand(com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderCommand) OrderCommand(com.github.jnidzwetzki.bitfinex.v2.commands.OrderCommand) ConnectionCapabilities(com.github.jnidzwetzki.bitfinex.v2.entity.ConnectionCapabilities)

Example 23 with APIException

use of com.github.jnidzwetzki.bitfinex.v2.entity.APIException in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class OrderManager method cancelOrderOnAPI.

/**
 * Cancel the order on the API
 * @param id
 * @return
 * @throws APIException
 * @throws InterruptedException
 */
private boolean cancelOrderOnAPI(final long id) throws APIException, InterruptedException {
    final CountDownLatch waitLatch = new CountDownLatch(1);
    final Consumer<ExchangeOrder> ordercallback = (o) -> {
        if (o.getOrderId() == id && o.getState() == ExchangeOrderState.STATE_CANCELED) {
            waitLatch.countDown();
        }
    };
    registerCallback(ordercallback);
    try {
        logger.info("Cancel order: {}", id);
        cancelOrder(id);
        waitLatch.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
        if (waitLatch.getCount() != 0) {
            throw new APIException("Timeout while waiting for order");
        }
        return true;
    } catch (Exception e) {
        throw e;
    } finally {
        removeCallback(ordercallback);
    }
}
Also used : BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) Logger(org.slf4j.Logger) CancelOrderCommand(com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderCommand) ConnectionCapabilities(com.github.jnidzwetzki.bitfinex.v2.entity.ConnectionCapabilities) LoggerFactory(org.slf4j.LoggerFactory) Callable(java.util.concurrent.Callable) Retryer(org.bboxdb.commons.Retryer) ExchangeOrderState(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrderState) ArrayList(java.util.ArrayList) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ExchangeOrder(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder) OrderCommand(com.github.jnidzwetzki.bitfinex.v2.commands.OrderCommand) BitfinexOrder(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder) CancelOrderGroupCommand(com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderGroupCommand) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) CountDownLatch(java.util.concurrent.CountDownLatch) ExchangeOrder(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException)

Example 24 with APIException

use of com.github.jnidzwetzki.bitfinex.v2.entity.APIException in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class TickHandlerTest method testTickUpdateAndNotify.

/**
 * Test the parsing of one tick
 * @throws APIException
 * @throws InterruptedException
 */
@Test(timeout = 20000)
public void testTickUpdateAndNotify() throws APIException, InterruptedException {
    final String callbackValue = "[26123,41.4645776,26129,33.68138507,2931,0.2231,26129,144327.10936387,26149,13139]";
    final JSONArray jsonArray = new JSONArray(callbackValue);
    final BitfinexCurrencyPair currencyPair = BitfinexCurrencyPair.BTC_USD;
    final BitfinexTickerSymbol symbol = new BitfinexTickerSymbol(currencyPair);
    final ExecutorService executorService = Executors.newFixedThreadPool(10);
    final BitfinexApiBroker bitfinexApiBroker = Mockito.mock(BitfinexApiBroker.class);
    Mockito.when(bitfinexApiBroker.getExecutorService()).thenReturn(executorService);
    final QuoteManager tickerManager = new QuoteManager(bitfinexApiBroker);
    Mockito.when(bitfinexApiBroker.getQuoteManager()).thenReturn(tickerManager);
    final CountDownLatch latch = new CountDownLatch(1);
    tickerManager.registerTickCallback(symbol, (s, c) -> {
        try {
            Assert.assertEquals(symbol, s);
            Assert.assertEquals(26129, c.getOpen().doubleValue(), DELTA);
            Assert.assertEquals(26129, c.getClose().doubleValue(), DELTA);
            Assert.assertEquals(26129, c.getHigh().doubleValue(), DELTA);
            Assert.assertEquals(26129, c.getLow().doubleValue(), DELTA);
            Assert.assertEquals(BitfinexTick.INVALID_VOLUME.doubleValue(), c.getVolume().doubleValue(), DELTA);
        } catch (Throwable e) {
            System.out.println(e);
            throw e;
        }
        latch.countDown();
    });
    Assert.assertEquals(-1, tickerManager.getHeartbeatForSymbol(symbol));
    Assert.assertEquals(null, tickerManager.getLastTick(symbol));
    final TickHandler tickHandler = new TickHandler();
    final long now = System.currentTimeMillis();
    tickHandler.handleChannelData(bitfinexApiBroker, symbol, jsonArray);
    // Tick callbacks are handled async
    latch.await();
    Assert.assertTrue(now <= tickerManager.getHeartbeatForSymbol(symbol));
    Assert.assertTrue(tickerManager.getLastTick(symbol) != null);
    Assert.assertTrue(tickerManager.getLastTick(symbol) != null);
}
Also used : BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) JSONArray(org.json.JSONArray) ExecutorService(java.util.concurrent.ExecutorService) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) BitfinexTickerSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexTickerSymbol) QuoteManager(com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager) CountDownLatch(java.util.concurrent.CountDownLatch) TickHandler(com.github.jnidzwetzki.bitfinex.v2.callback.channel.TickHandler) Test(org.junit.Test)

Example 25 with APIException

use of com.github.jnidzwetzki.bitfinex.v2.entity.APIException in project bitfinex-v2-wss-api-java by jnidzwetzki.

the class TradeManagerTest method testTradeChannelHandler1.

/**
 * Test the trade channel handler
 * @throws APIException
 * @throws InterruptedException
 */
@Test(timeout = 10000)
public void testTradeChannelHandler1() throws APIException, InterruptedException {
    final String jsonString = "[0,\"te\",[106655593,\"tBTCUSD\",1512247319827,5691690918,-0.002,10894,null,null,-1]]";
    final JSONArray jsonArray = new JSONArray(jsonString);
    final TradeHandler tradeHandler = new TradeHandler();
    final BitfinexApiBroker bitfinexApiBroker = buildMockedBitfinexConnection();
    final CountDownLatch latch = new CountDownLatch(1);
    bitfinexApiBroker.getTradeManager().registerCallback((t) -> {
        try {
            Assert.assertTrue(t.isExecuted());
            Assert.assertEquals(106655593, t.getId());
            Assert.assertEquals(BitfinexCurrencyPair.BTC_USD, t.getCurrency());
            Assert.assertEquals(1512247319827l, t.getMtsCreate());
            Assert.assertEquals(5691690918l, t.getOrderId());
            Assert.assertEquals(-0.002, t.getExecAmount().doubleValue(), DELTA);
            Assert.assertEquals(10894, t.getExecPrice().doubleValue(), DELTA);
            Assert.assertTrue(t.toString().length() > 0);
        } catch (Throwable e) {
            e.printStackTrace();
            throw e;
        }
        latch.countDown();
    });
    tradeHandler.handleChannelData(bitfinexApiBroker, jsonArray);
    latch.await();
}
Also used : BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) JSONArray(org.json.JSONArray) CountDownLatch(java.util.concurrent.CountDownLatch) TradeHandler(com.github.jnidzwetzki.bitfinex.v2.callback.api.TradeHandler) Test(org.junit.Test)

Aggregations

BitfinexApiBroker (com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker)33 Test (org.junit.Test)33 APIException (com.github.jnidzwetzki.bitfinex.v2.entity.APIException)25 BitfinexCurrencyPair (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair)20 JSONArray (org.json.JSONArray)20 CountDownLatch (java.util.concurrent.CountDownLatch)14 ExchangeOrder (com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder)12 HashMap (java.util.HashMap)11 BitfinexTickerSymbol (com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexTickerSymbol)10 BitfinexOrder (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder)9 ConnectionCapabilities (com.github.jnidzwetzki.bitfinex.v2.entity.ConnectionCapabilities)9 Wallet (com.github.jnidzwetzki.bitfinex.v2.entity.Wallet)9 BitfinexCandlestickSymbol (com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol)9 OrderManager (com.github.jnidzwetzki.bitfinex.v2.manager.OrderManager)8 QuoteManager (com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager)8 CurrencyEntry (com.github.jnidzwetzki.cryptobot.CurrencyEntry)8 BasePortfolioManager (com.github.jnidzwetzki.cryptobot.portfolio.BasePortfolioManager)8 BitfinexTick (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexTick)7 PortfolioManager (com.github.jnidzwetzki.cryptobot.portfolio.PortfolioManager)7 ArrayList (java.util.ArrayList)7