List of usage examples for java.math BigDecimal equals
@Override public boolean equals(Object x)
From source file:org.apache.olingo.client.core.AbstractPrimitiveTest.java
protected void decimal(final String entity, final String propertyName, final BigDecimal check) throws EdmPrimitiveTypeException { final ODataPrimitiveValue opv = readPrimitiveValue(entity, propertyName); assertEquals(EdmPrimitiveTypeKind.Decimal, opv.getTypeKind()); final BigDecimal value = opv.toCastValue(BigDecimal.class); assertNotNull(value);/* ww w . j ava 2s .co m*/ assertTrue(check.equals(value)); }
From source file:hjow.hgtable.util.DataUtil.java
/** * <p>2? 1 ? .</p>/*from w w w .j av a 2 s. c om*/ * * @param original : ?? * @param scale : ? * @return 2? 1 */ public static BigDecimal sqrt(BigDecimal original, int scale) { BigDecimal temp = new BigDecimal(String.valueOf(original)); BigDecimal results = new BigDecimal("1.0"); results.setScale(scale + 2); int loops = 0; while (true) { if (loops >= 1) { temp = new BigDecimal(String.valueOf(results)); } temp.setScale(scale + 2, BigDecimal.ROUND_FLOOR); results = original.divide(temp, scale + 2, BigDecimal.ROUND_FLOOR).add(temp) .divide(new BigDecimal("2.0"), scale + 2, BigDecimal.ROUND_FLOOR); if (temp.equals(results)) break; loops++; } return results.setScale(scale, BigDecimal.ROUND_HALF_UP); }
From source file:nl.strohalm.cyclos.services.accounts.AccountTypeServiceImpl.java
@Override public <AT extends AccountType> AT save(final AT accountType) { AT saved = null;//from ww w . j a va 2s . co m validate(accountType); SystemAccount systemAccount = null; if (accountType.isTransient()) { saved = accountTypeDao.insert(accountType); if (saved instanceof SystemAccountType) { // Create the system account now final SystemAccountType systemAccountType = ((SystemAccountType) accountType); systemAccount = new SystemAccount(); systemAccount.setCreationDate(Calendar.getInstance()); systemAccount.setCreditLimit(systemAccountType.getCreditLimit()); systemAccount.setUpperCreditLimit(systemAccountType.getUpperCreditLimit()); systemAccount.setType(saved); systemAccount.setOwnerName(saved.getName()); systemAccount = accountDao.insert(systemAccount); // Add permission to the admin group AdminGroup group = (AdminGroup) LoggedUser.group(); group = groupDao.load(group.getId(), AdminGroup.Relationships.VIEW_INFORMATION_OF); final Collection<SystemAccountType> systemAccountTypes = group.getViewInformationOf(); systemAccountTypes.add(systemAccountType); groupDao.update(group); } // Member accounts are created when an account type gets related to a group } else { if (accountType instanceof SystemAccountType) { final SystemAccountType currentAccountType = (SystemAccountType) accountTypeDao .load(accountType.getId(), SystemAccountType.Relationships.VIEWED_BY_GROUPS); final Collection<AdminGroup> viewedByGroups = new ArrayList<AdminGroup>(); if (currentAccountType.getViewedByGroups() != null) { viewedByGroups.addAll(currentAccountType.getViewedByGroups()); } final SystemAccountType systemAccountType = (SystemAccountType) accountType; systemAccountType.setViewedByGroups(viewedByGroups); // When updating a system account type, should update it's account too systemAccount = (SystemAccount) accountDao.load(SystemAccountOwner.instance(), systemAccountType); final BigDecimal oldLimit = systemAccount.getCreditLimit() == null ? null : systemAccount.getCreditLimit().abs(); final BigDecimal oldUpperLimit = systemAccount.getUpperCreditLimit(); // When there was a credit limit, and it has changed, we must update the account final BigDecimal newLimit = systemAccountType.getCreditLimit() == null ? null : systemAccountType.getCreditLimit().abs(); final BigDecimal newUpperLimit = systemAccountType.getUpperCreditLimit(); final boolean updateLimit = (newLimit != null && !newLimit.equals(oldLimit)) || ((newUpperLimit != null) && !newUpperLimit.equals(oldUpperLimit)); if (updateLimit) { systemAccount.setCreditLimit(newLimit); systemAccount.setUpperCreditLimit(newUpperLimit); } systemAccount.setOwnerName(systemAccountType.getName()); systemAccountType.setAccount(systemAccount); accountDao.update(systemAccount); if (updateLimit) { // Generate the log AccountLimitLog log = new AccountLimitLog(); log.setAccount(systemAccount); log.setBy((Administrator) LoggedUser.element()); log.setDate(Calendar.getInstance()); log.setCreditLimit(newLimit); log.setUpperCreditLimit(newUpperLimit); accountLimitLogDao.insert(log); } } saved = accountTypeDao.update(accountType); } if (systemAccount != null) { ((SystemAccountType) saved).setAccount(systemAccount); saved = accountTypeDao.update(saved); } getCache().clear(); return saved; }
From source file:com.feilong.core.bean.ConvertUtilTest.java
/** * Test./* w w w . jav a 2 s .c o m*/ */ @Test public void test() { BigDecimal a = toBigDecimal("1.000000"); BigDecimal b = new BigDecimal(1); LOGGER.debug(a.compareTo(b) + ""); LOGGER.debug(a.equals(b) + ""); }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.AdornedTargetListPersistenceModule.java
@Override public Entity update(PersistencePackage persistencePackage) throws ServiceException { String[] customCriteria = persistencePackage.getCustomCriteria(); if (customCriteria != null && customCriteria.length > 0) { LOG.warn(/*from w ww.ja v a 2 s.c o m*/ "custom persistence handlers and custom criteria not supported for update types other than BASIC"); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Entity entity = persistencePackage.getEntity(); AdornedTargetList adornedTargetList = (AdornedTargetList) persistencePerspective .getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.ADORNEDTARGETLIST); if (!adornedTargetList.getMutable()) { throw new SecurityServiceException("Field is not mutable"); } try { AdornedTargetRetrieval adornedTargetRetrieval = new AdornedTargetRetrieval(persistencePackage, entity, adornedTargetList).invokeForUpdate(); List<Serializable> records = adornedTargetRetrieval.getRecords(); Assert.isTrue(!CollectionUtils.isEmpty(records), "Entity not found"); int index = adornedTargetRetrieval.getIndex(); Map<String, FieldMetadata> mergedProperties = adornedTargetRetrieval.getMergedProperties(); FieldManager fieldManager = getFieldManager(); Serializable myRecord; if (adornedTargetList.getSortField() != null && entity.findProperty(adornedTargetList.getSortField()).getValue() != null) { myRecord = records.get(index); BigDecimal requestedSequence = new BigDecimal( entity.findProperty(adornedTargetList.getSortField()).getValue()); BigDecimal previousSequence = new BigDecimal(String .valueOf(getFieldManager().getFieldValue(myRecord, adornedTargetList.getSortField()))); if (!previousSequence.equals(requestedSequence)) { // Sequence has changed. Rebalance the list myRecord = records.remove(index); myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false); if (CollectionUtils.isEmpty(records)) { records.add(myRecord); } else { records.add(requestedSequence.intValue() - 1, myRecord); } index = 1; Class<?> type = fieldManager.getField(myRecord.getClass(), adornedTargetList.getSortField()) .getType(); boolean isBigDecimal = BigDecimal.class.isAssignableFrom(type); for (Serializable record : records) { fieldManager.setFieldValue(record, adornedTargetList.getSortField(), isBigDecimal ? new BigDecimal(index) : Long.valueOf(index)); index++; } } } else { myRecord = records.get(index); } String ceilingEntityFullyQualifiedClassname = persistencePackage .getCeilingEntityFullyQualifiedClassname(); Class<?>[] entities = persistenceManager.getPolymorphicEntities(ceilingEntityFullyQualifiedClassname); Map<String, FieldMetadata> mergedPropertiesTarget = persistenceManager.getDynamicEntityDao() .getMergedProperties(ceilingEntityFullyQualifiedClassname, entities, null, persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), ""); myRecord = createPopulatedInstance(myRecord, entity, mergedProperties, false); myRecord = persistenceManager.getDynamicEntityDao().merge(myRecord); List<Serializable> myList = new ArrayList<Serializable>(); myList.add(myRecord); Entity[] payload = getRecords(mergedPropertiesTarget, myList, mergedProperties, adornedTargetList.getTargetObjectPath()); entity = payload[0]; return entity; } catch (Exception e) { throw new ServiceException("Problem updating entity : " + e.getMessage(), e); } }
From source file:org.kuali.kfs.module.ar.document.CustomerCreditMemoDocument.java
public BigDecimal getInvoiceOpenItemQuantity(CustomerCreditMemoDetail customerCreditMemoDetail, CustomerInvoiceDetail customerInvoiceDetail) { BigDecimal invoiceOpenItemQuantity; BigDecimal invoiceItemUnitPrice = customerInvoiceDetail.getInvoiceItemUnitPrice(); if (ObjectUtils.isNull(invoiceItemUnitPrice) || invoiceItemUnitPrice.equals(BigDecimal.ZERO)) { invoiceOpenItemQuantity = BigDecimal.ZERO; } else {// www . j a v a 2s.c o m KualiDecimal invoiceOpenItemAmount = customerCreditMemoDetail.getInvoiceOpenItemAmount(); KualiDecimal invoiceOpenItemPretaxAmount = invoiceOpenItemAmount; if (getArTaxService().isCustomerInvoiceDetailTaxable(getInvoice(), customerInvoiceDetail)) { invoiceOpenItemPretaxAmount = getCustomerInvoiceDetailOpenPretaxAmount(invoiceOpenItemAmount); } invoiceOpenItemQuantity = invoiceOpenItemPretaxAmount.bigDecimalValue().divide(invoiceItemUnitPrice, ArConstants.ITEM_QUANTITY_SCALE, BigDecimal.ROUND_HALF_UP); } return invoiceOpenItemQuantity; }
From source file:org.multibit.viewsystem.swing.action.SendAssetConfirmAction.java
/** * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog. *///www. jav a2s.c o m @Override public void actionPerformed(ActionEvent e) { if (abort()) { return; } // SendAssetConfirmDialog sendAssetConfirmDialog = null; AssetValidationErrorDialog validationErrorDialog = null; try { String sendAddress = dataProvider.getAddress(); String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT); String sendMessage = null; boolean canSendMessage = false; final int assetId = dataProvider.getAssetId(); String assetAmount = dataProvider.getAssetAmount(); boolean isSenderPays = dataProvider.isSenderPays(); /* Is there a payment charge? If yes, the asset amount will change */ CSAsset asset = bitcoinController.getModel().getActiveWallet().CS.getAsset(assetId); CoinSparkGenesis genesis = asset.getGenesis(); BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, assetAmount); // Was there any rounding, which the user did not see because they clicked on send first, // without losing focus to any other widget which corrects field? String typedAmount = dataProvider.getAssetAmountText(); BigDecimal bd1 = new BigDecimal(typedAmount); BigDecimal bd2 = new BigDecimal(assetAmount); bd1 = bd1.stripTrailingZeros(); bd2 = bd2.stripTrailingZeros(); if (bd1.equals(bd2) == false) { String displayUnit = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, BigInteger.ONE); String s = "The smallest transactable unit is " + displayUnit + ", so we have rounded the sum down.\nPlease confirm the final amount and click 'Send' again."; JOptionPane.showMessageDialog(mainFrame, s); return; } // End rounding check/warning long desiredRawUnits = assetAmountRawUnits.longValue(); short chargeBasisPoints = genesis.getChargeBasisPoints(); long rawFlatChargeAmount = genesis.getChargeFlat(); boolean chargeExists = (rawFlatChargeAmount > 0 || chargeBasisPoints > 0); if (chargeExists) { if (isSenderPays) { long x = genesis.calcGross(desiredRawUnits); assetAmountRawUnits = new BigInteger(String.valueOf(x)); } else { // We don't have to do anything if recipient pays, just send gross amount. // calcNet() returns what the recipient will receive, but it's not what we send. // long x = genesis.calcNet(desiredRawUnits); // assetAmountRawUnits = new BigInteger(String.valueOf(x)); } } // Todo: Allow invalid assets to be sent even if spendable balance is 0 //if (CSMiscUtils.canSendInvalidAsset(bitcoinController) final AssetValidator validator = new AssetValidator(super.bitcoinController); if (validator.validate(sendAddress, sendAmount, assetId, assetAmountRawUnits.toString())) { /* CoinSpark START */ CoinSparkPaymentRef paymentRef = null; // We have already validated that the coinspark address and underlying bitcoin are good // and that the transfer flag is set on the coinspark address. We just want the actual // underlying bitcoin address to send assets to, which is used to create SendRequest object. CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress); String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa); sendAddress = btcAddress; // Does a payment ref exist? int flags = csa.getAddressFlags(); if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) { paymentRef = csa.getPaymentRef(); log.debug(">>>> CoinSpark address has payment refs flag set: " + paymentRef.toString()); } // Messages - can send message and BTC to CoinSpark address, without any assets. sendMessage = dataProvider.getMessage(); canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0; /* CoinSpark END */ // Create a SendRequest. Address sendAddressObject; sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress); //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) { //BigInteger assetAmountRawUnits = new BigInteger(assetAmount); BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount); final SendRequest sendRequest = SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetId, assetAmountRawUnits, 1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null if (paymentRef != null && paymentRef.getRef() != 0) { sendRequest.setPaymentRef(paymentRef); } // Send a message if the address will take it and message is not empty boolean willSendMessage = false; if (canSendMessage) { boolean isEmptyMessage = false; if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) { isEmptyMessage = true; } if (!isEmptyMessage) { willSendMessage = true; //int numParts = 1; CoinSparkMessagePart[] parts = { CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) }; String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController); sendRequest.setMessage(parts, serverURLs); log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs)); log.debug(">>>> parts[0] = " + parts[0]); log.debug(">>>> parts[0].fileName = " + parts[0].fileName); log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType); log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8")); //String message = "Hello, the time is now..." + DateTime.now().toString(); // parts[2].fileName = imagePath; // parts[2].mimeType = "image/png"; // byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath)); // parts[2].content = imageBytes; } } // // When sending a message, show a modal dialog. // CompleteTX now occurs in background thread so UI does not block // when "Send" is clicked with widget updates frozen. // // Show dialog with indeterminate progress bar final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame, "SparkBit", "Contacting message delivery servers..."); // Dialog is made visible after futures have been set up ListeningExecutorService service = MoreExecutors .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10)); ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() { public Boolean call() throws Exception { try { // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (Exception e) { throw e; } return true; } }); final BigInteger myAssetAmountRawUnits = assetAmountRawUnits; Futures.addCallback(future, new FutureCallback<Boolean>() { public void onSuccess(Boolean b) { // There is enough money. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); SendAssetConfirmDialog mySendAssetConfirmDialog = new SendAssetConfirmDialog( bitcoinController, mainFrame, sendRequest, assetId, myAssetAmountRawUnits, validator); mySendAssetConfirmDialog.setVisible(true); } }); } public void onFailure(Throwable thrown) { final String failureReason = thrown.getMessage(); final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode; final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException; // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.dispose(); if (isCSException) { JOptionPane .showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction:\n\n" + failureReason, "SparkBit Error", JOptionPane.ERROR_MESSAGE); } else if (isInsufficientMoney) { // Try to show a human friendly message, need to pass the missing satoshis from failure reason. try { String numberOnly = failureReason.replaceAll("[^0-9]", ""); BigInteger needed = new BigInteger(numberOnly); JOptionPane.showMessageDialog(mainFrame, "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require " + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.", "SparkBit Error", JOptionPane.ERROR_MESSAGE); } catch (NumberFormatException e) { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } else { AssetValidationErrorDialog myValidationErrorDialog = new AssetValidationErrorDialog( bitcoinController, mainFrame, sendRequest, true, validator); myValidationErrorDialog.setVisible(true); } } }); } }); // Show message server dialog only if we are going to send if (willSendMessage) { dialog.setVisible(true); } /* // Complete it (which works out the fee) but do not sign it yet. log.debug("Just about to complete the tx (and calculate the fee)..."); boolean completedOk; try { bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false); completedOk = true; log.debug("The fee after completing the transaction was " + sendRequest.fee); } catch (InsufficientMoneyException ime) { completedOk = false; } if (completedOk) { // There is enough money. sendAssetConfirmDialog = new SendAssetConfirmDialog(super.bitcoinController, mainFrame, sendRequest, assetId, assetAmountRawUnits, validator); sendAssetConfirmDialog.setVisible(true); } else { // There is not enough money. // TODO setup validation parameters accordingly so that it displays ok. validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true, validator); validationErrorDialog.setVisible(true); } */ } else { validationErrorDialog = new AssetValidationErrorDialog(super.bitcoinController, mainFrame, null, false, validator); validationErrorDialog.setVisible(true); } } catch (WrongNetworkException e1) { logMessage(e1); } catch (AddressFormatException e1) { logMessage(e1); } catch (KeyCrypterException e1) { logMessage(e1); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(mainFrame, "Please enter a valid amount."); } catch (Exception e1) { logMessage(e1); } }
From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java
public BigDecimal get(BigDecimal n) { // Make sure n is a positive number if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException(); }//from w w w . j ava 2 s . c o m BigDecimal initialGuess = getInitialApproximation(n); trace("Initial guess " + initialGuess.toString()); BigDecimal lastGuess = ZERO; BigDecimal guess = new BigDecimal(initialGuess.toString()); // Iterate iterations = 0; boolean more = true; while (more) { lastGuess = guess; guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); guess = guess.add(lastGuess); guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP); trace("Next guess " + guess.toString()); error = n.subtract(guess.multiply(guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals(guess)) { more = error.abs().compareTo(ONE) >= 0; } } return guess; }
From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG Date,Open,High,Low,Close,Volume,Adj Close 2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30 2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00 *///from w ww . ja v a 2 s. co m int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January int fromDD = Integer.valueOf(request.getParameter("b")); int fromYYYY = Integer.valueOf(request.getParameter("c")); int toMM = Integer.valueOf(request.getParameter("d")); int toDD = Integer.valueOf(request.getParameter("e")); int toYYYY = Integer.valueOf(request.getParameter("f")); String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear ValidationUtils.validateResolution(resolution); String symbol = request.getParameter("s"); ValidationUtils.validateSymbol(symbol); String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING)); String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY, toMM, toDD, toYYYY, URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache FileCache fileCache = JsquantContextListener.getFileCache(request); String responseBody = fileCache.get(cacheKey); if (responseBody == null) { HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString); ResponseHandler<String> responseHandler = new BasicResponseHandler(); log.debug("requesting uri=" + httpget.getURI()); responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler); //httpget.setReleaseTrigger(releaseTrigger); // no need to close? fileCache.put(cacheKey, responseBody); } String[] lines = responseBody.split("\n"); List<Stock> dayPrices = new ArrayList<Stock>(); int index = 0; for (String line : lines) if (index++ > 0 && line.length() > 0) dayPrices.add(new Stock(line)); Collections.reverse(dayPrices); index = 0; BigDecimal allTimeHighClose = new BigDecimal(0); BigDecimal stopAt = null; BigDecimal boughtPrice = null; Stock sPrev = null; for (Stock s : dayPrices) { allTimeHighClose = allTimeHighClose.max(s.adjClose); s.allTimeHighClose = allTimeHighClose; if (index > 0) { sPrev = dayPrices.get(index - 1); //true range = max(high,closeprev) - min(low,closeprev) s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose)); } int rng = 10; if (index > rng) { BigDecimal sum = new BigDecimal(0); for (Stock s2 : dayPrices.subList(index - rng, index)) sum = sum.add(s2.trueRange); s.ATR10 = sum.divide(new BigDecimal(rng)); if (allTimeHighClose.equals(s.adjClose)) { stopAt = s.adjClose.subtract(s.ATR10); } } s.stopAt = stopAt; if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) { s.order = OrderAction.SELL; s.soldPrice = s.adjClose; s.soldDifference = s.soldPrice.subtract(boughtPrice); } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null && sPrev.order == OrderAction.IGNORE) { s.order = OrderAction.BUY; boughtPrice = s.adjClose; s.boughtPrice = boughtPrice; } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) { s.order = OrderAction.HOLD; } else { s.order = OrderAction.IGNORE; } index++; } ServletOutputStream out = response.getOutputStream(); out.println(lines[0] + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference"); for (Stock s : dayPrices) out.println(s.getCSV()); }
From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java
private void writeNumberList(DirectiveArguments directiveArgs) { int prevNo = Integer.MAX_VALUE; int curNo = Integer.MAX_VALUE; List<DirectiveArgument<?>> args; if (directiveArgs.size() > 0) { args = directiveArgs.getDirectiveArguments(); Collections.sort(args);/*w ww . j a va 2 s .com*/ List<Integer> dataList = new ArrayList<Integer>(); BigDecimal curVal = BigDecimal.ZERO; BigDecimal prevVal = BigDecimal.ZERO; for (int i = 0; i <= args.size(); i++) { // Note that i is allowed to go up to directiveArgs.size() // This allows the last value to be handled correctly within the // loop. if (i != args.size()) { DirectiveArgument<?> arg = args.get(i); curNo = (Integer) arg.getId(); curVal = arg.getValue(); } if (i == 0 || (prevNo == curNo - 1 && prevVal.equals(curVal))) { dataList.add(curNo); } else { _textBuffer.append(' '); appendRange(dataList, ' ', false, _textBuffer); _textBuffer.append(','); _textBuffer.append(prevVal.toPlainString()); dataList = new ArrayList<Integer>(); dataList.add(curNo); } prevNo = curNo; prevVal = curVal; } } }