Search in sources :

Example 1 with Trade

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

the class TestPersistence method testGetOpenTrades.

/**
 * Test get open trades from order manager
 */
@Test
public void testGetOpenTrades() {
    final BitfinexApiBroker apiBroker = Mockito.mock(BitfinexApiBroker.class);
    final PortfolioOrderManager ordermanager = new PortfolioOrderManager(apiBroker);
    Assert.assertTrue(ordermanager.getAllOpenTrades().isEmpty());
    final Trade trade = new Trade("ABC", TradeDirection.LONG, BitfinexCurrencyPair.BTC_USD, 1);
    trade.setTradeState(TradeState.CREATED);
    final Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(trade);
    session.getTransaction().commit();
    Assert.assertTrue(ordermanager.getAllOpenTrades().isEmpty());
    session.beginTransaction();
    trade.setTradeState(TradeState.OPEN);
    session.saveOrUpdate(trade);
    session.getTransaction().commit();
    session.beginTransaction();
    Assert.assertEquals(1, ordermanager.getAllOpenTrades().size());
    session.getTransaction().commit();
    final Trade trade2 = new Trade("ABC", TradeDirection.LONG, BitfinexCurrencyPair.BTC_USD, 1);
    trade2.setTradeState(TradeState.OPEN);
    session.beginTransaction();
    session.save(trade2);
    session.getTransaction().commit();
    session.beginTransaction();
    Assert.assertEquals(2, ordermanager.getAllOpenTrades().size());
    session.getTransaction().commit();
    session.close();
}
Also used : Trade(com.github.jnidzwetzki.cryptobot.entity.Trade) BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) PortfolioOrderManager(com.github.jnidzwetzki.cryptobot.PortfolioOrderManager) Session(org.hibernate.Session) Test(org.junit.Test)

Example 2 with Trade

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

the class EMABot method updateScreen.

public synchronized void updateScreen() {
    if (!UPDATE_SCREEN) {
        return;
    }
    final QuoteManager tickerManager = bitfinexApiBroker.getQuoteManager();
    CliTools.clearScreen();
    System.out.println("");
    System.out.println("==========");
    System.out.println("Last ticks");
    System.out.println("==========");
    for (final BitfinexCurrencyPair currency : tradedCurrencies) {
        final String symbol = currency.toBitfinexString();
        final BitfinexTickerSymbol tickerSymbol = new BitfinexTickerSymbol(currency);
        System.out.println(symbol + " " + tickerManager.getLastTick(tickerSymbol));
    }
    System.out.println("");
    System.out.println("==========");
    System.out.println("Last bars");
    System.out.println("==========");
    for (final BitfinexCurrencyPair currency : tradedCurrencies) {
        System.out.println(currency + " " + timeSeries.get(currency).getLastBar());
    }
    System.out.println("");
    System.out.println("==========");
    System.out.println("P/L");
    System.out.println("==========");
    for (final BitfinexCurrencyPair currency : tradedCurrencies) {
        final String symbol = currency.toBitfinexString();
        final BitfinexTickerSymbol tickerSymbol = new BitfinexTickerSymbol(currency);
        final Trade trade = getOpenTrade(currency);
        if (trade != null) {
            final double priceIn = trade.getExpectedPriceOpen();
            final double currentPrice = tickerManager.getLastTick(tickerSymbol).getClose();
            System.out.println(symbol + ": price in " + priceIn + " / " + (currentPrice - priceIn));
        }
    }
    System.out.println("");
    System.out.println("==========");
    System.out.println("Trades");
    System.out.println("==========");
    for (final BitfinexCurrencyPair currency : tradedCurrencies) {
        final String symbol = currency.toBitfinexString();
        final List<Trade> lastTrades = trades.get(currency);
        if (lastTrades == null) {
            continue;
        }
        lastTrades.sort((t1, t2) -> Long.compare(t2.getTid(), t1.getTid()));
        final List<Trade> lastTwoTrades = lastTrades.subList(Math.max(lastTrades.size() - 2, 0), lastTrades.size());
        for (final Trade trade : lastTwoTrades) {
            System.out.println(symbol + " " + trade);
        }
    }
    try {
        System.out.println("");
        System.out.println("==========");
        System.out.println("Orders");
        System.out.println("==========");
        final List<ExchangeOrder> orders = new ArrayList<>(bitfinexApiBroker.getOrderManager().getOrders());
        orders.sort((o1, o2) -> Long.compare(o2.getCid(), o1.getCid()));
        final List<ExchangeOrder> lastOrders = orders.subList(Math.max(orders.size() - 3, 0), orders.size());
        for (final ExchangeOrder order : lastOrders) {
            System.out.println(order);
        }
    } catch (APIException e) {
        logger.error("Got eception while reading wallets", e);
    }
}
Also used : Trade(com.github.jnidzwetzki.cryptobot.entity.Trade) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) ArrayList(java.util.ArrayList) QuoteManager(com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) BitfinexTickerSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexTickerSymbol) ExchangeOrder(com.github.jnidzwetzki.bitfinex.v2.entity.ExchangeOrder)

Example 3 with Trade

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

the class ExecutedTradesHandlerTest method testExecutedTradesUpdateAndNotify.

/**
 * Test the parsing of one executed trade
 * @throws APIException
 * @throws InterruptedException
 */
@Test(timeout = 10000)
public void testExecutedTradesUpdateAndNotify() throws APIException, InterruptedException {
    final String callbackValue = "[190631057,1518037080162,0.007,8175.9]";
    final JSONArray jsonArray = new JSONArray(callbackValue);
    final BitfinexExecutedTradeSymbol symbol = new BitfinexExecutedTradeSymbol(BitfinexCurrencyPair.BTC_USD);
    final ExecutorService executorService = Executors.newFixedThreadPool(10);
    final BitfinexApiBroker bitfinexApiBroker = Mockito.mock(BitfinexApiBroker.class);
    Mockito.when(bitfinexApiBroker.getExecutorService()).thenReturn(executorService);
    final QuoteManager quoteManager = new QuoteManager(bitfinexApiBroker);
    Mockito.when(bitfinexApiBroker.getQuoteManager()).thenReturn(quoteManager);
    final CountDownLatch latch = new CountDownLatch(1);
    quoteManager.registerExecutedTradeCallback(symbol, (s, c) -> {
        try {
            Assert.assertEquals(symbol, s);
            Assert.assertEquals(190631057, c.getId());
            Assert.assertEquals(1518037080162l, c.getTimestamp());
            Assert.assertEquals(0.007, c.getAmount().doubleValue(), DELTA);
            Assert.assertEquals(8175.9, c.getPrice().doubleValue(), DELTA);
            latch.countDown();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    });
    final ExecutedTradeHandler handler = new ExecutedTradeHandler();
    handler.handleChannelData(bitfinexApiBroker, symbol, jsonArray);
    latch.await();
}
Also used : BitfinexExecutedTradeSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexExecutedTradeSymbol) BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) JSONArray(org.json.JSONArray) ExecutorService(java.util.concurrent.ExecutorService) ExecutedTradeHandler(com.github.jnidzwetzki.bitfinex.v2.callback.channel.ExecutedTradeHandler) QuoteManager(com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 4 with Trade

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

Example 5 with Trade

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

the class TradeHandler method handleTradeCallback.

/**
 * Handle a single trade callback
 * @param bitfinexApiBroker
 * @param orderArray
 * @throws APIException
 */
private void handleTradeCallback(final BitfinexApiBroker bitfinexApiBroker, final JSONArray jsonTrade, final boolean executed) throws APIException {
    final Trade trade = new Trade();
    trade.setExecuted(executed);
    trade.setApikey(bitfinexApiBroker.getApiKey());
    trade.setId(jsonTrade.getLong(0));
    trade.setCurrency(BitfinexCurrencyPair.fromSymbolString(jsonTrade.getString(1)));
    trade.setMtsCreate(jsonTrade.getLong(2));
    trade.setOrderId(jsonTrade.getLong(3));
    trade.setExecAmount(jsonTrade.getBigDecimal(4));
    trade.setExecPrice(jsonTrade.getBigDecimal(5));
    final String orderTypeString = jsonTrade.optString(6, null);
    if (orderTypeString != null) {
        trade.setOrderType(BitfinexOrderType.fromString(orderTypeString));
    }
    trade.setOrderPrice(jsonTrade.optBigDecimal(7, BigDecimal.valueOf(-1)));
    trade.setMaker(jsonTrade.getInt(8) == 1 ? true : false);
    trade.setFee(jsonTrade.optBigDecimal(9, BigDecimal.valueOf(-1)));
    trade.setFeeCurrency(jsonTrade.optString(10, ""));
    bitfinexApiBroker.getTradeManager().updateTrade(trade);
}
Also used : Trade(com.github.jnidzwetzki.bitfinex.v2.entity.Trade)

Aggregations

Test (org.junit.Test)5 BitfinexApiBroker (com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker)4 JSONArray (org.json.JSONArray)4 TradeHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.TradeHandler)3 APIException (com.github.jnidzwetzki.bitfinex.v2.entity.APIException)3 BitfinexOrder (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexOrder)3 Trade (com.github.jnidzwetzki.cryptobot.entity.Trade)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ExecutedTradeHandler (com.github.jnidzwetzki.bitfinex.v2.callback.channel.ExecutedTradeHandler)2 BitfinexCurrencyPair (com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair)2 QuoteManager (com.github.jnidzwetzki.bitfinex.v2.manager.QuoteManager)2 ArrayList (java.util.ArrayList)2 Session (org.hibernate.Session)2 DoNothingHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.DoNothingHandler)1 HeartbeatHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.HeartbeatHandler)1 NotificationHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.NotificationHandler)1 OrderHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.OrderHandler)1 PositionHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.PositionHandler)1 WalletHandler (com.github.jnidzwetzki.bitfinex.v2.callback.api.WalletHandler)1 SubscribeTradesCommand (com.github.jnidzwetzki.bitfinex.v2.commands.SubscribeTradesCommand)1