| 176 | } |
| 177 | |
| 178 | @Nullable |
| 179 | public Price getPrice() { |
| 180 | String currencyCode = getCurrencyCode(); |
| 181 | Optional<OfferPayload> optionalOfferPayload = getOfferPayload(); |
| 182 | if (optionalOfferPayload.isEmpty()) { |
| 183 | return Price.valueOf(currencyCode, offerPayloadBase.getPrice()); |
| 184 | } |
| 185 | |
| 186 | OfferPayload offerPayload = optionalOfferPayload.get(); |
| 187 | if (!offerPayload.isUseMarketBasedPrice()) { |
| 188 | return Price.valueOf(currencyCode, offerPayloadBase.getPrice()); |
| 189 | } |
| 190 | |
| 191 | checkNotNull(priceFeedService, "priceFeed must not be null"); |
| 192 | MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode); |
| 193 | if (marketPrice != null && marketPrice.isRecentExternalPriceAvailable()) { |
| 194 | double factor; |
| 195 | double marketPriceMargin = offerPayload.getMarketPriceMargin(); |
| 196 | if (CurrencyUtil.isCryptoCurrency(currencyCode)) { |
| 197 | factor = getDirection() == OfferDirection.SELL ? |
| 198 | 1 - marketPriceMargin : 1 + marketPriceMargin; |
| 199 | } else { |
| 200 | factor = getDirection() == OfferDirection.BUY ? |
| 201 | 1 - marketPriceMargin : 1 + marketPriceMargin; |
| 202 | } |
| 203 | double marketPriceAsDouble = marketPrice.getPrice(); |
| 204 | double targetPriceAsDouble = marketPriceAsDouble * factor; |
| 205 | try { |
| 206 | int precision = CurrencyUtil.isCryptoCurrency(currencyCode) ? |
| 207 | Altcoin.SMALLEST_UNIT_EXPONENT : |
| 208 | Fiat.SMALLEST_UNIT_EXPONENT; |
| 209 | double scaled = MathUtils.scaleUpByPowerOf10(targetPriceAsDouble, precision); |
| 210 | final long roundedToLong = MathUtils.roundDoubleToLong(scaled); |
| 211 | return Price.valueOf(currencyCode, roundedToLong); |
| 212 | } catch (Exception e) { |
| 213 | log.error("Exception at getPrice / parseToFiat: " + e + "\n" + |
| 214 | "That case should never happen."); |
| 215 | return null; |
| 216 | } |
| 217 | } else { |
| 218 | log.trace("We don't have a market price. " + |
| 219 | "That case could only happen if you don't have a price feed."); |
| 220 | return null; |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | public long getFixedPrice() { |
| 225 | return offerPayloadBase.getPrice(); |