/** * Obtains an instance from a currency pair. * <p> * The two currencies may be the same, but if they are then the rate must be one. * * @param pair the currency pair * @param rate the conversion rate, greater than zero * @return the FX rate * @throws IllegalArgumentException if the rate is invalid */ public static FxRate of(CurrencyPair pair, double rate) { return new FxRate(pair, rate); }
@Override public FxRate build() { return new FxRate( pair, rate); }
/** * Gets the inverse rate. * <p> * The inverse rate has the same currencies but in reverse order. * The rate is the reciprocal of the original. * * @return the inverse pair */ public FxRate inverse() { return new FxRate(pair.inverse(), 1d / rate); }
/** * Obtains an instance from two currencies. * <p> * The first currency is the base and the second is the counter. * The two currencies may be the same, but if they are then the rate must be one. * * @param base the base currency * @param counter the counter currency * @param rate the conversion rate, greater than zero * @return the FX rate * @throws IllegalArgumentException if the rate is invalid */ public static FxRate of(Currency base, Currency counter, double rate) { return new FxRate(CurrencyPair.of(base, counter), rate); }
/** * Parses a rate from a string with format AAA/BBB RATE. * <p> * The parsed format is '${baseCurrency}/${counterCurrency} ${rate}'. * Currency parsing is case insensitive. * * @param rateStr the rate as a string AAA/BBB RATE * @return the FX rate * @throws IllegalArgumentException if the FX rate cannot be parsed */ public static FxRate parse(String rateStr) { ArgChecker.notNull(rateStr, "rateStr"); Matcher matcher = REGEX_FORMAT.matcher(rateStr.toUpperCase(Locale.ENGLISH)); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid rate: " + rateStr); } try { Currency base = Currency.parse(matcher.group(1)); Currency counter = Currency.parse(matcher.group(2)); double rate = Double.parseDouble(matcher.group(3)); return new FxRate(CurrencyPair.of(base, counter), rate); } catch (RuntimeException ex) { throw new IllegalArgumentException("Unable to parse rate: " + rateStr, ex); } }