use of bisq.core.provider.price.MarketPrice in project bisq-desktop by bisq-network.
the class BsqDashboardView method updatePrice.
private void updatePrice() {
final Coin issuedAmount = bsqBlockChain.getIssuedAmountAtGenesis();
final MarketPrice bsqMarketPrice = priceFeedService.getMarketPrice("BSQ");
if (bsqMarketPrice != null) {
long bsqPrice = MathUtils.roundDoubleToLong(MathUtils.scaleUpByPowerOf10(bsqMarketPrice.getPrice(), Altcoin.SMALLEST_UNIT_EXPONENT));
priceTextField.setText(bsqFormatter.formatPrice(Price.valueOf("BSQ", bsqPrice)) + " BSQ/BTC");
marketCapTextField.setText(bsqFormatter.formatMarketCap(bsqMarketPrice, priceFeedService.getMarketPrice("USD"), issuedAmount));
}
}
use of bisq.core.provider.price.MarketPrice in project bisq-api by mrosseel.
the class BisqProxy method getPriceFeed.
public PriceFeed getPriceFeed(String[] codes) {
final PriceFeedService priceFeedService = injector.getInstance(PriceFeedService.class);
final List<FiatCurrency> fiatCurrencies = preferences.getFiatCurrencies();
final List<CryptoCurrency> cryptoCurrencies = preferences.getCryptoCurrencies();
final Stream<String> codesStream;
if (null == codes || 0 == codes.length)
codesStream = Stream.concat(fiatCurrencies.stream(), cryptoCurrencies.stream()).map(TradeCurrency::getCode);
else
codesStream = Arrays.asList(codes).stream();
final List<MarketPrice> marketPrices = codesStream.map(priceFeedService::getMarketPrice).filter(i -> null != i).collect(toList());
final PriceFeed priceFeed = new PriceFeed();
for (MarketPrice price : marketPrices) priceFeed.prices.put(price.getCurrencyCode(), price.getPrice());
return priceFeed;
}
use of bisq.core.provider.price.MarketPrice in project bisq-desktop by bisq-network.
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();
Coin totalAmount = null;
for (String currencyCode : offersByCurrencyMap.keySet()) {
List<Offer> offers = offersByCurrencyMap.get(currencyCode);
final boolean isFiatCurrency = CurrencyUtil.isFiatCurrency(currencyCode);
List<Offer> buyOffers = offers.stream().filter(e -> e.getDirection().equals(OfferPayload.Direction.BUY)).sorted((o1, o2) -> {
long a = o1.getPrice() != null ? o1.getPrice().getValue() : 0;
long b = o2.getPrice() != null ? o2.getPrice().getValue() : 0;
if (a != b) {
if (isFiatCurrency) {
return a < b ? 1 : -1;
} else {
return a < b ? -1 : 1;
}
}
return 0;
}).collect(Collectors.toList());
List<Offer> sellOffers = offers.stream().filter(e -> e.getDirection().equals(OfferPayload.Direction.SELL)).sorted((o1, o2) -> {
long a = o1.getPrice() != null ? o1.getPrice().getValue() : 0;
long b = o2.getPrice() != null ? o2.getPrice().getValue() : 0;
if (a != b) {
if (isFiatCurrency) {
return a > b ? 1 : -1;
} else {
return a > b ? -1 : 1;
}
}
return 0;
}).collect(Collectors.toList());
Price spread = null;
String percentage = "";
Price bestSellOfferPrice = sellOffers.isEmpty() ? null : sellOffers.get(0).getPrice();
Price bestBuyOfferPrice = buyOffers.isEmpty() ? null : buyOffers.get(0).getPrice();
if (bestBuyOfferPrice != null && bestSellOfferPrice != null) {
MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode);
// happens again
try {
if (isFiatCurrency)
spread = bestSellOfferPrice.subtract(bestBuyOfferPrice);
else
spread = bestBuyOfferPrice.subtract(bestSellOfferPrice);
if (spread != null && marketPrice != null && marketPrice.isPriceAvailable()) {
double marketPriceAsDouble = marketPrice.getPrice();
final double precision = isFiatCurrency ? Math.pow(10, Fiat.SMALLEST_UNIT_EXPONENT) : Math.pow(10, Altcoin.SMALLEST_UNIT_EXPONENT);
BigDecimal marketPriceAsBigDecimal = BigDecimal.valueOf(marketPriceAsDouble).multiply(BigDecimal.valueOf(precision));
// We multiply with 10000 because we use precision of 2 at % (100.00%)
double result = BigDecimal.valueOf(spread.getValue()).multiply(BigDecimal.valueOf(10000)).divide(marketPriceAsBigDecimal, RoundingMode.HALF_UP).doubleValue() / 10000;
percentage = formatter.formatPercentagePrice(result);
}
} catch (Throwable t) {
try {
// Don't translate msg. It is just for rare error cases and can be removed probably later if
// that error never gets reported again.
String msg = "An error occurred at the spread calculation.\n" + "Error msg: " + t.toString() + "\n" + "Details of offer data: \n" + "bestSellOfferPrice: " + bestSellOfferPrice.getValue() + "\n" + "bestBuyOfferPrice: " + bestBuyOfferPrice.getValue() + "\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();
}
}
}
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));
}
maxPlacesForAmount.set(formatAmount(totalAmount, false).length());
}
use of bisq.core.provider.price.MarketPrice in project bisq-desktop by bisq-network.
the class CreateOfferViewModel method createListeners.
private void createListeners() {
amountStringListener = (ov, oldValue, newValue) -> {
if (!ignoreAmountStringListener) {
if (isBtcInputValid(newValue).isValid) {
setAmountToModel();
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
minAmountStringListener = (ov, oldValue, newValue) -> {
if (isBtcInputValid(newValue).isValid)
setMinAmountToModel();
updateButtonDisableState();
};
priceStringListener = (ov, oldValue, newValue) -> {
updateMarketPriceAvailable();
final String currencyCode = dataModel.getTradeCurrencyCode().get();
if (!ignorePriceStringListener) {
if (isPriceInputValid(newValue).isValid) {
setPriceToModel();
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
if (!inputIsMarketBasedPrice) {
if (marketPrice != null && marketPrice.isRecentExternalPriceAvailable()) {
double marketPriceAsDouble = marketPrice.getPrice();
try {
double priceAsDouble = btcFormatter.parseNumberStringToDouble(price.get());
double relation = priceAsDouble / marketPriceAsDouble;
final OfferPayload.Direction compareDirection = CurrencyUtil.isCryptoCurrency(currencyCode) ? OfferPayload.Direction.SELL : OfferPayload.Direction.BUY;
double percentage = dataModel.getDirection() == compareDirection ? 1 - relation : relation - 1;
percentage = MathUtils.roundDouble(percentage, 4);
dataModel.setMarketPriceMargin(percentage);
marketPriceMargin.set(btcFormatter.formatToPercent(percentage));
applyMakerFee();
} catch (NumberFormatException t) {
marketPriceMargin.set("");
new Popup<>().warning(Res.get("validation.NaN")).show();
}
} else {
log.debug("We don't have a market price. We use the static price instead.");
}
}
}
}
updateButtonDisableState();
};
marketPriceMarginStringListener = (ov, oldValue, newValue) -> {
if (inputIsMarketBasedPrice) {
try {
if (!newValue.isEmpty() && !newValue.equals("-")) {
double percentage = btcFormatter.parsePercentStringToDouble(newValue);
if (percentage >= 1 || percentage <= -1) {
new Popup<>().warning(Res.get("popup.warning.tooLargePercentageValue") + "\n" + Res.get("popup.warning.examplePercentageValue")).show();
} else {
final String currencyCode = dataModel.getTradeCurrencyCode().get();
MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode);
if (marketPrice != null && marketPrice.isRecentExternalPriceAvailable()) {
percentage = MathUtils.roundDouble(percentage, 4);
double marketPriceAsDouble = marketPrice.getPrice();
final boolean isCryptoCurrency = CurrencyUtil.isCryptoCurrency(currencyCode);
final OfferPayload.Direction compareDirection = isCryptoCurrency ? OfferPayload.Direction.SELL : OfferPayload.Direction.BUY;
double factor = dataModel.getDirection() == compareDirection ? 1 - percentage : 1 + percentage;
double targetPrice = marketPriceAsDouble * factor;
int precision = isCryptoCurrency ? Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT;
// protect from triggering unwanted updates
ignorePriceStringListener = true;
price.set(btcFormatter.formatRoundedDoubleWithPrecision(targetPrice, precision));
ignorePriceStringListener = false;
setPriceToModel();
dataModel.setMarketPriceMargin(percentage);
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
updateButtonDisableState();
applyMakerFee();
} else {
new Popup<>().warning(Res.get("popup.warning.noPriceFeedAvailable")).show();
marketPriceMargin.set("");
}
}
}
} catch (NumberFormatException t) {
log.error(t.toString());
t.printStackTrace();
new Popup<>().warning(Res.get("validation.NaN")).show();
} catch (Throwable t) {
log.error(t.toString());
t.printStackTrace();
new Popup<>().warning(Res.get("validation.inputError", t.toString())).show();
}
}
};
useMarketBasedPriceListener = (observable, oldValue, newValue) -> {
if (newValue)
priceValidationResult.set(new InputValidator.ValidationResult(true));
};
volumeStringListener = (ov, oldValue, newValue) -> {
if (!ignoreVolumeStringListener) {
if (isVolumeInputValid(newValue).isValid) {
setVolumeToModel();
setPriceToModel();
dataModel.calculateAmount();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
securityDepositStringListener = (ov, oldValue, newValue) -> {
if (!ignoreSecurityDepositStringListener) {
if (securityDepositValidator.validate(newValue).isValid) {
setBuyerSecurityDepositToModel();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
amountAsCoinListener = (ov, oldValue, newValue) -> {
if (newValue != null)
amount.set(btcFormatter.formatCoin(newValue));
else
amount.set("");
applyMakerFee();
};
minAmountAsCoinListener = (ov, oldValue, newValue) -> {
if (newValue != null)
minAmount.set(btcFormatter.formatCoin(newValue));
else
minAmount.set("");
};
priceListener = (ov, oldValue, newValue) -> {
ignorePriceStringListener = true;
if (newValue != null)
price.set(btcFormatter.formatPrice(newValue));
else
price.set("");
ignorePriceStringListener = false;
applyMakerFee();
};
volumeListener = (ov, oldValue, newValue) -> {
ignoreVolumeStringListener = true;
if (newValue != null)
volume.set(btcFormatter.formatVolume(newValue));
else
volume.set("");
ignoreVolumeStringListener = false;
applyMakerFee();
};
securityDepositAsCoinListener = (ov, oldValue, newValue) -> {
if (newValue != null)
buyerSecurityDeposit.set(btcFormatter.formatCoin(newValue));
else
buyerSecurityDeposit.set("");
};
isWalletFundedListener = (ov, oldValue, newValue) -> updateButtonDisableState();
/* feeFromFundingTxListener = (ov, oldValue, newValue) -> {
updateButtonDisableState();
};*/
currenciesUpdateListener = (observable, oldValue, newValue) -> {
updateMarketPriceAvailable();
updateButtonDisableState();
};
}
use of bisq.core.provider.price.MarketPrice in project bisq-desktop by bisq-network.
the class CreateOfferViewModelTest method setUp.
@Before
public void setUp() {
final CryptoCurrency btc = new CryptoCurrency("BTC", "bitcoin");
GlobalSettings.setDefaultTradeCurrency(btc);
Res.setBaseCurrencyCode(btc.getCode());
Res.setBaseCurrencyName(btc.getName());
final BSFormatter bsFormatter = new BSFormatter();
final BtcValidator btcValidator = new BtcValidator(bsFormatter);
final AltcoinValidator altcoinValidator = new AltcoinValidator();
final FiatPriceValidator fiatPriceValidator = new FiatPriceValidator();
FeeService feeService = mock(FeeService.class);
AddressEntry addressEntry = mock(AddressEntry.class);
BtcWalletService btcWalletService = mock(BtcWalletService.class);
PriceFeedService priceFeedService = mock(PriceFeedService.class);
User user = mock(User.class);
PaymentAccount paymentAccount = mock(PaymentAccount.class);
BsqWalletService bsqWalletService = mock(BsqWalletService.class);
SecurityDepositValidator securityDepositValidator = mock(SecurityDepositValidator.class);
when(btcWalletService.getOrCreateAddressEntry(anyString(), any())).thenReturn(addressEntry);
when(btcWalletService.getBalanceForAddress(any())).thenReturn(Coin.valueOf(1000L));
when(priceFeedService.updateCounterProperty()).thenReturn(new SimpleIntegerProperty());
when(priceFeedService.getMarketPrice(anyString())).thenReturn(new MarketPrice("USD", 12684.0450, Instant.now().getEpochSecond(), true));
when(feeService.getTxFee(anyInt())).thenReturn(Coin.valueOf(1000L));
when(user.findFirstPaymentAccountWithCurrency(any())).thenReturn(paymentAccount);
when(user.getPaymentAccountsAsObservable()).thenReturn(FXCollections.observableSet());
when(securityDepositValidator.validate(any())).thenReturn(new InputValidator.ValidationResult(false));
CreateOfferDataModel dataModel = new CreateOfferDataModel(null, btcWalletService, bsqWalletService, empty, user, null, null, priceFeedService, null, null, null, feeService, bsFormatter);
dataModel.initWithData(OfferPayload.Direction.BUY, new CryptoCurrency("BTC", "bitcoin"));
dataModel.activate();
model = new CreateOfferViewModel(dataModel, null, fiatPriceValidator, altcoinValidator, btcValidator, null, securityDepositValidator, null, null, priceFeedService, null, null, bsFormatter, null);
model.activate();
}
Aggregations