Search in sources :

Example 26 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class SpreadViewModel method update.

private void update(ObservableList<OfferBookListItem> offerBookListItems) {
    Map<String, List<Offer>> offersByCurrencyMap = new HashMap<>();
    for (OfferBookListItem offerBookListItem : offerBookListItems) {
        Offer offer = offerBookListItem.getOffer();
        String currencyCode = offer.getCurrencyCode();
        if (!offersByCurrencyMap.containsKey(currencyCode))
            offersByCurrencyMap.put(currencyCode, new ArrayList<>());
        offersByCurrencyMap.get(currencyCode).add(offer);
    }
    spreadItems.clear();
    for (String currencyCode : offersByCurrencyMap.keySet()) {
        List<Offer> offers = offersByCurrencyMap.get(currencyCode);
        List<Offer> buyOffers = offers.stream().filter(e -> e.getDirection().equals(Offer.Direction.BUY)).sorted((o1, o2) -> {
            long a = o1.getPrice() != null ? o1.getPrice().value : 0;
            long b = o2.getPrice() != null ? o2.getPrice().value : 0;
            if (a != b)
                return a < b ? 1 : -1;
            return 0;
        }).collect(Collectors.toList());
        List<Offer> sellOffers = offers.stream().filter(e -> e.getDirection().equals(Offer.Direction.SELL)).sorted((o1, o2) -> {
            long a = o1.getPrice() != null ? o1.getPrice().value : 0;
            long b = o2.getPrice() != null ? o2.getPrice().value : 0;
            if (a != b)
                return a > b ? 1 : -1;
            return 0;
        }).collect(Collectors.toList());
        Fiat spread = null;
        String percentage = "";
        Fiat bestSellOfferPrice = sellOffers.isEmpty() ? null : sellOffers.get(0).getPrice();
        Fiat bestBuyOfferPrice = buyOffers.isEmpty() ? null : buyOffers.get(0).getPrice();
        if (bestBuyOfferPrice != null && bestSellOfferPrice != null) {
            MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode);
            // happens again
            try {
                spread = bestSellOfferPrice.subtract(bestBuyOfferPrice);
                if (spread != null && marketPrice != null) {
                    double marketPriceAsDouble = marketPrice.getPrice(PriceFeedService.Type.LAST);
                    if (CurrencyUtil.isFiatCurrency(currencyCode)) {
                        double result = ((double) spread.value / 10000D) / marketPriceAsDouble;
                        percentage = " (" + formatter.formatPercentagePrice(result) + ")";
                    } else {
                        final double spreadAsDouble = spread.value != 0 ? 10000D / spread.value : 0;
                        double result = marketPriceAsDouble / spreadAsDouble;
                        percentage = " (" + formatter.formatPercentagePrice(result) + ")";
                    }
                }
            } catch (Throwable t) {
                try {
                    String msg = "An error occurred at the spread calculation.\n" + "Error msg: " + t.toString() + "\n" + "Details of offer data: \n" + "bestSellOfferPrice: " + bestSellOfferPrice.value + "\n" + "bestBuyOfferPrice: " + bestBuyOfferPrice.value + "\n" + "sellOffer getCurrencyCode: " + sellOffers.get(0).getCurrencyCode() + "\n" + "buyOffer getCurrencyCode: " + buyOffers.get(0).getCurrencyCode() + "\n\n" + "Please copy and paste this data and send it to the developers so they can investigate the issue.";
                    new Popup().error(msg).show();
                    log.error(t.toString());
                    t.printStackTrace();
                } catch (Throwable t2) {
                    log.error(t2.toString());
                    t2.printStackTrace();
                }
            }
        }
        Coin totalAmount = Coin.valueOf(offers.stream().mapToLong(offer -> offer.getAmount().getValue()).sum());
        spreadItems.add(new SpreadItem(currencyCode, buyOffers.size(), sellOffers.size(), offers.size(), spread, percentage, totalAmount));
    }
}
Also used : PriceFeedService(io.bitsquare.btc.pricefeed.PriceFeedService) Popup(io.bitsquare.gui.main.overlays.popups.Popup) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) ActivatableViewModel(io.bitsquare.gui.common.model.ActivatableViewModel) Coin(org.bitcoinj.core.Coin) Inject(com.google.inject.Inject) FXCollections(javafx.collections.FXCollections) Fiat(org.bitcoinj.utils.Fiat) HashMap(java.util.HashMap) OfferBookListItem(io.bitsquare.gui.main.offer.offerbook.OfferBookListItem) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Offer(io.bitsquare.trade.offer.Offer) List(java.util.List) OfferBook(io.bitsquare.gui.main.offer.offerbook.OfferBook) ListChangeListener(javafx.collections.ListChangeListener) Map(java.util.Map) ObservableList(javafx.collections.ObservableList) CurrencyUtil(io.bitsquare.locale.CurrencyUtil) BSFormatter(io.bitsquare.gui.util.BSFormatter) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Coin(org.bitcoinj.core.Coin) OfferBookListItem(io.bitsquare.gui.main.offer.offerbook.OfferBookListItem) MarketPrice(io.bitsquare.btc.pricefeed.MarketPrice) Offer(io.bitsquare.trade.offer.Offer) Fiat(org.bitcoinj.utils.Fiat) Popup(io.bitsquare.gui.main.overlays.popups.Popup) ArrayList(java.util.ArrayList) List(java.util.List) ObservableList(javafx.collections.ObservableList)

Example 27 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class DepositView method initialize.

@Override
public void initialize() {
    // trigger creation of at least 1 savings address
    walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE);
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No deposit addresses have been generated yet"));
    tableViewSelectionListener = (observableValue, oldValue, newValue) -> {
        if (newValue != null)
            fillForm(newValue.getAddressString());
    };
    setSelectColumnCellFactory();
    setAddressColumnCellFactory();
    setBalanceColumnCellFactory();
    setUsageColumnCellFactory();
    setConfidenceColumnCellFactory();
    addressColumn.setComparator((o1, o2) -> o1.getAddressString().compareTo(o2.getAddressString()));
    balanceColumn.setComparator((o1, o2) -> o1.getBalanceAsCoin().compareTo(o2.getBalanceAsCoin()));
    confidenceColumn.setComparator((o1, o2) -> Double.valueOf(o1.getTxConfidenceIndicator().getProgress()).compareTo(o2.getTxConfidenceIndicator().getProgress()));
    usageColumn.setComparator((a, b) -> (a.getNumTxOutputs() < b.getNumTxOutputs()) ? -1 : ((a.getNumTxOutputs() == b.getNumTxOutputs()) ? 0 : 1));
    tableView.getSortOrder().add(usageColumn);
    tableView.setItems(sortedList);
    titledGroupBg = addTitledGroupBg(gridPane, gridRow, 3, "Fund your wallet");
    qrCodeLabel = addLabel(gridPane, gridRow, "", 0);
    //GridPane.setMargin(qrCodeLabel, new Insets(Layout.FIRST_ROW_DISTANCE - 9, 0, 0, 5));
    qrCodeImageView = new ImageView();
    qrCodeImageView.setStyle("-fx-cursor: hand;");
    Tooltip.install(qrCodeImageView, new Tooltip("Open large QR-Code window"));
    qrCodeImageView.setOnMouseClicked(e -> GUIUtil.showFeeInfoBeforeExecute(() -> UserThread.runAfter(() -> new QRCodeWindow(getBitcoinURI()).show(), 200, TimeUnit.MILLISECONDS)));
    GridPane.setRowIndex(qrCodeImageView, gridRow);
    GridPane.setColumnIndex(qrCodeImageView, 1);
    GridPane.setMargin(qrCodeImageView, new Insets(Layout.FIRST_ROW_DISTANCE, 0, 0, 0));
    gridPane.getChildren().add(qrCodeImageView);
    Tuple2<Label, AddressTextField> addressTuple = addLabelAddressTextField(gridPane, ++gridRow, "Address:");
    addressLabel = addressTuple.first;
    //GridPane.setValignment(addressLabel, VPos.TOP);
    //GridPane.setMargin(addressLabel, new Insets(3, 0, 0, 0));
    addressTextField = addressTuple.second;
    addressTextField.setPaymentLabel(paymentLabelString);
    Tuple2<Label, InputTextField> amountTuple = addLabelInputTextField(gridPane, ++gridRow, "Amount in BTC (optional):");
    amountLabel = amountTuple.first;
    amountTextField = amountTuple.second;
    if (DevFlags.DEV_MODE)
        amountTextField.setText("10");
    titledGroupBg.setVisible(false);
    titledGroupBg.setManaged(false);
    qrCodeLabel.setVisible(false);
    qrCodeLabel.setManaged(false);
    qrCodeImageView.setVisible(false);
    qrCodeImageView.setManaged(false);
    addressLabel.setVisible(false);
    addressLabel.setManaged(false);
    addressTextField.setVisible(false);
    addressTextField.setManaged(false);
    amountLabel.setVisible(false);
    amountTextField.setManaged(false);
    generateNewAddressButton = addButton(gridPane, ++gridRow, "Generate new address", -20);
    GridPane.setColumnIndex(generateNewAddressButton, 0);
    GridPane.setHalignment(generateNewAddressButton, HPos.LEFT);
    generateNewAddressButton.setOnAction(event -> {
        boolean hasUnUsedAddress = observableList.stream().filter(e -> e.getNumTxOutputs() == 0).findAny().isPresent();
        if (hasUnUsedAddress) {
            new Popup().warning("Please select an unused address from the table above rather than generating a new one.").show();
        } else {
            AddressEntry newSavingsAddressEntry = walletService.getOrCreateUnusedAddressEntry(AddressEntry.Context.AVAILABLE);
            updateList();
            observableList.stream().filter(depositListItem -> depositListItem.getAddressString().equals(newSavingsAddressEntry.getAddressString())).findAny().ifPresent(depositListItem -> tableView.getSelectionModel().select(depositListItem));
        }
    });
    balanceListener = new BalanceListener() {

        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateList();
        }
    };
}
Also used : Insets(javafx.geometry.Insets) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) AddressEntry(io.bitsquare.btc.AddressEntry) AddressTextField(io.bitsquare.gui.components.AddressTextField) InputTextField(io.bitsquare.gui.components.InputTextField) QRCodeWindow(io.bitsquare.gui.main.overlays.windows.QRCodeWindow) Coin(org.bitcoinj.core.Coin) Transaction(org.bitcoinj.core.Transaction) Popup(io.bitsquare.gui.main.overlays.popups.Popup) ImageView(javafx.scene.image.ImageView)

Example 28 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class CreateOfferDataModel method calculateTotalToPay.

void calculateTotalToPay() {
    if (direction != null && amount.get() != null) {
        Coin feeAndSecDeposit = offerFeeAsCoin.add(networkFeeAsCoin).add(securityDepositAsCoin);
        Coin feeAndSecDepositAndAmount = feeAndSecDeposit.add(amount.get());
        Coin required = direction == Offer.Direction.BUY ? feeAndSecDeposit : feeAndSecDepositAndAmount;
        totalToPayAsCoin.set(required);
        log.debug("totalToPayAsCoin " + totalToPayAsCoin.get().toFriendlyString());
        updateBalance();
    }
}
Also used : Coin(org.bitcoinj.core.Coin)

Example 29 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class ReservedView method initialize.

@Override
public void initialize() {
    tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No funds are reserved in open offers"));
    setDateColumnCellFactory();
    setDetailsColumnCellFactory();
    setAddressColumnCellFactory();
    setBalanceColumnCellFactory();
    addressColumn.setComparator((o1, o2) -> o1.getAddressString().compareTo(o2.getAddressString()));
    detailsColumn.setComparator((o1, o2) -> o1.getOpenOffer().getId().compareTo(o2.getOpenOffer().getId()));
    balanceColumn.setComparator((o1, o2) -> o1.getBalance().compareTo(o2.getBalance()));
    dateColumn.setComparator((o1, o2) -> {
        if (getTradable(o1).isPresent() && getTradable(o2).isPresent())
            return getTradable(o2).get().getDate().compareTo(getTradable(o1).get().getDate());
        else
            return 0;
    });
    tableView.getSortOrder().add(dateColumn);
    dateColumn.setSortType(TableColumn.SortType.DESCENDING);
    balanceListener = new BalanceListener() {

        @Override
        public void onBalanceChanged(Coin balance, Transaction tx) {
            updateList();
        }
    };
    openOfferListChangeListener = c -> updateList();
    tradeListChangeListener = c -> updateList();
}
Also used : Coin(org.bitcoinj.core.Coin) BalanceListener(io.bitsquare.btc.listeners.BalanceListener) Transaction(org.bitcoinj.core.Transaction)

Example 30 with Coin

use of org.bitcoinj.core.Coin in project bitsquare by bitsquare.

the class DisputeSummaryWindow method applyCustomAmounts.

private void applyCustomAmounts(InputTextField inputTextField) {
    Coin securityDeposit = FeePolicy.getSecurityDeposit(dispute.getContract().offer);
    Coin tradeAmount = dispute.getContract().getTradeAmount();
    Coin buyerAmount = formatter.parseToCoin(buyerPayoutAmountInputTextField.getText());
    Coin sellerAmount = formatter.parseToCoin(sellerPayoutAmountInputTextField.getText());
    Coin arbitratorAmount = formatter.parseToCoin(arbitratorPayoutAmountInputTextField.getText());
    Coin available = tradeAmount.add(securityDeposit).add(securityDeposit);
    Coin totalAmount = buyerAmount.add(sellerAmount).add(arbitratorAmount);
    if (totalAmount.compareTo(available) > 0) {
        new Popup<>().warning("Amount entered exceeds available amount of " + available.toFriendlyString() + ".\n" + "We adjust this input field to the max possible value.").show();
        if (inputTextField == buyerPayoutAmountInputTextField) {
            buyerAmount = available.subtract(sellerAmount).subtract(arbitratorAmount);
            inputTextField.setText(formatter.formatCoin(buyerAmount));
        } else if (inputTextField == sellerPayoutAmountInputTextField) {
            sellerAmount = available.subtract(buyerAmount).subtract(arbitratorAmount);
            inputTextField.setText(formatter.formatCoin(sellerAmount));
        } else if (inputTextField == arbitratorPayoutAmountInputTextField) {
            arbitratorAmount = available.subtract(sellerAmount).subtract(buyerAmount);
            inputTextField.setText(formatter.formatCoin(arbitratorAmount));
        }
    }
    disputeResult.setBuyerPayoutAmount(buyerAmount);
    disputeResult.setSellerPayoutAmount(sellerAmount);
    disputeResult.setArbitratorPayoutAmount(arbitratorAmount);
    if (buyerAmount.compareTo(sellerAmount) == 0)
        disputeResult.setWinner(DisputeResult.Winner.STALE_MATE);
    else if (buyerAmount.compareTo(sellerAmount) > 0)
        disputeResult.setWinner(DisputeResult.Winner.BUYER);
    else
        disputeResult.setWinner(DisputeResult.Winner.SELLER);
}
Also used : Coin(org.bitcoinj.core.Coin) Popup(io.bitsquare.gui.main.overlays.popups.Popup)

Aggregations

Coin (org.bitcoinj.core.Coin)35 AddressEntry (io.bitsquare.btc.AddressEntry)13 WalletService (io.bitsquare.btc.WalletService)13 Transaction (org.bitcoinj.core.Transaction)11 Popup (io.bitsquare.gui.main.overlays.popups.Popup)9 BalanceListener (io.bitsquare.btc.listeners.BalanceListener)8 Offer (io.bitsquare.trade.offer.Offer)7 Address (org.bitcoinj.core.Address)6 BSFormatter (io.bitsquare.gui.util.BSFormatter)5 Trade (io.bitsquare.trade.Trade)5 Inject (com.google.inject.Inject)4 Log (io.bitsquare.app.Log)4 UserThread (io.bitsquare.common.UserThread)4 DevFlags (io.bitsquare.app.DevFlags)3 Dispute (io.bitsquare.arbitration.Dispute)3 DisputeManager (io.bitsquare.arbitration.DisputeManager)3 TradeWalletService (io.bitsquare.btc.TradeWalletService)3 MarketPrice (io.bitsquare.btc.pricefeed.MarketPrice)3 PriceFeedService (io.bitsquare.btc.pricefeed.PriceFeedService)3 CurrencyUtil (io.bitsquare.locale.CurrencyUtil)3