Java Code Examples for java.math.BigDecimal#min()

The following examples show how to use java.math.BigDecimal#min() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LifxMessageUtil.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
public static PercentType increaseDecreasePercentType(IncreaseDecreaseType increaseDecreaseType, PercentType old) {
    BigDecimal delta = ZERO;
    if (increaseDecreaseType == IncreaseDecreaseType.INCREASE) {
        delta = INCREASE_DECREASE_STEP;
    } else if (increaseDecreaseType == IncreaseDecreaseType.DECREASE) {
        delta = INCREASE_DECREASE_STEP.negate();
    }

    if (!ZERO.equals(delta)) {
        BigDecimal newValue = old.toBigDecimal().add(delta);
        newValue = newValue.setScale(0, RoundingMode.HALF_UP);
        newValue = newValue.min(HUNDRED);
        newValue = newValue.max(ZERO);
        return new PercentType(newValue);
    } else {
        return old;
    }
}
 
Example 2
Source File: ReservedQtyServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Reallocate quantity in stock location line after entry into storage.
 *
 * @param stockMoveLine
 * @param stockLocation
 * @param stockLocationLine
 * @param product
 * @param qty the quantity in stock move line unit.
 * @throws AxelorException
 */
protected void reallocateQty(
    StockMoveLine stockMoveLine,
    StockLocation stockLocation,
    StockLocationLine stockLocationLine,
    Product product,
    BigDecimal qty)
    throws AxelorException {

  Unit stockMoveLineUnit = stockMoveLine.getUnit();
  Unit stockLocationLineUnit = stockLocationLine.getUnit();

  BigDecimal stockLocationQty =
      convertUnitWithProduct(stockMoveLineUnit, stockLocationLineUnit, qty, product);
  // the quantity that will be allocated in stock location line
  BigDecimal realReservedQty;

  // the quantity that will be allocated in stock move line
  BigDecimal leftToAllocate =
      stockLocationLine.getRequestedReservedQty().subtract(stockLocationLine.getReservedQty());
  realReservedQty = stockLocationQty.min(leftToAllocate);

  allocateReservedQuantityInSaleOrderLines(
      realReservedQty, stockLocation, product, stockLocationLineUnit, Optional.of(stockMoveLine));
  updateReservedQty(stockLocationLine);
}
 
Example 3
Source File: PaymentVoucherLoadService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param moveLineInvoiceToPay Les lignes de factures récupérées depuis l'échéance
 * @param payVoucherElementToPay La Ligne de saisie paiement
 * @return
 */
public List<MoveLine> assignMaxAmountToReconcile(
    List<MoveLine> moveLineInvoiceToPay, BigDecimal amountToPay) {
  List<MoveLine> debitMoveLines = new ArrayList<MoveLine>();
  if (moveLineInvoiceToPay != null && moveLineInvoiceToPay.size() != 0) {
    // Récupération du montant imputé sur l'échéance, et assignation de la valeur
    // dans la moveLine (champ temporaire)
    BigDecimal maxAmountToPayRemaining = amountToPay;
    for (MoveLine moveLine : moveLineInvoiceToPay) {
      if (maxAmountToPayRemaining.compareTo(BigDecimal.ZERO) > 0) {
        BigDecimal amountPay = maxAmountToPayRemaining.min(moveLine.getAmountRemaining());
        moveLine.setMaxAmountToReconcile(amountPay);
        debitMoveLines.add(moveLine);
        maxAmountToPayRemaining = maxAmountToPayRemaining.subtract(amountPay);
      }
    }
  }
  return debitMoveLines;
}
 
Example 4
Source File: NumericalConsumerAggregator.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void accept(IDataConsumer obj) {
    NumericalConsumer consumer = (NumericalConsumer) obj;

    BigDecimal nextMin = new BigDecimal(consumer.getMin().toString());
    BigDecimal nextMax = new BigDecimal(consumer.getMax().toString());

    BigDecimal min = fMinimum;
    BigDecimal max = fMaximum;

    /* Set initial min and max values */
    if (min == null || max == null) {
        fMinimum = nextMin;
        fMaximum = nextMax;

        return;
    }

    /* Update min and max values */
    fMinimum = min.min(nextMin);
    fMaximum = max.max(nextMax);
}
 
Example 5
Source File: AlgebraicBigDecimalMathBase.java    From spork with Apache License 2.0 5 votes vote down vote up
private static BigDecimal doWork(BigDecimal arg1, BigDecimal arg2, KNOWN_OP op) {
    if (arg1 == null) {
        return arg2;
    } else if (arg2 == null) {
        return arg1;
    } else {
        BigDecimal retVal = null;
        switch (op) {
        case SUM:
            retVal = arg1.add(arg2);
            break;
        case MAX:
            if (BigDecimalWrapper.class.isInstance(arg1) && (((BigDecimalWrapper)arg1).isNegativeInfinity())) {
                retVal = arg2;
            } else if (BigDecimalWrapper.class.isInstance(arg2) && (((BigDecimalWrapper)arg2).isNegativeInfinity())) {
                retVal = arg1;
            } else {
                retVal = arg1.max(arg2);
            }
            break;
        case MIN:
            if (BigDecimalWrapper.class.isInstance(arg1) && (((BigDecimalWrapper)arg1).isPositiveInfinity())) {
                retVal = arg2;
            } else if (BigDecimalWrapper.class.isInstance(arg2) && (((BigDecimalWrapper)arg2).isPositiveInfinity())) {
                retVal = arg1;
            } else {
                retVal = arg1.min(arg2);
            }
            break;
        default:
            retVal = null;
            break;
        }
        return retVal;
    }
}
 
Example 6
Source File: SensitivityMargin.java    From simm-lib with MIT License 5 votes vote down vote up
private static BigDecimal calculateTheta(List<WeightingMargin> weighted) {
  BigDecimal sumOfRiskExposures = BigDecimalUtils.sum(weighted, WeightingMargin::getMargin);
  BigDecimal sumOfAbsRiskExposures = BigDecimalUtils.sum(weighted, m -> m.getMargin().abs());

  // need to check to make sure that sums are not equal to zero
  if (sumOfAbsRiskExposures.stripTrailingZeros().equals(BigDecimal.ZERO)) {
    return BigDecimal.ZERO;
  } else {
    BigDecimal quotient = BigDecimalUtils.divideWithPrecision(sumOfRiskExposures, sumOfAbsRiskExposures);
    return quotient.min(BigDecimal.ZERO);
  }
}
 
Example 7
Source File: LifxMessageUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public static PercentType kelvinToPercentType(int kelvin, TemperatureRange temperatureRange) {
    if (temperatureRange.getRange() == 0) {
        return PercentType.HUNDRED;
    }
    BigDecimal value = BigDecimal
            .valueOf((kelvin - temperatureRange.getMaximum()) / (temperatureRange.getRange() / -100));
    value = value.min(HUNDRED);
    value = value.max(ZERO);
    return new PercentType(value);
}
 
Example 8
Source File: MathLib.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@TLFunctionAnnotation("Returns min value of the arguments.")
public static final BigDecimal min(TLFunctionCallContext context, BigDecimal a, BigDecimal b) {
	if (a==null){
		return b;
	}else{
		if (b==null){
			return a;
		}
		else{
			return a.min(b);
		}
	}
}
 
Example 9
Source File: VectorMinAggregation.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
protected BigDecimal agg(final BigDecimal a, final BigDecimal b) {
  if (a == null) {
    return b;
  } else if (b == null) {
    return a;
  }
  return a.min(b);
}
 
Example 10
Source File: MoveValidator.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
static BigDecimal getLeastMovement(final Collection<Unit> units) {
  if (units.isEmpty()) {
    throw new IllegalArgumentException("no units");
  }
  BigDecimal least = new BigDecimal(Integer.MAX_VALUE);
  for (final Unit unit : units) {
    final BigDecimal left = unit.getMovementLeft();
    least = left.min(least);
  }
  return least;
}
 
Example 11
Source File: DiscountFactor.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the discount factor.
 *
 * @param rateAndPeriods the target rate and periods, not null.
 * @return the factor calculated.
 */
public static BigDecimal calculate(RateAndPeriods rateAndPeriods) {
    Objects.requireNonNull(rateAndPeriods);
    // (1-(1+r)^n)/1-(1+rate)
    final BigDecimal ONE = CalculationContext.one();
    BigDecimal div = ONE.min(ONE.add(rateAndPeriods.getRate().get()));
    BigDecimal factor = ONE.subtract(ONE.add(rateAndPeriods.getRate().get()).pow(rateAndPeriods.getPeriods()))
            .divide(div, CalculationContext.mathContext());
    return ONE.add(factor);
}
 
Example 12
Source File: ALU.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Object minusOne(final Object o1, ASTNode node)
{
	if (o1 != null)
	{
		if (o1 instanceof Number)
		{
			final Number num;
			switch (getNumberType(num = (Number) o1))
			{
				case INTEGER:
					return Integer.valueOf(num.intValue() - 1);
				case LONG:
					return Long.valueOf(num.longValue() - 1l);
				case DOUBLE:
					return Double.valueOf(num.doubleValue() - 1d);
				case FLOAT:
					return Float.valueOf(num.floatValue() - 1f);
				case SHORT:
					return Short.valueOf((short) (num.intValue() - 1));
				case HS:
					BigDecimal bd = (BigDecimal) o1;
					return bd.min(BigDecimal.ONE);
			}
		}
		else
		{
			throw numberExpectedException(o1, node);
		}
	}
	throw valueIsNullException(o1, node);
}
 
Example 13
Source File: PaymentVoucherLoadService.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
public PayVoucherElementToPay createPayVoucherElementToPay(
    PayVoucherDueElement payVoucherDueElement, int sequence) throws AxelorException {

  PaymentVoucher paymentVoucher = payVoucherDueElement.getPaymentVoucher();
  BigDecimal amountRemaining = paymentVoucher.getRemainingAmount();
  LocalDate paymentDate = paymentVoucher.getPaymentDate();

  PayVoucherElementToPay payVoucherElementToPay = new PayVoucherElementToPay();

  payVoucherElementToPay.setSequence(sequence);
  payVoucherElementToPay.setMoveLine(payVoucherDueElement.getMoveLine());
  payVoucherElementToPay.setTotalAmount(payVoucherDueElement.getDueAmount());
  payVoucherElementToPay.setRemainingAmount(payVoucherDueElement.getAmountRemaining());
  payVoucherElementToPay.setCurrency(payVoucherDueElement.getCurrency());

  BigDecimal amountRemainingInElementCurrency =
      currencyService
          .getAmountCurrencyConvertedAtDate(
              paymentVoucher.getCurrency(),
              payVoucherElementToPay.getCurrency(),
              amountRemaining,
              paymentDate)
          .setScale(2, RoundingMode.HALF_EVEN);

  BigDecimal amountImputedInElementCurrency =
      amountRemainingInElementCurrency.min(payVoucherElementToPay.getRemainingAmount());

  BigDecimal amountImputedInPayVouchCurrency =
      currencyService
          .getAmountCurrencyConvertedAtDate(
              payVoucherElementToPay.getCurrency(),
              paymentVoucher.getCurrency(),
              amountImputedInElementCurrency,
              paymentDate)
          .setScale(2, RoundingMode.HALF_EVEN);

  payVoucherElementToPay.setAmountToPay(amountImputedInElementCurrency);
  payVoucherElementToPay.setAmountToPayCurrency(amountImputedInPayVouchCurrency);
  payVoucherElementToPay.setRemainingAmountAfterPayment(
      payVoucherElementToPay.getRemainingAmount().subtract(amountImputedInElementCurrency));

  return payVoucherElementToPay;
}
 
Example 14
Source File: MoveServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void createMoveUseExcessPayment(Invoice invoice) throws AxelorException {

  Company company = invoice.getCompany();

  // Récupération des acomptes de la facture
  List<MoveLine> creditMoveLineList = moveExcessPaymentService.getAdvancePaymentMoveList(invoice);

  AccountConfig accountConfig = accountConfigService.getAccountConfig(company);

  // Récupération des trop-perçus
  creditMoveLineList.addAll(moveExcessPaymentService.getExcessPayment(invoice));
  if (creditMoveLineList != null && creditMoveLineList.size() != 0) {

    Partner partner = invoice.getPartner();
    Account account = invoice.getPartnerAccount();
    MoveLine invoiceCustomerMoveLine = moveToolService.getCustomerMoveLineByLoop(invoice);

    Journal journal = accountConfigService.getAutoMiscOpeJournal(accountConfig);

    // Si c'est le même compte sur les trop-perçus et sur la facture, alors on lettre directement
    if (moveToolService.isSameAccount(creditMoveLineList, account)) {
      List<MoveLine> debitMoveLineList = new ArrayList<MoveLine>();
      debitMoveLineList.add(invoiceCustomerMoveLine);
      paymentService.useExcessPaymentOnMoveLines(debitMoveLineList, creditMoveLineList);
    }
    // Sinon on créée une O.D. pour passer du compte de la facture à un autre compte sur les
    // trop-perçus
    else {

      log.debug(
          "Création d'une écriture comptable O.D. spécifique à l'emploie des trop-perçus {} (Société : {}, Journal : {})",
          new Object[] {invoice.getInvoiceId(), company.getName(), journal.getCode()});

      Move move =
          moveCreateService.createMove(
              journal,
              company,
              null,
              partner,
              invoice.getInvoiceDate(),
              null,
              MoveRepository.TECHNICAL_ORIGIN_AUTOMATIC);

      if (move != null) {
        BigDecimal totalCreditAmount = moveToolService.getTotalCreditAmount(creditMoveLineList);
        BigDecimal amount = totalCreditAmount.min(invoiceCustomerMoveLine.getDebit());

        // Création de la ligne au crédit
        MoveLine creditMoveLine =
            moveLineService.createMoveLine(
                move,
                partner,
                account,
                amount,
                false,
                appAccountService.getTodayDate(),
                1,
                invoice.getInvoiceId(),
                null);
        move.getMoveLineList().add(creditMoveLine);

        // Emploie des trop-perçus sur les lignes de debit qui seront créées au fil de l'eau
        paymentService.useExcessPaymentWithAmountConsolidated(
            creditMoveLineList,
            amount,
            move,
            2,
            partner,
            company,
            account,
            invoice.getInvoiceDate(),
            invoice.getDueDate());

        moveValidateService.validate(move);

        // Création de la réconciliation
        Reconcile reconcile =
            reconcileService.createReconcile(
                invoiceCustomerMoveLine, creditMoveLine, amount, false);
        if (reconcile != null) {
          reconcileService.confirmReconcile(reconcile, true);
        }
      }
    }

    invoice.setCompanyInTaxTotalRemaining(moveToolService.getInTaxTotalRemaining(invoice));
  }
}
 
Example 15
Source File: MoveServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Move createMoveUseDebit(
    Invoice invoice, List<MoveLine> debitMoveLines, MoveLine invoiceCustomerMoveLine)
    throws AxelorException {
  Company company = invoice.getCompany();
  Partner partner = invoice.getPartner();
  Account account = invoice.getPartnerAccount();

  Journal journal =
      accountConfigService.getAutoMiscOpeJournal(accountConfigService.getAccountConfig(company));

  log.debug(
      "Création d'une écriture comptable O.D. spécifique à l'emploie des trop-perçus {} (Société : {}, Journal : {})",
      new Object[] {invoice.getInvoiceId(), company.getName(), journal.getCode()});

  BigDecimal remainingAmount = invoice.getInTaxTotal().abs();

  log.debug("Montant à payer avec l'avoir récupéré : {}", remainingAmount);

  Move oDmove =
      moveCreateService.createMove(
          journal,
          company,
          null,
          partner,
          invoice.getInvoiceDate(),
          null,
          MoveRepository.TECHNICAL_ORIGIN_AUTOMATIC);

  if (oDmove != null) {
    BigDecimal totalDebitAmount = moveToolService.getTotalDebitAmount(debitMoveLines);
    BigDecimal amount = totalDebitAmount.min(invoiceCustomerMoveLine.getCredit());

    // Création de la ligne au débit
    MoveLine debitMoveLine =
        moveLineService.createMoveLine(
            oDmove,
            partner,
            account,
            amount,
            true,
            appAccountService.getTodayDate(),
            1,
            invoice.getInvoiceId(),
            null);
    oDmove.getMoveLineList().add(debitMoveLine);

    // Emploie des dûs sur les lignes de credit qui seront créées au fil de l'eau
    paymentService.createExcessPaymentWithAmount(
        debitMoveLines,
        amount,
        oDmove,
        2,
        partner,
        company,
        null,
        account,
        appAccountService.getTodayDate());

    moveValidateService.validate(oDmove);

    // Création de la réconciliation
    Reconcile reconcile =
        reconcileService.createReconcile(debitMoveLine, invoiceCustomerMoveLine, amount, false);
    if (reconcile != null) {
      reconcileService.confirmReconcile(reconcile, true);
    }
  }
  return oDmove;
}
 
Example 16
Source File: WEBUI_PP_Order_M_Source_HU_IssueCUQty.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
private BigDecimal computeQtyToIssue(final PPOrderLineRow row)
{
	final I_PP_Order_BOMLine bomLine = Services.get(IPPOrderBOMDAO.class).getOrderBOMLineById(row.getOrderBOMLineId());
	final IMutableHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(getCtx());
	final List<I_M_Source_HU> activeSourceHus = WEBUI_PP_Order_ProcessHelper.retrieveActiveSourceHus(row);

	final I_M_HU hu = activeSourceHus
			.stream()
			.sorted(Comparator.comparing(I_M_Source_HU::getM_HU_ID))
			.map(I_M_Source_HU::getM_HU)
			.findFirst()
			.orElseThrow(() -> new AdempiereException("@NoSelection@"));

	final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory().getStorage(hu).getProductStorages();

	final String issueMethod = row.getIssueMethod();

	if (X_PP_Order_BOMLine.ISSUEMETHOD_IssueOnlyForReceived.equals(issueMethod))
	{
		final BigDecimal qtyLeftToIssue = row.getQtyPlan().subtract(row.getQty());

		if (qtyLeftToIssue.signum() <= 0)
		{
			return BigDecimal.ZERO;
		}

		if (row.isProcessed())
		{
			final Quantity quantityToIssueForWhatWasReceived = ppOrderBomBL.computeQtyToIssueBasedOnFinishedGoodReceipt(bomLine, row.getUom());
			return qtyLeftToIssue.min(quantityToIssueForWhatWasReceived.toBigDecimal());
		}
		else
		{
			return qtyLeftToIssue;
		}

	}
	else
	{
		final BigDecimal sourceHuStorageQty = productStorages.get(0).getQty().toBigDecimal();

		return sourceHuStorageQty;
	}
}
 
Example 17
Source File: PayflowPro.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> ccRefund(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal amount = (BigDecimal) context.get("refundAmount");
    String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
    String configString = (String) context.get("paymentConfig");
    Locale locale = (Locale) context.get("locale");
    if (configString == null) {
        configString = "payment.properties";
    }

    GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(paymentPref);

    if (captureTrans == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                "AccountingPaymentTransactionAuthorizationNotFoundCannotRefund", locale));
    }

    boolean isPayPal = false;
    // Are we doing a cc or a paypal payment?
    if ("EXT_PAYPAL".equals(paymentPref.getString("paymentMethodTypeId"))) {
        isPayPal = true;
    }

    // auth ref number
    String refNum = captureTrans.getString("referenceNum");
    Map<String, String> data = UtilMisc.toMap("ORIGID", refNum);

    // tx type (Credit)
    data.put("TRXTYPE", "C");

    // get the orderID
    String orderId = paymentPref.getString("orderId");

    if (isPayPal) {
        data.put("TENDER", "P");

        data.put("MEMO", orderId);
        // PayPal won't allow us to refund more than the capture amount
        BigDecimal captureAmount = captureTrans.getBigDecimal("amount");
        amount = amount.min(captureAmount);
    } else {
        // credit card tender
        data.put("TENDER", "C");

        data.put("COMMENT1", orderId);
    }

    // amount to capture
    data.put("AMT", amount.toString());

    PayflowAPI pfp = init(delegator, paymentGatewayConfigId, configString, context);

    // get the base params
    StringBuilder params = makeBaseParams(delegator, paymentGatewayConfigId, configString);

    // parse the context parameters
    params.append("&").append(parseContext(data));

    // transmit the request
    if (Debug.verboseOn()) Debug.logVerbose("Sending to Verisign: " + params.toString(), module);
    String resp;
    if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
        resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
    } else {
        resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
    }

    if (Debug.verboseOn()) Debug.logVerbose("Response from Verisign: " + resp, module);

    // check the response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    parseRefundResponse(resp, result);
    result.put("refundAmount", amount);
    return result;
}
 
Example 18
Source File: AggregateNode.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static BigDecimal min(BigDecimal a, BigDecimal b) {
  return a.min(b);
}
 
Example 19
Source File: PropertyManagerImpl.java    From cryptotrader with GNU Affero General Public License v3.0 3 votes vote down vote up
@VisibleForTesting
BigDecimal getDecimal(String site, String instrument,
                      PropertyType type, BigDecimal min, BigDecimal max, BigDecimal defaultValue) {

    try {

        BigDecimal value = get(type, site, instrument, Configuration::getBigDecimal);

        BigDecimal adjusted = value;

        if (min != null) {
            adjusted = adjusted.max(min);
        }

        if (max != null) {
            adjusted = adjusted.min(max);
        }

        log.trace("Fetched {} ({}.{}) : {} -> {}", type, site, instrument, value, adjusted);

        return adjusted;

    } catch (RuntimeException e) {

        log.warn(format("Invalid %s (%s.%s)", type, site, instrument), e);

        return defaultValue;

    }

}
 
Example 20
Source File: TemplateAdviser.java    From cryptotrader with GNU Affero General Public License v3.0 2 votes vote down vote up
@VisibleForTesting
BigDecimal calculateSellLimitSize(Context context, Request request, BigDecimal price) {

    BigDecimal instrumentSize = calculateInstrumentExposureSize(context, request);

    BigDecimal fundingSize = calculateFundingExposureSize(context, request, price);

    if (instrumentSize == null || fundingSize == null) {
        return ZERO;
    }

    Key key = Key.from(request);

    BigDecimal size;

    if (Objects.equals(TRUE, context.isMarginable(key))) {

        size = fundingSize.add(instrumentSize).max(ZERO).multiply(HALF);

    } else {

        BigDecimal excess = fundingSize.subtract(instrumentSize).max(ZERO).movePointLeft(INTEGER_ONE);

        size = instrumentSize.subtract(excess).max(ZERO);

        BigDecimal available = context.getInstrumentPosition(key);

        size = size.min(trimToZero(available));

    }

    BigDecimal rounded = trimToZero(context.roundLotSize(key, size, DOWN));

    BigDecimal minimum = request.getTradingThreshold();

    if (minimum != null && rounded.compareTo(minimum) < 0) {
        rounded = ZERO;
    }

    StateType state = context.getState(key);

    log.trace("Sell size : {} (state=[{}] funding=[{}] instrument[{}])",
            rounded, state, fundingSize, instrumentSize);

    return TRADE_ALLOWED.contains(state) ? rounded : ZERO;

}