Guest User

Untitled

a guest
Nov 25th, 2017
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.16 KB | None | 0 0
  1. public class Main {
  2. protected static TrayIcon trayIcon;
  3.  
  4. public static void main(String[] args) {
  5. List<List<MarketData>> fiveMinList = new ArrayList<List<MarketData>>();
  6. List<List<MarketData>> oneHourList = new ArrayList<List<MarketData>>();
  7. List<List<MarketData>> twentyfourHourList = new ArrayList<List<MarketData>>();
  8. Database db = new Database(); //Establish connection to database
  9.  
  10. //command line args setup [table name] sets up new table
  11. if (args.length > 0){
  12. if (args[0].equals("setup")){
  13. setupDB(args[1], db);
  14. return;
  15. }
  16. }
  17.  
  18.  
  19. //Display a icon in the system tray so the user can exit
  20. if (SystemTray.isSupported()) {
  21. // get the SystemTray instance
  22. SystemTray tray = SystemTray.getSystemTray();
  23. // load an image
  24. Image image = Toolkit.getDefaultToolkit().getImage("java.png");
  25. // create a action listener to listen for default action executed on the tray icon
  26. ActionListener listener = new ActionListener() {
  27. @Override
  28. public void actionPerformed(ActionEvent arg0) {
  29. }
  30. };
  31.  
  32. ActionListener exitListener = new ActionListener(){
  33. @Override
  34. public void actionPerformed(ActionEvent e) {
  35. //JOptionPane.showMessageDialog(null, "Exiting program!");
  36. trayIcon.displayMessage("Market Summary", "Exiting", TrayIcon.MessageType.INFO);
  37. System.exit(0);
  38. }
  39. };
  40.  
  41. ActionListener aboutListener = new ActionListener(){
  42. @Override
  43. public void actionPerformed(ActionEvent e) {
  44. 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>");
  45. }
  46. };
  47. // create a popup menu
  48. PopupMenu popup = new PopupMenu();
  49. MenuItem defaultItem = new MenuItem();
  50. MenuItem aboutItem = new MenuItem("About");
  51. MenuItem exitItem = new MenuItem("Exit");
  52. //defaultItem.addActionListener(listener);
  53. exitItem.addActionListener(exitListener);
  54. aboutItem.addActionListener(aboutListener);
  55. //popup.add(defaultItem);
  56. popup.add(aboutItem);
  57. popup.add(exitItem);
  58. // construct a TrayIcon
  59. trayIcon = new TrayIcon(image, "Market Summary - Running", popup);
  60. // set the TrayIcon properties
  61. trayIcon.addActionListener(listener);
  62.  
  63. try {
  64. tray.add(trayIcon);
  65. } catch (AWTException e) {
  66. System.err.println(e);
  67. }
  68. } else {
  69. // disable tray option in your application or
  70. // perform other actions
  71. }
  72.  
  73. //Display message on start
  74. trayIcon.displayMessage("Market Summary", "Running", TrayIcon.MessageType.INFO);
  75.  
  76.  
  77.  
  78. if(getOption(db, "reset").equals("true")){
  79. System.out.println("Resetting database values...");
  80. 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;");
  81. }
  82.  
  83. Runnable minuteRun = new Runnable(){
  84. @Override
  85. public void run() {
  86. System.out.println("1 minute update");
  87. MarketData temp = null;
  88.  
  89. for(JsonElement t : getJSONArray()){
  90. JsonObject obj2 = t.getAsJsonObject();
  91.  
  92.  
  93. int result = db.query("UPDATE tblBittrex SET 0min=" + obj2.get("BaseVolume").getAsDouble() + " WHERE market='" + obj2.get("MarketName").getAsString() + "' AND type='volume';");
  94. result += db.query("UPDATE tblBittrex SET 0min=" + obj2.get("Last").getAsDouble() + " WHERE market='" + obj2.get("MarketName").getAsString() + "' AND type='price';");
  95.  
  96. temp = new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble());
  97.  
  98. if (result == 0){
  99. System.out.println("Record not found, attempting to add to database.");
  100. insertNew(db, temp);
  101. }
  102. }
  103. }
  104. };
  105.  
  106.  
  107. //Recover fiveMinList from binary file
  108. File f = new File("mincache.dat");
  109.  
  110. if(f.exists()){
  111. List<List<MarketData>> read = readFile("mincache.dat");
  112. for (List<MarketData> temp : read){
  113. fiveMinList.add(0, temp);
  114. }
  115. }
  116.  
  117. //Recover fiveMinList from binary file
  118. f = new File("hourcache.dat");
  119.  
  120. if(f.exists()){
  121. List<List<MarketData>> read = readFile("hourcache.dat");
  122. for (List<MarketData> temp : read){
  123. oneHourList.add(0, temp);
  124. }
  125. }
  126.  
  127. f = new File("daycache.dat");
  128.  
  129. if(f.exists()){
  130. List<List<MarketData>> read = readFile("daycache.dat");
  131. for (List<MarketData> temp : read){
  132. twentyfourHourList.add(0, temp);
  133. }
  134. }
  135.  
  136. Runnable fiveMinuteRun = new Runnable(){
  137. @Override
  138. public void run() {
  139. System.out.println("5 minute update - " + fiveMinList.size() + " run.");
  140. Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  141. System.out.println(timestamp);
  142. List<MarketData> tempList = new ArrayList<MarketData>();
  143.  
  144. for(JsonElement t : getJSONArray()){
  145. JsonObject obj2 = t.getAsJsonObject();
  146. tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
  147. }
  148.  
  149. fiveMinList.add(0, tempList);
  150.  
  151. for(int i = 1; i < fiveMinList.size(); i++){
  152. if (i < 4 || i == 6){
  153. for(MarketData data : fiveMinList.get(i)){
  154. db.query("UPDATE tblBittrex SET " + (i * 5) + "min=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
  155. db.query("UPDATE tblBittrex SET " + (i * 5) + "min=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
  156. }
  157. }
  158. if (i == 6){ break; }
  159. }
  160.  
  161. if (fiveMinList.size() > 288){
  162. System.out.println("24 hour update");
  163. timestamp = new Timestamp(System.currentTimeMillis());
  164. System.out.println(timestamp);
  165. for(MarketData data : fiveMinList.get(288)){
  166. db.query("UPDATE tblBittrex SET 1day=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
  167. db.query("UPDATE tblBittrex SET 1day=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
  168. }
  169. fiveMinList.remove(288);
  170. }
  171.  
  172. //Save fiveMinList to binary file
  173. deleteCache("mincache.dat");
  174. saveFile(fiveMinList, "mincache.dat");
  175. }
  176. };
  177.  
  178. Runnable oneHourRun = new Runnable(){
  179. @Override
  180. public void run() {
  181. System.out.println("1 hour update");
  182. Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  183. System.out.println(timestamp);
  184. List<MarketData> tempList = new ArrayList<MarketData>();
  185.  
  186. for(JsonElement t : getJSONArray()){
  187. JsonObject obj2 = t.getAsJsonObject();
  188. tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
  189. }
  190.  
  191. oneHourList.add(0, tempList);
  192. if(oneHourList.size() > 5){
  193. oneHourList.remove(oneHourList.size() - 1);
  194. }
  195.  
  196. for(int i = 1; i < oneHourList.size(); i++){
  197. System.out.println(i);
  198. if (i < 5 && i != 3){
  199. for(MarketData data : oneHourList.get(i)){
  200. db.query("UPDATE tblBittrex SET " + i + "hour=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
  201. db.query("UPDATE tblBittrex SET " + i + "hour=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
  202. }
  203. }
  204. }
  205.  
  206. //Save fiveMinList to binary file
  207. deleteCache("hourcache.dat");
  208. saveFile(oneHourList, "hourcache.dat");
  209. }
  210. };
  211.  
  212. Runnable tfHourRun = new Runnable(){
  213. @Override
  214. public void run() {
  215. System.out.println("Daily update");
  216. List<MarketData> tempList = new ArrayList<MarketData>();
  217.  
  218. for(JsonElement t : getJSONArray()){
  219. JsonObject obj2 = t.getAsJsonObject();
  220. tempList.add(new MarketData(obj2.get("MarketName").getAsString(),obj2.get("BaseVolume").getAsDouble(),obj2.get("Last").getAsDouble()));
  221. }
  222.  
  223.  
  224. twentyfourHourList.add(0, tempList);
  225. if(twentyfourHourList.size() > 8){
  226. twentyfourHourList.remove(8);
  227. }
  228.  
  229. for(int i = 2; i < twentyfourHourList.size(); i++){
  230. System.out.println("Day " + i + " updating");
  231. for(MarketData data : twentyfourHourList.get(i)){
  232. db.query("UPDATE tblBittrex SET " + i + "day=" + data.getVolume() + " WHERE market='" + data.getName() + "' AND type='volume';");
  233. db.query("UPDATE tblBittrex SET " + i + "day=" + data.getPrice() + " WHERE market='" + data.getName() + "' AND type='price';");
  234. }
  235. }
  236.  
  237. //Save fiveMinList to binary file
  238. deleteCache("daycache.dat");
  239. saveFile(twentyfourHourList, "daycache.dat");
  240. }
  241. };
  242.  
  243.  
  244. LocalDateTime localNow = LocalDateTime.now();
  245. ZoneId currentZone = ZoneId.of(getOption(db, "zone"));
  246. ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
  247. ZonedDateTime zonedNext5 ;
  248. int hour = Integer.parseInt(getOption(db, "hour"));
  249. int min = Integer.parseInt(getOption(db, "minute"));
  250. System.out.println(hour);
  251. System.out.println(min);
  252. zonedNext5 = zonedNow.withHour(hour).withMinute(min).withSecond(0);
  253. if(zonedNow.compareTo(zonedNext5) > 0)
  254. zonedNext5 = zonedNext5.plusDays(1);
  255.  
  256. Duration duration = Duration.between(zonedNow, zonedNext5);
  257. long initalDelay = duration.getSeconds();
  258.  
  259. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  260. scheduler.scheduleAtFixedRate(tfHourRun, initalDelay,
  261. 24*60*60, TimeUnit.SECONDS);
  262.  
  263.  
  264.  
  265. ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
  266. exec.scheduleAtFixedRate(minuteRun , 0, 1, TimeUnit.SECONDS);
  267. exec.scheduleAtFixedRate(fiveMinuteRun , 0, 5, TimeUnit.MINUTES);
  268. exec.scheduleAtFixedRate(oneHourRun , 0, 1, TimeUnit.HOURS);
  269. }
  270.  
  271. private static void deleteCache(String fileName){
  272. File file = new File(fileName);
  273.  
  274. if(file.delete()){
  275. System.out.println("File deleted successfully");
  276. } else {
  277. System.out.println("Failed to delete the file");
  278. }
  279. }
  280.  
  281. private static List<List<MarketData>> readFile(String fileName){
  282. FileInputStream fis;
  283. List<List<MarketData>> read = null;
  284.  
  285. try {
  286. fis = new FileInputStream(fileName);
  287. ObjectInputStream ois = new ObjectInputStream(fis);
  288. read = (List<List<MarketData>>)ois.readObject();
  289. } catch (Exception e) {
  290. e.printStackTrace();
  291. }
  292.  
  293. return read;
  294. }
  295.  
  296. private static void saveFile(List<List<MarketData>> list, String fileName){
  297. FileOutputStream fos;
  298. try {
  299. fos = new FileOutputStream(fileName);
  300. ObjectOutputStream out = new ObjectOutputStream(fos);
  301. out.writeObject(list);
  302. out.close();
  303. } catch (Exception e) {
  304. e.printStackTrace();
  305. }
  306. }
  307.  
  308. private static void insertNew(Database db, MarketData data){
  309. String query = "INSERT INTO tblBittrex"
  310. + " (market,"
  311. + "type,"
  312. + "0min,"
  313. + "5min,"
  314. + "10min,"
  315. + "15min,"
  316. + "30min,"
  317. + "1hour,"
  318. + "2hour,"
  319. + "4hour,"
  320. + "1day,"
  321. + "2day,"
  322. + "3day,"
  323. + "4day,"
  324. + "5day,"
  325. + "6day,"
  326. + "7day"
  327. + ")"
  328. + " VALUES ('" + data.getName() + "','price',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);" ;
  329. System.out.println(query);
  330. db.query(query);
  331.  
  332. query = "INSERT INTO tblBittrex"
  333. + " (market,"
  334. + "type,"
  335. + "0min,"
  336. + "5min,"
  337. + "10min,"
  338. + "15min,"
  339. + "30min,"
  340. + "1hour,"
  341. + "2hour,"
  342. + "4hour,"
  343. + "1day,"
  344. + "2day,"
  345. + "3day,"
  346. + "4day,"
  347. + "5day,"
  348. + "6day,"
  349. + "7day"
  350. + ")"
  351. + " VALUES ('" + data.getName() + "','volume',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);" ;
  352. System.out.println(query);
  353. db.query(query);
  354.  
  355.  
  356. }
  357.  
  358. private static String getOption(Database db, String option){
  359. ResultSet result = db.select("SELECT value FROM tblOption WHERE name='" + option + "'");
  360. String str = null;
  361.  
  362. try {
  363. while(result.next()){
  364. str = result.getString("value");
  365. }
  366. } catch (SQLException e) {
  367. e.printStackTrace();
  368. }
  369.  
  370. return str;
  371. }
  372.  
  373. private static JsonArray getJSONArray(){
  374. String requestURL = "https://bittrex.com/api/v1.1/public/getmarketsummaries";
  375. URL request;
  376. BufferedReader reader = null;
  377.  
  378. //Pull data from Brettix API
  379. try {
  380. request = new URL(requestURL);
  381. reader = new BufferedReader(new InputStreamReader(request.openStream()));
  382. } catch (IOException e) {
  383. e.printStackTrace();
  384. }
  385.  
  386. JsonReader jsonReader = new JsonReader(reader);
  387. JsonParser jsonParser = new JsonParser();
  388. JsonObject obj = jsonParser.parse(jsonReader).getAsJsonObject();
  389. JsonArray array = obj.getAsJsonArray("result");
  390.  
  391. return array;
  392. }
  393.  
  394. private static void sqlQuery(Connection c, String query) {
  395. try {
  396. Statement stmt = c.createStatement();
  397. stmt.executeUpdate(query) ;
  398. } catch (SQLException e) {
  399. e.printStackTrace();
  400. }
  401. }
  402.  
  403. class Database {
  404. //String url = "jdbc:mysql://149.56.32.77:3306/bittrexdb";
  405. String url = "jdbc:mysql://localhost:3306/bittrexdb";
  406. String dbUser = "administrator";
  407. String dbPass = "Bittrex1";
  408. Connection conn = null;
  409.  
  410. Database(){
  411. //Establish connection to MySQL database
  412. try {
  413. Class.forName ("com.mysql.jdbc.Driver");
  414. this.conn = DriverManager.getConnection (url, dbUser, dbPass);
  415. System.out.println ("Database connection established");
  416. } catch (Exception e) {
  417. e.printStackTrace();
  418. }
  419. }
  420.  
  421. public int query(String q){
  422. try {
  423. Statement stmt = conn.createStatement();
  424. int count = stmt.executeUpdate(q) ;
  425. return count;
  426. //System.out.println(q);
  427. } catch (SQLException e) {
  428. System.out.println("error");
  429. e.printStackTrace();
  430. }
  431. return 0;
  432. }
  433.  
  434. public ResultSet select(String q){
  435. ResultSet rs = null;
  436. try {
  437. Statement stmt = conn.createStatement();
  438. rs = stmt.executeQuery(q) ;
  439. //System.out.println(q);
  440. } catch (SQLException e) {
  441.  
  442. e.printStackTrace();
  443. }
  444. return rs;
  445. }
  446.  
  447. public int count(String table){
  448. int c = this.query("SELECT COUNT(*) FROM " + table);
  449. return c;
  450. }
  451. }
  452.  
  453. class MarketData implements Serializable {
  454. private String name;
  455. private double volume;
  456. private double price;
  457.  
  458. MarketData(String name, double volume, double price){
  459. this.name = name;
  460. this.volume = volume;
  461. this.price = price;
  462. }
  463.  
  464. public String getName(){
  465. return name;
  466. }
  467.  
  468. public double getVolume(){
  469. return volume;
  470. }
  471.  
  472. public double getPrice(){
  473. return price;
  474. }
  475. }
Add Comment
Please, Sign In to add comment