public class MainChart extends Chart {
  private static TextField periodTF;
  private static ComboBox<String> periodCB, intervalCB;
  public static HBox centerHbox = new HBox(10);

  public MainChart(){
  }

  public MainChart(BorderPane centerBorderPane) {
    Label periodLabel = new Label("Period:");
    periodTF = new TextField();
    periodTF.setPrefWidth(50);
    periodTF.setText("1");
    periodCB = new ComboBox<String>();
    periodCB.getItems().addAll("Days", "Weeks", "Months", "Years");
    periodCB.setPromptText("Select a period:");
    periodCB.setValue("Years");
    Label intervalLabel = new Label("Interval:");
    intervalCB = new ComboBox<String>();
    intervalCB.getItems().addAll("Days", "Weeks", "Months");
    intervalCB.setPromptText("Select an interval:");
    intervalCB.setValue("Weeks");
    Button adjustChartButton = new Button("Adjust Chart");

    centerHbox.getChildren().addAll(periodLabel, periodTF, periodCB, intervalLabel, intervalCB,
        adjustChartButton);
    centerHbox.setAlignment(Pos.BASELINE_CENTER);
    centerHbox.setPadding(new Insets(0, 0, 10, 0));
    centerHbox.setVisible(false);

    adjustChartButton.setOnAction(e -> {
      try {
        centerBorderPane.setCenter(drawMainChart(NewChart.lastCompanyChart));
      } catch (Exception e1) {
        System.out.println("adjustChartButton throws unlucky exception" + e1.getStackTrace());
      }
    });
  }

  public LineChart<String, Number> drawMainChart(String company) throws IOException {
    String period = periodCB.getValue();
    String interval = intervalCB.getValue();
    makeChart(company, periodTF.getText(), period, interval);
    centerHbox.setVisible(true);
    return lineChart;
  }

} public class NewChart extends Chart {
  public static String lastCompanyChart = "";
  private ComboBox<String> periodCB, intervalCB;
  private TextField periodTF;
  public Stage window;


  public NewChart() {
    super();// calls the constructor of the extended class
    window = new Stage();
    window.setTitle("New Chart");
    window.initModality(Modality.APPLICATION_MODAL);
    GridPane grid = new GridPane();
    grid.setPadding(new Insets(20, 20, 0, 20));
    grid.setVgap(8);
    grid.setHgap(10);

    Label companyLabel = new Label("Company:");
    GridPane.setConstraints(companyLabel, 0, 0);

    TextField companyTF = new TextField();
    companyTF.setPromptText("company");
    GridPane.setConstraints(companyTF, 1, 0);

    Label periodLabel = new Label("Period:");
    GridPane.setConstraints(periodLabel, 0, 1);

    HBox hbox = new HBox(10);
    periodCB = new ComboBox<String>();
    periodCB.getItems().addAll("Days", "Weeks", "Months", "Years");
    periodCB.setPromptText("Select a period:");
    periodTF = new TextField();
    periodTF.setPromptText("period");
    periodTF.setPrefWidth(60);
    hbox.getChildren().addAll(periodTF, periodCB);
    GridPane.setConstraints(hbox, 1, 1);

    Label intervalLabel = new Label("Interval:");
    GridPane.setConstraints(intervalLabel, 0, 2);
    intervalCB = new ComboBox<String>();
    intervalCB.getItems().addAll("Days", "Weeks", "Months");
    intervalCB.setPromptText("Select an interval:");
    GridPane.setConstraints(intervalCB, 1, 2);
    intervalCB.setPrefWidth(194);

    Button adjustButton = new Button("New Chart");
    adjustButton.setPrefWidth(250);
    grid.getChildren().addAll(companyLabel, companyTF, periodLabel, hbox, intervalLabel,
        intervalCB);
    BorderPane borderPane = new BorderPane();
    borderPane.setTop(grid);
    borderPane.setCenter(adjustButton);
    Scene scene = new Scene(borderPane, 290, 180);
    window.setScene(scene);
    window.setResizable(false);
    window.getIcons().add(new Image("blue.png"));


    adjustButton.setOnAction(e1 -> {
      MainChart.centerHbox.setVisible(true);
      try {
        drawNewChart(companyTF.getText());
      } catch (IOException e2) {
        e2.printStackTrace();
      }
      LineChart<String, Number> lchart = getLineChart();
      Main.centerBorderPane.setCenter(lchart);
    });
  }

  public void drawNewChart(String company) throws IOException {
    lastCompanyChart = company;
    String period = periodCB.getValue();
    String interval = intervalCB.getValue();
    makeChart(lastCompanyChart, periodTF.getText(), period, interval);
    setLineChart(lineChart);
    window.close();
  }

  public LineChart<String, Number> getLineChart() {
    return lineChart;
  }

  public void setLineChart(LineChart<String, Number> line) {
    lineChart = line;
  }


} public class TradeData {
  private String company;
  private String symbol;
  private int orderNumber;
  private String orderTime;
  private String orderType;
  private int volume;
  private BigDecimal purchasePrice;
  private BigDecimal currentPrice;
  private BigDecimal profit;

  public String getCompany() {
    return company;
  }

  public void setCompany(String company) {
    this.company = company;
  }

  public String getSymbol() {
    return symbol;
  }

  public void setSymbol(String symbol) {
    this.symbol = symbol;
  }

  public int getOrderNumber() {
    return orderNumber;
  }

  public void setOrderNumber(int orderNumber) {
    this.orderNumber = orderNumber;
  }

  public String getOrderTime() {
    return orderTime;
  }

  public void setOrderTime(String orderTime) {
    this.orderTime = orderTime;
  }

  public String getOrderType() {
    return orderType;
  }

  public void setOrderType(String orderType) {
    this.orderType = orderType;
  }

  public int getVolume() {
    return volume;
  }

  public void setVolume(int volume) {
    this.volume = volume;
  }

  public BigDecimal getPurchasePrice() {
    return purchasePrice;
  }

  public void setPurchasePrice(BigDecimal purchasePrice) {
    this.purchasePrice = purchasePrice;
  }

  public BigDecimal getCurrentPrice() {
    return currentPrice;
  }

  public void setCurrentPrice(BigDecimal currentPrice) {
    this.currentPrice = currentPrice;
  }

  public BigDecimal getProfit() {
    return profit;
  }

  public void setProfit(BigDecimal profit) {
    this.profit = profit;
  }
} public class LoggedUser {

  private static StringProperty loggedUser = new SimpleStringProperty("");

  public static StringProperty loggedUserProperty() {
    return loggedUser;
  }

  public static String getLoggedUser() {
    return loggedUser.get();
  }


  public static void setLoggedUser(String currentLoggedUser) {
    loggedUser.set(currentLoggedUser);
  }

} public class UpdateTables {

  private static IntegerProperty updateTables = new SimpleIntegerProperty();

  public static IntegerProperty updateTableProperty() {
    return updateTables;
  }

  public static int getUpdateTable() {
    return updateTables.get();
  }


  public static void setUpdateTable(int change) {
    updateTables.set(change);
  }
} public class Database {

  private static final String DBURL = "jdbc:h2:~/test";
  private static final String DBUSER = "Kaloyan_Bogoslovov";
  private static final String DBPASS = "qwerty";
  private static Connection connection;

  public static void connectingToDB() throws ClassNotFoundException, SQLException {
    Class.forName("org.h2.Driver");
    connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
  }

  public static void createDB() throws ClassNotFoundException, SQLException {
    Class.forName("org.h2.Driver");
    Connection con = DriverManager.getConnection("jdbc:h2:~/test", "Kaloyan_Bogoslovov", "qwerty");
    Statement st = con.createStatement();
    String createUsersTable =
        "CREATE TABLE IF NOT EXISTS USERS(USERNAME VARCHAR2(20) primary key,FIRSTNAME VARCHAR2,lastname varchar2,password varchar2 ,balance number,leverage integer,margin NUMBER,totalprofit NUMBER,equity NUMBER,freemargin number,ordernumber integer,stockexchange varchar2);";
    String createTradesTable =
        "CREATE TABLE IF NOT EXISTS TRADES(USERNAME VARCHAR2(20) references users(username),SYMBOL VARCHAR2(8),ORDERNUMBER INTEGER,TRADETIME DATETIME ,TRADETYPE VARCHAR2(8),VOLUME NUMBER,PURCHASEPRICE NUMBER,CURRENTPRICE NUMBER,PROFIT NUMBER,TRADESTATE VARCHAR2,LASTPRICE NUMBER,COMPANY varchar2,Closetime datetime);";
    st.executeUpdate(createUsersTable);
    st.executeUpdate(createTradesTable);
    con.close();
  }

  public static ResultSet SelectDB(String data) throws SQLException {
    Statement st = connection.createStatement();
    ResultSet rs = st.executeQuery(data);
    return rs;
  }

  public static void insertDB(String data) throws SQLException {
    Statement st = connection.createStatement();
    st.executeUpdate(data);
  }

  public static void closeConnectionToDB() throws SQLException {
    connection.close();
  }

} public class Main extends Application {
  public static TabPane leftTabPane;
  public static Tab detailsTab;
  public static BorderPane centerBorderPane = new BorderPane();
  public static ComboBox<String> inputCB;
  private Tabs symbolTable;


  public static void main(String[] args) {
    launch(args);
  }

  public void start(Stage primaryStage) throws Exception {
    Stage window = primaryStage;
    window.setTitle("Virtual Trading");

    Menu fileMenu = new Menu("File");
    Menu toolsMenu = new Menu("Tools");
    Menu helpMenu = new Menu("Help");

    Tabs balanceTable = TabsFactory.createElement(0);
    Tabs tradeTable = TabsFactory.createElement(1);
    Tabs historyTable = TabsFactory.createElement(2);
    symbolTable = TabsFactory.createElement(3);
    new MainChart(centerBorderPane);

    MenuItem logOutMI = new MenuItem("Logout...");
    MenuItem exitMI = new MenuItem("Exit");
    fileMenu.getItems().addAll(logOutMI, exitMI);

    MenuItem orderMI = new MenuItem("New Order...");
    MenuItem newChartMI = new MenuItem("New Chart...");
    toolsMenu.getItems().addAll(orderMI, newChartMI);

    MenuItem aboutMI = new MenuItem("About...");
    helpMenu.getItems().addAll(aboutMI);

    inputCB = new ComboBox<String>();
    inputCB.setMinWidth(209);
    inputCB.setMaxWidth(200);
    inputCB.setEditable(true);
    inputCB.getStyleClass().add("combo-box1");

    Button searchButton = new Button("Search");
    Separator separator1 = new Separator();
    separator1.setOrientation(Orientation.VERTICAL);
    Button newOrderButton = new Button("New Order...");
    Separator separator2 = new Separator();
    separator2.setOrientation(Orientation.VERTICAL);
    Button newChartButton = new Button("New Chart...");

    ToolBar topToolBar = new ToolBar();
    topToolBar.getItems().addAll(inputCB, searchButton, separator1, newOrderButton, newChartButton,
        separator2);

    MenuBar mainMenuBar = new MenuBar();
    mainMenuBar.getMenus().addAll(fileMenu, toolsMenu, helpMenu);

    VBox topVBox = new VBox(5);
    topVBox.getChildren().addAll(mainMenuBar, topToolBar);

    leftTabPane = new TabPane();
    Tab symbolsTab = new Tab("Company symbols");
    detailsTab = new Tab("Company details");
    symbolsTab.setContent(symbolTable.getTable());
    leftTabPane.getTabs().addAll(symbolsTab, detailsTab);
    leftTabPane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
    leftTabPane.setSide(Side.BOTTOM);

    TabPane bottomTabPane = new TabPane();
    Tab tradeTab = new Tab("Trades");
    Tab balanceTab = new Tab("Balance");
    Tab historyTab = new Tab("History");
    bottomTabPane.getTabs().addAll(tradeTab, balanceTab, historyTab);
    bottomTabPane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
    bottomTabPane.setSide(Side.BOTTOM);

    tradeTab.setContent(tradeTable.getTable());
    historyTab.setContent(historyTable.getTable());
    balanceTab.setContent(balanceTable.getTable());

    inputCB.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
      public void handle(KeyEvent e) {
        inputCompanyListener(e);
      }
    });

    UpdateTables.updateTableProperty().addListener((v, oldvalue, newvalue) -> {
      initTables(tradeTable, balanceTable, historyTable);
    });

    LoggedUser.loggedUserProperty().addListener((v, oldvalue, newvalue) -> {
      initTables(tradeTable, balanceTable, historyTable);
    });

    searchButton.setOnAction(e -> {
      symbolTable.initTableContent();
    });

    exitMI.setOnAction(e -> {
      window.close();
      System.exit(0);
    });

    newOrderButton.setOnAction(e -> {
      new NewPosition(LogIn.symbols);
    });

    logOutMI.setOnAction(e -> {
      LoggedUser.setLoggedUser("");
      new LogIn();
    });

    orderMI.setOnAction(e -> {
      new NewPosition(LogIn.symbols);
    });

    aboutMI.setOnAction(e -> {
      new About();
      System.out.println("153756");
    });

    newChartButton.setOnAction(e -> {
      new NewChart().window.show();
    });

    newChartMI.setOnAction(e -> {
      new NewChart().window.show();
    });

    window.setOnCloseRequest(e -> {
      System.exit(0);
    });

    BorderPane borderPane = new BorderPane();
    borderPane.setTop(topVBox);
    borderPane.setLeft(leftTabPane);
    borderPane.setBottom(bottomTabPane);
    borderPane.setCenter(centerBorderPane);
    centerBorderPane.setBottom(MainChart.centerHbox);
    Rectangle2D a = Screen.getPrimary().getVisualBounds(); // making object with the screens
                                                           // properties
    Scene mainScene = new Scene(borderPane, (a.getMaxX()) * 0.9, (a.getMaxY()) * 0.9);
    mainScene.getStylesheets().add("comboStyles.css");

    leftTabPane.prefWidthProperty().bind(mainScene.widthProperty().multiply(0.325));
    bottomTabPane.prefHeightProperty().bind(mainScene.heightProperty().multiply(0.3));
    bottomTabPane.prefWidthProperty().bind(mainScene.widthProperty());

    window.getIcons().add(new Image("blue.png"));
    window.setScene(mainScene);
    window.show();

    Database.createDB();
    new DataUpdating().dataUpdate();
    LogFile.initPathLocationAndCreateFile();
    new LogIn();
  }

  private void initTables(Tabs tradeTable, Tabs balanceTable, Tabs historyTable) {
    try {
      tradeTable.initTableContent();
      balanceTable.initTableContent();
      historyTable.initTableContent();
    } catch (Exception e1) {
      e1.printStackTrace();
    }
  }

  private void inputCompanyListener(KeyEvent e) {
    KeyCode key = e.getCode();
    if ((key != KeyCode.ENTER) && (key != KeyCode.UP) && (key != KeyCode.DOWN)) {
      searchCompany();
    }
    if (!inputCB.getEditor().getText().isEmpty() && e.getCode() == KeyCode.ENTER) {
      symbolTable.initTableContent();
    }
  }

  /**
   * check for company names that contain the inputed chars in the combobox and display them as
   * hints
   */
  private void searchCompany() {
    inputCB.hide();
    inputCB.getItems().clear();
    String s_typed = inputCB.getEditor().getText();

    for (String key : LogIn.keys) {
      if (s_typed.length() > 1) {
        boolean toadd =
            s_typed.length() == 0 ? true : key.toLowerCase().contains(s_typed.toLowerCase());
        if (toadd)
          inputCB.getItems().add(key);
      }
    }
    boolean showlist = s_typed.length() > 1;
    if (showlist)
      inputCB.show();
  }
} public interface Tabs {
  public TableView<Object> getTable();
  public void initTableContent();

} public class DetailsTab {

  DetailsData info = null;

  public DetailsTab() {}

  public DetailsTab(DetailsData data) {
    info = data;
  }

  public GridPane getDetails() throws IOException, NullPointerException {
    GridPane detailsGrid = new GridPane();
    detailsGrid.setPadding(new Insets(10, 10, 10, 10));
    detailsGrid.setVgap(8);
    detailsGrid.setHgap(10);

    Label companyName = new Label("Company Name:");
    GridPane.setConstraints(companyName, 0, 0);
    Label companyNameInfo = new Label(info.getName());
    GridPane.setConstraints(companyNameInfo, 2, 0);

    Label companySymbol = new Label("Symbol:");
    GridPane.setConstraints(companySymbol, 0, 1);
    Label companySymbolInfo = new Label(info.getSymbol());
    GridPane.setConstraints(companySymbolInfo, 1, 1);

    Label companyBid = new Label("Sell price:");
    GridPane.setConstraints(companyBid, 0, 2);
    Label companyBidInfoLabel = new Label();
    companyBidInfoLabel.setText(info.getBid());
    GridPane.setConstraints(companyBidInfoLabel, 1, 2);

    Label companyAsk = new Label("Buy price:");
    GridPane.setConstraints(companyAsk, 0, 3);
    Label companyAskInfo = new Label();
    companyAskInfo.setText(info.getAsk());
    GridPane.setConstraints(companyAskInfo, 1, 3);

    Label companyPrice = new Label("Last trade price:");
    GridPane.setConstraints(companyPrice, 0, 4);
    Label companyPriceInfo = new Label();
    companyPriceInfo.setText(info.getPrice());
    GridPane.setConstraints(companyPriceInfo, 1, 4);

    Label companyOpen = new Label("Day open:");
    GridPane.setConstraints(companyOpen, 2, 1);
    Label companyOpenInfo = new Label();
    companyOpenInfo.setText(info.getOpen());
    GridPane.setConstraints(companyOpenInfo, 3, 1);

    Label companyDayl = new Label("Day low:");
    GridPane.setConstraints(companyDayl, 2, 2);
    Label companyDaylInfo = new Label();
    companyDaylInfo.setText(info.getDayLow());
    GridPane.setConstraints(companyDaylInfo, 3, 2);

    Label companyDayh = new Label("Day high:");
    GridPane.setConstraints(companyDayh, 2, 3);
    Label companyDayhInfo = new Label();
    companyDayhInfo.setText(info.getDayHigh());
    GridPane.setConstraints(companyDayhInfo, 3, 3);

    Label companyClose = new Label("Close price:");
    GridPane.setConstraints(companyClose, 2, 4);
    Label companyCloseInfo = new Label();
    companyCloseInfo.setText(info.getPreviousClose());
    GridPane.setConstraints(companyCloseInfo, 3, 4);

    Label companyVolume = new Label("Volume:");
    GridPane.setConstraints(companyVolume, 0, 5);
    Label companyVolumeInfo = new Label();
    companyVolumeInfo.setText(info.getVolume());
    GridPane.setConstraints(companyVolumeInfo, 1, 5);

    Label companyVolumeA = new Label("Avg volume(3m):");
    GridPane.setConstraints(companyVolumeA, 2, 5);
    Label companyVolumeAInfo = new Label();
    companyVolumeAInfo.setText(info.getAvgVolumeDaily());
    GridPane.setConstraints(companyVolumeAInfo, 3, 5);

    Label companyStats = new Label("Company Stats:");
    GridPane.setConstraints(companyStats, 0, 6);

    Label companyBVPS = new Label("Book value per share:");
    GridPane.setConstraints(companyBVPS, 0, 7);
    Label companyBVPSInfo = new Label();
    companyBVPSInfo.setText(info.getBookValuePerShare());
    GridPane.setConstraints(companyBVPSInfo, 1, 7);

    Label companyRevenue = new Label("Revenue:");
    GridPane.setConstraints(companyRevenue, 0, 8);
    Label companyRevenueInfo = new Label();
    companyRevenueInfo.setText(info.getRevenue());
    GridPane.setConstraints(companyRevenueInfo, 1, 8);

    Label companyEBITDA = new Label("EBITDA:");
    GridPane.setConstraints(companyEBITDA, 0, 9);
    Label companyEBITDAInfo = new Label();
    companyEBITDAInfo.setText(info.getEBITDA());
    GridPane.setConstraints(companyEBITDAInfo, 1, 9);

    Label companyOutstandingShares = new Label("Outstanding shares:");
    GridPane.setConstraints(companyOutstandingShares, 0, 10);
    Label companyOutstandingSharesInfo = new Label();
    companyOutstandingSharesInfo.setText(info.getSharesOutstanding());
    GridPane.setConstraints(companyOutstandingSharesInfo, 1, 10);

    Label companyMarketCap = new Label("Market Capitalization:");
    GridPane.setConstraints(companyMarketCap, 0, 11);
    Label companyMarketCapInfo = new Label();
    companyMarketCapInfo.setText(info.getMarketCap());
    GridPane.setConstraints(companyMarketCapInfo, 1, 11);

    detailsGrid.getChildren().addAll(companyName, companyNameInfo, companySymbol, companySymbolInfo,
        companyBid, companyBidInfoLabel, companyAsk, companyAskInfo, companyPrice, companyPriceInfo,
        companyOpen, companyOpenInfo, companyDayl, companyDaylInfo, companyDayh, companyDayhInfo,
        companyClose, companyCloseInfo, companyVolume, companyVolumeInfo, companyVolumeA,
        companyVolumeAInfo, companyStats, companyBVPS, companyBVPSInfo, companyRevenue,
        companyRevenueInfo, companyEBITDA, companyEBITDAInfo, companyOutstandingShares,
        companyOutstandingSharesInfo, companyMarketCap, companyMarketCapInfo);
    return detailsGrid;

  }

} public class DetailsData {

  private String name;
  private String symbol;
  private String bid;
  private String ask;
  private String price;
  private String open;
  private String dayLow;
  private String dayHigh;
  private String previousClose;
  private String volume;
  private String avgVolumeDaily;
  private String bookValuePerShare;
  private String revenue;
  private String EBITDA;

  public String getEBITDA() {
    return EBITDA;
  }

  public void setEBITDA(String eBITDA) {
    EBITDA = eBITDA;
  }

  private String sharesOutstanding;
  private String marketCap;

  public DetailsData() {}

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSymbol() {
    return symbol;
  }

  public void setSymbol(String symbol) {
    this.symbol = symbol;
  }

  public String getBid() {
    return bid;
  }

  public void setBid(String bid) {
    this.bid = bid;
  }

  public String getAsk() {
    return ask;
  }

  public void setAsk(String ask) {
    this.ask = ask;
  }

  public String getPrice() {
    return price;
  }

  public void setPrice(String price) {
    this.price = price;
  }

  public String getOpen() {
    return open;
  }

  public void setOpen(String open) {
    this.open = open;
  }

  public String getDayLow() {
    return dayLow;
  }

  public void setDayLow(String dayLow) {
    this.dayLow = dayLow;
  }

  public String getDayHigh() {
    return dayHigh;
  }

  public void setDayHigh(String dayHigh) {
    this.dayHigh = dayHigh;
  }

  public String getPreviousClose() {
    return previousClose;
  }

  public void setPreviousClose(String previousClose) {
    this.previousClose = previousClose;
  }

  public String getVolume() {
    return volume;
  }

  public void setVolume(String volume) {
    this.volume = volume;
  }

  public String getAvgVolumeDaily() {
    return avgVolumeDaily;
  }

  public void setAvgVolumeDaily(String avgVolumeDaily) {
    this.avgVolumeDaily = avgVolumeDaily;
  }

  public String getBookValuePerShare() {
    return bookValuePerShare;
  }

  public void setBookValuePerShare(String bookValuePerShare) {
    this.bookValuePerShare = bookValuePerShare;
  }

  public String getRevenue() {
    return revenue;
  }

  public void setRevenue(String revenue) {
    this.revenue = revenue;
  }

  public String getSharesOutstanding() {
    return sharesOutstanding;
  }

  public void setSharesOutstanding(String sharesOutstanding) {
    this.sharesOutstanding = sharesOutstanding;
  }

  public String getMarketCap() {
    return marketCap;
  }

  public void setMarketCap(String marketCap) {
    this.marketCap = marketCap;
  }



} public class DetailsDataFromYahoo extends YahooFinance {
  String company = "";
  String[] data;
  DetailsData result = null;

  public DetailsDataFromYahoo(String company) {
    this.company = company;
  }

  @Override
  public Object getData() {
    String url = makeURL();
    URLConnection connection = setConnectionWithYahoo(url);
    getInformationFromYahoo(connection);
    setDataToDetailsData();
    return result;
  }

  private String makeURL() {
    String url =
        "http://finance.yahoo.com/d/quotes.csv?s=" + company + "&f=nsbal1oghpva2b4s6j4j2j1&e=.csv";
    return url;
  }

  public void getInformationFromYahoo(URLConnection connection) {
    try {
      InputStreamReader is = new InputStreamReader(connection.getInputStream());
      BufferedReader br = new BufferedReader(is);
      String line = br.readLine();
      br.close();
      System.out.println("Details parsing:" + line);
      parseTheInformation(line);
    } catch (IOException e) {
      System.out.println();
    }
  }

  public void parseTheInformation(String line) {
    // removing the first element '"' to be able to get the name of the company
    line = line.substring(1);
    int iend = line.indexOf('"');
    // getting the company name
    String companyName = line.substring(0, iend);
    // getting the remaining data
    line = line.substring(iend);
    data = line.split(",");
    data[0] = companyName;
    data[1] = data[1].substring(1, data[1].length() - 1);
    System.out.println(data[0] + data[1]);
  }

  public void setDataToDetailsData() {
    result = new DetailsData();
    result.setName(data[0]);
    result.setSymbol(data[1]);
    result.setBid(data[2]);
    result.setAsk(data[3]);
    result.setPrice(data[4]);
    result.setOpen(data[5]);
    result.setDayLow(data[6]);
    result.setDayHigh(data[7]);
    result.setPreviousClose(data[8]);
    result.setVolume(data[9]);
    result.setAvgVolumeDaily(data[10]);
    result.setBookValuePerShare(data[11]);
    result.setRevenue(data[12]);
    result.setEBITDA(data[13]);
    result.setSharesOutstanding(data[14]);
    try {
      result.setMarketCap(data[15]);
    } catch (ArrayIndexOutOfBoundsException a) {
      Alert alert = new Alert(AlertType.ERROR,
          "Currently there isn't data, for the company that you requested. Sorry for the inconvenience.");
      alert.setHeaderText("No data from Yahoo");
      alert.showAndWait();
    }
  }

} public class EssentialData {

  private String name;
  private String symbol;
  private BigDecimal bid;
  private BigDecimal ask;

  public EssentialData() {

  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSymbol() {
    return symbol;
  }

  public void setSymbol(String symbol) {
    this.symbol = symbol;
  }

  public BigDecimal getBid() {
    return bid;
  }

  public void setBid(String bid) {
    this.bid = new BigDecimal(bid);
  }

  public BigDecimal getAsk() {
    return ask;
  }

  public void setAsk(String ask) {
    this.ask = new BigDecimal(ask);
  }

} public class EssentialDataFromYahoo extends YahooFinance {
  private String company = "";
  private String[] data;
  EssentialData result = null;

  public EssentialDataFromYahoo(String company) {
    this.company = company;
  }

  public Object getData() {
    String url = makeURL();
    URLConnection connection = setConnectionWithYahoo(url);
    getInformationFromYahoo(connection);
    setDataToEssentialData();
    return result;
  }

  private String makeURL() {
    String url = "http://finance.yahoo.com/d/quotes.csv?s=" + company + "&f=nsba&e=.csv";
    return url;
  }

  private void getInformationFromYahoo(URLConnection connection) {
    try {
      InputStreamReader is = new InputStreamReader(connection.getInputStream());
      BufferedReader br = new BufferedReader(is);
      String line = br.readLine();
      br.close();
      System.out.println("Essential data parsing:" + line);
      parseTheInformation(line);
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("getInformationFromYahoo exception");
    }
  }

  private void parseTheInformation(String line) {
    // removing the first element '"' to be able to get the name of the company
    line = line.substring(1);
    int iend = line.indexOf('"');
    // getting the company name
    String companyName = line.substring(0, iend);
    line = line.substring(iend);
    data = line.split(",");
    data[0] = companyName;
    data[1] = data[1].substring(1, data[1].length() - 1);
  }

  private void setDataToEssentialData() {
    result = new EssentialData();
    try {
      result.setName(data[0]);
      result.setSymbol(data[1]);
      result.setBid(data[2]);
      result.setAsk(data[3]);
    } catch (NumberFormatException e) {
      System.out.println("no data exception");
    }
  }


} public abstract class YahooFinance {
  public static final int CONNECTION_TIMEOUT =
      Integer.parseInt(System.getProperty("yahoofinance.connection.timeout", "10000"));

  public abstract Object getData();

  public URLConnection setConnectionWithYahoo(String url) {
    URLConnection connection = null;
    try {
      System.out.println("URL:" + url);
      URL request = new URL(url);
      connection = request.openConnection();
      connection.setConnectTimeout(CONNECTION_TIMEOUT);
      connection.setReadTimeout(CONNECTION_TIMEOUT);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return connection;
  }



}
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import charts.MainChart;
import charts.NewChart;
import data.tables.TradeData;
import data.updating.LoggedUser;
import data.updating.UpdateTables;
import database.Database;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import main.Main;
import tabs.Tabs;
import tabs.left.DetailsTab;
import yahoo.DetailsData;
import yahoo.DetailsDataFromYahoo;
import yahoo.EssentialData;
import yahoo.EssentialDataFromYahoo;
import yahoo.YahooFinance;
package tabs.bottom;




public class TradeTab implements Tabs {
  private TableView<TradeData> tradeTable;
  TableColumn<TradeData, String> symbolColumn, orderColumn, timeColumn, typeColumn, volumeColumn,
      priceColumn, currentPriceColumn, profitColumn, companyColumn;
  BigDecimal profit = new BigDecimal(0);
  BigDecimal lastPrice = new BigDecimal(0);
  BigDecimal purchasePrice = new BigDecimal(0);
  BigDecimal volume = new BigDecimal(0);

  @SuppressWarnings({"unchecked", "rawtypes"})
  public TradeTab() {
    MenuItem closeTradeMI = new MenuItem("Close Trade");
    MenuItem showChartMI = new MenuItem("Open Chart");
    MenuItem showDetailMI = new MenuItem("Details");
    companyColumn = new TableColumn<TradeData, String>("Company");
    companyColumn.setCellValueFactory(new PropertyValueFactory("company"));
    symbolColumn = new TableColumn<TradeData, String>("Symbol");
    symbolColumn.setCellValueFactory(new PropertyValueFactory("symbol"));
    orderColumn = new TableColumn<TradeData, String>("Order ¹");
    orderColumn.setCellValueFactory(new PropertyValueFactory("orderNumber"));
    timeColumn = new TableColumn<TradeData, String>("Time");
    timeColumn.setCellValueFactory(new PropertyValueFactory("orderTime"));
    typeColumn = new TableColumn<TradeData, String>("Type");
    typeColumn.setCellValueFactory(new PropertyValueFactory("orderType"));
    volumeColumn = new TableColumn<TradeData, String>("Volume");
    volumeColumn.setCellValueFactory(new PropertyValueFactory("volume"));
    priceColumn = new TableColumn<TradeData, String>("Purchase Price");
    priceColumn.setCellValueFactory(new PropertyValueFactory("purchasePrice"));
    currentPriceColumn = new TableColumn<TradeData, String>("Current Price");
    currentPriceColumn.setCellValueFactory(new PropertyValueFactory("currentPrice"));
    profitColumn = new TableColumn<TradeData, String>("Profit");
    profitColumn.setCellValueFactory(new PropertyValueFactory("profit"));
    tradeTable = new TableView<TradeData>();
    tradeTable.getColumns().addAll(companyColumn, symbolColumn, orderColumn, timeColumn, typeColumn,
        volumeColumn, priceColumn, currentPriceColumn, profitColumn);
    tradeTable.setContextMenu(new ContextMenu(closeTradeMI, showChartMI, showDetailMI));
    setColumnsSizes();

    showChartMI.setOnAction(e -> {
      showChartMI();
    });

    showDetailMI.setOnAction(e -> {
      showDetailsMI();
    });

    closeTradeMI.setOnAction(e -> {
      try {
        TradeData closeTrade = tradeTable.getSelectionModel().getSelectedItem();
        closeTrade(closeTrade);
      } catch (Exception e1) {
        e1.printStackTrace();
      }
    });
  }

  private void setColumnsSizes() {
    companyColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.2));
    symbolColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    orderColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    timeColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    typeColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    volumeColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    priceColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    currentPriceColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
    profitColumn.prefWidthProperty().bind(tradeTable.widthProperty().multiply(0.1));
  }


  private void closeTrade(TradeData closeTrade)
      throws ClassNotFoundException, SQLException, IOException {

    getDataFromDB(closeTrade);
    YahooFinance yahoo = new EssentialDataFromYahoo(closeTrade.getSymbol());
    EssentialData stock = (EssentialData) yahoo.getData();
    if (closeTrade.getOrderType().equals("buy")) {
      lastPrice = stock.getBid();
      if (lastPrice == null) {
        showAlertMessage();
        return;
      }
      profit = (lastPrice.subtract(purchasePrice)).multiply(volume);
    } else if (closeTrade.getOrderType().equals("sell")) {
      lastPrice = stock.getAsk();
      if (lastPrice == null) {
        showAlertMessage();
        return;
      }
      profit = (purchasePrice.subtract(lastPrice)).multiply(volume);
    }

    profit = profit.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    saveDataToDB(closeTrade);
  }

  private void getDataFromDB(TradeData closeTrade) throws ClassNotFoundException, SQLException {
    Database.connectingToDB();
    ResultSet userTrade =
        Database.SelectDB("select volume,purchaseprice,symbol from trades where username='"
            + LoggedUser.getLoggedUser() + "'" + "and ordernumber=" + closeTrade.getOrderNumber()