public void testCounterOfferTradeRequest() { MasterController mc = new MasterController(); mc.initializeController(); UserDatabase db = mc.getUserDB(); DatabaseController.deleteAllData(); try { User user = DatabaseController.createUser("u"); User user2 = DatabaseController.createUser("u2"); List<Skill> offer = new ArrayList<Skill>(); List<Skill> counterOffer = new ArrayList<Skill>(); offer.add( new Skill(db, "illlllll", "LLLLLLLLLLLLLLLL", "desc", true, new ArrayList<Image>())); counterOffer.add( new Skill(db, "Counter skill", "meta", "desc", true, new ArrayList<Image>())); Trade trade = user.getTradeList().createTrade(db, user, user2, offer); trade.getHalfForUser(user2).setAccepted(false); trade.getHalfForUser(user2).setOffer(counterOffer); List<ID> ids = new ArrayList<ID>(); for (Skill skill : counterOffer) { ids.add(skill.getSkillID()); } assertEquals(trade.getHalfForUser(user2).getOffer(), ids); } catch (UserAlreadyExistsException e) { assertTrue(false); } }
public void testBrowseTradeHistory() { MasterController mc = new MasterController(); mc.initializeController(); UserDatabase db = mc.getUserDB(); DatabaseController.deleteAllData(); try { User bob = DatabaseController.createUser("Bob"); User joel = DatabaseController.createUser("Joel"); List<Skill> skillz1 = new ArrayList<Skill>(), skillz2 = new ArrayList<Skill>(); skillz1.add(new Skill(db, "...YEP", "BAR", "desc", true, new ArrayList<Image>())); TradeList tl = bob.getTradeList(); tl.createTrade(db, bob, joel, skillz2); Trade t1 = tl.getMostRecentTrade(db); tl.createTrade(db, bob, joel, skillz1); Trade t2 = tl.getMostRecentTrade(db); // Trade History Has been updated assertTrue(!t1.equals(t2)); } catch (UserAlreadyExistsException e) { assertTrue(false); } }
public void testModifyActiveTrade() { MasterController mc = new MasterController(); mc.initializeController(); UserDatabase db = mc.getUserDB(); DatabaseController.deleteAllData(); try { User bob = DatabaseController.createUser("Bob"); User joel = DatabaseController.createUser("Joel"); List<Skill> skillz1 = new ArrayList<Skill>(), skillz2 = new ArrayList<Skill>(); skillz1.add(new Skill(db, "...YEP", "FOO", "desc", true, new ArrayList<Image>())); TradeList tl = bob.getTradeList(); tl.createTrade(db, bob, joel, skillz2); Trade t = tl.getMostRecentTrade(db); // Modify An Active Trade t.getHalfForUser(bob).setOffer(skillz1); List<ID> ids = new ArrayList<ID>(); for (Skill skill : skillz1) { ids.add(skill.getSkillID()); } assertEquals(t.getHalfForUser(bob).getOffer(), ids); // Delete An Active Trade tl.delete(t); assertTrue(tl.getActiveTrades(db).size() == 0); } catch (UserAlreadyExistsException e) { assertTrue(false); } }
private void handleInitialTakeOfferRequest(TradeMessage message, Address peerAddress) { log.trace( "handleNewMessage: message = " + message.getClass().getSimpleName() + " from " + peerAddress); try { nonEmptyStringOf(message.tradeId); } catch (Throwable t) { log.warn("Invalid requestDepositTxInputsMessage " + message.toString()); return; } Optional<OpenOffer> openOfferOptional = openOfferManager.findOpenOffer(message.tradeId); if (openOfferOptional.isPresent() && openOfferOptional.get().getState() == OpenOffer.State.AVAILABLE) { Offer offer = openOfferOptional.get().getOffer(); openOfferManager.reserveOpenOffer(openOfferOptional.get()); Trade trade; if (offer.getDirection() == Offer.Direction.BUY) trade = new BuyerAsOffererTrade(offer, tradableListStorage); else trade = new SellerAsOffererTrade(offer, tradableListStorage); trade.setStorage(tradableListStorage); initTrade(trade); trades.add(trade); ((OffererTrade) trade).handleTakeOfferRequest(message, peerAddress); } else { // TODO respond // (RequestDepositTxInputsMessage)message. // messageService.sendEncryptedMessage(peerAddress,messageWithPubKey.getMessage().); log.info("We received a take offer request but don't have that offer anymore."); } }
private void initPendingTrades() { if (firstPeerAuthenticatedListener != null) p2PService.removeP2PServiceListener(firstPeerAuthenticatedListener); List<Trade> failedTrades = new ArrayList<>(); for (Trade trade : trades) { // We continue an interrupted trade. // TODO if the peer has changed its IP address, we need to make another findPeer request. At // the moment we use the peer stored in trade to // continue the trade, but that might fail. // TODO /* if (trade.isFailedState()) { failedTrades.add(trade); } else {*/ trade.setStorage(tradableListStorage); trade.updateDepositTxFromWallet(tradeWalletService); initTrade(trade); // after we are authenticated we remove mailbox messages. DecryptedMsgWithPubKey mailboxMessage = trade.getMailboxMessage(); if (mailboxMessage != null) { log.trace("initPendingTrades/removeEntryFromMailbox mailboxMessage = " + mailboxMessage); p2PService.removeEntryFromMailbox(mailboxMessage); trade.setMailboxMessage(null); } // } } pendingTradesInitialized.set(true); failedTrades.stream().filter(Trade::isTakerFeePaid).forEach(this::addTradeToFailedTrades); }
public void testRefuseTradeRequest() { MasterController mc = new MasterController(); mc.initializeController(); UserDatabase db = mc.getUserDB(); DatabaseController.deleteAllData(); try { User user = DatabaseController.createUser("u"); User user2 = DatabaseController.createUser("u2"); List<Skill> offer = new ArrayList<Skill>(); offer.add( new Skill(db, "illlllll", "LLLLLLLLLLLLLLLL", "desc", true, new ArrayList<Image>())); Trade trade = user.getTradeList().createTrade(db, user, user2, offer); // decline the trade trade.getHalfForUser(user2).setAccepted(false); DatabaseController.save(); assertTrue(trade.isActive()); // delete the trade user2.getTradeList().delete(user2.getTradeList().getMostRecentTrade(db)); DatabaseController.save(); assertTrue(user.getTradeList().getActiveTrades(db).size() == 0); } catch (UserAlreadyExistsException e) { assertTrue(false); } }
@Override public void onClick(View v) { // 使用工厂方法模式和策略模式模拟交易 // 初始化一张IC卡 Card card = initIC(); // 显示一下卡内信息 System.out.println("========初始卡信息:========="); showCard(card); // 是否停止运行标志 boolean flag = true; while (flag) { Trade trade = createTrade(); DeductionFacade.deduct(card, trade); // 交易成功,打印出成功处理消息 System.out.println("\n======交易凭证========"); System.out.println(trade.getTradeNo() + " 交易成功!"); System.out.println("本次发生的交易金额为:" + trade.getAmount() / 100.0 + " 元"); // 展示一下卡内信息 showCard(card); System.out.print("\n是否需要退出?(Y/N)"); if (getInput().equalsIgnoreCase("y")) { flag = false; // 退出; } } }
public void closeDisputedTrade(String tradeId) { Optional<Trade> tradeOptional = getTradeById(tradeId); if (tradeOptional.isPresent()) { Trade trade = tradeOptional.get(); trade.setDisputeState(Trade.DisputeState.DISPUTE_CLOSED); addTradeToClosedTrades(trade); } }
@Override public TradeRow apply(Trade input) { TradeRow tradeRow = new TradeRow(); tradeRow.setBuyingBroker(input.getBuyBroker()); tradeRow.setPrice(input.getPrice()); tradeRow.setQuantity(input.getQuantity()); tradeRow.setSellingBroker(input.getSellBroker()); return tradeRow; }
public void add(Trade trade) throws TradeException { // Is a valid trade? if (trade.getDate() == null) throw new TradeException("Trade date must be informed!"); if (trade.getPrice() <= 0) throw new TradeException("Trade price must be greater than zero!"); if (trade.getQuantity() <= 0) throw new TradeException("Trade quantity must be greater than zero!"); tradesRecordTable.add(trade); Collections.sort(tradesRecordTable); }
// 产生一条交易 private Trade createTrade() { Trade trade = new Trade(); System.out.print("请输入交易编号:"); trade.setTradeNo(getInput()); System.out.print("请输入交易金额:"); trade.setAmount(Integer.parseInt(getInput())); // 返回交易 return trade; }
@Override public String toString() { StringBuilder sb = new StringBuilder("Trades\n"); for (Trade trade : getTrades()) { sb.append("[trade="); sb.append(trade.toString()); sb.append("]\n"); } return sb.toString(); }
/** * Adds returns to the returnList. * * @return return. */ public double getReturn(Trade current, Trade previous) { double retrn = (current.getPrice() - previous.getPrice()) / previous.getPrice(); if (count >= 9) { returnList = resize(returnList); returnList[count] = retrn; } else { returnList[count] = retrn; count++; } return retrn; }
public Double calcProfit(Trade trade, Double brokerFeeFactor) { Double profit = 0.0; if (reversedOrder != null) { Double totalTradeAmount = trade.getAmount() * brokerFeeFactor; Double tradeAmountRatio = trade.getAmount() / reversedOrder.getBrokerAmount(); Double bruttoAmountEquivalent = reversedOrder.getAmount() * tradeAmountRatio; Double feeDeduction = (bruttoAmountEquivalent - totalTradeAmount) * rate; if (type.equals("sell")) { Double sellPrice = totalTradeAmount * rate; Double buyPrice = bruttoAmountEquivalent * reversedOrder.getRate(); System.out.println( "sell: " + totalTradeAmount + "*" + rate + ", " + bruttoAmountEquivalent + "*" + reversedOrder.getRate()); profit = (sellPrice - buyPrice) - feeDeduction; System.out.println("profit=" + profit); } else if (type.equals("buy")) { Double buyPrice = bruttoAmountEquivalent * rate; Double sellPrice = totalTradeAmount * reversedOrder.getRate(); System.out.println( "buy: " + totalTradeAmount + "*" + rate + ", " + bruttoAmountEquivalent + "*" + reversedOrder.getRate()); profit = (sellPrice - buyPrice) - feeDeduction; System.out.println("profit=" + profit); } } return profit; }
/** * find trade in history using the orderId * * @param orderId * @return */ protected Trade findTradeInHistory(long orderId) { Trade trade = null; ListIterator<Trade> list = ((LinkedList<Trade>) _recentTrades).listIterator(_recentTrades.size()); while (list.hasPrevious()) { trade = (Trade) list.previous(); if (trade.getTradeMessage().OrderID == orderId) { break; } } return (trade); }
@Override public void onDisable() { i18n.onDisable(); Economy.setEss(null); Trade.closeLog(); }
@Override public void setMoney(final BigDecimal value) throws MaxMoneyException { if (ess.getSettings().isEcoDisabled()) { if (ess.getSettings().isDebug()) { ess.getLogger().info("Internal economy functions disabled, aborting balance change."); } return; } final BigDecimal oldBalance = _getMoney(); if (Methods.hasMethod()) { try { final Method method = Methods.getMethod(); if (!method.hasAccount(this.getName())) { throw new Exception(); } final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); account.set(value.doubleValue()); } catch (Exception ex) { } } super.setMoney(value, true); ess.getServer() .getPluginManager() .callEvent(new UserBalanceUpdateEvent(this.getBase(), oldBalance, value)); Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess); }
public boolean runScript() throws Exception { int fuel = 0; int org = 0; int equip = 0; int holds = Swath.ship.holds(); // Set product amounts switch (m_type.getCurrentChoice()) { case Swath.FUEL_ORE: fuel = holds; break; case Swath.ORGANICS: org = holds; break; case Swath.EQUIPMENT: equip = holds; break; } // Loop while (true) { Land.exec(m_planet.getInteger()); TakeLeaveProducts.exec(fuel, org, equip); LiftOff.exec(); Trade.exec(-fuel, -org, -equip); } }
void onSelectTrade(PendingTradesListItem item) { // clean up previous selectedItem selectedItem = item; if (item == null) { trade = null; tradeProperty.set(null); } else { trade = item.getTrade(); tradeProperty.set(trade); isOfferer = tradeManager.isMyOffer(trade.getOffer()); if (trade.getDepositTx() != null) txId.set(trade.getDepositTx().getHashAsString()); } }
void onFiatPaymentStarted(ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) { checkNotNull(trade, "trade must not be null"); checkArgument(trade instanceof BuyerTrade, "Check failed: trade instanceof BuyerTrade"); checkArgument( trade.getDisputeState() == Trade.DisputeState.NONE, "Check failed: trade.getDisputeState() == Trade.DisputeState.NONE"); ((BuyerTrade) trade).onFiatPaymentStarted(resultHandler, errorMessageHandler); }
private void tryOpenDispute(boolean isSupportTicket) { if (trade != null) { Transaction depositTx = trade.getDepositTx(); if (depositTx != null) { doOpenDispute(isSupportTicket, trade.getDepositTx()); } else { log.warn("Trade.depositTx is null. We try to find the tx in our wallet."); List<Transaction> candidates = new ArrayList<>(); List<Transaction> transactions = walletService.getWallet().getRecentTransactions(100, true); transactions .stream() .forEach( transaction -> { Coin valueSentFromMe = transaction.getValueSentFromMe(walletService.getWallet()); if (!valueSentFromMe.isZero()) { // spending tx for (TransactionOutput transactionOutput : transaction.getOutputs()) { if (!transactionOutput.isMine(walletService.getWallet())) { if (transactionOutput.getScriptPubKey().isPayToScriptHash()) { // MS tx candidates.add(transaction); } } } } }); if (candidates.size() == 1) doOpenDispute(isSupportTicket, candidates.get(0)); else if (candidates.size() > 1) new SelectDepositTxPopup() .transactions(candidates) .onSelect( transaction -> { doOpenDispute(isSupportTicket, transaction); }) .closeButtonText("Cancel") .show(); else log.error("Trade.depositTx is null and we did not find any MultiSig transaction."); } } else { log.error("Trade is null"); } }
private void createTrade( Coin amount, Offer offer, String paymentAccountId, OfferAvailabilityModel model, TradeResultHandler tradeResultHandler) { Trade trade; if (offer.getDirection() == Offer.Direction.BUY) trade = new SellerAsTakerTrade(offer, amount, model.getPeerAddress(), tradableListStorage); else trade = new BuyerAsTakerTrade(offer, amount, model.getPeerAddress(), tradableListStorage); trade.setTakeOfferDate(new Date()); trade.setTakerPaymentAccountId(paymentAccountId); initTrade(trade); trades.add(trade); ((TakerTrade) trade).takeAvailableOffer(); tradeResultHandler.handleResult(trade); }
private void initTrade(Trade trade) { trade.init( p2PService, walletService, tradeWalletService, arbitratorManager, this, openOfferManager, user, keyRing); }
@Override public void reload() { Trade.closeLog(); for (IConf iConf : confList) { iConf.reloadConfig(); execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")"); } i18n.updateLocale(settings.getLocale()); }
/** * process trade to mark as being investigated * * @param orderId * @param investigationStatus (valid values: 1 or 2) */ public void processInvestigatedTrade(long orderId, char investigationStatus) { if (logger.isTraceEnabled()) { logger.trace("processInvestigatedTrade:" + orderId); } Trade trade = findTradeInHistory(orderId); if (trade == null) { if (logger.isTraceEnabled()) { logger.trace("Trade not found while trying to mark for investigation:" + orderId); } return; } trade.setInvestigationStatus(InvestigationStatus.getInvestigationStatus(investigationStatus)); _orderUpdated.compareAndSet(false, true); _tradeHistoryUpdated.compareAndSet(false, true); return; }
public void onWithdrawRequest( String toAddress, KeyParameter aesKey, Trade trade, ResultHandler resultHandler, FaultHandler faultHandler) { AddressEntry addressEntry = walletService.getAddressEntryByOfferId(trade.getId()); String fromAddress = addressEntry.getAddressString(); FutureCallback<Transaction> callback = new FutureCallback<Transaction>() { @Override public void onSuccess(@javax.annotation.Nullable Transaction transaction) { if (transaction != null) { log.info("onWithdraw onSuccess tx ID:" + transaction.getHashAsString()); trade.setState(Trade.State.WITHDRAW_COMPLETED); addTradeToClosedTrades(trade); resultHandler.handleResult(); } } @Override public void onFailure(@NotNull Throwable t) { t.printStackTrace(); log.error(t.getMessage()); faultHandler.handleFault("An exception occurred at requestWithdraw (onFailure).", t); } }; try { walletService.sendFunds(fromAddress, toAddress, trade.getPayoutAmount(), aesKey, callback); } catch (AddressFormatException | InsufficientMoneyException e) { e.printStackTrace(); log.error(e.getMessage()); faultHandler.handleFault("An exception occurred at requestWithdraw.", e); } }
public static void main(String[] args) throws IOException, TTransportException, ClassNotFoundException { Trade trade = new Trade(); trade.symbol = "F"; trade.price = 13.10; trade.size = 2500; TSimpleFileTransport trans_out = new TSimpleFileTransport("data", false, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(trade); trans_out.write(baos.toByteArray()); trans_out.close(); TSimpleFileTransport trans_in = new TSimpleFileTransport("data", true, false); byte[] buf = new byte[128]; int iBytesRead = trans_in.read(buf, 0, buf.length); ByteArrayInputStream bais = new ByteArrayInputStream(buf); ObjectInputStream ois = new ObjectInputStream(bais); trade = (Trade) ois.readObject(); System.out.println( "Trade(" + iBytesRead + "): " + trade.symbol + " " + trade.size + " @ " + trade.price); }
/** * In real application a trade is probably executed in an external system, i.e. asynchronously. */ public void executeTrade(Trade trade) { Portfolio portfolio = this.portfolioService.findPortfolio(trade.getUsername()); String ticker = trade.getTicker(); int sharesToTrade = trade.getShares(); PortfolioPosition newPosition = (trade.getAction() == TradeAction.Buy) ? portfolio.buy(ticker, sharesToTrade) : portfolio.sell(ticker, sharesToTrade); if (newPosition == null) { String payload = "Rejected trade " + trade; this.messagingTemplate.convertAndSendToUser(trade.getUsername(), "/queue/errors", payload); return; } this.tradeResults.add(new TradeResult(trade.getUsername(), newPosition)); }
public double calculateVolumeWeightedStockPrice(String stockSymbol, int lastMinutes) { // Get end date Calendar startDate = Calendar.getInstance(); startDate.add(Calendar.MINUTE, lastMinutes * -1); double totalTradedPrice = 0, totalQuantity = 0; // Acumulate quantity and price for (Trade trade : tradesRecordTable) { // Is the stock requested? if (!trade.getStock().getStockSymbol().equals(stockSymbol)) continue; // Check date range of trade if (lastMinutes > 0 && trade.getDate().before(startDate.getTime())) continue; totalTradedPrice += (trade.getPrice() * trade.getQuantity()); totalQuantity += trade.getQuantity(); } // Prevent zero divide if (totalQuantity == 0) return 0; return totalTradedPrice / totalQuantity; }
@Override public void setState(State state) { super.setState(state); if (state == State.WITHDRAW_COMPLETED) tradeProtocol.completed(); }