Merge branch 'percentbasedprice' into Development

This commit is contained in:
Manfred Karrer 2016-04-16 11:46:27 +02:00
commit 1434d37733
45 changed files with 613 additions and 152 deletions

View File

@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
// TODO use https://github.com/timmolter/XChange
public class PriceFeed {
private static final Logger log = LoggerFactory.getLogger(PriceFeed.class);
@ -44,9 +45,9 @@ public class PriceFeed {
}
}
private static final long PERIOD_FIAT_SEC = 2 * 60;
private static final long PERIOD_ALL_FIAT_SEC = 60 * 5;
private static final long PERIOD_ALL_CRYPTO_SEC = 60 * 5;
private static final long PERIOD_FIAT_SEC = 90;
private static final long PERIOD_ALL_FIAT_SEC = 60 * 3;
private static final long PERIOD_ALL_CRYPTO_SEC = 60 * 3;
private final Map<String, MarketPrice> cache = new HashMap<>();
private final PriceProvider fiatPriceProvider = new BitcoinAveragePriceProvider();

View File

@ -7,7 +7,6 @@ import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
// https://api.bitfinex.com/v1/pubticker/BTCUSD
public interface PriceProvider extends Serializable {
Map<String, MarketPrice> getAllPrices() throws IOException, HttpException;

View File

@ -18,22 +18,18 @@
package io.bitsquare.trade;
import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer;
import io.bitsquare.trade.protocol.trade.BuyerAsOffererProtocol;
import io.bitsquare.trade.protocol.trade.OffererProtocol;
import io.bitsquare.trade.protocol.trade.messages.TradeMessage;
import org.bitcoinj.core.Coin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.ObjectInputStream;
import static com.google.common.base.Preconditions.checkNotNull;
public final class BuyerAsOffererTrade extends BuyerTrade implements OffererTrade {
// That object is saved to disc. We need to take care of changes to not break deserialization.
private static final long serialVersionUID = Version.LOCAL_DB_VERSION;
@ -73,12 +69,4 @@ public final class BuyerAsOffererTrade extends BuyerTrade implements OffererTrad
public void handleTakeOfferRequest(TradeMessage message, NodeAddress taker) {
((OffererProtocol) tradeProtocol).handleTakeOfferRequest(message, taker);
}
@Override
public Coin getPayoutAmount() {
checkNotNull(getTradeAmount(), "Invalid state: getTradeAmount() = null");
return FeePolicy.getSecurityDeposit().add(getTradeAmount());
}
}

View File

@ -18,7 +18,6 @@
package io.bitsquare.trade;
import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.storage.Storage;
import io.bitsquare.trade.offer.Offer;
@ -32,7 +31,6 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public final class BuyerAsTakerTrade extends BuyerTrade implements TakerTrade {
// That object is saved to disc. We need to take care of changes to not break deserialization.
@ -45,8 +43,8 @@ public final class BuyerAsTakerTrade extends BuyerTrade implements TakerTrade {
// Constructor, initialization
///////////////////////////////////////////////////////////////////////////////////////////
public BuyerAsTakerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerNodeAddress, storage);
public BuyerAsTakerTrade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradePrice, tradingPeerNodeAddress, storage);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
@ -74,11 +72,4 @@ public final class BuyerAsTakerTrade extends BuyerTrade implements TakerTrade {
checkArgument(tradeProtocol instanceof TakerProtocol, "tradeProtocol NOT instanceof TakerProtocol");
((TakerProtocol) tradeProtocol).takeAvailableOffer();
}
@Override
public Coin getPayoutAmount() {
checkNotNull(getTradeAmount(), "Invalid state: getTradeAmount() = null");
return FeePolicy.getSecurityDeposit().add(getTradeAmount());
}
}

View File

@ -18,6 +18,7 @@
package io.bitsquare.trade;
import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.NodeAddress;
@ -29,6 +30,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public abstract class BuyerTrade extends Trade {
// That object is saved to disc. We need to take care of changes to not break deserialization.
@ -36,8 +38,8 @@ public abstract class BuyerTrade extends Trade {
private static final Logger log = LoggerFactory.getLogger(BuyerAsOffererTrade.class);
BuyerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerNodeAddress, storage);
BuyerTrade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradePrice, tradingPeerNodeAddress, storage);
}
BuyerTrade(Offer offer, Storage<? extends TradableList> storage) {
@ -64,6 +66,12 @@ public abstract class BuyerTrade extends Trade {
}
}
@Override
public Coin getPayoutAmount() {
checkNotNull(getTradeAmount(), "Invalid state: getTradeAmount() = null");
return FeePolicy.getSecurityDeposit().add(getTradeAmount());
}
///////////////////////////////////////////////////////////////////////////////////////////
// Setter for Mutable objects

View File

@ -25,6 +25,7 @@ import io.bitsquare.p2p.NodeAddress;
import io.bitsquare.payment.PaymentAccountContractData;
import io.bitsquare.trade.offer.Offer;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.Fiat;
import javax.annotation.concurrent.Immutable;
import java.util.Arrays;
@ -40,6 +41,7 @@ public final class Contract implements Payload {
public final Offer offer;
private final long tradeAmount;
private final long tradePrice;
public final String takeOfferFeeTxID;
public final NodeAddress arbitratorNodeAddress;
private final boolean isBuyerOffererAndSellerTaker;
@ -64,6 +66,7 @@ public final class Contract implements Payload {
public Contract(Offer offer,
Coin tradeAmount,
Fiat tradePrice,
String takeOfferFeeTxID,
NodeAddress buyerNodeAddress,
NodeAddress sellerNodeAddress,
@ -80,6 +83,7 @@ public final class Contract implements Payload {
byte[] offererBtcPubKey,
byte[] takerBtcPubKey) {
this.offer = offer;
this.tradePrice = tradePrice.value;
this.buyerNodeAddress = buyerNodeAddress;
this.sellerNodeAddress = sellerNodeAddress;
this.tradeAmount = tradeAmount.value;
@ -154,6 +158,10 @@ public final class Contract implements Payload {
return Coin.valueOf(tradeAmount);
}
public Fiat getTradePrice() {
return Fiat.valueOf(offer.getCurrencyCode(), tradePrice);
}
public NodeAddress getBuyerNodeAddress() {
return buyerNodeAddress;
}
@ -171,6 +179,7 @@ public final class Contract implements Payload {
Contract contract = (Contract) o;
if (tradeAmount != contract.tradeAmount) return false;
if (tradePrice != contract.tradePrice) return false;
if (isBuyerOffererAndSellerTaker != contract.isBuyerOffererAndSellerTaker) return false;
if (offer != null ? !offer.equals(contract.offer) : contract.offer != null) return false;
if (takeOfferFeeTxID != null ? !takeOfferFeeTxID.equals(contract.takeOfferFeeTxID) : contract.takeOfferFeeTxID != null)
@ -206,6 +215,7 @@ public final class Contract implements Payload {
public int hashCode() {
int result = offer != null ? offer.hashCode() : 0;
result = 31 * result + (int) (tradeAmount ^ (tradeAmount >>> 32));
result = 31 * result + (int) (tradePrice ^ (tradePrice >>> 32));
result = 31 * result + (takeOfferFeeTxID != null ? takeOfferFeeTxID.hashCode() : 0);
result = 31 * result + (arbitratorNodeAddress != null ? arbitratorNodeAddress.hashCode() : 0);
result = 31 * result + (isBuyerOffererAndSellerTaker ? 1 : 0);
@ -229,6 +239,7 @@ public final class Contract implements Payload {
return "Contract{" +
"\n\toffer=" + offer +
"\n\ttradeAmount=" + tradeAmount +
"\n\ttradePrice=" + tradePrice +
"\n\ttakeOfferFeeTxID='" + takeOfferFeeTxID + '\'' +
"\n\tarbitratorAddress=" + arbitratorNodeAddress +
"\n\tisBuyerOffererAndSellerTaker=" + isBuyerOffererAndSellerTaker +

View File

@ -42,8 +42,8 @@ public final class SellerAsTakerTrade extends SellerTrade implements TakerTrade
// Constructor, initialization
///////////////////////////////////////////////////////////////////////////////////////////
public SellerAsTakerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerNodeAddress, storage);
public SellerAsTakerTrade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradePrice, tradingPeerNodeAddress, storage);
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {

View File

@ -18,6 +18,7 @@
package io.bitsquare.trade;
import io.bitsquare.app.Version;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.NodeAddress;
@ -36,8 +37,8 @@ public abstract class SellerTrade extends Trade {
private static final Logger log = LoggerFactory.getLogger(BuyerAsTakerTrade.class);
SellerTrade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradingPeerNodeAddress, storage);
SellerTrade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) {
super(offer, tradeAmount, tradePrice, tradingPeerNodeAddress, storage);
}
SellerTrade(Offer offer, Storage<? extends TradableList> storage) {
@ -64,6 +65,11 @@ public abstract class SellerTrade extends Trade {
}
}
@Override
public Coin getPayoutAmount() {
return FeePolicy.getSecurityDeposit();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Setter for Mutable objects
///////////////////////////////////////////////////////////////////////////////////////////

View File

@ -24,7 +24,6 @@ import com.google.common.util.concurrent.ListenableFuture;
import io.bitsquare.app.Log;
import io.bitsquare.app.Version;
import io.bitsquare.arbitration.ArbitratorManager;
import io.bitsquare.btc.FeePolicy;
import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService;
import io.bitsquare.common.crypto.KeyRing;
@ -42,6 +41,7 @@ import javafx.beans.property.*;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.utils.ExchangeRate;
import org.bitcoinj.utils.Fiat;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
@ -168,6 +168,7 @@ public abstract class Trade implements Tradable, Model {
transient private ObjectProperty<Fiat> tradeVolumeProperty;
@Nullable
private String takeOfferFeeTxId;
private long tradePrice;
///////////////////////////////////////////////////////////////////////////////////////////
@ -190,11 +191,12 @@ public abstract class Trade implements Tradable, Model {
}
// taker
protected Trade(Offer offer, Coin tradeAmount, NodeAddress tradingPeerNodeAddress,
protected Trade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress,
Storage<? extends TradableList> storage) {
this(offer, storage);
this.tradeAmount = tradeAmount;
this.tradePrice = tradePrice;
this.tradingPeerNodeAddress = tradingPeerNodeAddress;
tradeAmountProperty.set(tradeAmount);
tradeVolumeProperty.set(getTradeVolume());
@ -374,9 +376,7 @@ public abstract class Trade implements Tradable, Model {
return offer;
}
public Coin getPayoutAmount() {
return FeePolicy.getSecurityDeposit();
}
abstract public Coin getPayoutAmount();
public ProcessModel getProcessModel() {
return processModel;
@ -384,8 +384,8 @@ public abstract class Trade implements Tradable, Model {
@Nullable
public Fiat getTradeVolume() {
if (tradeAmount != null)
return offer.getVolumeByAmount(tradeAmount);
if (tradeAmount != null && getTradePrice() != null)
return new ExchangeRate(getTradePrice()).coinToFiat(tradeAmount);
else
return null;
}
@ -455,6 +455,14 @@ public abstract class Trade implements Tradable, Model {
tradeVolumeProperty.set(getTradeVolume());
}
public void setTradePrice(long tradePrice) {
this.tradePrice = tradePrice;
}
public Fiat getTradePrice() {
return Fiat.valueOf(offer.getCurrencyCode(), tradePrice);
}
@Nullable
public Coin getTradeAmount() {
return tradeAmount;

View File

@ -24,6 +24,7 @@ import io.bitsquare.btc.AddressEntry;
import io.bitsquare.btc.AddressEntryException;
import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.handlers.FaultHandler;
import io.bitsquare.common.handlers.ResultHandler;
@ -97,6 +98,7 @@ public class TradeManager {
FailedTradesManager failedTradesManager,
ArbitratorManager arbitratorManager,
P2PService p2PService,
PriceFeed priceFeed,
@Named("storage.dir") File storageDir) {
this.user = user;
this.keyRing = keyRing;
@ -109,7 +111,8 @@ public class TradeManager {
this.p2PService = p2PService;
tradableListStorage = new Storage<>(storageDir);
this.trades = new TradableList<>(tradableListStorage, "PendingTrades");
trades = new TradableList<>(tradableListStorage, "PendingTrades");
trades.forEach(e -> e.getOffer().setPriceFeed(priceFeed));
p2PService.addDecryptedDirectMessageListener(new DecryptedDirectMessageListener() {
@Override
@ -261,6 +264,7 @@ public class TradeManager {
// First we check if offer is still available then we create the trade with the protocol
public void onTakeOffer(Coin amount,
long tradePrice,
Coin fundsNeededForTrade,
Offer offer,
String paymentAccountId,
@ -270,11 +274,12 @@ public class TradeManager {
offer.checkOfferAvailability(model,
() -> {
if (offer.getState() == Offer.State.AVAILABLE)
createTrade(amount, fundsNeededForTrade, offer, paymentAccountId, useSavingsWallet, model, tradeResultHandler);
createTrade(amount, tradePrice, fundsNeededForTrade, offer, paymentAccountId, useSavingsWallet, model, tradeResultHandler);
});
}
private void createTrade(Coin amount,
long tradePrice,
Coin fundsNeededForTrade,
Offer offer,
String paymentAccountId,
@ -283,9 +288,9 @@ public class TradeManager {
TradeResultHandler tradeResultHandler) {
Trade trade;
if (offer.getDirection() == Offer.Direction.BUY)
trade = new SellerAsTakerTrade(offer, amount, model.getPeerNodeAddress(), tradableListStorage);
trade = new SellerAsTakerTrade(offer, amount, tradePrice, model.getPeerNodeAddress(), tradableListStorage);
else
trade = new BuyerAsTakerTrade(offer, amount, model.getPeerNodeAddress(), tradableListStorage);
trade = new BuyerAsTakerTrade(offer, amount, tradePrice, model.getPeerNodeAddress(), tradableListStorage);
trade.setTakerPaymentAccountId(paymentAccountId);

View File

@ -18,6 +18,7 @@
package io.bitsquare.trade.closed;
import com.google.inject.Inject;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.storage.Storage;
import io.bitsquare.trade.Tradable;
@ -37,9 +38,10 @@ public class ClosedTradableManager {
private final KeyRing keyRing;
@Inject
public ClosedTradableManager(KeyRing keyRing, @Named("storage.dir") File storageDir) {
public ClosedTradableManager(KeyRing keyRing, PriceFeed priceFeed, @Named("storage.dir") File storageDir) {
this.keyRing = keyRing;
this.closedTrades = new TradableList<>(new Storage<>(storageDir), "ClosedTrades");
closedTrades.forEach(e -> e.getOffer().setPriceFeed(priceFeed));
}
public void add(Tradable tradable) {

View File

@ -18,6 +18,7 @@
package io.bitsquare.trade.failed;
import com.google.inject.Inject;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.storage.Storage;
import io.bitsquare.trade.TradableList;
@ -37,9 +38,10 @@ public class FailedTradesManager {
private final KeyRing keyRing;
@Inject
public FailedTradesManager(KeyRing keyRing, @Named("storage.dir") File storageDir) {
public FailedTradesManager(KeyRing keyRing, PriceFeed priceFeed, @Named("storage.dir") File storageDir) {
this.keyRing = keyRing;
this.failedTrades = new TradableList<>(new Storage<>(storageDir), "FailedTrades");
failedTrades.forEach(e -> e.getOffer().setPriceFeed(priceFeed));
}
public void add(Trade trade) {

View File

@ -19,6 +19,8 @@ package io.bitsquare.trade.offer;
import io.bitsquare.app.Version;
import io.bitsquare.btc.Restrictions;
import io.bitsquare.btc.pricefeed.MarketPrice;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.crypto.KeyRing;
import io.bitsquare.common.crypto.PubKeyRing;
import io.bitsquare.common.handlers.ResultHandler;
@ -106,6 +108,8 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
private final long date;
private final long protocolVersion;
private final long fiatPrice;
private final double marketPriceMargin;
private final boolean usePercentageBasedPrice;
private final long amount;
private final long minAmount;
private final NodeAddress offererNodeAddress;
@ -127,6 +131,7 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
transient private OfferAvailabilityProtocol availabilityProtocol;
@JsonExclude
transient private StringProperty errorMessageProperty = new SimpleStringProperty();
transient private PriceFeed priceFeed;
///////////////////////////////////////////////////////////////////////////////////////////
@ -138,6 +143,8 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
PubKeyRing pubKeyRing,
Direction direction,
long fiatPrice,
double marketPriceMargin,
boolean usePercentageBasedPrice,
long amount,
long minAmount,
String currencyCode,
@ -147,12 +154,15 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
@Nullable String countryCode,
@Nullable ArrayList<String> acceptedCountryCodes,
@Nullable String bankId,
@Nullable ArrayList<String> acceptedBankIds) {
@Nullable ArrayList<String> acceptedBankIds,
PriceFeed priceFeed) {
this.id = id;
this.offererNodeAddress = offererNodeAddress;
this.pubKeyRing = pubKeyRing;
this.direction = direction;
this.fiatPrice = fiatPrice;
this.marketPriceMargin = marketPriceMargin;
this.usePercentageBasedPrice = usePercentageBasedPrice;
this.amount = amount;
this.minAmount = minAmount;
this.currencyCode = currencyCode;
@ -163,6 +173,7 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
this.acceptedCountryCodes = acceptedCountryCodes;
this.bankId = bankId;
this.acceptedBankIds = acceptedBankIds;
this.priceFeed = priceFeed;
protocolVersion = Version.TRADE_PROTOCOL_VERSION;
@ -218,7 +229,7 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
public Fiat getVolumeByAmount(Coin amount) {
if (fiatPrice != 0 && amount != null && !amount.isZero())
return new ExchangeRate(Fiat.valueOf(currencyCode, fiatPrice)).coinToFiat(amount);
return new ExchangeRate(getPrice()).coinToFiat(amount);
else
return null;
}
@ -263,6 +274,10 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
// Setters
///////////////////////////////////////////////////////////////////////////////////////////
public void setPriceFeed(PriceFeed priceFeed) {
this.priceFeed = priceFeed;
}
public void setState(State state) {
this.state = state;
stateProperty().set(state);
@ -312,7 +327,45 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
}
public Fiat getPrice() {
return Fiat.valueOf(currencyCode, fiatPrice);
Fiat priceAsFiat = Fiat.valueOf(currencyCode, fiatPrice);
if (usePercentageBasedPrice && priceFeed != null) {
MarketPrice marketPrice = priceFeed.getMarketPrice(currencyCode);
if (marketPrice != null) {
PriceFeed.Type priceFeedType = direction == Direction.SELL ? PriceFeed.Type.ASK : PriceFeed.Type.BID;
double marketPriceAsDouble = marketPrice.getPrice(priceFeedType);
double factor = direction == Offer.Direction.BUY ? 1 - marketPriceMargin : 1 + marketPriceMargin;
double targetPrice = marketPriceAsDouble * factor;
// round
long factor1 = (long) Math.pow(10, 2);
targetPrice = targetPrice * factor1;
long tmp = Math.round(targetPrice);
targetPrice = (double) tmp / factor1;
try {
return Fiat.parseFiat(currencyCode, String.valueOf(targetPrice));
} catch (Exception e) {
log.warn("Exception at parseToFiat: " + e.toString());
log.warn("We use the static price.");
return priceAsFiat;
}
} else {
log.warn("We don't have a market price. We use the static price instead.");
return priceAsFiat;
}
} else {
if (priceFeed == null)
log.warn("priceFeed must not be null");
return priceAsFiat;
}
}
public double getMarketPriceMargin() {
return marketPriceMargin;
}
public boolean getUsePercentageBasedPrice() {
return usePercentageBasedPrice;
}
public Coin getAmount() {
@ -391,11 +444,11 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Offer)) return false;
Offer offer = (Offer) o;
if (date != offer.date) return false;
if (fiatPrice != offer.fiatPrice) return false;
if (Double.compare(offer.marketPriceMargin, marketPriceMargin) != 0) return false;
if (usePercentageBasedPrice != offer.usePercentageBasedPrice) return false;
if (amount != offer.amount) return false;
if (minAmount != offer.minAmount) return false;
if (id != null ? !id.equals(offer.id) : offer.id != null) return false;
@ -418,7 +471,6 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
if (arbitratorNodeAddresses != null ? !arbitratorNodeAddresses.equals(offer.arbitratorNodeAddresses) : offer.arbitratorNodeAddresses != null)
return false;
return !(offerFeePaymentTxID != null ? !offerFeePaymentTxID.equals(offer.offerFeePaymentTxID) : offer.offerFeePaymentTxID != null);
}
@Override
@ -428,6 +480,9 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
result = 31 * result + (currencyCode != null ? currencyCode.hashCode() : 0);
result = 31 * result + (int) (date ^ (date >>> 32));
result = 31 * result + (int) (fiatPrice ^ (fiatPrice >>> 32));
long temp = Double.doubleToLongBits(marketPriceMargin);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + (usePercentageBasedPrice ? 1 : 0);
result = 31 * result + (int) (amount ^ (amount >>> 32));
result = 31 * result + (int) (minAmount ^ (minAmount >>> 32));
result = 31 * result + (offererNodeAddress != null ? offererNodeAddress.hashCode() : 0);
@ -451,6 +506,8 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
"\n\tcurrencyCode='" + currencyCode + '\'' +
"\n\tdate=" + date +
"\n\tfiatPrice=" + fiatPrice +
"\n\tmarketPriceMargin=" + marketPriceMargin +
"\n\tusePercentageBasedPrice=" + usePercentageBasedPrice +
"\n\tamount=" + amount +
"\n\tminAmount=" + minAmount +
"\n\toffererAddress=" + offererNodeAddress +
@ -471,5 +528,4 @@ public final class Offer implements StoragePayload, RequiresOwnerIsOnlinePayload
"\n\tTAC_TAKER=" + TAC_TAKER +
'}';
}
}

View File

@ -17,6 +17,7 @@
package io.bitsquare.trade.offer;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.handlers.ErrorMessageHandler;
import io.bitsquare.common.handlers.ResultHandler;
import io.bitsquare.p2p.P2PService;
@ -45,6 +46,7 @@ public class OfferBookService {
}
private final P2PService p2PService;
private PriceFeed priceFeed;
private final List<OfferBookChangedListener> offerBookChangedListeners = new LinkedList<>();
@ -53,15 +55,19 @@ public class OfferBookService {
///////////////////////////////////////////////////////////////////////////////////////////
@Inject
public OfferBookService(P2PService p2PService) {
public OfferBookService(P2PService p2PService, PriceFeed priceFeed) {
this.p2PService = p2PService;
this.priceFeed = priceFeed;
p2PService.addHashSetChangedListener(new HashMapChangedListener() {
@Override
public void onAdded(ProtectedStorageEntry data) {
offerBookChangedListeners.stream().forEach(listener -> {
if (data.getStoragePayload() instanceof Offer)
listener.onAdded((Offer) data.getStoragePayload());
if (data.getStoragePayload() instanceof Offer) {
Offer offer = (Offer) data.getStoragePayload();
offer.setPriceFeed(priceFeed);
listener.onAdded(offer);
}
});
}
@ -118,7 +124,11 @@ public class OfferBookService {
public List<Offer> getOffers() {
return p2PService.getDataMap().values().stream()
.filter(data -> data.getStoragePayload() instanceof Offer)
.map(data -> (Offer) data.getStoragePayload())
.map(data -> {
Offer offer = (Offer) data.getStoragePayload();
offer.setPriceFeed(priceFeed);
return offer;
})
.collect(Collectors.toList());
}

View File

@ -22,6 +22,7 @@ import io.bitsquare.app.Log;
import io.bitsquare.btc.AddressEntry;
import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.common.Timer;
import io.bitsquare.common.UserThread;
import io.bitsquare.common.crypto.KeyRing;
@ -95,6 +96,7 @@ public class OpenOfferManager implements PeerManager.Listener, DecryptedDirectMe
TradeWalletService tradeWalletService,
OfferBookService offerBookService,
ClosedTradableManager closedTradableManager,
PriceFeed priceFeed,
@Named("storage.dir") File storageDir) {
this.keyRing = keyRing;
this.user = user;
@ -105,7 +107,8 @@ public class OpenOfferManager implements PeerManager.Listener, DecryptedDirectMe
this.closedTradableManager = closedTradableManager;
openOffersStorage = new Storage<>(storageDir);
this.openOffers = new TradableList<>(openOffersStorage, "OpenOffers");
openOffers = new TradableList<>(openOffersStorage, "OpenOffers");
openOffers.forEach(e -> e.getOffer().setPriceFeed(priceFeed));
// In case the app did get killed the shutDown from the modules is not called, so we use a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(OpenOfferManager.this::shutDown,

View File

@ -68,7 +68,6 @@ public class ProcessModel implements Model, Serializable {
transient private KeyRing keyRing;
transient private P2PService p2PService;
// Mutable
public final TradingPeer tradingPeer;
transient private TradeMessage tradeMessage;

View File

@ -35,6 +35,7 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
public final long tradeAmount;
public final long tradePrice;
public final byte[] takerMultiSigPubKey;
public final ArrayList<RawTransactionInput> rawTransactionInputs;
public final long changeOutputValue;
@ -52,6 +53,7 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
public PayDepositRequest(NodeAddress senderNodeAddress,
String tradeId,
long tradeAmount,
long tradePrice,
ArrayList<RawTransactionInput> rawTransactionInputs,
long changeOutputValue,
String changeOutputAddress,
@ -66,6 +68,7 @@ public final class PayDepositRequest extends TradeMessage implements MailboxMess
super(tradeId);
this.senderNodeAddress = senderNodeAddress;
this.tradeAmount = tradeAmount;
this.tradePrice = tradePrice;
this.rawTransactionInputs = rawTransactionInputs;
this.changeOutputValue = changeOutputValue;
this.changeOutputAddress = changeOutputAddress;

View File

@ -60,6 +60,7 @@ public class CreateAndSignContract extends TradeTask {
Contract contract = new Contract(
processModel.getOffer(),
trade.getTradeAmount(),
trade.getTradePrice(),
trade.getTakeOfferFeeTxId(),
buyerNodeAddress,
sellerNodeAddress,

View File

@ -26,6 +26,7 @@ import io.bitsquare.trade.Trade;
import io.bitsquare.trade.protocol.trade.messages.PayDepositRequest;
import io.bitsquare.trade.protocol.trade.tasks.TradeTask;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.Fiat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -76,6 +77,26 @@ public class ProcessPayDepositRequest extends TradeTask {
if (payDepositRequest.acceptedArbitratorNodeAddresses.size() < 1)
failed("acceptedArbitratorNames size must be at least 1");
trade.setArbitratorNodeAddress(checkNotNull(payDepositRequest.arbitratorNodeAddress));
long takersTradePrice = payDepositRequest.tradePrice;
checkArgument(takersTradePrice > 0);
Fiat tradePriceAsFiat = Fiat.valueOf(trade.getOffer().getCurrencyCode(), takersTradePrice);
Fiat offerPriceAsFiat = trade.getOffer().getPrice();
double factor = (double) takersTradePrice / (double) offerPriceAsFiat.value;
// We allow max. 2 % difference between own offer price calculation and takers calculation.
// Market price might be different at offerers and takers side so we need a bit of tolerance.
// The tolerance will get smaller once we have multiple price feeds avoiding fast price fluctuations
// from one provider.
if (Math.abs(1 - factor) > 0.02) {
String msg = "Takers tradePrice is outside our market price tolerance.\n" +
"tradePriceAsFiat=" + tradePriceAsFiat.toFriendlyString() + "\n" +
"offerPriceAsFiat=" + offerPriceAsFiat.toFriendlyString();
log.warn(msg);
failed(msg);
}
trade.setTradePrice(takersTradePrice);
checkArgument(payDepositRequest.tradeAmount > 0);
trade.setTradeAmount(Coin.valueOf(payDepositRequest.tradeAmount));
@ -83,7 +104,7 @@ public class ProcessPayDepositRequest extends TradeTask {
trade.setTradingPeerNodeAddress(processModel.getTempTradingPeerNodeAddress());
removeMailboxMessageAfterProcessing();
complete();
} catch (Throwable t) {
failed(t);

View File

@ -49,6 +49,7 @@ public class SendPayDepositRequest extends TradeTask {
processModel.getMyAddress(),
processModel.getId(),
trade.getTradeAmount().value,
trade.getTradePrice().value,
processModel.getRawTransactionInputs(),
processModel.getChangeOutputValue(),
processModel.getChangeOutputAddress(),

View File

@ -61,6 +61,7 @@ public class VerifyAndSignContract extends TradeTask {
Contract contract = new Contract(
processModel.getOffer(),
trade.getTradeAmount(),
trade.getTradePrice(),
trade.getTakeOfferFeeTxId(),
buyerNodeAddress,
sellerNodeAddress,

View File

@ -110,6 +110,7 @@ public final class Preferences implements Persistable {
private double maxPriceDistanceInPercent;
private boolean useInvertedMarketPrice;
private boolean useStickyMarketPrice = false;
private boolean usePercentageBasedPrice = false;
// Observable wrappers
transient private final StringProperty btcDenominationProperty = new SimpleStringProperty(btcDenomination);
@ -162,6 +163,7 @@ public final class Preferences implements Persistable {
// useTorForBitcoinJ = persisted.getUseTorForBitcoinJ();
useTorForBitcoinJ = false;
useStickyMarketPrice = persisted.getUseStickyMarketPrice();
usePercentageBasedPrice = persisted.getUsePercentageBasedPrice();
showOwnOffersInOfferBook = persisted.getShowOwnOffersInOfferBook();
maxPriceDistanceInPercent = persisted.getMaxPriceDistanceInPercent();
// Backward compatible to version 0.3.6. Can be removed after a while
@ -368,6 +370,12 @@ public final class Preferences implements Persistable {
storage.queueUpForSave();
}
public void setUsePercentageBasedPrice(boolean usePercentageBasedPrice) {
this.usePercentageBasedPrice = usePercentageBasedPrice;
storage.queueUpForSave();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getter
///////////////////////////////////////////////////////////////////////////////////////////
@ -488,6 +496,10 @@ public final class Preferences implements Persistable {
return useStickyMarketPrice;
}
public boolean getUsePercentageBasedPrice() {
return usePercentageBasedPrice;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private

View File

@ -76,7 +76,7 @@ import static io.bitsquare.app.BitsquareEnvironment.APP_NAME_KEY;
public class BitsquareApp extends Application {
private static final Logger log = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(BitsquareApp.class);
public static final boolean DEV_MODE = false;
public static final boolean DEV_MODE = true;
public static final boolean IS_RELEASE_VERSION = !DEV_MODE && true;
private static Environment env;

View File

@ -496,6 +496,26 @@ textfield */
-fx-border-insets: 0 0 0 -2;
}
#toggle-price-left {
-fx-border-radius: 4 0 0 4;
-fx-padding: 4 4 4 4;
-fx-border-color: #aaa;
-fx-border-style: solid none solid solid;
-fx-border-insets: 0 -2 0 0;
-fx-background-insets: 0 -2 0 0;
-fx-background-radius: 4 0 0 4;
}
#toggle-price-right {
-fx-border-radius: 0 4 4 0;
-fx-padding: 4 4 4 4;
-fx-border-color: #aaa;
-fx-border-style: solid solid solid none;
-fx-border-insets: 0 0 0 -2;
-fx-background-insets: 0 0 0 -2;
-fx-background-radius: 0 4 4 0;
}
#totals-separator {
-fx-background: #AAAAAA;
}

View File

@ -404,7 +404,7 @@ public class MainViewModel implements ViewModel {
result = numPeersString + " / synchronized with " + btcNetworkAsString;
btcSplashSyncIconId.set("image-connection-synced");
} else if (percentage > 0.0) {
result = numPeersString + " / synchronizing with " + btcNetworkAsString + ": " + formatter.formatToPercent(percentage);
result = numPeersString + " / synchronizing with " + btcNetworkAsString + ": " + formatter.formatToPercentWithSymbol(percentage);
} else {
result = numPeersString + " / connecting to " + btcNetworkAsString;
}
@ -497,7 +497,11 @@ public class MainViewModel implements ViewModel {
setupBtcNumPeersWatcher();
setupP2PNumPeersWatcher();
updateBalance();
setupDevDummyPaymentAccount();
if (BitsquareApp.DEV_MODE) {
preferences.setShowOwnOffersInOfferBook(true);
if (user.getPaymentAccounts().isEmpty())
setupDevDummyPaymentAccount();
}
setupMarketPriceFeed();
swapPendingOfferFundingEntries();
fillPriceFeedComboBoxItems();
@ -713,7 +717,7 @@ public class MainViewModel implements ViewModel {
marketPriceBinding.subscribe((observable, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(oldValue)) {
setMarketPriceInItems();
String code = preferences.getUseStickyMarketPrice() ?
preferences.getPreferredTradeCurrency().getCode() :
priceFeed.currencyCodeProperty().get();
@ -896,12 +900,10 @@ public class MainViewModel implements ViewModel {
}
private void setupDevDummyPaymentAccount() {
if (BitsquareApp.DEV_MODE && user.getPaymentAccounts().isEmpty()) {
OKPayAccount okPayAccount = new OKPayAccount();
okPayAccount.setAccountNr("dummy");
okPayAccount.setAccountName("OKPay dummy");
okPayAccount.setSelectedTradeCurrency(CurrencyUtil.getDefaultTradeCurrency());
user.addPaymentAccount(okPayAccount);
}
OKPayAccount okPayAccount = new OKPayAccount();
okPayAccount.setAccountNr("dummy");
okPayAccount.setAccountName("OKPay dummy");
okPayAccount.setSelectedTradeCurrency(CurrencyUtil.getDefaultTradeCurrency());
user.addPaymentAccount(okPayAccount);
}
}

View File

@ -89,6 +89,7 @@ class CreateOfferDataModel extends ActivatableDataModel {
final StringProperty btcCode = new SimpleStringProperty();
final BooleanProperty isWalletFunded = new SimpleBooleanProperty();
final BooleanProperty usePercentageBasedPrice = new SimpleBooleanProperty();
//final BooleanProperty isMainNet = new SimpleBooleanProperty();
//final BooleanProperty isFeeFromFundingTxSufficient = new SimpleBooleanProperty();
@ -108,6 +109,7 @@ class CreateOfferDataModel extends ActivatableDataModel {
private Notification walletFundedNotification;
boolean useSavingsWallet;
Coin totalAvailableBalance;
private double percentageBasedPrice = 0;
///////////////////////////////////////////////////////////////////////////////////////////
@ -138,6 +140,8 @@ class CreateOfferDataModel extends ActivatableDataModel {
networkFeeAsCoin = FeePolicy.getFixedTxFeeForTrades();
securityDepositAsCoin = FeePolicy.getSecurityDeposit();
usePercentageBasedPrice.set(preferences.getUsePercentageBasedPrice());
balanceListener = new BalanceListener(getAddressEntry().getAddress()) {
@Override
public void onBalanceChanged(Coin balance, Transaction tx) {
@ -253,6 +257,7 @@ class CreateOfferDataModel extends ActivatableDataModel {
Offer createAndGetOffer() {
long fiatPrice = priceAsFiat.get() != null ? priceAsFiat.get().getValue() : 0L;
long amount = amountAsCoin.get() != null ? amountAsCoin.get().getValue() : 0L;
long minAmount = minAmountAsCoin.get() != null ? minAmountAsCoin.get().getValue() : 0L;
@ -284,6 +289,8 @@ class CreateOfferDataModel extends ActivatableDataModel {
keyRing.getPubKeyRing(),
direction,
fiatPrice,
percentageBasedPrice,
usePercentageBasedPrice.get(),
amount,
minAmount,
tradeCurrencyCode.get(),
@ -293,7 +300,8 @@ class CreateOfferDataModel extends ActivatableDataModel {
countryCode,
acceptedCountryCodes,
bankId,
acceptedBanks);
acceptedBanks,
priceFeed);
}
void onPlaceOffer(Offer offer, TransactionResultHandler resultHandler) {
@ -378,6 +386,11 @@ class CreateOfferDataModel extends ActivatableDataModel {
return user.getAcceptedArbitrators().size() > 0;
}
public void setUsePercentageBasedPrice(boolean usePercentageBasedPrice) {
this.usePercentageBasedPrice.set(usePercentageBasedPrice);
preferences.setUsePercentageBasedPrice(usePercentageBasedPrice);
}
/*boolean isFeeFromFundingTxSufficient() {
return !isMainNet.get() || feeFromFundingTxProperty.get().compareTo(FeePolicy.getMinRequiredFeeForFundingTx()) >= 0;
}*/
@ -484,4 +497,12 @@ class CreateOfferDataModel extends ActivatableDataModel {
walletService.swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.OFFER_FUNDING);
walletService.swapTradeEntryToAvailableEntry(offerId, AddressEntry.Context.RESERVED_FOR_TRADE);
}
double getPercentageBasedPrice() {
return percentageBasedPrice;
}
void setPercentageBasedPrice(double percentageBasedPrice) {
this.percentageBasedPrice = percentageBasedPrice;
}
}

View File

@ -52,6 +52,7 @@ import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.*;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
@ -70,6 +71,8 @@ import org.jetbrains.annotations.NotNull;
import javax.inject.Inject;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static io.bitsquare.gui.util.FormBuilder.*;
@ -88,22 +91,23 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
private BalanceTextField balanceTextField;
private TitledGroupBg payFundsPane;
private ProgressIndicator spinner;
private Button nextButton, cancelButton1, cancelButton2, fundFromSavingsWalletButton, fundFromExternalWalletButton, placeOfferButton;
private InputTextField amountTextField, minAmountTextField, priceTextField, volumeTextField;
private Button nextButton, cancelButton1, cancelButton2, fundFromSavingsWalletButton, fundFromExternalWalletButton, placeOfferButton, usePercentageBasedPriceButton;
private InputTextField amountTextField, minAmountTextField, priceTextField, priceAsPercentageTextField, volumeTextField;
private TextField currencyTextField;
private Label directionLabel, amountDescriptionLabel, addressLabel, balanceLabel, totalToPayLabel, totalToPayInfoIconLabel, amountBtcLabel, priceCurrencyLabel,
volumeCurrencyLabel, minAmountBtcLabel, priceDescriptionLabel, volumeDescriptionLabel, currencyTextFieldLabel,
currencyComboBoxLabel, spinnerInfoLabel;
currencyComboBoxLabel, spinnerInfoLabel, priceAsPercentageLabel;
private TextFieldWithCopyIcon totalToPayTextField;
private ComboBox<PaymentAccount> paymentAccountsComboBox;
private ComboBox<TradeCurrency> currencyComboBox;
private PopOver totalToPayInfoPopover;
private ToggleButton fixedPriceButton, percentagePriceButton;
private OfferView.CloseHandler closeHandler;
private ChangeListener<Boolean> amountFocusedListener;
private ChangeListener<Boolean> minAmountFocusedListener;
private ChangeListener<Boolean> priceFocusedListener;
private ChangeListener<Boolean> priceFocusedListener, priceAsPercentageFocusedListener;
private ChangeListener<Boolean> volumeFocusedListener;
private ChangeListener<Boolean> showWarningInvalidBtcDecimalPlacesListener;
private ChangeListener<Boolean> showWarningInvalidFiatDecimalPlacesPlacesListener;
@ -122,6 +126,7 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
private Subscription isSpinnerVisibleSubscription;
private Subscription cancelButton2StyleSubscription;
private Subscription balanceSubscription;
private List<Node> editOfferElements = new ArrayList<>();
///////////////////////////////////////////////////////////////////////////////////////////
@ -175,6 +180,9 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
if (spinner != null && spinner.isVisible())
spinner.setProgress(-1);
percentagePriceButton.setSelected(model.dataModel.usePercentageBasedPrice.get());
fixedPriceButton.setSelected(!model.dataModel.usePercentageBasedPrice.get());
directionLabel.setText(model.getDirectionLabel());
amountDescriptionLabel.setText(model.getAmountDescription());
addressTextField.setAddress(model.getAddressAsString());
@ -277,12 +285,10 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
private void onShowPayFundsScreen() {
model.onShowPayFundsScreen();
amountTextField.setMouseTransparent(true);
minAmountTextField.setMouseTransparent(true);
priceTextField.setMouseTransparent(true);
volumeTextField.setMouseTransparent(true);
currencyComboBox.setMouseTransparent(true);
paymentAccountsComboBox.setMouseTransparent(true);
editOfferElements.stream().forEach(node -> {
node.setMouseTransparent(true);
node.setFocusTraversable(false);
});
balanceTextField.setTargetAmount(model.dataModel.totalToPayAsCoin.get());
@ -407,6 +413,11 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
private void addBindings() {
amountBtcLabel.textProperty().bind(model.btcCode);
priceCurrencyLabel.textProperty().bind(createStringBinding(() -> model.tradeCurrencyCode.get() + "/" + model.btcCode.get(), model.btcCode, model.tradeCurrencyCode));
priceTextField.disableProperty().bind(model.dataModel.usePercentageBasedPrice);
priceCurrencyLabel.disableProperty().bind(model.dataModel.usePercentageBasedPrice);
priceAsPercentageTextField.disableProperty().bind(model.dataModel.usePercentageBasedPrice.not());
priceAsPercentageLabel.disableProperty().bind(model.dataModel.usePercentageBasedPrice.not());
priceAsPercentageLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty());
volumeCurrencyLabel.textProperty().bind(model.tradeCurrencyCode);
minAmountBtcLabel.textProperty().bind(model.btcCode);
priceDescriptionLabel.textProperty().bind(createStringBinding(() -> BSResources.get("createOffer.amountPriceBox.priceDescription", model.tradeCurrencyCode.get()), model.tradeCurrencyCode));
@ -414,6 +425,7 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
amountTextField.textProperty().bindBidirectional(model.amount);
minAmountTextField.textProperty().bindBidirectional(model.minAmount);
priceTextField.textProperty().bindBidirectional(model.price);
priceAsPercentageTextField.textProperty().bindBidirectional(model.priceAsPercentage);
volumeTextField.textProperty().bindBidirectional(model.volume);
volumeTextField.promptTextProperty().bind(model.volumePromptLabel);
totalToPayTextField.textProperty().bind(model.totalToPay);
@ -452,6 +464,10 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
private void removeBindings() {
amountBtcLabel.textProperty().unbind();
priceCurrencyLabel.textProperty().unbind();
priceTextField.disableProperty().unbind();
priceCurrencyLabel.disableProperty().unbind();
priceAsPercentageTextField.disableProperty().unbind();
priceAsPercentageLabel.disableProperty().unbind();
volumeCurrencyLabel.textProperty().unbind();
minAmountBtcLabel.textProperty().unbind();
priceDescriptionLabel.textProperty().unbind();
@ -459,6 +475,8 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
amountTextField.textProperty().unbindBidirectional(model.amount);
minAmountTextField.textProperty().unbindBidirectional(model.minAmount);
priceTextField.textProperty().unbindBidirectional(model.price);
priceAsPercentageTextField.textProperty().unbindBidirectional(model.priceAsPercentage);
priceAsPercentageLabel.prefWidthProperty().unbind();
volumeTextField.textProperty().unbindBidirectional(model.volume);
volumeTextField.promptTextProperty().unbindBidirectional(model.volume);
totalToPayTextField.textProperty().unbind();
@ -524,6 +542,10 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
model.onFocusOutPriceTextField(oldValue, newValue, priceTextField.getText());
priceTextField.setText(model.price.get());
};
priceAsPercentageFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutPriceAsPercentageTextField(oldValue, newValue, priceAsPercentageTextField.getText());
priceAsPercentageTextField.setText(model.priceAsPercentage.get());
};
volumeFocusedListener = (o, oldValue, newValue) -> {
model.onFocusOutVolumeTextField(oldValue, newValue, volumeTextField.getText());
volumeTextField.setText(model.volume.get());
@ -583,6 +605,7 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
tradeCurrencyCodeListener = (observable, oldValue, newValue) -> {
priceTextField.clear();
priceAsPercentageTextField.clear();
volumeTextField.clear();
};
@ -621,6 +644,7 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
amountTextField.focusedProperty().addListener(amountFocusedListener);
minAmountTextField.focusedProperty().addListener(minAmountFocusedListener);
priceTextField.focusedProperty().addListener(priceFocusedListener);
priceAsPercentageTextField.focusedProperty().addListener(priceAsPercentageFocusedListener);
volumeTextField.focusedProperty().addListener(volumeFocusedListener);
// warnings
@ -644,6 +668,7 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
amountTextField.focusedProperty().removeListener(amountFocusedListener);
minAmountTextField.focusedProperty().removeListener(minAmountFocusedListener);
priceTextField.focusedProperty().removeListener(priceFocusedListener);
priceAsPercentageTextField.focusedProperty().removeListener(priceAsPercentageFocusedListener);
volumeTextField.focusedProperty().removeListener(volumeFocusedListener);
// warnings
@ -702,11 +727,14 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
paymentAccountsComboBox = addLabelComboBox(gridPane, gridRow, "Payment account:", Layout.FIRST_ROW_DISTANCE).second;
paymentAccountsComboBox.setPromptText("Select payment account");
editOfferElements.add(paymentAccountsComboBox);
// we display either currencyComboBox (multi currency account) or currencyTextField (single)
Tuple2<Label, ComboBox> currencyComboBoxTuple = addLabelComboBox(gridPane, ++gridRow, "Currency:");
currencyComboBoxLabel = currencyComboBoxTuple.first;
editOfferElements.add(currencyComboBoxLabel);
currencyComboBox = currencyComboBoxTuple.second;
editOfferElements.add(currencyComboBox);
currencyComboBox.setPromptText("Select currency");
currencyComboBox.setConverter(new StringConverter<TradeCurrency>() {
@Override
@ -722,7 +750,9 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
Tuple2<Label, TextField> currencyTextFieldTuple = addLabelTextField(gridPane, gridRow, "Currency:", "", 5);
currencyTextFieldLabel = currencyTextFieldTuple.first;
editOfferElements.add(currencyTextFieldLabel);
currencyTextField = currencyTextFieldTuple.second;
editOfferElements.add(currencyTextField);
}
private void addAmountPriceGroup() {
@ -745,14 +775,15 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
gridPane.getChildren().add(imageVBox);
addAmountPriceFields();
addMinAmountBox();
addSecondRow();
Tuple2<Button, Button> tuple = add2ButtonsAfterGroup(gridPane, ++gridRow, BSResources.get("createOffer.amountPriceBox.next"), BSResources.get("shared.cancel"));
nextButton = tuple.first;
editOfferElements.add(nextButton);
nextButton.disableProperty().bind(model.isNextButtonDisabled);
//UserThread.runAfter(() -> nextButton.requestFocus(), 100, TimeUnit.MILLISECONDS);
cancelButton1 = tuple.second;
editOfferElements.add(cancelButton1);
cancelButton1.setDefaultButton(false);
cancelButton1.setOnAction(e -> {
close();
@ -887,9 +918,12 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
Tuple3<HBox, InputTextField, Label> amountValueCurrencyBoxTuple = FormBuilder.getValueCurrencyBox(BSResources.get("createOffer.amount.prompt"));
HBox amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
amountTextField = amountValueCurrencyBoxTuple.second;
editOfferElements.add(amountTextField);
amountBtcLabel = amountValueCurrencyBoxTuple.third;
editOfferElements.add(amountBtcLabel);
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox, model.getAmountDescription());
amountDescriptionLabel = amountInputBoxTuple.first;
editOfferElements.add(amountDescriptionLabel);
VBox amountBox = amountInputBoxTuple.second;
// x
@ -897,15 +931,42 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
xLabel.setFont(Font.font("Helvetica-Bold", 20));
xLabel.setPadding(new Insets(14, 3, 0, 3));
// price
// price as fiat
Tuple3<HBox, InputTextField, Label> priceValueCurrencyBoxTuple = FormBuilder.getValueCurrencyBox(BSResources.get("createOffer.price.prompt"));
HBox priceValueCurrencyBox = priceValueCurrencyBoxTuple.first;
priceTextField = priceValueCurrencyBoxTuple.second;
editOfferElements.add(priceTextField);
priceCurrencyLabel = priceValueCurrencyBoxTuple.third;
editOfferElements.add(priceCurrencyLabel);
Tuple2<Label, VBox> priceInputBoxTuple = getTradeInputBox(priceValueCurrencyBox, BSResources.get("createOffer.amountPriceBox.priceDescription"));
priceDescriptionLabel = priceInputBoxTuple.first;
editOfferElements.add(priceDescriptionLabel);
VBox priceBox = priceInputBoxTuple.second;
// Fixed/Percentage toggle
ToggleGroup toggleGroup = new ToggleGroup();
fixedPriceButton = new ToggleButton("Fixed");
editOfferElements.add(fixedPriceButton);
fixedPriceButton.setId("toggle-price-left");
fixedPriceButton.setToggleGroup(toggleGroup);
fixedPriceButton.selectedProperty().addListener((ov, oldValue, newValue) -> {
model.dataModel.setUsePercentageBasedPrice(!newValue);
percentagePriceButton.setSelected(!newValue);
});
percentagePriceButton = new ToggleButton("Percentage");
editOfferElements.add(percentagePriceButton);
percentagePriceButton.setId("toggle-price-right");
percentagePriceButton.setToggleGroup(toggleGroup);
percentagePriceButton.selectedProperty().addListener((ov, oldValue, newValue) -> {
model.dataModel.setUsePercentageBasedPrice(newValue);
fixedPriceButton.setSelected(!newValue);
});
HBox toggleButtons = new HBox();
toggleButtons.setPadding(new Insets(18, 0, 0, 0));
toggleButtons.getChildren().addAll(fixedPriceButton, percentagePriceButton);
// =
Label resultLabel = new Label("=");
resultLabel.setFont(Font.font("Helvetica-Bold", 20));
@ -915,15 +976,18 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
Tuple3<HBox, InputTextField, Label> volumeValueCurrencyBoxTuple = FormBuilder.getValueCurrencyBox(BSResources.get("createOffer.volume.prompt"));
HBox volumeValueCurrencyBox = volumeValueCurrencyBoxTuple.first;
volumeTextField = volumeValueCurrencyBoxTuple.second;
editOfferElements.add(volumeTextField);
volumeCurrencyLabel = volumeValueCurrencyBoxTuple.third;
editOfferElements.add(volumeCurrencyLabel);
Tuple2<Label, VBox> volumeInputBoxTuple = getTradeInputBox(volumeValueCurrencyBox, model.volumeDescriptionLabel.get());
volumeDescriptionLabel = volumeInputBoxTuple.first;
editOfferElements.add(volumeDescriptionLabel);
VBox volumeBox = volumeInputBoxTuple.second;
HBox hBox = new HBox();
hBox.setSpacing(5);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(amountBox, xLabel, priceBox, resultLabel, volumeBox);
hBox.getChildren().addAll(amountBox, xLabel, priceBox, toggleButtons, resultLabel, volumeBox);
GridPane.setRowIndex(hBox, gridRow);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(Layout.FIRST_ROW_AND_GROUP_DISTANCE, 10, 0, 0));
@ -931,19 +995,46 @@ public class CreateOfferView extends ActivatableViewAndModel<AnchorPane, CreateO
gridPane.getChildren().add(hBox);
}
private void addMinAmountBox() {
private void addSecondRow() {
Tuple3<HBox, InputTextField, Label> priceAsPercentageTuple = FormBuilder.getValueCurrencyBox(BSResources.get("createOffer.price.prompt"));
HBox priceAsPercentageValueCurrencyBox = priceAsPercentageTuple.first;
priceAsPercentageTextField = priceAsPercentageTuple.second;
editOfferElements.add(priceAsPercentageTextField);
priceAsPercentageLabel = priceAsPercentageTuple.third;
editOfferElements.add(priceAsPercentageLabel);
Tuple2<Label, VBox> priceAsPercentageInputBoxTuple = getTradeInputBox(priceAsPercentageValueCurrencyBox, "Distance in % from market price");
priceAsPercentageInputBoxTuple.first.setPrefWidth(200);
VBox priceAsPercentageInputBox = priceAsPercentageInputBoxTuple.second;
priceAsPercentageTextField.setPromptText("Enter % value");
priceAsPercentageLabel.setText("%");
priceAsPercentageLabel.setStyle("-fx-alignment: center;");
Tuple3<HBox, InputTextField, Label> amountValueCurrencyBoxTuple = getValueCurrencyBox(BSResources.get("createOffer.amount.prompt"));
HBox amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
minAmountTextField = amountValueCurrencyBoxTuple.second;
editOfferElements.add(minAmountTextField);
minAmountBtcLabel = amountValueCurrencyBoxTuple.third;
editOfferElements.add(minAmountBtcLabel);
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox, BSResources.get("createOffer.amountPriceBox" +
".minAmountDescription"));
VBox box = amountInputBoxTuple.second;
GridPane.setRowIndex(box, ++gridRow);
GridPane.setColumnIndex(box, 1);
GridPane.setMargin(box, new Insets(5, 10, 5, 0));
gridPane.getChildren().add(box);
Label xLabel = new Label("x");
xLabel.setFont(Font.font("Helvetica-Bold", 20));
xLabel.setPadding(new Insets(14, 3, 0, 3));
xLabel.setVisible(false); // we just use it to get the same layout as the upper row
HBox hBox = new HBox();
hBox.setSpacing(5);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(amountInputBoxTuple.second, xLabel, priceAsPercentageInputBox);
GridPane.setRowIndex(hBox, ++gridRow);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(5, 10, 5, 0));
GridPane.setColumnSpan(hBox, 2);
gridPane.getChildren().add(hBox);
}

View File

@ -71,6 +71,7 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
final StringProperty amount = new SimpleStringProperty();
final StringProperty minAmount = new SimpleStringProperty();
final StringProperty price = new SimpleStringProperty();
final StringProperty priceAsPercentage = new SimpleStringProperty();
final StringProperty volume = new SimpleStringProperty();
final StringProperty volumeDescriptionLabel = new SimpleStringProperty();
final StringProperty volumePromptLabel = new SimpleStringProperty();
@ -103,7 +104,7 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
private ChangeListener<String> amountListener;
private ChangeListener<String> minAmountListener;
private ChangeListener<String> priceListener;
private ChangeListener<String> priceListener, priceAsPercentageListener;
private ChangeListener<String> volumeListener;
private ChangeListener<Coin> amountAsCoinListener;
private ChangeListener<Coin> minAmountAsCoinListener;
@ -114,6 +115,9 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
private ChangeListener<String> errorMessageListener;
private Offer offer;
private Timer timeoutTimer;
private PriceFeed.Type priceFeedType;
private boolean priceAsPercentageIsInput;
private ChangeListener<Boolean> usePercentageBasedPriceListener;
///////////////////////////////////////////////////////////////////////////////////////////
@ -235,9 +239,70 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
setPriceToModel();
calculateVolume();
dataModel.calculateTotalToPay();
if (!priceAsPercentageIsInput) {
MarketPrice marketPrice = priceFeed.getMarketPrice(dataModel.tradeCurrencyCode.get());
if (marketPrice != null) {
double marketPriceAsDouble = marketPrice.getPrice(priceFeedType);
try {
double priceAsDouble = formatter.parseNumberStringToDouble(price.get());
double priceFactor = priceAsDouble / marketPriceAsDouble;
priceFactor = dataModel.getDirection() == Offer.Direction.BUY ? 1 - priceFactor : 1 + priceFactor;
priceAsPercentage.set(formatter.formatToPercent(priceFactor, 2));
} catch (NumberFormatException t) {
priceAsPercentage.set("");
new Popup().warning("Your input is not a valid number.")
.show();
}
}
}
}
updateButtonDisableState();
};
priceAsPercentageListener = (ov, oldValue, newValue) -> {
if (priceAsPercentageIsInput) {
try {
if (!newValue.isEmpty() && !newValue.equals("-")) {
double percentageBasedPrice = formatter.parsePercentStringToDouble(newValue);
if (percentageBasedPrice >= 1 || percentageBasedPrice <= -1) {
dataModel.setPercentageBasedPrice(0);
UserThread.execute(() -> priceAsPercentage.set("0"));
new Popup().warning("You cannot set a percentage of 100% or larger. Please enter a percentage number like \"5.4\" for 5.4%")
.show();
} else {
MarketPrice marketPrice = priceFeed.getMarketPrice(dataModel.tradeCurrencyCode.get());
if (marketPrice != null) {
percentageBasedPrice = formatter.roundDouble(percentageBasedPrice, 4);
dataModel.setPercentageBasedPrice(percentageBasedPrice);
double marketPriceAsDouble = marketPrice.getPrice(priceFeedType);
double factor = dataModel.getDirection() == Offer.Direction.BUY ? 1 - percentageBasedPrice : 1 + percentageBasedPrice;
double targetPrice = marketPriceAsDouble * factor;
price.set(formatter.formatToNumberString(targetPrice, 2));
setPriceToModel();
calculateVolume();
dataModel.calculateTotalToPay();
updateButtonDisableState();
} else {
new Popup().warning("There is no price feed available for that currency. You cannot use percent based price.")
.show();
}
}
} else {
dataModel.setPercentageBasedPrice(0);
}
} catch (Throwable t) {
dataModel.setPercentageBasedPrice(0);
UserThread.execute(() -> priceAsPercentage.set("0"));
new Popup().warning("Your input is not a valid number. Please enter a percentage number like \"5.4\" for 5.4%")
.show();
}
}
};
usePercentageBasedPriceListener = (observable, oldValue, newValue) -> {
if (newValue)
priceValidationResult.set(new InputValidator.ValidationResult(true));
};
volumeListener = (ov, oldValue, newValue) -> {
if (isFiatInputValid(newValue).isValid) {
setVolumeToModel();
@ -266,6 +331,8 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
amount.addListener(amountListener);
minAmount.addListener(minAmountListener);
price.addListener(priceListener);
priceAsPercentage.addListener(priceAsPercentageListener);
dataModel.usePercentageBasedPrice.addListener(usePercentageBasedPriceListener);
volume.addListener(volumeListener);
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding
@ -282,6 +349,8 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
amount.removeListener(amountListener);
minAmount.removeListener(minAmountListener);
price.removeListener(priceListener);
priceAsPercentage.removeListener(priceAsPercentageListener);
dataModel.usePercentageBasedPrice.removeListener(usePercentageBasedPriceListener);
volume.removeListener(volumeListener);
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding
@ -307,6 +376,8 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
if (dataModel.paymentAccount != null)
btcValidator.setMaxTradeLimitInBitcoin(dataModel.paymentAccount.getPaymentMethod().getMaxTradeLimit());
priceFeedType = direction == Offer.Direction.SELL ? PriceFeed.Type.ASK : PriceFeed.Type.BID;
return result;
}
@ -417,8 +488,9 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
// handle minAmount/amount relationship
if (!dataModel.isMinAmountLessOrEqualAmount()) {
amountValidationResult.set(new InputValidator.ValidationResult(false,
BSResources.get("createOffer.validation.amountSmallerThanMinAmount")));
minAmount.set(amount.get());
/*amountValidationResult.set(new InputValidator.ValidationResult(false,
BSResources.get("createOffer.validation.amountSmallerThanMinAmount")));*/
} else {
amountValidationResult.set(result);
if (minAmount.get() != null)
@ -438,8 +510,9 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
minAmount.set(formatter.formatCoin(dataModel.minAmountAsCoin.get()));
if (!dataModel.isMinAmountLessOrEqualAmount()) {
minAmountValidationResult.set(new InputValidator.ValidationResult(false,
BSResources.get("createOffer.validation.minAmountLargerThanAmount")));
amount.set(minAmount.get());
/* minAmountValidationResult.set(new InputValidator.ValidationResult(false,
BSResources.get("createOffer.validation.minAmountLargerThanAmount")));*/
} else {
minAmountValidationResult.set(result);
if (amount.get() != null)
@ -464,6 +537,12 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
}
}
void onFocusOutPriceAsPercentageTextField(boolean oldValue, boolean newValue, String userInput) {
priceAsPercentageIsInput = !oldValue && newValue;
if (oldValue && !newValue)
priceAsPercentage.set(formatter.formatToNumberString(dataModel.getPercentageBasedPrice() * 100, 2));
}
void onFocusOutVolumeTextField(boolean oldValue, boolean newValue, String userInput) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = isFiatInputValid(volume.get());
@ -492,21 +571,14 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
public boolean isPriceInRange() {
MarketPrice marketPrice = priceFeed.getMarketPrice(getTradeCurrency().getCode());
if (marketPrice != null) {
double marketPriceAsDouble = marketPrice.getPrice(PriceFeed.Type.LAST);
double marketPriceAsDouble = marketPrice.getPrice(priceFeedType);
Fiat priceAsFiat = dataModel.priceAsFiat.get();
long shiftDivisor = checkedPow(10, priceAsFiat.smallestUnitExponent());
double offerPrice = ((double) priceAsFiat.longValue()) / ((double) shiftDivisor);
if (marketPriceAsDouble != 0 && Math.abs(1 - (offerPrice / marketPriceAsDouble)) > preferences.getMaxPriceDistanceInPercent()) {
Popup popup = new Popup();
popup.warning("The price you have entered is outside the max. allowed deviation from the market price.\n" +
"The max. allowed deviation is " +
formatter.formatToPercent(preferences.getMaxPriceDistanceInPercent()) +
" and can be adjusted in the preferences.")
.actionButtonText("Change price")
.onAction(() -> popup.hide())
.closeButtonText("Go to \"Preferences\"")
.onClose(() -> navigation.navigateTo(MainView.class, SettingsView.class, PreferencesView.class))
.show();
double percentage = Math.abs(1 - (offerPrice / marketPriceAsDouble));
percentage = formatter.roundDouble(percentage, 2);
if (marketPriceAsDouble != 0 && percentage > preferences.getMaxPriceDistanceInPercent()) {
displayPriceOutOfRangePopup();
return false;
} else {
return true;
@ -516,6 +588,19 @@ class CreateOfferViewModel extends ActivatableWithDataModel<CreateOfferDataModel
}
}
private void displayPriceOutOfRangePopup() {
Popup popup = new Popup();
popup.warning("The price you have entered is outside the max. allowed deviation from the market price.\n" +
"The max. allowed deviation is " +
formatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent()) +
" and can be adjusted in the preferences.")
.actionButtonText("Change price")
.onAction(() -> popup.hide())
.closeButtonText("Go to \"Preferences\"")
.onClose(() -> navigation.navigateTo(MainView.class, SettingsView.class, PreferencesView.class))
.show();
}
BSFormatter getFormatter() {
return formatter;
}

View File

@ -257,10 +257,19 @@ class OfferBookViewModel extends ActivatableViewModel {
}
String getPrice(OfferBookListItem item) {
if ((item == null))
return "";
Offer offer = item.getOffer();
Fiat price = offer.getPrice();
String postFix = "";
if (offer.getUsePercentageBasedPrice()) {
postFix = " (" + formatter.formatToPercentWithSymbol(offer.getMarketPriceMargin()) + ")";
}
if (showAllTradeCurrenciesProperty.get())
return (item != null) ? formatter.formatFiatWithCode(item.getOffer().getPrice()) : "";
return formatter.formatPriceWithCode(price) + postFix;
else
return (item != null) ? formatter.formatFiat(item.getOffer().getPrice()) : "";
return formatter.formatFiat(price) + postFix;
}
String getVolume(OfferBookListItem item) {

View File

@ -92,6 +92,7 @@ class TakeOfferDataModel extends ActivatableDataModel {
boolean useSavingsWallet;
Coin totalAvailableBalance;
private Notification walletFundedNotification;
Fiat tradePrice;
///////////////////////////////////////////////////////////////////////////////////////////
@ -158,6 +159,7 @@ class TakeOfferDataModel extends ActivatableDataModel {
// called before activate
void initWithData(Offer offer) {
this.offer = offer;
tradePrice = offer.getPrice();
addressEntry = walletService.getOrCreateAddressEntry(offer.getId(), AddressEntry.Context.OFFER_FUNDING);
checkNotNull(addressEntry, "addressEntry must not be null");
@ -227,6 +229,7 @@ class TakeOfferDataModel extends ActivatableDataModel {
// have it persisted as well.
void onTakeOffer(TradeResultHandler tradeResultHandler) {
tradeManager.onTakeOffer(amountAsCoin.get(),
tradePrice.getValue(),
totalToPayAsCoin.get().subtract(takerFeeAsCoin),
offer,
paymentAccount.getId(),
@ -308,7 +311,7 @@ class TakeOfferDataModel extends ActivatableDataModel {
if (offer != null &&
amountAsCoin.get() != null &&
!amountAsCoin.get().isZero()) {
volumeAsFiat.set(new ExchangeRate(offer.getPrice()).coinToFiat(amountAsCoin.get()));
volumeAsFiat.set(new ExchangeRate(tradePrice).coinToFiat(amountAsCoin.get()));
updateBalance();
}

View File

@ -90,9 +90,9 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
private TitledGroupBg payFundsPane;
private Button nextButton, cancelButton1, cancelButton2, fundFromSavingsWalletButton, fundFromExternalWalletButton, takeOfferButton;
private InputTextField amountTextField;
private TextField paymentMethodTextField, currencyTextField, priceTextField, volumeTextField, amountRangeTextField;
private TextField paymentMethodTextField, currencyTextField, priceTextField, priceAsPercentageTextField, volumeTextField, amountRangeTextField;
private Label directionLabel, amountDescriptionLabel, addressLabel, balanceLabel, totalToPayLabel, totalToPayInfoIconLabel,
amountBtcLabel, priceCurrencyLabel,
amountBtcLabel, priceCurrencyLabel, priceAsPercentageLabel,
volumeCurrencyLabel, amountRangeBtcLabel, priceDescriptionLabel, volumeDescriptionLabel, spinnerInfoLabel, offerAvailabilitySpinnerLabel;
private TextFieldWithCopyIcon totalToPayTextField;
private PopOver totalToPayInfoPopover;
@ -116,6 +116,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
// private Subscription noSufficientFeeSubscription;
// private MonadicBinding<Boolean> noSufficientFeeBinding;
private Subscription cancelButton2StyleSubscription;
private VBox priceAsPercentageInputBox;
///////////////////////////////////////////////////////////////////////////////////////////
@ -195,6 +196,8 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
public void initWithData(Offer offer) {
model.initWithData(offer);
priceAsPercentageInputBox.setVisible(offer.getUsePercentageBasedPrice());
if (model.getOffer().getDirection() == Offer.Direction.SELL) {
imageView.setId("image-buy-large");
directionLabel.setId("direction-icon-label-buy");
@ -211,7 +214,6 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
takeOfferButton.setText("Review offer for selling bitcoin");
}
boolean showComboBox = model.getPossiblePaymentAccounts().size() > 1;
paymentAccountsLabel.setVisible(showComboBox);
paymentAccountsLabel.setManaged(showComboBox);
@ -228,6 +230,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
amountDescriptionLabel.setText(model.getAmountDescription());
amountRangeTextField.setText(model.getAmountRange());
priceTextField.setText(model.getPrice());
priceAsPercentageTextField.setText(model.marketPriceMargin);
addressTextField.setPaymentLabel(model.getPaymentLabel());
addressTextField.setAddress(model.dataModel.getAddressEntry().getAddressString());
}
@ -269,7 +272,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
offerDetailsWindow.hide();
offerDetailsWindowDisplayed = false;
})
).show(model.getOffer(), model.dataModel.amountAsCoin.get());
).show(model.getOffer(), model.dataModel.amountAsCoin.get(), model.dataModel.tradePrice);
offerDetailsWindowDisplayed = true;
} else {
new Popup().warning("You have no arbitrator selected.\n" +
@ -284,7 +287,9 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
model.onShowPayFundsScreen();
amountTextField.setMouseTransparent(true);
amountTextField.setFocusTraversable(false);
priceTextField.setMouseTransparent(true);
priceAsPercentageTextField.setMouseTransparent(true);
volumeTextField.setMouseTransparent(true);
balanceTextField.setTargetAmount(model.dataModel.totalToPayAsCoin.get());
@ -389,6 +394,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
addressTextField.amountAsCoinProperty().bind(model.dataModel.missingCoin);
amountTextField.validationResultProperty().bind(model.amountValidationResult);
priceCurrencyLabel.textProperty().bind(createStringBinding(() -> model.dataModel.getCurrencyCode() + "/" + model.btcCode.get(), model.btcCode));
priceAsPercentageLabel.prefWidthProperty().bind(priceCurrencyLabel.widthProperty());
amountRangeBtcLabel.textProperty().bind(model.btcCode);
nextButton.disableProperty().bind(model.isNextButtonDisabled);
@ -414,6 +420,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
addressTextField.amountAsCoinProperty().unbind();
amountTextField.validationResultProperty().unbind();
priceCurrencyLabel.textProperty().unbind();
priceAsPercentageLabel.prefWidthProperty().unbind();
amountRangeBtcLabel.textProperty().unbind();
nextButton.disableProperty().unbind();
@ -638,8 +645,7 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
gridPane.getChildren().add(imageVBox);
addAmountPriceFields();
addAmountRangeBox();
addSecondRow();
HBox hBox = new HBox();
hBox.setSpacing(10);
@ -839,18 +845,43 @@ public class TakeOfferView extends ActivatableViewAndModel<AnchorPane, TakeOffer
gridPane.getChildren().add(hBox);
}
private void addAmountRangeBox() {
private void addSecondRow() {
Tuple3<HBox, TextField, Label> priceAsPercentageTuple = getValueCurrencyBox();
HBox priceAsPercentageValueCurrencyBox = priceAsPercentageTuple.first;
priceAsPercentageTextField = priceAsPercentageTuple.second;
priceAsPercentageLabel = priceAsPercentageTuple.third;
Tuple2<Label, VBox> priceAsPercentageInputBoxTuple = getTradeInputBox(priceAsPercentageValueCurrencyBox, "Distance in % from market price");
priceAsPercentageInputBoxTuple.first.setPrefWidth(200);
priceAsPercentageInputBox = priceAsPercentageInputBoxTuple.second;
priceAsPercentageTextField.setPromptText("Enter % value");
priceAsPercentageLabel.setText("%");
priceAsPercentageLabel.setStyle("-fx-alignment: center;");
Tuple3<HBox, TextField, Label> amountValueCurrencyBoxTuple = getValueCurrencyBox();
HBox amountValueCurrencyBox = amountValueCurrencyBoxTuple.first;
amountRangeTextField = amountValueCurrencyBoxTuple.second;
amountRangeBtcLabel = amountValueCurrencyBoxTuple.third;
Tuple2<Label, VBox> amountInputBoxTuple = getTradeInputBox(amountValueCurrencyBox, BSResources.get("takeOffer.amountPriceBox.amountRangeDescription"));
VBox box = amountInputBoxTuple.second;
GridPane.setRowIndex(box, ++gridRow);
GridPane.setColumnIndex(box, 1);
GridPane.setMargin(box, new Insets(5, 10, 5, 0));
gridPane.getChildren().add(box);
Label xLabel = new Label("x");
xLabel.setFont(Font.font("Helvetica-Bold", 20));
xLabel.setPadding(new Insets(14, 3, 0, 3));
xLabel.setVisible(false); // we just use it to get the same layout as the upper row
HBox hBox = new HBox();
hBox.setSpacing(5);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.getChildren().addAll(amountInputBoxTuple.second, xLabel, priceAsPercentageInputBox);
GridPane.setRowIndex(hBox, ++gridRow);
GridPane.setColumnIndex(hBox, 1);
GridPane.setMargin(hBox, new Insets(5, 10, 5, 0));
GridPane.setColumnSpan(hBox, 2);
gridPane.getChildren().add(hBox);
}

View File

@ -18,6 +18,7 @@
package io.bitsquare.gui.main.offer.takeoffer;
import io.bitsquare.arbitration.Arbitrator;
import io.bitsquare.btc.pricefeed.PriceFeed;
import io.bitsquare.gui.Navigation;
import io.bitsquare.gui.common.model.ActivatableWithDataModel;
import io.bitsquare.gui.common.model.ViewModel;
@ -52,6 +53,7 @@ class TakeOfferViewModel extends ActivatableWithDataModel<TakeOfferDataModel> im
final TakeOfferDataModel dataModel;
private final BtcValidator btcValidator;
private final P2PService p2PService;
private PriceFeed priceFeed;
private final Navigation navigation;
final BSFormatter formatter;
@ -94,6 +96,7 @@ class TakeOfferViewModel extends ActivatableWithDataModel<TakeOfferDataModel> im
private ConnectionListener connectionListener;
// private Subscription isFeeSufficientSubscription;
private Runnable takeOfferSucceededHandler;
String marketPriceMargin;
///////////////////////////////////////////////////////////////////////////////////////////
@ -101,13 +104,14 @@ class TakeOfferViewModel extends ActivatableWithDataModel<TakeOfferDataModel> im
///////////////////////////////////////////////////////////////////////////////////////////
@Inject
public TakeOfferViewModel(TakeOfferDataModel dataModel, BtcValidator btcValidator, P2PService p2PService,
public TakeOfferViewModel(TakeOfferDataModel dataModel, BtcValidator btcValidator, P2PService p2PService, PriceFeed priceFeed,
Navigation navigation, BSFormatter formatter) {
super(dataModel);
this.dataModel = dataModel;
this.btcValidator = btcValidator;
this.p2PService = p2PService;
this.priceFeed = priceFeed;
this.navigation = navigation;
this.formatter = formatter;
@ -159,7 +163,8 @@ class TakeOfferViewModel extends ActivatableWithDataModel<TakeOfferDataModel> im
}
amountRange = formatter.formatCoin(offer.getMinAmount()) + " - " + formatter.formatCoin(offer.getAmount());
price = formatter.formatFiat(offer.getPrice());
price = formatter.formatFiat(dataModel.tradePrice);
marketPriceMargin = formatter.formatToPercentWithSymbol(offer.getMarketPriceMargin());
paymentLabel = BSResources.get("takeOffer.fundsBox.paymentLabel", offer.getId());
checkNotNull(dataModel.getAddressEntry(), "dataModel.getAddressEntry() must not be null");

View File

@ -123,7 +123,7 @@ public class ContractWindow extends Overlay<ContractWindow> {
addLabelTextField(gridPane, ++rowIndex, "Offer date:", formatter.formatDateTime(offer.getDate()));
addLabelTextField(gridPane, ++rowIndex, "Trade date:", formatter.formatDateTime(dispute.getTradeDate()));
addLabelTextField(gridPane, ++rowIndex, "Trade type:", formatter.getDirectionBothSides(offer.getDirection()));
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatFiat(offer.getPrice()) + " " + offer.getCurrencyCode());
addLabelTextField(gridPane, ++rowIndex, "Trade price:", formatter.formatFiat(contract.getTradePrice()) + " " + offer.getCurrencyCode());
addLabelTextField(gridPane, ++rowIndex, "Trade amount:", formatter.formatCoinWithCode(contract.getTradeAmount()));
addLabelTextFieldWithCopyIcon(gridPane, ++rowIndex, "Buyer bitcoin address:",
contract.getBuyerPayoutAddressString()).second.setMouseTransparent(false);

View File

@ -47,6 +47,7 @@ import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.ExchangeRate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -232,8 +233,8 @@ public class DisputeSummaryWindow extends Overlay<DisputeSummaryWindow> {
}
addLabelTextField(gridPane, ++rowIndex, "Traders role:", role);
addLabelTextField(gridPane, ++rowIndex, "Trade amount:", formatter.formatCoinWithCode(contract.getTradeAmount()));
addLabelTextField(gridPane, ++rowIndex, "Trade volume:", formatter.formatFiatWithCode(contract.offer.getVolumeByAmount(contract.getTradeAmount())));
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatFiatWithCode(contract.offer.getPrice()));
addLabelTextField(gridPane, ++rowIndex, "Trade price:", formatter.formatFiatWithCode(contract.getTradePrice()));
addLabelTextField(gridPane, ++rowIndex, "Trade volume:", formatter.formatFiatWithCode(new ExchangeRate(contract.getTradePrice()).coinToFiat(contract.getTradeAmount())));
}
private void addCheckboxes() {

View File

@ -41,6 +41,7 @@ import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.Fiat;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -61,6 +62,7 @@ public class OfferDetailsWindow extends Overlay<OfferDetailsWindow> {
private final Navigation navigation;
private Offer offer;
private Coin tradeAmount;
private Fiat tradePrice;
private Optional<Runnable> placeOfferHandlerOptional = Optional.empty();
private Optional<Runnable> takeOfferHandlerOptional = Optional.empty();
private ProgressIndicator spinner;
@ -80,9 +82,10 @@ public class OfferDetailsWindow extends Overlay<OfferDetailsWindow> {
type = Type.Confirmation;
}
public void show(Offer offer, Coin tradeAmount) {
public void show(Offer offer, Coin tradeAmount, Fiat tradePrice) {
this.offer = offer;
this.tradeAmount = tradeAmount;
this.tradePrice = tradePrice;
rowIndex = -1;
width = 900;
@ -172,7 +175,10 @@ public class OfferDetailsWindow extends Overlay<OfferDetailsWindow> {
addLabelTextField(gridPane, ++rowIndex, CurrencyUtil.getNameByCode(offer.getCurrencyCode()) + " amount" + fiatDirectionInfo, formatter.formatFiatWithCode(offer.getVolumeByAmount(offer.getAmount())));
}
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatFiat(offer.getPrice()) + " " + offer.getCurrencyCode() + "/" + "BTC");
if (takeOfferHandlerOptional.isPresent())
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatFiat(tradePrice) + " " + offer.getCurrencyCode() + "/" + "BTC");
else
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatFiat(offer.getPrice()) + " " + offer.getCurrencyCode() + "/" + "BTC");
if (offer.isMyOffer(keyRing) && user.getPaymentAccount(offer.getOffererPaymentAccountId()) != null)
addLabelTextField(gridPane, ++rowIndex, "Payment account:", user.getPaymentAccount(offer.getOffererPaymentAccountId()).getAccountName());

View File

@ -127,7 +127,7 @@ public class TradeDetailsWindow extends Overlay<TradeDetailsWindow> {
addLabelTextField(gridPane, ++rowIndex, "Bitcoin amount" + btcDirectionInfo, formatter.formatCoinWithCode(trade.getTradeAmount()));
addLabelTextField(gridPane, ++rowIndex, CurrencyUtil.getNameByCode(offer.getCurrencyCode()) + " amount" + fiatDirectionInfo, formatter.formatFiatWithCode(trade.getTradeVolume()));
addLabelTextField(gridPane, ++rowIndex, "Price:", formatter.formatPriceWithCode(offer.getPrice()));
addLabelTextField(gridPane, ++rowIndex, "Trade price:", formatter.formatPriceWithCode(trade.getTradePrice()));
addLabelTextField(gridPane, ++rowIndex, "Payment method:", BSResources.get(offer.getPaymentMethod().getId()));
// second group

View File

@ -81,7 +81,13 @@ public class ClosedTradesView extends ActivatableViewAndModel<VBox, ClosedTrades
tradeIdColumn.setComparator((o1, o2) -> o1.getTradable().getId().compareTo(o2.getTradable().getId()));
dateColumn.setComparator((o1, o2) -> o1.getTradable().getDate().compareTo(o2.getTradable().getDate()));
directionColumn.setComparator((o1, o2) -> o1.getTradable().getOffer().getDirection().compareTo(o2.getTradable().getOffer().getDirection()));
priceColumn.setComparator((o1, o2) -> o1.getTradable().getOffer().getPrice().compareTo(o2.getTradable().getOffer().getPrice()));
priceColumn.setComparator((o1, o2) -> {
Tradable tradable = o1.getTradable();
if (tradable instanceof Trade)
return ((Trade) o1.getTradable()).getTradePrice().compareTo(((Trade) o2.getTradable()).getTradePrice());
else
return o1.getTradable().getOffer().getPrice().compareTo(o2.getTradable().getOffer().getPrice());
});
volumeColumn.setComparator((o1, o2) -> {
if (o1.getTradable() instanceof Trade && o2.getTradable() instanceof Trade) {
Fiat tradeVolume1 = ((Trade) o1.getTradable()).getTradeVolume();

View File

@ -21,6 +21,7 @@ import com.google.inject.Inject;
import io.bitsquare.gui.common.model.ActivatableWithDataModel;
import io.bitsquare.gui.common.model.ViewModel;
import io.bitsquare.gui.util.BSFormatter;
import io.bitsquare.trade.Tradable;
import io.bitsquare.trade.Trade;
import io.bitsquare.trade.offer.OpenOffer;
import javafx.collections.ObservableList;
@ -54,7 +55,13 @@ class ClosedTradesViewModel extends ActivatableWithDataModel<ClosedTradesDataMod
}
String getPrice(ClosedTradableListItem item) {
return (item != null) ? formatter.formatFiat(item.getTradable().getOffer().getPrice()) : "";
if (item == null)
return "";
Tradable tradable = item.getTradable();
if (tradable instanceof Trade)
return formatter.formatFiat(((Trade) tradable).getTradePrice());
else
return formatter.formatFiat(tradable.getOffer().getPrice());
}
String getVolume(ClosedTradableListItem item) {

View File

@ -62,7 +62,7 @@ public class FailedTradesView extends ActivatableViewAndModel<VBox, FailedTrades
tradeIdColumn.setComparator((o1, o2) -> o1.getTrade().getId().compareTo(o2.getTrade().getId()));
dateColumn.setComparator((o1, o2) -> o1.getTrade().getDate().compareTo(o2.getTrade().getDate()));
priceColumn.setComparator((o1, o2) -> o1.getTrade().getOffer().getPrice().compareTo(o2.getTrade().getOffer().getPrice()));
priceColumn.setComparator((o1, o2) -> o1.getTrade().getTradePrice().compareTo(o2.getTrade().getTradePrice()));
volumeColumn.setComparator((o1, o2) -> o1.getTrade().getTradeVolume().compareTo(o2.getTrade().getTradeVolume()));
amountColumn.setComparator((o1, o2) -> o1.getTrade().getTradeAmount().compareTo(o2.getTrade().getTradeAmount()));
stateColumn.setComparator((o1, o2) -> model.getState(o1).compareTo(model.getState(o2)));

View File

@ -51,7 +51,7 @@ class FailedTradesViewModel extends ActivatableWithDataModel<FailedTradesDataMod
}
String getPrice(FailedTradesListItem item) {
return (item != null) ? formatter.formatFiat(item.getTrade().getOffer().getPrice()) : "";
return (item != null) ? formatter.formatFiat(item.getTrade().getTradePrice()) : "";
}
String getVolume(FailedTradesListItem item) {

View File

@ -46,7 +46,7 @@ public class PendingTradesListItem {
}
public Fiat getPrice() {
return trade.getOffer().getPrice();
return trade.getTradePrice();
}
}

View File

@ -336,7 +336,7 @@ public class PendingTradesView extends ActivatableViewAndModel<VBox, PendingTrad
public void updateItem(final PendingTradesListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty)
setText(formatter.formatCoinWithCode(item.getTrade().getPayoutAmount()));
setText(formatter.formatCoinWithCode(item.getTrade().getTradeAmount()));
else
setText(null);
}
@ -380,7 +380,7 @@ public class PendingTradesView extends ActivatableViewAndModel<VBox, PendingTrad
public void updateItem(final PendingTradesListItem item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty)
setText(formatter.formatPriceWithCode(item.getTrade().getTradeVolume()));
setText(formatter.formatFiatWithCode(item.getTrade().getTradeVolume()));
else
setText(null);
}

View File

@ -296,19 +296,16 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Activatab
deviationListener = (observable, oldValue, newValue) -> {
try {
String input = newValue.replace("%", "");
input = input.replace(",", ".");
input = input.replace(" ", "");
double value = Double.parseDouble(input);
preferences.setMaxPriceDistanceInPercent(value / 100);
} catch (Throwable t) {
double value = formatter.parsePercentStringToDouble(newValue);
preferences.setMaxPriceDistanceInPercent(value);
} catch (NumberFormatException t) {
log.error("Exception at parseDouble deviation: " + t.toString());
UserThread.runAfter(() -> deviationInputTextField.setText(formatter.formatToPercent(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS);
UserThread.runAfter(() -> deviationInputTextField.setText(formatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS);
}
};
deviationFocusedListener = (observable1, oldValue1, newValue1) -> {
if (oldValue1 && !newValue1)
UserThread.runAfter(() -> deviationInputTextField.setText(formatter.formatToPercent(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS);
UserThread.runAfter(() -> deviationInputTextField.setText(formatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent())), 100, TimeUnit.MILLISECONDS);
};
transactionFeeInputTextField = addLabelInputTextField(root, ++gridRow, "Withdrawal transaction fee (satoshi/byte):").second;
@ -427,7 +424,7 @@ public class PreferencesView extends ActivatableViewAndModel<GridPane, Activatab
});
blockChainExplorerComboBox.setOnAction(e -> preferences.setBlockChainExplorer(blockChainExplorerComboBox.getSelectionModel().getSelectedItem()));
deviationInputTextField.setText(formatter.formatToPercent(preferences.getMaxPriceDistanceInPercent()));
deviationInputTextField.setText(formatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent()));
deviationInputTextField.textProperty().addListener(deviationListener);
deviationInputTextField.focusedProperty().addListener(deviationFocusedListener);

View File

@ -325,11 +325,57 @@ public class BSFormatter {
}
public String formatToPercent(double value) {
return formatToPercent(value, 1);
}
public String formatToPercent(double value, int digits) {
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMinimumFractionDigits(1);
decimalFormat.setMaximumFractionDigits(1);
decimalFormat.setMinimumFractionDigits(digits);
decimalFormat.setMaximumFractionDigits(digits);
decimalFormat.setGroupingUsed(false);
return decimalFormat.format(value * 100.0) + " %";
return decimalFormat.format(value * 100.0);
}
public String formatToNumberString(double value, int digits) {
DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(locale);
decimalFormat.setMinimumFractionDigits(digits);
decimalFormat.setMaximumFractionDigits(digits);
decimalFormat.setGroupingUsed(false);
return decimalFormat.format(value);
}
public double parseNumberStringToDouble(String percentString) throws NumberFormatException {
try {
String input = percentString.replace(",", ".");
input = input.replace(" ", "");
return Double.parseDouble(input);
} catch (NumberFormatException e) {
throw e;
}
}
public String formatToPercentWithSymbol(double value) {
return formatToPercent(value) + " %";
}
public double parsePercentStringToDouble(String percentString) throws NumberFormatException {
try {
String input = percentString.replace("%", "");
input = input.replace(",", ".");
input = input.replace(" ", "");
double value = Double.parseDouble(input);
return value / 100;
} catch (NumberFormatException e) {
throw e;
}
}
public double roundDouble(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
private String cleanInput(String input) {

View File

@ -267,6 +267,8 @@ public class OfferBookViewModelTest {
null,
0,
0,
false,
0,
0,
tradeCurrencyCode,
null,
@ -275,6 +277,7 @@ public class OfferBookViewModelTest {
countryCode,
acceptedCountryCodes,
bankId,
acceptedBanks);
acceptedBanks,
null);
}
}