Search in sources :

Example 1 with BitfinexOrder

use of com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder in project crypto-bot by jnidzwetzki.

the class PortfolioManager method placeNewExitOrders.

/**
 * Place the exit orders
 * @param exits
 * @throws APIException
 * @throws InterruptedException
 */
private void placeNewExitOrders(final Map<BitfinexCurrencyPair, Double> exits) throws APIException, InterruptedException {
    for (final BitfinexCurrencyPair currency : exits.keySet()) {
        final ExchangeOrder order = getOpenOrderForSymbol(currency.toBitfinexString());
        final double exitPrice = exits.get(currency);
        // Check old orders
        if (order != null) {
            final double orderPrice = order.getPrice();
            if (orderPrice >= exitPrice || MathHelper.almostEquals(orderPrice, exitPrice)) {
                logger.info("Old order price for {} is fine (price: order {} model {})", currency, orderPrice, exitPrice);
                continue;
            }
            logger.info("Exit price for {} has moved form {} to {}, canceling old order", currency, orderPrice, exitPrice);
            cancelOrder(order);
        }
        final double positionSize = getOpenPositionSizeForCurrency(currency.getCurrency1());
        // * -1.0 for sell order
        final double positionSizeSell = positionSize * -1.0;
        final BitfinexOrder newOrder = BitfinexOrderBuilder.create(currency, getOrderType(), positionSizeSell).withPrice(exitPrice).setPostOnly().build();
        placeOrder(newOrder);
    }
}
Also used : BitfinexOrder(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) ExchangeOrder(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder)

Example 2 with BitfinexOrder

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

the class OrderManagerTest method testPlaceOrderUnauth.

/**
 * Test the placement of an order
 * @throws InterruptedException
 * @throws APIException
 */
@Test(expected = APIException.class)
public void testPlaceOrderUnauth() throws APIException, InterruptedException {
    final BitfinexApiBroker bitfinexApiBroker = buildMockedBitfinexConnection();
    Mockito.when(bitfinexApiBroker.getCapabilities()).thenReturn(ConnectionCapabilities.NO_CAPABILITIES);
    final OrderManager orderManager = bitfinexApiBroker.getOrderManager();
    final BitfinexOrder order = BitfinexOrderBuilder.create(BitfinexCurrencyPair.BCH_USD, BitfinexOrderType.MARKET, 12).build();
    orderManager.placeOrderAndWaitUntilActive(order);
}
Also used : BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) BitfinexOrder(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder) OrderManager(com.github.jnidzwetzki.bitfinex.v2.manager.OrderManager) Test(org.junit.Test)

Example 3 with BitfinexOrder

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

the class OrderManagerTest method testPlaceOrder.

/**
 * Test the placement of an order
 * @throws InterruptedException
 * @throws APIException
 */
@Test(timeout = 60000)
public void testPlaceOrder() throws APIException, InterruptedException {
    final BitfinexApiBroker bitfinexApiBroker = buildMockedBitfinexConnection();
    Mockito.when(bitfinexApiBroker.isAuthenticated()).thenReturn(true);
    final OrderManager orderManager = bitfinexApiBroker.getOrderManager();
    final BitfinexOrder order = BitfinexOrderBuilder.create(BitfinexCurrencyPair.BCH_USD, BitfinexOrderType.MARKET, 1).build();
    final Runnable r = () -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            return;
        }
        final ExchangeOrder exchangeOrder = new ExchangeOrder();
        exchangeOrder.setCid(order.getCid());
        exchangeOrder.setState(ExchangeOrderState.STATE_ACTIVE);
        orderManager.updateOrder(exchangeOrder);
    };
    // Cancel event
    (new Thread(r)).start();
    orderManager.placeOrderAndWaitUntilActive(order);
}
Also used : BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) BitfinexOrder(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder) ExchangeOrder(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder) OrderManager(com.github.jnidzwetzki.bitfinex.v2.manager.OrderManager) Test(org.junit.Test)

Example 4 with BitfinexOrder

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

the class OrderManager method placeOrderOrderOnAPI.

/**
 * Execute a new Order
 * @param order
 * @return
 * @throws Exception
 */
private boolean placeOrderOrderOnAPI(final BitfinexOrder order) throws Exception {
    final CountDownLatch waitLatch = new CountDownLatch(1);
    final Consumer<ExchangeOrder> ordercallback = (o) -> {
        if (o.getCid() == order.getCid()) {
            waitLatch.countDown();
        }
    };
    registerCallback(ordercallback);
    try {
        placeOrder(order);
        waitLatch.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
        if (waitLatch.getCount() != 0) {
            throw new APIException("Timeout while waiting for order");
        }
        // Check for order error
        final boolean orderInErrorState = bitfinexApiBroker.getOrderManager().getOrders().stream().filter(o -> o.getCid() == order.getCid()).anyMatch(o -> o.getState() == ExchangeOrderState.STATE_ERROR);
        if (orderInErrorState) {
            throw new APIException("Unable to place order " + 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 5 with BitfinexOrder

use of com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder 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)

Aggregations

BitfinexOrder (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder)11 Test (org.junit.Test)6 BitfinexApiBroker (com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker)5 APIException (com.github.jnidzwetzki.bitfinex.v2.entity.APIException)5 CancelOrderCommand (com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderCommand)4 OrderCommand (com.github.jnidzwetzki.bitfinex.v2.commands.OrderCommand)4 ExchangeOrder (com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder)4 ConnectionCapabilities (com.github.jnidzwetzki.bitfinex.v2.entity.ConnectionCapabilities)3 CancelOrderGroupCommand (com.github.jnidzwetzki.bitfinex.v2.commands.CancelOrderGroupCommand)2 BitfinexCurrencyPair (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair)2 OrderManager (com.github.jnidzwetzki.bitfinex.v2.manager.OrderManager)2 Retryer (org.bboxdb.commons.Retryer)2 Session (org.hibernate.Session)2 AbstractAPICommand (com.github.jnidzwetzki.bitfinex.v2.commands.AbstractAPICommand)1 AuthCommand (com.github.jnidzwetzki.bitfinex.v2.commands.AuthCommand)1 PingCommand (com.github.jnidzwetzki.bitfinex.v2.commands.PingCommand)1 SubscribeCandlesCommand (com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeCandlesCommand)1 SubscribeOrderbookCommand (com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeOrderbookCommand)1 SubscribeRawOrderbookCommand (com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeRawOrderbookCommand)1 SubscribeTickerCommand (com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeTickerCommand)1