Bootstrap

【Java练习】文本处理:实时股价

需求

可以查询股票当前价格。
用户可以设定数据刷新频率,程序会用绿色和红色的箭头表示股价走势。

思路

这个重点主要是定时访问接口,然后定时可以设置,用Timer可以实现。
GPT生成的代码,增加了设置属性方法,方便填充KEY

实现

由于有API访问,因此需要引入json转换的依赖

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20210307</version>
        </dependency>

public class StockPriceTracker extends JFrame {
    private JLabel priceLabel;
    private JLabel trendLabel;
    private JTextField symbolField;
    private JTextField frequencyField;
    private Timer timer;
    private double lastPrice = -1.0;
    private String urlPrefix;
    private String urlSuffix;
    private String apiKey;

    public StockPriceTracker(){
        setTitle("Stock Price Tracker");
        setSize(400, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(4, 2));

        add(new JLabel("Stock Symbol:"));
        symbolField = new JTextField();
        add(symbolField);

        add(new JLabel("Refresh Frequency (seconds):"));
        frequencyField = new JTextField();
        add(frequencyField);

        priceLabel = new JLabel("Price: ");
        add(priceLabel);

        trendLabel = new JLabel();
        add(trendLabel);

        JButton startButton = new JButton("Start");
        startButton.addActionListener(e -> startTracking());

        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(e -> stopTracking());

        add(stopButton);
        add(startButton);

        urlPrefix = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=";
        urlSuffix = "&apikey=";
        apiKey = "YOUR_API_KEY";
    }

    public void setProperties(String key){
        apiKey = key;
    }

    public void setProperties(String prefix, String suffix, String key){
        urlPrefix = prefix;
        urlSuffix = suffix;
        apiKey = key;
    }

    private void startTracking() {
        if(timer != null){
            timer.stop();
        }

        int frequency = Integer.parseInt(frequencyField.getText()) * 1000;
        timer = new Timer(frequency, e -> updatePrice());
        timer.start();

    }

    private void stopTracking() {
        if(timer != null){
            timer.stop();
        }
    }

    private void updatePrice(){
        String symbol = symbolField.getText();
        String urlString = urlPrefix + symbol + urlSuffix + apiKey;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = reader.readLine()) != null){
                content.append(inputLine);
            }
            reader.close();
            connection.disconnect();

            JSONObject jsonObject = new JSONObject(content.toString());
            double price = jsonObject.getJSONObject("Global Quote").getDouble("05. price");

            SwingUtilities.invokeLater(() -> {
                priceLabel.setText("Price:" + price);
                if(lastPrice != -1){
                    if(price > lastPrice){
                        trendLabel.setText("↑");
                        trendLabel.setForeground(Color.GREEN);
                    }else if(price < lastPrice){
                        trendLabel.setText("↓");
                        trendLabel.setForeground(Color.RED);
                    }else{
                        trendLabel.setText("→");
                        trendLabel.setForeground(Color.BLACK);
                    }
                }
                lastPrice = price;
            });

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public static void main(String[] args) {
        String Key = "FEYTUMTVFTFBW8T0";
        SwingUtilities.invokeLater(() -> {

            StockPriceTracker tracker = new StockPriceTracker();
            tracker.setProperties(Key);
            tracker.setVisible(true);
        });
    }

拓展

文本处理这个频道有不少API访问的代码段,所以这里的API访问可以封装到工具类里,比如:

public class ApiUtils {

    public static String getApiResponse(String questUrl) throws Exception {
        URL url = new URL(questUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder content = new StringBuilder();
        while((line = reader.readLine()) != null){
            content.append(line);
        }
        reader.close();
        connection.disconnect();
        return content.toString();
    }
}

当然了,用其它API的话记得注意修改json转义位置,请求方式这些,总的来说这个代码示例成分偏多,毕竟gpt生成的,需求也不难

;