Refine search
public void sendPayment(Author author, BigDecimal amount, String url) throws TransferFailedException { try { String note = "Commit payment:\n__" + author.getUsername() + "__ " + url; Transaction transaction = new Transaction(); transaction.setTo(author.getEmail()); transaction.setAmount(Money.of(CurrencyUnit.of("BTC"), amount, RoundingMode.DOWN)); transaction.setNotes(note); Transaction response = coinbase.sendMoney(transaction); if (response.getStatus() != Transaction.Status.COMPLETE) { throw new TransferFailedException(); } } catch (CoinbaseException | IOException e) { throw new TransferFailedException(e); } }
public static BigDecimal of(final BigDecimal amount, final Currency currency) { final CurrencyUnit currencyUnit = CurrencyUnit.getInstance(currency.toString()); return amount.setScale(currencyUnit.getDecimalPlaces(), ROUNDING_METHOD); } }
BigMoney balanceBTC = AccountManager.getInstance(exchangeName).getBalance(CurrencyUnit.of("BTC")); if(!balanceBTC.isZero()) { BigMoney qtyToSell; BigDecimal bigWeight = new BigDecimal(weight / Math.pow(2, asksInARow.get(localCurrency))); if(riskAlgorithm.equals(1)) { qtyToSell = balanceBTC.multipliedBy(bigWeight); log.info("Trend following trade agent has decided that there is not enough {} momentum to trade at this time.",localCurrency.getCode()); } else if (Application.getInstance().getArbMode()) { if (ArbitrageEngine.getInstance(exchangeName).getDisableTrendTrade()) { log.error("ERROR: Could not find {} wallet for {}.",exchangeName,localCurrency.getCurrencyCode()); System.exit(1);
result = Money.of(CurrencyUnit.of(currency), new BigDecimal(amount)); } else { result = Money.ofMinor(CurrencyUnit.of(currency), cents);
throw new IllegalArgumentException("Money amount '" + moneyStr + "' cannot be parsed"); return BigMoney.of(CurrencyUnit.of(currStr), new BigDecimal(amountStr));
/** * Returns a copy of this monetary value with the amount in minor units added. * <p> * This adds the specified amount in minor units to this monetary amount, * returning a new object. * <p> * No precision is lost in the result. * The scale of the result will be the maximum of the current scale and the default currency scale. * For example, 'USD 23.45' plus '138' gives 'USD 24.83'. * <p> * This instance is immutable and unaffected by this method. * * @param amountToAdd the monetary value to add, not null * @return the new instance with the input amount added, never null */ public BigMoney plusMinor(long amountToAdd) { if (amountToAdd == 0) { return this; } BigDecimal newAmount = amount.add(BigDecimal.valueOf(amountToAdd, currency.getDecimalPlaces())); return BigMoney.of(currency, newAmount); }
@Override public Transfer buy(Money amount, String paymentMethodId, Boolean commit) throws CoinbaseException, IOException { URL buysUrl; try { buysUrl = new URL(_baseApiUrl, "buys"); } catch (MalformedURLException ex) { throw new AssertionError(ex); } Request request = newAccountSpecificRequest(); request.setQty(amount.getAmount().doubleValue()); request.setPaymentMethodId(paymentMethodId); request.setCurrency(amount.getCurrencyUnit().getCurrencyCode()); request.setCommit(commit); return post(buysUrl, request, TransferResponse.class).getTransfer(); }
/** * Returns a copy of this monetary value with the amount in minor units subtracted. * <p> * This subtracts the specified amount in minor units from this monetary amount, * returning a new object. * <p> * No precision is lost in the result. * The scale of the result will be the maximum of the current scale and the default currency scale. * For example, USD 23.45 minus '138' gives 'USD 22.07'. * <p> * This instance is immutable and unaffected by this method. * * @param amountToSubtract the monetary value to subtract, not null * @return the new instance with the input amount subtracted, never null */ public BigMoney minusMinor(long amountToSubtract) { if (amountToSubtract == 0) { return this; } BigDecimal newAmount = amount.subtract(BigDecimal.valueOf(amountToSubtract, currency.getDecimalPlaces())); return BigMoney.of(currency, newAmount); }
public PriceRepresentation(BigDecimal amount, Currency currency, Locale locale) { MoneyFormatter formatter = new MoneyFormatterBuilder().appendAmount(MoneyAmountStyle.of(locale)).toFormatter(); CurrencyUnit currencyUnit = CurrencyUnit.of(currency); this.amount = formatter.withLocale(locale) .print(Money.of(currencyUnit, amount, RoundingMode.HALF_EVEN)); this.currency = new CurrencyRepresentation(currency, locale); if (amount.doubleValue() == amount.intValue()) { this.amountCompact = "" + amount.intValue(); } else { this.amountCompact = this.amount; } }
BigDecimal oneDivFrom = BigDecimal.ONE.divide(lastTickAskFrom.getAmount(),16,RoundingMode.HALF_EVEN); BigDecimal oneDivTo = BigDecimal.ONE.divide(lastTickBidTo.getAmount(),16,RoundingMode.HALF_EVEN); log.debug("BTC/"+from.getCurrencyUnit().toString()+" is "+oneDivFrom.toString()); log.debug("Last ticker Bid price was "+lastTickBidTo.toString()); log.debug("BTC/"+to.getCurrencyUnit().toString()+" is "+oneDivTo.toString()); BigMoney qtyFromBTC = qtyFrom.convertedTo(CurrencyUnit.of("BTC"),oneDivFrom); BigMoney qtyTo = qtyFromBTC.convertedTo(to.getCurrencyUnit(),lastTickBidTo.getAmount()); BigMoney qtyToBTC = qtyTo.convertedTo(CurrencyUnit.of("BTC"),oneDivTo); MarketOrder buyOrder = new MarketOrder(OrderType.BID,qtyFromBTC.getAmount(),"BTC",from.getCurrencyUnit().toString()); MarketOrder sellOrder = new MarketOrder(OrderType.ASK,qtyToBTC.getAmount(),"BTC",to.getCurrencyUnit().toString());
/** * Gets the minor part of the amount. * <p> * This return the minor unit part of the monetary amount. * This is defined as the amount in minor units excluding major units. * <p> * For example, EUR has a scale of 2, so the minor part is always between 0 and 99 * for positive amounts, and 0 and -99 for negative amounts. * Thus 'EUR 2.35' will return 35, and 'EUR -1.34' will return -34. * * @return the minor part of the amount, negative if the amount is negative */ public int getMinorPart() { int cdp = getCurrencyUnit().getDecimalPlaces(); return amount.setScale(cdp, RoundingMode.DOWN) .remainder(BigDecimal.ONE) .movePointRight(cdp).intValueExact(); }
/** * Obtains an instance of {@code Money} representing zero. * <p> * For example, {@code zero(USD)} creates the instance {@code USD 0.00}. * * @param currency the currency, not null * @return the instance representing zero, never null */ public static Money zero(CurrencyUnit currency) { MoneyUtils.checkNotNull(currency, "Currency must not be null"); BigDecimal bd = BigDecimal.valueOf(0, currency.getDecimalPlaces()); return new Money(BigMoney.of(currency, bd)); }
/** * Obtains an instance of {@code BigMoney} from an amount in minor units. * <p> * This allows you to create an instance with a specific currency and amount * expressed in terms of the minor unit. * The scale of the money will be that of the currency, such as 2 for USD or 0 for JPY. * <p> * For example, if constructing US Dollars, the input to this method represents cents. * Note that when a currency has zero decimal places, the major and minor units are the same. * For example, {@code ofMinor(USD, 2595)} creates the instance {@code USD 25.95}. * * @param currency the currency, not null * @param amountMinor the amount of money in the minor division of the currency * @return the new instance, never null */ public static BigMoney ofMinor(CurrencyUnit currency, long amountMinor) { MoneyUtils.checkNotNull(currency, "CurrencyUnit must not be null"); return BigMoney.of(currency, BigDecimal.valueOf(amountMinor, currency.getDecimalPlaces())); }
private String getFormattedAmountByLocaleAndInvoiceCurrency(final BigDecimal amount) { final String invoiceCurrencyCode = invoice.getCurrency().toString(); final CurrencyUnit currencyUnit = CurrencyUnit.of(invoiceCurrencyCode); final DecimalFormat numberFormatter = (DecimalFormat) DecimalFormat.getCurrencyInstance(locale); final DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setInternationalCurrencySymbol(currencyUnit.getCurrencyCode()); try { Currency currency = Currency.fromCode(invoiceCurrencyCode); dfs.setCurrencySymbol(currency.getSymbol()); } catch (final IllegalArgumentException e) { dfs.setCurrencySymbol(currencyUnit.getSymbol(locale)); } numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.setMinimumFractionDigits(currencyUnit.getDefaultFractionDigits()); numberFormatter.setMaximumFractionDigits(currencyUnit.getDefaultFractionDigits()); return numberFormatter.format(amount.doubleValue()); }
@JsonProperty @JsonDeserialize(using=MoneyDeserializer.class) public void setAmount(Money amount) { _amount = amount; if (amount != null) { setAmountString(amount.getAmount().toPlainString()); setAmountCurrencyIso(amount.getCurrencyUnit().getCurrencyCode()); } else { setAmountString(null); setAmountCurrencyIso(null); } }
/** * Gets the amount in minor units as a {@code BigDecimal} with scale 0. * <p> * This returns the monetary amount in terms of the minor units of the currency, * truncating the amount if necessary. * For example, 'EUR 2.35' will return 235, and 'BHD -1.345' will return -1345. * <p> * This is returned as a {@code BigDecimal} rather than a {@code BigInteger}. * This is to allow further calculations to be performed on the result. * Should you need a {@code BigInteger}, simply call {@link BigDecimal#toBigInteger()}. * * @return the minor units part of the amount, never null */ public BigDecimal getAmountMinor() { int cdp = getCurrencyUnit().getDecimalPlaces(); return amount.setScale(cdp, RoundingMode.DOWN).movePointRight(cdp); }
/** * Compares this monetary value to another. * The compared values must be in the same currency. * * @param other the other monetary value, not null * @return -1 if this is less than , 0 if equal, 1 if greater than * @throws CurrencyMismatchException if the currencies differ */ @Override public int compareTo(BigMoneyProvider other) { BigMoney otherMoney = of(other); if (currency.equals(otherMoney.currency) == false) { throw new CurrencyMismatchException(getCurrencyUnit(), otherMoney.getCurrencyUnit()); } return amount.compareTo(otherMoney.amount); }
.toFormatter(); CurrencyUnit currencyUnit = CurrencyUnit.of(order.getCurrency()); String grandTotal = formatter.withLocale(locale) .print(Money.of(currencyUnit, order.getGrandTotal(), RoundingMode.HALF_EVEN)); String itemsTotal = formatter.withLocale(locale) .print(Money.of(currencyUnit, order.getItemsTotal(), RoundingMode.HALF_EVEN)); Double unitPrice = item.getUnitPrice().doubleValue(); Double itemTotal = item.getItemTotal().doubleValue(); .print(Money.of(currencyUnit, unitPrice, RoundingMode.HALF_EVEN))); orderItem.put("itemTotal", formatter.withLocale(locale) .print(Money.of(currencyUnit, itemTotal, RoundingMode.HALF_EVEN)));
@Override public Quote getBuyQuote(Money amount, String paymentMethodId) throws IOException, CoinbaseException { String qtyParam; if(amount.getCurrencyUnit().getCode().equals("BTC")) { qtyParam = "qty"; } else { qtyParam = "native_qty"; } URL buyPriceUrl; try { buyPriceUrl = new URL( _baseApiUrl, "prices/buy?" + qtyParam +"=" + URLEncoder.encode(amount.getAmount().toPlainString(), "UTF-8") + (_accountId != null ? "&account_id=" + _accountId : "") + (paymentMethodId != null ? "&payment_method_id=" + paymentMethodId : "") ); } catch (MalformedURLException ex) { throw new AssertionError(ex); } return deserialize(doHttp(buyPriceUrl, "GET", null), Quote.class); }
public void calcProfitLoss() { BigMoney equivBTCStartBal = BigMoney.zero(CurrencyUnit.of("BTC")); BigMoney equivBTCEndBal = BigMoney.zero(CurrencyUnit.of("BTC")); BigMoney startBal = BigMoney.zero(CurrencyUnit.of("BTC")); BigMoney endBal = BigMoney.zero(CurrencyUnit.of("BTC")); BigDecimal startRate = BigDecimal.ZERO; BigDecimal endRate = BigDecimal.ZERO; endBal = balances.get(currency).get(balances.get(currency).size() - 1); if (currency.equals(CurrencyUnit.of("BTC"))) { equivBTCStartBal = equivBTCStartBal.plus(startBal); equivBTCEndBal = equivBTCEndBal.plus(endBal); endRate=rates.get(currency).get(rates.get(currency).size() - 1).getAmount(); equivBTCStartBal = equivBTCStartBal.plus(startBal.convertedTo(CurrencyUnit.of("BTC"),BigDecimal.ONE.divide(startRate,16,RoundingMode.HALF_EVEN))); equivBTCEndBal = equivBTCEndBal.plus(endBal.convertedTo(CurrencyUnit.of("BTC"),BigDecimal.ONE.divide(endRate,16,RoundingMode.HALF_EVEN))); } else { log.info("Not enough "+currency.getCode()+" ticker data collected yet to calculate profit/loss"); return; log.info("No "+currency.getCode()+" ticker data collected yet, cannot calculate profit/loss"); return; profitPercent = profitBTC.getAmount().divide(equivBTCStartBal.getAmount(),16,RoundingMode.HALF_EVEN); String profitToDisplay = percentFormat.format(profitPercent); log.info("Equivalent BTC Start Balance: "+equivBTCStartBal.withScale(8,RoundingMode.HALF_EVEN).toString()+" Equivalent BTC Current Balance: "+equivBTCEndBal.withScale(8,RoundingMode.HALF_EVEN).toString());