import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main {
record Candle(
long openTime,
double open,
double high,
double low,
double close,
double volume,
long closeTime) {}
private static void drawCandles(String symbol, int limit) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
CandleJPanel panel = getChartPanel(getCandles(symbol, limit), 1250, 800);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.repaint();
try {
ImageIO.write(panel.getImage(), "png", new java.io.File("chart.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static class CandleJPanel extends JPanel {
public BufferedImage getImage() {
Dimension size = getPreferredSize();
BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
paint(g);
g.dispose();
return image;
}
}
private static CandleJPanel getChartPanel(List<Candle> candles, int width, int height) {
long min_x = candles.get(0).openTime();
long max_x = candles.get(candles.size() - 1).openTime();
double mul_x = (double) (width - 50) / (max_x - min_x);
double step_x = (double) (width - 50) / candles.size();
double temp1 = Double.MAX_VALUE;
double temp2 = Double.MIN_VALUE;
for (Candle candle : candles) {
if (candle.low() < temp1) {
temp1 = candle.low();
}
if (candle.high() > temp2) {
temp2 = candle.high();
}
}
double min_y = temp1;
double max_y = temp2;
double mul_y = (double) (height - 50) / (max_y - min_y);
CandleJPanel panel =
new CandleJPanel() {
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < candles.size(); i++) {
Candle c1 = candles.get(i);
int x0 = 25 + (int) Math.round(step_x * i);
int x1 = 25 + (int) Math.round(step_x * (i + 1));
int y0 = 25 + (int) Math.round(mul_y * (max_y - c1.high()));
int y1 = 25 + (int) Math.round(mul_y * (max_y - c1.low()));
g2d.setColor(Color.RED);
g2d.fillRect(x0, y0, x1 - x0 - 1, y1 - y0);
}
}
};
panel.setPreferredSize(new Dimension(width, height));
return panel;
}
}