Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- protected static TrayIcon trayIcon;
- public static void main(String[] args) {
- List<List<MarketData>> fiveMinList = new ArrayList<List<MarketData>>();
- List<List<MarketData>> oneHourList = new ArrayList<List<MarketData>>();
- List<List<MarketData>> twentyfourHourList = new ArrayList<List<MarketData>>();
- Database db = new Database(); //Establish connection to database
- //command line args setup [table name] sets up new table
- if (args.length > 0){
- if (args[0].equals("setup")){
- setupDB(args[1], db);
- return;
- }
- }
- //Display a icon in the system tray so the user can exit
- if (SystemTray.isSupported()) {
- // get the SystemTray instance
- SystemTray tray = SystemTray.getSystemTray();
- // load an image
- Image image = Toolkit.getDefaultToolkit().getImage("java.png");
- // create a action listener to listen for default action executed on the tray icon
- ActionListener listener = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent arg0) {
- }
- };
- ActionListener exitListener = new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent e) {
- //JOptionPane.showMessageDialog(null, "Exiting program!");
- trayIcon.displayMessage("Market Summary", "Exiting", TrayIcon.MessageType.INFO);
- System.exit(0);
- }
- };
- ActionListener aboutListener = new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent e) {
- JOptionPane.showMessageDialog(null, "<html><div>Icons made by <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div></html>");
- }
- };
- // create a popup menu
- PopupMenu popup = new PopupMenu();
- MenuItem defaultItem = new MenuItem();
- MenuItem aboutItem = new MenuItem("About");
- MenuItem exitItem = new MenuItem("Exit");
- //defaultItem.addActionListener(listener);
- exitItem.addActionListener(exitListener);
- aboutItem.addActionListener(aboutListener);
- //popup.add(defaultItem);
- popup.add(aboutItem);
- popup.add(exitItem);
- // construct a TrayIcon
- trayIcon = new TrayIcon(image, "Market Summary - Running", popup);
- // set the TrayIcon properties
- trayIcon.addActionListener(listener);
- try {
- tray.add(trayIcon);
- } catch (AWTException e) {
- System.err.println(e);
- }
- } else {
- // disable tray option in your application or
- // perform other actions
- }
- //Display message on start
- trayIcon.displayMessage("Market Summary", "Running", TrayIcon.MessageType.INFO);
- if(getOption(db, "reset").equals("true")){
- System.out.println("Resetting database values...");
- db.query("UPDATE tblBittrex SET 0min=0,5min=0,10min=0,15min=0,30min=0,1hour=0,2hour=0,4hour=0,1day=0,2day=0,3day=0,4day=0,5day=0,6day=0,7day=0;");
- }
- Runnable minuteRun = new Runnable(){
- @Override
- public void run() {
- System.out.println("1 minute update");
- MarketData temp = null;
- for(JsonElement t : getJSONArray()){
- JsonObject obj2 = t.getAsJsonObject();
- int result = db.query("UPDATE tblBittrex SET 0min=" + obj2.get("BaseVolume").getAsDouble() + " WHERE market='" + obj2.get("MarketName").getAsString() + "' AND type='volume';");
- result += db.query("UPDATE tblBittrex SET 0min=" + obj2.get("Last").getAsDouble() + " WHERE market='" + obj2.get("MarketName").getAsString() + "' AND type='price';");
- temp = new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble());
- if (result == 0){
- System.out.println("Record not found, attempting to add to database.");
- insertNew(db, temp);
- }
- }
- }
- };
- //Recover fiveMinList from binary file
- File f = new File("mincache.dat");
- if(f.exists()){
- List<List<MarketData>> read = readFile("mincache.dat");
- for (List<MarketData> temp : read){
- fiveMinList.add(0, temp);
- }
- }
- //Recover fiveMinList from binary file
- f = new File("hourcache.dat");
- if(f.exists()){
- List<List<MarketData>> read = readFile("hourcache.dat");
- for (List<MarketData> temp : read){
- oneHourList.add(0, temp);
- }
- }
- f = new File("daycache.dat");
- if(f.exists()){
- List<List<MarketData>> read = readFile("daycache.dat");
- for (List<MarketData> temp : read){
- twentyfourHourList.add(0, temp);
- }
- }
- Runnable fiveMinuteRun = new Runnable(){
- @Override
- public void run() {
- System.out.println("5 minute update - " + fiveMinList.size() + " run.");
- Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- System.out.println(timestamp);
- List<MarketData> tempList = new ArrayList<MarketData>();
- for(JsonElement t : getJSONArray()){
- JsonObject obj2 = t.getAsJsonObject();
- tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
- }
- fiveMinList.add(0, tempList);
- for(int i = 1; i < fiveMinList.size(); i++){
- if (i < 4 || i == 6){
- for(MarketData data : fiveMinList.get(i)){
- db.query("UPDATE tblBittrex SET " + (i * 5) + "min=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
- db.query("UPDATE tblBittrex SET " + (i * 5) + "min=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
- }
- }
- if (i == 6){ break; }
- }
- if (fiveMinList.size() > 288){
- System.out.println("24 hour update");
- timestamp = new Timestamp(System.currentTimeMillis());
- System.out.println(timestamp);
- for(MarketData data : fiveMinList.get(288)){
- db.query("UPDATE tblBittrex SET 1day=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
- db.query("UPDATE tblBittrex SET 1day=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
- }
- fiveMinList.remove(288);
- }
- //Save fiveMinList to binary file
- deleteCache("mincache.dat");
- saveFile(fiveMinList, "mincache.dat");
- }
- };
- Runnable oneHourRun = new Runnable(){
- @Override
- public void run() {
- System.out.println("1 hour update");
- Timestamp timestamp = new Timestamp(System.currentTimeMillis());
- System.out.println(timestamp);
- List<MarketData> tempList = new ArrayList<MarketData>();
- for(JsonElement t : getJSONArray()){
- JsonObject obj2 = t.getAsJsonObject();
- tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
- }
- oneHourList.add(0, tempList);
- if(oneHourList.size() > 5){
- oneHourList.remove(oneHourList.size() - 1);
- }
- for(int i = 1; i < oneHourList.size(); i++){
- System.out.println(i);
- if (i < 5 && i != 3){
- for(MarketData data : oneHourList.get(i)){
- db.query("UPDATE tblBittrex SET " + i + "hour=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
- db.query("UPDATE tblBittrex SET " + i + "hour=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
- }
- }
- }
- //Save fiveMinList to binary file
- deleteCache("hourcache.dat");
- saveFile(oneHourList, "hourcache.dat");
- }
- };
- Runnable tfHourRun = new Runnable(){
- @Override
- public void run() {
- System.out.println("Daily update");
- List<MarketData> tempList = new ArrayList<MarketData>();
- for(JsonElement t : getJSONArray()){
- JsonObject obj2 = t.getAsJsonObject();
- tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
- }
- twentyfourHourList.add(0, tempList);
- if(twentyfourHourList.size() > 8){
- twentyfourHourList.remove(8);
- }
- for(int i = 2; i < twentyfourHourList.size(); i++){
- System.out.println("Day " + i + " updating");
- for(MarketData data : twentyfourHourList.get(i)){
- db.query("UPDATE tblBittrex SET " + i + "day=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
- db.query("UPDATE tblBittrex SET " + i + "day=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
- }
- }
- //Save fiveMinList to binary file
- deleteCache("daycache.dat");
- saveFile(twentyfourHourList, "daycache.dat");
- }
- };
- LocalDateTime localNow = LocalDateTime.now();
- ZoneId currentZone = ZoneId.of(getOption(db, "zone"));
- ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
- ZonedDateTime zonedNext5 ;
- int hour = Integer.parseInt(getOption(db, "hour"));
- int min = Integer.parseInt(getOption(db, "minute"));
- System.out.println(hour);
- System.out.println(min);
- zonedNext5 = zonedNow.withHour(hour).withMinute(min).withSecond(0);
- if(zonedNow.compareTo(zonedNext5) > 0)
- zonedNext5 = zonedNext5.plusDays(1);
- Duration duration = Duration.between(zonedNow, zonedNext5);
- long initalDelay = duration.getSeconds();
- ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
- scheduler.scheduleAtFixedRate(tfHourRun, initalDelay,
- 24*60*60, TimeUnit.SECONDS);
- ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
- exec.scheduleAtFixedRate(minuteRun , 0, 1, TimeUnit.SECONDS);
- exec.scheduleAtFixedRate(fiveMinuteRun , 0, 5, TimeUnit.MINUTES);
- exec.scheduleAtFixedRate(oneHourRun , 0, 1, TimeUnit.HOURS);
- }
- private static void deleteCache(String fileName){
- File file = new File(fileName);
- if(file.delete()){
- System.out.println("File deleted successfully");
- } else {
- System.out.println("Failed to delete the file");
- }
- }
- private static List<List<MarketData>> readFile(String fileName){
- FileInputStream fis;
- List<List<MarketData>> read = null;
- try {
- fis = new FileInputStream(fileName);
- ObjectInputStream ois = new ObjectInputStream(fis);
- read = (List<List<MarketData>>)ois.readObject();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return read;
- }
- private static void saveFile(List<List<MarketData>> list, String fileName){
- FileOutputStream fos;
- try {
- fos = new FileOutputStream(fileName);
- ObjectOutputStream out = new ObjectOutputStream(fos);
- out.writeObject(list);
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void insertNew(Database db, MarketData data){
- String query = "INSERT INTO tblBittrex"
- + " (market,"
- + "type,"
- + "0min,"
- + "5min,"
- + "10min,"
- + "15min,"
- + "30min,"
- + "1hour,"
- + "2hour,"
- + "4hour,"
- + "1day,"
- + "2day,"
- + "3day,"
- + "4day,"
- + "5day,"
- + "6day,"
- + "7day"
- + ")"
- + " VALUES ('" + data.getName() + "','price',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);" ;
- System.out.println(query);
- db.query(query);
- query = "INSERT INTO tblBittrex"
- + " (market,"
- + "type,"
- + "0min,"
- + "5min,"
- + "10min,"
- + "15min,"
- + "30min,"
- + "1hour,"
- + "2hour,"
- + "4hour,"
- + "1day,"
- + "2day,"
- + "3day,"
- + "4day,"
- + "5day,"
- + "6day,"
- + "7day"
- + ")"
- + " VALUES ('" + data.getName() + "','volume',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);" ;
- System.out.println(query);
- db.query(query);
- }
- private static String getOption(Database db, String option){
- ResultSet result = db.select("SELECT value FROM tblOption WHERE name='" + option + "'");
- String str = null;
- try {
- while(result.next()){
- str = result.getString("value");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return str;
- }
- private static JsonArray getJSONArray(){
- String requestURL = "https://bittrex.com/api/v1.1/public/getmarketsummaries";
- URL request;
- BufferedReader reader = null;
- //Pull data from Brettix API
- try {
- request = new URL(requestURL);
- reader = new BufferedReader(new InputStreamReader(request.openStream()));
- } catch (IOException e) {
- e.printStackTrace();
- }
- JsonReader jsonReader = new JsonReader(reader);
- JsonParser jsonParser = new JsonParser();
- JsonObject obj = jsonParser.parse(jsonReader).getAsJsonObject();
- JsonArray array = obj.getAsJsonArray("result");
- return array;
- }
- private static void sqlQuery(Connection c, String query) {
- try {
- Statement stmt = c.createStatement();
- stmt.executeUpdate(query) ;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- class Database {
- //String url = "jdbc:mysql://149.56.32.77:3306/bittrexdb";
- String url = "jdbc:mysql://localhost:3306/bittrexdb";
- String dbUser = "administrator";
- String dbPass = "Bittrex1";
- Connection conn = null;
- Database(){
- //Establish connection to MySQL database
- try {
- Class.forName ("com.mysql.jdbc.Driver");
- this.conn = DriverManager.getConnection (url, dbUser, dbPass);
- System.out.println ("Database connection established");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public int query(String q){
- try {
- Statement stmt = conn.createStatement();
- int count = stmt.executeUpdate(q) ;
- return count;
- //System.out.println(q);
- } catch (SQLException e) {
- System.out.println("error");
- e.printStackTrace();
- }
- return 0;
- }
- public ResultSet select(String q){
- ResultSet rs = null;
- try {
- Statement stmt = conn.createStatement();
- rs = stmt.executeQuery(q) ;
- //System.out.println(q);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return rs;
- }
- public int count(String table){
- int c = this.query("SELECT COUNT(*) FROM " + table);
- return c;
- }
- }
- class MarketData implements Serializable {
- private String name;
- private double volume;
- private double price;
- MarketData(String name, double volume, double price){
- this.name = name;
- this.volume = volume;
- this.price = price;
- }
- public String getName(){
- return name;
- }
- public double getVolume(){
- return volume;
- }
- public double getPrice(){
- return price;
- }
- }
Add Comment
Please, Sign In to add comment