List of usage examples for org.apache.commons.csv CSVPrinter print
public void print(final Object value) throws IOException
From source file:com.rcv.ResultsWriter.java
private void generateSummarySpreadsheet(Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath) throws IOException { String csvPath = outputPath + ".csv"; Logger.log(Level.INFO, "Generating summary spreadsheets: %s...", csvPath); // Get all candidates sorted by their first round tally. This determines the display order. // container for firstRoundTally Map<String, BigDecimal> firstRoundTally = roundTallies.get(1); // candidates sorted by first round tally List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally); // totalActiveVotesPerRound is a map of round to total votes cast in each round Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>(); // round indexes over all rounds plus final results round for (int round = 1; round <= numRounds; round++) { // tally is map of candidate to tally for the current round Map<String, BigDecimal> tallies = roundTallies.get(round); // total will contain total votes for all candidates in this round // this is used for calculating other derived data BigDecimal total = BigDecimal.ZERO; // tally indexes over all tallies for the current round for (BigDecimal tally : tallies.values()) { total = total.add(tally);//from w ww . j a v a 2s. com } totalActiveVotesPerRound.put(round, total); } // csvPrinter will be used to write output to csv file CSVPrinter csvPrinter; try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath)); csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s", csvPath, exception.toString()); throw exception; } // print contest info addHeaderRows(csvPrinter, precinct); // add a row header for the round column labels csvPrinter.print("Rounds"); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // label string will have the actual text which goes in the cell String label = String.format("Round %d", round); // cell for round label csvPrinter.print(label); } csvPrinter.println(); // actions don't make sense in individual precinct results if (precinct == null || precinct.isEmpty()) { addActionRows(csvPrinter); } final BigDecimal totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1); // For each candidate: for each round: output total votes // candidate indexes over all candidates for (String candidate : sortedCandidates) { // show each candidate row with their totals for each round // text for the candidate name String candidateDisplayName = this.config.getNameForCandidateID(candidate); csvPrinter.print(candidateDisplayName); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // vote tally this round BigDecimal thisRoundTally = roundTallies.get(round).get(candidate); // not all candidates may have a tally in every round if (thisRoundTally == null) { thisRoundTally = BigDecimal.ZERO; } // total votes cell csvPrinter.print(thisRoundTally.toString()); } // advance to next line csvPrinter.println(); } // row for the inactive CVR counts // inactive CVR header cell csvPrinter.print("Inactive ballots"); // round indexes through all rounds for (int round = 1; round <= numRounds; round++) { // count of votes inactive this round BigDecimal thisRoundInactive = BigDecimal.ZERO; if (round > 1) { // Exhausted count is the difference between the total votes in round 1 and the total votes // in the current round. thisRoundInactive = totalActiveVotesFirstRound.subtract(totalActiveVotesPerRound.get(round)) .subtract(roundToResidualSurplus.get(round)); } // total votes cell csvPrinter.print(thisRoundInactive.toString()); } csvPrinter.println(); // row for residual surplus (if needed) // We check if we accumulated any residual surplus over the course of the tabulation by testing // whether the value in the final round is positive. if (roundToResidualSurplus.get(numRounds).signum() == 1) { csvPrinter.print("Residual surplus"); for (int round = 1; round <= numRounds; round++) { csvPrinter.print(roundToResidualSurplus.get(round).toString()); } csvPrinter.println(); } // write xls to disk try { // output stream is used to write data to disk csvPrinter.flush(); csvPrinter.close(); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString()); throw exception; } }
From source file:ai.grakn.test.graql.analytics.ScalingTestIT.java
@Ignore @Test/*from w ww. jav a 2 s . c om*/ public void countIT() throws InterruptedException, ExecutionException, InvalidGraphException, IOException { CSVPrinter printer = createCSVPrinter("countIT.txt"); // Insert super nodes into graph simpleOntology(keyspace); // get a count before adding any data Long emptyCount = Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE).admin() .getTinkerTraversal().count().next(); LOGGER.info("gremlin count before data is: " + emptyCount); Set<String> superNodes = makeSuperNodes(keyspace); int previousGraphSize = 0; for (int graphSize : graphSizes) { LOGGER.info("current scale - super " + NUM_SUPER_NODES + " - nodes " + graphSize); Long conceptCount = (long) (NUM_SUPER_NODES * (graphSize + 1) + graphSize); printer.print(String.valueOf(conceptCount)); LOGGER.info("start generate graph " + System.currentTimeMillis() / 1000L + "s"); addNodesToSuperNodes(keyspace, superNodes, previousGraphSize, graphSize); previousGraphSize = graphSize; LOGGER.info("stop generate graph " + System.currentTimeMillis() / 1000L + "s"); Long gremlinCount = (long) (NUM_SUPER_NODES * (3 * graphSize + 1) + graphSize); LOGGER.info("gremlin count is: " + Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE) .admin().getTinkerTraversal().count().next()); gremlinCount += emptyCount; LOGGER.info("expected gremlin count is: " + gremlinCount); for (int workerNumber : workerNumbers) { LOGGER.info("Setting number of workers to: " + workerNumber); Long countTime = 0L; for (int i = 0; i < REPEAT; i++) { LOGGER.info("repeat number: " + i); Long startTime = System.currentTimeMillis(); Long count = getCountQuery(Grakn.DEFAULT_URI, keyspace, workerNumber).execute(); assertEquals(conceptCount, count); LOGGER.info("count: " + count); Long stopTime = System.currentTimeMillis(); countTime += stopTime - startTime; LOGGER.info("count time: " + countTime / ((i + 1) * 1000)); } countTime /= REPEAT * 1000; LOGGER.info("time to count: " + countTime); printer.print(String.valueOf(countTime)); } printer.println(); printer.flush(); } printer.flush(); printer.close(); }
From source file:com.gs.obevo.db.apps.reveng.CsvStaticDataWriter.java
private void writeTable(DbPlatform dbtype, PhysicalSchema schema, String tableName, File directory, MutableSet<String> updateTimeColumns, final CSVFormat csvFormat) { directory.mkdirs();//ww w . j a va2s .c o m DaTable table = this.metadataManager.getTableInfo(schema.getPhysicalName(), tableName, new DaSchemaInfoLevel().setRetrieveTableColumns(true)); if (table == null) { System.out.println("No data found for table " + tableName); return; } MutableList<String> columnNames = table.getColumns().collect(DaNamedObject.TO_NAME).toList(); final String updateTimeColumnForTable = updateTimeColumns == null ? null : updateTimeColumns.detect(Predicates.in(columnNames)); if (updateTimeColumnForTable != null) { columnNames.remove(updateTimeColumnForTable); System.out.println("Will mark " + updateTimeColumnForTable + " as an updateTimeColumn on this table"); } final File tableFile = new File(directory, tableName + ".csv"); final String selectSql = String.format("SELECT %s FROM %s%s", columnNames.makeString(", "), dbtype.getSchemaPrefix(schema), tableName); // using the jdbcTempate and ResultSetHandler to avoid sql-injection warnings in findbugs sqlExecutor.executeWithinContext(schema, new Procedure<Connection>() { @Override public void value(Connection conn) { sqlExecutor.getJdbcTemplate().query(conn, selectSql, new ResultSetHandler<Void>() { @Override public Void handle(ResultSet rs) throws SQLException { CSVPrinter writer = null; try { FileWriter fw = new FileWriter(tableFile); writer = new CSVPrinter(fw, csvFormat); if (updateTimeColumnForTable != null) { String metadataLine = String.format("//// METADATA %s=\"%s\"", TextMarkupDocumentReader.ATTR_UPDATE_TIME_COLUMN, updateTimeColumnForTable); fw.write(metadataLine + "\n"); // writing using the FileWriter directly to avoid having the quotes // delimited } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); int columnCount = rs.getMetaData().getColumnCount(); // print headers for (int i = 1; i <= columnCount; ++i) { writer.print(rs.getMetaData().getColumnName(i)); } writer.println(); while (rs.next()) { for (int i = 1; i <= columnCount; ++i) { Object object = rs.getObject(i); if (object != null) { switch (rs.getMetaData().getColumnType(i)) { case Types.DATE: object = dateFormat.format(object); break; case Types.TIMESTAMP: object = dateTimeFormat.format(object); break; case Types.LONGVARCHAR: case Types.VARCHAR: case Types.CHAR: // escape the string text if declared so that the input CSV can also handle the escapes if (csvFormat.getEscapeCharacter() != null && object instanceof String) { object = ((String) object).replace( "" + csvFormat.getEscapeCharacter(), "" + csvFormat.getEscapeCharacter() + csvFormat.getEscapeCharacter()); } break; } } writer.print(object); } writer.println(); } writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(writer); } return null; } }); } }); int blankFileSize = updateTimeColumnForTable == null ? 1 : 2; if (!tableFile.canRead() || FileUtilsCobra.readLines(tableFile).size() <= blankFileSize) { System.out.println("No data found for table " + tableName + "; will clean up file"); FileUtils.deleteQuietly(tableFile); } }
From source file:com.itemanalysis.jmetrik.file.JmetrikFileExporter.java
private boolean exportFile() { JmetrikFileReader reader = null;/*from w w w.j a va 2 s .c o m*/ BufferedWriter writer = null; CSVPrinter printer = null; if (outputFile.exists() && !overwrite) return false; try { reader = new JmetrikFileReader(dataFile); writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputFile.toPath()))); reader.openConnection(); if (hasHeader) { String[] colNames = reader.getColumnNames(); printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter).withHeader(colNames)); } else { printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter)); } LinkedHashMap<VariableName, VariableAttributes> variableAttributes = reader.getVariableAttributes(); JmetrikCSVRecord record = null; VariableAttributes tempAttributes = null; //print scored values if (scored) { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempAttributes = variableAttributes.get(v); tempValue = record.originalValue(v); if (tempAttributes.getItemType() == ItemType.NOT_ITEM) { //write original string if not an item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } else { //write scored value if a test item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempAttributes.getItemScoring().computeItemScore(tempValue)); } } } printer.println(); } //print original values } else { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempValue = record.originalValue(v); if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } printer.println(); } } } catch (IOException ex) { theException = ex; } finally { try { if (reader != null) reader.close(); if (printer != null) printer.close(); if (writer != null) writer.close(); } catch (IOException ex) { theException = ex; } } return true; }
From source file:com.itemanalysis.jmetrik.file.JmetrikFileImporter.java
private void convertFile() { CSVParser parser = null;/*from w w w .ja v a 2 s . co m*/ Reader reader = null; CSVPrinter printer = null; Writer writer = null; try { if (outputFile.exists()) { if (!overwrite) { theException = new IOException("File already exists and overwrite==false"); return; } } else { outputFile.createNewFile(); } //For debugging // System.out.println("CREATED: " + outputFile.getAbsolutePath()); //Writer header to file writer = new OutputStreamWriter(new FileOutputStream(outputFile)); printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#')); printer.printComment("VERSION"); printer.printRecord(new String[] { "jmetrik1" }); printer.printComment("METADATA"); printer.printRecord(new String[] { Integer.valueOf(nrow).toString() }); printer.printComment("ATTRIBUTES"); for (VariableName v : variableAttributeMap.keySet()) { printer.printRecord(variableAttributeMap.get(v).getAttributeArray()); } printer.printComment("DATA"); //Write data to file reader = new InputStreamReader(new BOMInputStream(new FileInputStream(dataFile)), "UTF-8"); parser = new CSVParser(reader, dataFileFormat); if (hasHeader) { parser = new CSVParser(reader, dataFileFormat.withHeader(colNames).withSkipHeaderRecord(true)); } else { parser = new CSVParser(reader, dataFileFormat.withHeader(colNames)); } Iterator<CSVRecord> iter = parser.iterator(); CSVRecord csvRecord = null; VariableAttributes variableAttributes = null; DataType dataType = null; String temp = ""; while (iter.hasNext()) { csvRecord = iter.next(); for (VariableName v : variableAttributeMap.keySet()) { temp = csvRecord.get(v.toString()); variableAttributes = variableAttributeMap.get(v); dataType = variableAttributes.getDataType(); if (!variableAttributes.isMissing(temp)) { if (DataType.INTEGER == dataType) { printer.print(Double.valueOf(Double.parseDouble(temp)).intValue()); } else if (DataType.DOUBLE == dataType) { printer.print(Double.parseDouble(temp)); } else { printer.print(temp); } } else { printer.print(temp); } } printer.println(); } } catch (IOException ex) { theException = ex; } finally { try { if (parser != null) parser.close(); if (reader != null) reader.close(); if (printer != null) printer.close(); if (writer != null) writer.close(); } catch (IOException ex) { theException = ex; logger.fatal(ex); } } }
From source file:net.tradelib.misc.StrategyText.java
public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date, String csvPath, char csvSep) throws Exception { // public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date) throws Exception { ArrayList<InstrumentText> result = new ArrayList<InstrumentText>(); CSVPrinter printer = null; if (csvPath != null) { // Add withHeader for headers printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath))); }// w w w . j av a2 s .co m int numCsvColumns = 12; int rollMethod = 2; DatabaseMetaData dmd = con.getMetaData(); String driverName = dmd.getDriverName(); String query = ""; if (driverName.startsWith("MySQL")) { query = STRATEGY_QUERY_MYSQL; } else { query = STRATEGY_QUERY; } String prevCategory = ""; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, strategy); pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay())); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String category = rs.getString(2); if (!category.equals(prevCategory)) { result.add(InstrumentText.makeSection(category)); prevCategory = category; if (printer != null) { printer.print(category); for (int ii = 1; ii < numCsvColumns; ++ii) { printer.print(""); } printer.println(); } } String name = rs.getString(3); String symbol = rs.getString(4); String contract = ""; if (rollMethod == 1) { // Uses current_contract and trading_days int ndays = rs.getInt(12); if (ndays > 1) { contract = rs.getString(10); } else { contract = "Roll to " + rs.getString(11); } } else if (rollMethod == 2) { // Uses current_contract2 and roll_today int rollToday = rs.getInt(14); if (rollToday == 0) { contract = rs.getString(13); } else { contract = "Roll to " + rs.getString(13); } } if (printer != null) { printer.print(name); printer.print(symbol); printer.print(contract); } String signal; long position = (long) rs.getDouble(5); JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class); if (position > 0.0) { BigDecimal entryPrice; double pnl; try { entryPrice = jo.get("entry_price").getAsBigDecimal(); pnl = jo.get("pnl").getAsDouble(); } catch (Exception e) { entryPrice = BigDecimal.valueOf(Double.MIN_VALUE); pnl = Double.MIN_VALUE; } signal = String.format("Long [%d] since %s [at %s].", position, rs.getString(6), formatBigDecimal(entryPrice)); if (printer != null) printer.print(signal); String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl)); signal += " " + openProfit; if (printer != null) printer.print(openProfit); } else if (position < 0.0) { BigDecimal entryPrice; double pnl; try { entryPrice = jo.get("entry_price").getAsBigDecimal(); pnl = jo.get("pnl").getAsDouble(); } catch (Exception e) { entryPrice = BigDecimal.valueOf(-1); pnl = -1; } signal = String.format("Short [%d] since %s [at %s].", Math.abs(position), rs.getString(6), formatBigDecimal(entryPrice)); if (printer != null) printer.print(signal); String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl)); signal += " " + openProfit; if (printer != null) printer.print(openProfit); } else { signal = "Out."; if (printer != null) { printer.print(signal); // An empty column follows the status if there is no position - there is no profit. printer.print(""); } } boolean hasOrder = false; JsonArray ja = jo.get("orders").getAsJsonArray(); double entryRisk; try { entryRisk = jo.get("entry_risk").getAsDouble(); } catch (Exception ee) { entryRisk = Double.NaN; } String profitTarget; Double profitTargetDbl; try { profitTarget = formatBigDecimal(jo.get("profit_target").getAsBigDecimal()); profitTargetDbl = jo.get("profit_target").getAsDouble(); } catch (Exception ee) { profitTarget = null; profitTargetDbl = null; } String stopLoss; Double stopLossDbl; try { stopLoss = formatBigDecimal(jo.get("stop_loss").getAsBigDecimal()); stopLossDbl = jo.get("stop_loss").getAsDouble(); } catch (Exception ee) { stopLoss = null; stopLossDbl = null; } Double lastClose; try { lastClose = jo.get("last_close").getAsDouble(); } catch (Exception ee) { lastClose = null; } // Currently maximum one entry and maximum one exit are supported. String entryStr = ""; String exitStr = ""; String contractRiskStr = ""; for (int ii = 0; ii < ja.size(); ++ii) { JsonObject jorder = ja.get(ii).getAsJsonObject(); switch (jorder.get("type").getAsString()) { case "EXIT_LONG_STOP": exitStr = "Exit long at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + "."; signal += " " + exitStr; break; case "EXIT_SHORT_STOP": exitStr = "Exit short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + "."; signal += " " + exitStr; break; case "ENTER_LONG": if (!Double.isNaN(entryRisk)) { entryStr = String.format("Enter long at open. Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += " " + entryStr; } else { entryStr = "Enter long at open."; signal += " " + entryStr; } break; case "ENTER_SHORT": if (!Double.isNaN(entryRisk)) { entryStr = String.format("Enter short at open. Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += " " + entryStr; } else { entryStr = "Enter short at open."; signal += " " + entryStr; } break; case "ENTER_LONG_STOP": position = jorder.get("quantity").getAsLong(); entryStr = String.format("Enter long [%d] at stop %s [%s%%].", position, formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()), formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)); signal += " " + entryStr; if (!Double.isNaN(entryRisk)) { contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += " " + contractRiskStr; } break; case "ENTER_LONG_STOP_LIMIT": position = jorder.get("quantity").getAsLong(); entryStr = String.format("Enter long [%d] at limit %s, stop at %s [%s%%].", position, formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()), formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()), formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)); signal += " " + entryStr; if (!Double.isNaN(entryRisk)) { contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += contractRiskStr; } break; case "ENTER_SHORT_STOP": // signal += " Enter short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + "."; position = jorder.get("quantity").getAsLong(); entryStr = String.format("Enter short [%d] at stop %s [%s%%].", Math.abs(position), formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()), formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)); signal += " " + entryStr; if (!Double.isNaN(entryRisk)) { contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += " " + contractRiskStr; } break; case "ENTER_SHORT_STOP_LIMIT": position = jorder.get("quantity").getAsLong(); entryStr = String.format("Enter short [%d] at limit %s, stop at %s [%s%%].", Math.abs(position), formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()), formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()), formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)); signal += " " + entryStr; if (!Double.isNaN(entryRisk)) { contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0)); signal += " " + contractRiskStr; } break; case "EXIT_LONG": exitStr = "Exit long at open."; signal += " " + exitStr; break; case "EXIT_SHORT": exitStr = "Exit short at open."; signal += " " + exitStr; break; case "EXIT_SHORT_STOP_LIMIT": exitStr = "Exit short at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()) + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " [" + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100) + "%]" + "."; signal += " " + exitStr; break; case "EXIT_LONG_STOP_LIMIT": exitStr = "Exit long at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()) + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " [" + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100) + "%]" + "."; signal += " " + exitStr; break; } hasOrder = true; } String lastCloseStr = "Last close at " + formatBigDecimal(jo.get("last_close").getAsBigDecimal()) + "."; String stopLossStr = ""; String profitTargetStr = ""; if (hasOrder) { signal += " " + lastCloseStr; } if (stopLoss != null) { stopLossStr = "Stop loss at " + stopLoss; if (lastClose != null && stopLossDbl != null) { stopLossStr += " [" + formatPercentage(stopLossDbl / lastClose * 100 - 100) + "%]"; } stopLossStr += "."; signal += " " + stopLossStr; } if (profitTarget != null) { profitTargetStr = "Profit target at about " + profitTarget; if (profitTargetDbl != null && lastClose != null) { profitTargetStr += " [" + formatPercentage(profitTargetDbl / lastClose * 100 - 100) + "%]"; } profitTargetStr += "."; signal += " " + profitTargetStr; } if (printer != null) { printer.print(exitStr); printer.print(entryStr); printer.print(contractRiskStr); printer.print(lastCloseStr); printer.print(stopLossStr); printer.print(profitTargetStr); printer.println(); } result.add(InstrumentText.make(name, symbol, contract, signal)); } rs.close(); pstmt.close(); if (printer != null) printer.flush(); return result; }
From source file:net.tradelib.misc.StrategyText.java
public static void buildOrdersCsv(String dbUrl, String strategy, LocalDate date, String csvPath) throws Exception { Connection con = DriverManager.getConnection(dbUrl); CSVPrinter printer = null; if (csvPath != null) { // Add withHeader for headers printer = CSVFormat.DEFAULT.withDelimiter(',').withHeader(CSV_HEADER) .print(new BufferedWriter(new FileWriter(csvPath))); }/*from w ww. ja v a2 s.c o m*/ int rollMethod = 2; DatabaseMetaData dmd = con.getMetaData(); String driverName = dmd.getDriverName(); String query = ""; if (driverName.startsWith("MySQL")) { query = STRATEGY_ORDER_QUERY_MYSQL; } else { query = STRATEGY_ORDER_QUERY; } PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, strategy); pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay())); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class); JsonArray ja = jo.get("orders").getAsJsonArray(); int ndays = rs.getInt(12); String contract = ""; if (rollMethod == 1) { if (ndays > 1) { contract = rs.getString(10); } else { contract = rs.getString(11); } } else if (rollMethod == 2) { contract = rs.getString(15); } for (int ii = 0; ii < ja.size(); ++ii) { JsonObject jorder = ja.get(ii).getAsJsonObject(); switch (jorder.get("type").getAsString()) { case "EXIT_LONG_STOP": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP"); // LmtPrice printer.print(""); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "EXIT_SHORT_STOP": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP"); // LmtPrice printer.print(""); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "ENTER_LONG": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("MKT"); // LmtPrice printer.print(""); // AuxPrice printer.print(""); printer.println(); break; case "ENTER_SHORT": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("MKT"); // LmtPrice printer.print(""); // AuxPrice printer.print(""); printer.println(); break; case "ENTER_LONG_STOP": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP"); // LmtPrice printer.print(""); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "ENTER_LONG_STOP_LIMIT": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP LMT"); // LmtPrice printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal())); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "ENTER_SHORT_STOP": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP"); // LmtPrice printer.print(""); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "ENTER_SHORT_STOP_LIMIT": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP LMT"); // LmtPrice printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal())); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "EXIT_LONG": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("MKT"); // LmtPrice printer.print(""); // AuxPrice printer.print(""); printer.println(); break; case "EXIT_SHORT": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("MKT"); // LmtPrice printer.print(""); // AuxPrice printer.print(""); printer.println(); break; case "EXIT_SHORT_STOP_LIMIT": // Action printer.print("BUY"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP LMT"); // LmtPrice printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal())); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; case "EXIT_LONG_STOP_LIMIT": // Action printer.print("SELL"); // Quantity printer.print(jorder.get("quantity").getAsLong()); // Symbol printer.print(rs.getString(4)); // SecType printer.print(rs.getString(14)); // LastTradingDayOrContractMonth printer.print(contract); // Exchange printer.print(rs.getString(13)); // OrderType printer.print("STP LMT"); // LmtPrice printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal())); // AuxPrice printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal())); printer.println(); break; } } if (printer != null) printer.flush(); } }
From source file:norbert.mynemo.dataimport.fileformat.MynemoRating.java
/** * Prints the internal data to the given printer. The printer is usually created by calling the * {@link #createPrinter(String)} method. *///from w w w . j a v a2 s .c o m public void printOn(CSVPrinter printer) throws IOException { // the write order depends on the *_INDEX values printer.print(user); printer.print(movie); printer.print(value); // end of the record printer.println(); }
From source file:norbert.mynemo.dataimport.scraping.CkMapping.java
/** * Prints the internal data to the given printer. The printer is usually created by calling the * {@link #createPrinter(String)} method. *//*from w w w . j a v a 2 s .c om*/ public void printOn(CSVPrinter printer) throws IOException { // the write order depends on the order of the headers in the csv format printer.print(ckMovie); printer.print(imdbMovie); // end of the record printer.println(); }
From source file:norbert.mynemo.dataimport.scraping.CkRating.java
/** * Prints the internal data to the given printer. The printer is usually created by calling the * {@link #createPrinter(String)} method. *///from w w w . java2s .c o m public void printOn(CSVPrinter printer) throws IOException { checkNotNull(printer); // the write order depends on the order of the headers in the csv format printer.print(user); printer.print(movie); printer.print(value); // end of the record printer.println(); }