如何使用javaFX从arrayList创建折线图

时间:2018-07-20 15:57:06

标签: java javafx

我希望使用String和Integer类型的arraylist创建一个Linechart。我创建了一个类来检索股票信息,例如; API的开盘价,收盘价等。我正在尝试创建一个折线图,该折线图使用我的方法之一的时间戳和开盘价作为其轴。我最初的想法是创建两个包含x坐标和y坐标的数组列表。但是,我在创建图形时遇到了麻烦。我不知道如何将带有y坐标的arraylist移到我的图形类中,并使用y.get(i)方法获取某些索引处的值。我知道我将需要解析变量类型,但是,我仍然很困惑。请在下面找到我的代码,以从API,股票对象和图形的创建中获取信息。感谢所有帮助。

干杯。

public class PortfolioScreen {

    private static String AA_URL = "https://www.alphavantage.co/query?function=@SRS@&symbol@SYM@";
    private static String AA_API_KEY = "key from website";
    private static String urlKey = "https://www.alphavantage.co/query?function=@SRS@&symbol@SYM@" + "key from website";
    private static String SYMBOL = "@SYM@";
    private static String ONE_MINUTE = "&interval=1min";
    private static int BUF_SLAB = 512;
    private HttpsURLConnection https;
    private InputStream outFromWebServer;
    private StringBuilder buffer;
    private String urlTemplate;
    private String series;
    private boolean history;
    private static String TIME_SERIES_WEEKLY = "Weekly Adjusted Time Series";
    private static String TIME_SERIES_INTRADAY = "Time Series (1min)";
    private static String STOCK_QUOTES = "Stock Quotes";
    private static String TSW_OPEN = "1. open";
    private static String TSW_HIGH = "2. high";
    private static String TSW_LOW = "3. low";
    private static String TSW_CLOSE = "4. close";
    private static String TSW_ADJUSTED = "5. adjusted close";
    private static String TSW_VOLUME = "6. volume";
    private static String TSW_DIVIDEND = "7. dividend amount";
    protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static String ERROR_MSG = "\"Error Message\":";
    private static String STOCK_NAME = "1. symbol";
    private static String STOCK_PRICE = "2. price";
    private static String STOCK_VOLUME = "3. volume";
    private static String STOCK_TIMESTAMP = "4. timestamp";
    private int pointer;
    private String closingprice;

    @FXML
            DatePicker datepicker;

    DbConn dbConn = new DbConn();
    //PortfolioScreen a = new PortfolioScreen();

    Connection conn = dbConn.createConnection();
    ResultSet rs;

    @FXML
    TextField symbol;
    @FXML
    TextField priceText;
    @FXML
    TextField volume;
    @FXML
    Button button;
    @FXML
    TextField searchItem;
    @FXML
    TableView tableView;
    @FXML
    TableColumn<Stock, String> priceColumn;
    @FXML
    TableColumn<Stock, String> volumeColumn;
    @FXML
    TableColumn<Stock, String> timeStampColumn;
    @FXML
    TextArea textArea;
    @FXML
            //TextArea calender;

    ArrayList<Integer> x = new ArrayList<>();
    ArrayList<String> y = new ArrayList<>();


    public Vector<Stock> getMultipleStockQuotes(String symbols) throws Exception {
        //symbols = symbol.getText().toString().trim();
        System.out.println("Getting Current Prices for multiple stocks");
        this.setTemplate(1);
        if (this.callAlphaAdvantage(false, symbols) != 0) {
            throw new Exception("Multiple quoting fails");
        } else {
            return this.findStockQuotes();
        }
    }

    public void Action(ActionEvent event) throws Exception {


        getMultipleStockQuotes(symbol.getText());

    }

    public void Action2() throws Exception {
        boolean t = true;
        Date date = new Date();
        Calendar cal = Calendar.getInstance();

        getMultipleStockQuotes("GE");
        getStockQuote("GE",t,DateProducer.getAnyDate(2018));
        findHistoricQuote("GE",DateProducer.getAnyDate(2018));

    }

    public Stock getStockQuote(String symbol, boolean history, Calendar when) {
        //int rc = false;
        Stock quote = null;
        this.history = history;
        setTemplate(2);
        System.out.println("Starting AlphaAdvantage for '" + symbol + "'");

        int rc;
        if ((rc = this.callAlphaAdvantage(true, symbol)) != 0) {
            quote = new Stock(symbol, when);
            quote.setCondition(-1);
            if (rc == Stock.AA_NO_SERVICE) {
                quote.setCondition(Stock.AA_NO_SERVICE);
            }
        } else {
            quote = this.findHistoricQuote(symbol, when);
        }

        System.out.println("Ending AlphaAdvantage for '" + symbol + "'");
        return quote;
    }

    private void setTemplate(int immediate) {
        if (immediate == 1) {
            this.series = STOCK_QUOTES;
            this.urlTemplate = urlKey.replaceAll("@SRS@", String.valueOf(ChoiceOfTicker.BATCH_STOCK_QUOTES));

        } else if (immediate == 2) {
            this.urlTemplate = urlKey.replaceAll("@SRS@", String.valueOf(ChoiceOfTicker.TIME_SERIES_WEEKLY_ADJUSTED));
            this.series = TIME_SERIES_WEEKLY;
        } else {
            this.urlTemplate = urlKey.replaceAll("@SRS@", String.valueOf(ChoiceOfTicker.TIME_SERIES_INTRADAY));
            this.series = TIME_SERIES_INTRADAY;
        }

    }

    private int callAlphaAdvantage(boolean single, String symbol) {
        int rc = 0;
        String ss = "=" + symbol;
        if (!single) {
            ss = "s" + ss;
        }

        String tickerURL = this.urlTemplate.replace(SYMBOL, ss);

        try {
            URL AVurl = new URL(tickerURL);
            HttpURLConnection connection = (HttpURLConnection) AVurl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "text/html; charset=utf-8");


            this.outFromWebServer = new DataInputStream(connection.getInputStream());

            if (!this.loadBuffer()) {
                rc = -1;
            }

            this.outFromWebServer.close();

        } catch (IOException var7) {
            System.out.println("1. HTTPS FAIL=" + var7.getMessage());
            rc = -1;
        }

        return rc;
    }

    public Stock findHistoricQuote(String symbol, Calendar when) {
        Stock quote = null;
        String open = null;
        String high = null;
        String low = null;
        String adjusted = null;
        String volume = null;
        String timestamp = null;
        String price = null;
        String dividend = null;
        BigDecimal bigDividend = BigDecimal.ZERO;
        this.pointer = this.buffer.indexOf(this.series);
        if (this.pointer != -1) {
            this.pointer = this.pointer + this.series.length() + 3;

            String quoteDate;
            do {
                int i =0;
                while(true || i < 10000) {
                    ++this.pointer;
                    int endPtr = this.buffer.indexOf("}", this.pointer);
                    if (endPtr == -1) {
                        return quote;
                    }

                    int len = endPtr - this.pointer - 1;
                    char[] dst = new char[len];
                    this.buffer.getChars(this.pointer, this.pointer + len, dst, 0);
                    String text = new String(dst);
                    int d0 = text.indexOf("\"") + 1;
                    if (d0 > 0) {
                        int d1 = text.indexOf("\"", d0);
                        quoteDate = text.substring(d0, d1).replaceAll(" ", "");
                        if (quoteDate.length() > 10) {
                            quoteDate = quoteDate.substring(0, 10);
                        }

                        open = this.getNextElement(TSW_OPEN);
                        high = this.getNextElement(TSW_HIGH);
                        low = this.getNextElement(TSW_LOW);
                        price = this.getNextElement(TSW_CLOSE);
                        if (this.history) {
                            adjusted = this.getNextElement(TSW_ADJUSTED);
                        }

                        volume = this.getNextElement(TSW_VOLUME);
                        if (this.history) {
                            dividend = this.getNextElement(TSW_DIVIDEND);
                            if (dividend != null && !dividend.startsWith("\"")) {
                                bigDividend = bigDividend.add(new BigDecimal(dividend));
                            }
                        }

                        this.pointer = this.buffer.indexOf("}", this.pointer);
                       System.out.println(symbol + " HIST=" + this.history + " DATE=" + quoteDate + " OPENNING PRICE=" + open +
                              "CLOSING PRICE=" + price + " " + "HIGH PRICE=" + high + " " + "LOW PRICE=" + low + " " +
                               "VOLUME=" + " " + volume + " DIV=" + dividend);



                        i++;
                    }

                    this.pointer = endPtr;
                }

            } while(this.history && (quoteDate == null || DateProducer.getAnyDate(quoteDate).after(when)));

            quote = new Stock(symbol, symbol, checkBigDecimal(price), DateProducer.getAnyDate(quoteDate));
            quote.setDividend(bigDividend);
        }

        return quote;

    }




    private static BigDecimal checkBigDecimal(String value) {

        if (value.contains("null") && value != null && !value.isEmpty()) {

            if (value.contains(",")) {
                value = value.replaceAll(",", "");
            }
            return new BigDecimal(value);
        }
        return new BigDecimal(value);
    }

    private boolean loadBuffer() {
        boolean rc = true;

        try {
            this.buffer = new StringBuilder(BUF_SLAB);
            int k;

            do {
                byte[] bytes = new byte[BUF_SLAB];
                k = this.outFromWebServer.read(bytes);
                this.buffer.append(new String(bytes, "UTF-8"));
            } while (k != -1);

            if (this.buffer.indexOf(ERROR_MSG) != -1) {
                rc = false;
            }
        } catch (IOException var4) {
            System.out.println("3. BUFFER FAIL=" + var4.getMessage());
        }

        return rc;
    }


    private String getNextElement(String name) {
        int initialIndex = 0;
        int jsonFormat = 4;
        if ((this.pointer = this.buffer.indexOf(name, this.pointer)) == -1) {
            return null;
        } else {
            this.pointer += name.length() + jsonFormat;
            int length = this.buffer.indexOf("\"", this.pointer) - this.pointer;
            char[] dst = new char[length];
            this.buffer.getChars(this.pointer, this.buffer.indexOf("\"", this.pointer), dst, initialIndex);
            return new String(dst);
        }
    }

    private Vector<Stock> findStockQuotes() {
        Vector<Stock> quotes = new Vector();
        String symbol = null;
        String price = null;
        String volume = null;
        String timestamp = null;
        this.pointer = this.buffer.indexOf(STOCK_QUOTES);
        this.pointer = this.pointer + STOCK_QUOTES.length() + 4;

        while ((symbol = this.getNextElement(STOCK_NAME)) != null) {
            price = this.getNextElement(STOCK_PRICE);
            volume = this.getNextElement(STOCK_VOLUME);
            timestamp = this.getNextElement(STOCK_TIMESTAMP);
            Calendar ts = DateProducer.getAnyTimestamp(timestamp);
            Stock quote = new Stock(symbol, symbol, checkBigDecimal(price), ts);
           // quote.setVolume(Double.valueOf(volume));
            quotes.add(quote);
            System.out.println("Symbol=" + symbol + " PRICE=" + price + " VOL=" + volume + " TS=" + DateProducer.getAnyTimestamp(ts));


        }


        return quotes;
    }

    public ArrayList findStockQuotesAL() {
        Vector<Stock> quotes = new Vector();
        String symbol = null;
        String price = null;
        String volume = null;
        String timestamp = null;
        this.pointer = this.buffer.indexOf(STOCK_QUOTES);
        this.pointer = this.pointer + STOCK_QUOTES.length() + 4;

       int i =0;
        int counter = 0;

        while ((symbol = this.getNextElement(STOCK_NAME)) != null) {
            price = this.getNextElement(STOCK_PRICE);
            volume = this.getNextElement(STOCK_VOLUME);
            timestamp = this.getNextElement(STOCK_TIMESTAMP);
            Calendar ts = DateProducer.getAnyTimestamp(timestamp);
            Stock quote = new Stock(symbol, symbol, checkBigDecimal(price), ts);
            // quote.setVolume(Double.valueOf(volume));
            quotes.add(quote);
            System.out.println("Symbol=" + symbol + " PRICE=" + price + " VOL=" + volume + " TS=" + DateProducer.getAnyTimestamp(ts));

            // adding opening price to an arraylist which I plan to use as the y coordinate.
            y.add(price);
            i++;
        }


        return y;

    }

    public void searchStock(ActionEvent event) {

        try {
            String sql = "SELECT * FROM stockname WHERE stockname =? ";
            PreparedStatement pStatement = conn.prepareStatement(sql);
            pStatement.setString((1), searchItem.getText());

            rs = pStatement.executeQuery();
            if (rs.next()) {
                getMultipleStockQuotes(searchItem.getText());


            } else {
                System.out.println("failed");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        PortfolioScreen a = new PortfolioScreen();
        boolean t = true;
       a.getMultipleStockQuotes("MSFT");
       a.getStockQuote("MSFT", t, DateProducer.getAnyDate(20170111));
       a.findHistoricQuote("MSFT", DateProducer.getAnyDate(20170111));
        System.out.println(a.findStockQuotesAL());
        a.findStockQuotesAL();




    }


}

public class Stock implements Cloneable {

    private SimpleDateFormat DATE_ONLY;
    public static int AA_NO_SERVICE = 503;
    private String ticker;
    private String title;
    private String exchange;
    private Boolean closed;
    private BigDecimal price;
    private BigDecimal change;
    private BigDecimal peg;
    private BigDecimal dividend;
    private double volume;
    private Calendar tradeDate;
    private Calendar dividendDate;
    private boolean unknownTicker;
    private int condition;

    public Stock(String ticker, Calendar tradeDate) {
        this(ticker, ticker, (String)null, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, tradeDate, (Calendar)null, true);
    }

    public Stock(String ticker, String title, BigDecimal price, Calendar tradeDate) {
        this(ticker, title, (String)null, price, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, tradeDate, (Calendar)null, false);
    }

    public Stock(String ticker, String title, String exchange, BigDecimal price, BigDecimal change, BigDecimal peg, BigDecimal dividend, Calendar tradeDate, Calendar dividendDate, boolean unknownTicker) {
        this.DATE_ONLY = new SimpleDateFormat("yyyy-MM-dd");
        this.ticker = ticker;
        this.title = title;
        this.exchange = exchange;
        this.price = price;
        this.change = change;
        this.peg = peg;
        this.dividend = dividend;
        this.tradeDate = tradeDate;
        this.dividendDate = dividendDate;
        this.unknownTicker = unknownTicker;
    }

    public Stock clone() throws CloneNotSupportedException {
        return (Stock)super.clone();
    }

    public boolean isUnknownTicker() {
        return this.unknownTicker;
    }

    public void setUnknownTicker(boolean b) {
        this.unknownTicker = b;
    }

    public boolean isClosed() {
        return this.closed;
    }

    public void setIsClosed() {
        this.closed = true;
    }

    public String getTicker() {
        return this.ticker;
    }

    public BigDecimal getPrice() {
        return this.price;
    }

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

    public double getVolume() {
        return this.volume;
    }

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

    public BigDecimal getChange() {
        return this.change == null ? BigDecimal.ZERO : this.change;
    }

    public void setChange(BigDecimal change) {
        this.change = change;
    }

    public BigDecimal getPeg() {
        return this.peg;
    }

    public void setPeg(BigDecimal peg) {
        this.peg = peg;
    }

    public BigDecimal getDividend() {
        return this.dividend == null ? BigDecimal.ZERO : this.dividend;
    }

    public void setDividend(BigDecimal dividend) {
        this.dividend = dividend;
    }

    public Calendar getTradeDate() {
        return this.tradeDate;
    }

    public String getTradeDateStr() {
        return this.tradeDate == null ? "-" : this.DATE_ONLY.format(this.tradeDate.getTime());
    }

    public void setTradeDate(Calendar tradeDate) {
        this.tradeDate = tradeDate;
    }

    public int getCondition() {
        return this.condition;
    }

    public void setCondition(int c) {
        this.condition = c;
    }

    public Calendar getDividendDate() {
        return this.dividendDate;
    }

    public String getDividendDateStr() {
        return this.dividendDate == null ? "-" : this.DATE_ONLY.format(this.dividendDate.getTime());
    }

    public void setDividendDate(Calendar dividendDate) {
        this.dividendDate = dividendDate;
    }

    public String getTitle() {
        return this.title;
    }

    public String getExchange() {
        return this.exchange;
    }
}

public class Graph extends Application {

    PortfolioScreen a = new PortfolioScreen();
    ArrayList<String> x = new ArrayList<>();
    ArrayList<Double> y;


    @Override
    public void start(Stage stage) throws Exception {
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Number of Month");
        final LineChart<String, Number> lineChart = new LineChart<String, Number>(
                xAxis, yAxis);

        lineChart.setTitle("Line Chart");
        XYChart.Series<String, Number> series = new XYChart.Series<String, Number>();
        series.setName("My Data");
        // populating the series with data

        for(int i = 0; i < 1; i++) {

            x.add("1");
            y.add(1.0);



            series.getData().add(new XYChart.Data<String, Number>(x.get(0), y.get(0)));
        }
        Scene scene = new Scene(lineChart, 800, 600);
        lineChart.getData().add(series);

        stage.setScene(scene);
        stage.show();
    }

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

0 个答案:

没有答案
相关问题