Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
8.5 kB
3
Indexable
Never
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.binance.BinanceExchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OHLCV;
import org.knowm.xchange.service.marketdata.MarketDataService;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.data.xy.DefaultHighLowDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.ui.ApplicationFrame;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PriceWeightedIndexPlotter extends ApplicationFrame {

    public PriceWeightedIndexPlotter(String title) {
        super(title);
    }

    public static void main(String[] args) {
        String exchangeId = "binance";
        List<String> tokens = Arrays.asList("ETH", "ADA", "BNB", "SOL", "AVAX", "TRX");
        plotPriceWeightedIndexWithVolume(tokens, exchangeId, "Layer1");
    }

    public static void plotPriceWeightedIndexWithVolume(List<String> tokens, String exchangeId, String titleSuffix) {
        try {
            Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BinanceExchange.class);
            MarketDataService marketDataService = exchange.getMarketDataService();
            List<Map<Date, OHLCV>> dataFrames = new ArrayList<>();

            for (String token : tokens) {
                try {
                    List<OHLCV> ohlcvList = marketDataService.getHistoricalOHLCV(new CurrencyPair(token + "/USDT"), org.knowm.xchange.utils.Interval.ONE_DAY, null);
                    Map<Date, OHLCV> ohlcvMap = ohlcvList.stream().collect(Collectors.toMap(OHLCV::getTimestamp, ohlcv -> ohlcv));
                    dataFrames.add(ohlcvMap);
                } catch (Exception e) {
                    System.out.println("Failed to fetch data for " + token + ": " + e.getMessage());
                }
            }

            if (!dataFrames.isEmpty()) {
                Set<Date> allDates = dataFrames.get(0).keySet();
                List<Date> timestamps = new ArrayList<>(allDates);
                Collections.sort(timestamps);

                double[] openPrices = new double[timestamps.size()];
                double[] highPrices = new double[timestamps.size()];
                double[] lowPrices = new double[timestamps.size()];
                double[] closePrices = new double[timestamps.size()];
                double[] volumes = new double[timestamps.size()];

                for (int i = 0; i < timestamps.size(); i++) {
                    Date timestamp = timestamps.get(i);
                    double sumOpen = 0, sumHigh = 0, sumLow = 0, sumClose = 0, sumVolume = 0;
                    int count = 0;

                    for (Map<Date, OHLCV> ohlcvMap : dataFrames) {
                        if (ohlcvMap.containsKey(timestamp)) {
                            OHLCV ohlcv = ohlcvMap.get(timestamp);
                            sumOpen += ohlcv.getOpen().doubleValue();
                            sumHigh += ohlcv.getHigh().doubleValue();
                            sumLow += ohlcv.getLow().doubleValue();
                            sumClose += ohlcv.getClose().doubleValue();
                            sumVolume += ohlcv.getVolume().doubleValue();
                            count++;
                        }
                    }
                    openPrices[i] = sumOpen / count;
                    highPrices[i] = sumHigh / count;
                    lowPrices[i] = sumLow / count;
                    closePrices[i] = sumClose / count;
                    volumes[i] = sumVolume / count;
                }

                // Calculate SMA for close prices
                double[] sma21 = calculateSMA(closePrices, 21);

                // Fetch BTCUSDT data over the last 200 days
                List<OHLCV> btcBars = marketDataService.getHistoricalOHLCV(new CurrencyPair("BTC/USDT"), org.knowm.xchange.utils.Interval.ONE_DAY, null);
                Map<Date, OHLCV> btcMap = btcBars.stream().collect(Collectors.toMap(OHLCV::getTimestamp, ohlcv -> ohlcv));
                double[] btcClosePrices = new double[timestamps.size()];
                double[] btcRatios = new double[timestamps.size()];
                double[] btcRatiosSma21 = new double[timestamps.size()];

                for (int i = 0; i < timestamps.size(); i++) {
                    Date timestamp = timestamps.get(i);
                    if (btcMap.containsKey(timestamp)) {
                        btcClosePrices[i] = btcMap.get(timestamp).getClose().doubleValue();
                        btcRatios[i] = closePrices[i] / btcClosePrices[i];
                    } else {
                        btcClosePrices[i] = 0;
                        btcRatios[i] = 0;
                    }
                }
                btcRatiosSma21 = calculateSMA(btcRatios, 21);

                // Prepare the dataset
                Date[] dates = timestamps.toArray(new Date[0]);
                OHLCDataset dataset = new DefaultHighLowDataset("Price Weighted Index", dates, highPrices, lowPrices, openPrices, closePrices, volumes);

                // Create the chart
                JFreeChart chart = createChart(dataset, sma21, btcRatios, btcRatiosSma21, titleSuffix);

                // Display the chart
                ChartPanel chartPanel = new ChartPanel(chart);
                chartPanel.setPreferredSize(new Dimension(800, 600));
                chartPanel.setMouseZoomable(true, false);

                ApplicationFrame frame = new ApplicationFrame("Price Weighted Index with Volume");
                frame.setContentPane(chartPanel);
                frame.pack();
                frame.setVisible(true);

            } else {
                System.out.println("No data fetched for tokens");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static double[] calculateSMA(double[] prices, int window) {
        double[] sma = new double[prices.length];
        for (int i = 0; i < prices.length; i++) {
            if (i < window - 1) {
                sma[i] = Double.NaN;
            } else {
                double sum = 0;
                for (int j = 0; j < window; j++) {
                    sum += prices[i - j];
                }
                sma[i] = sum / window;
            }
        }
        return sma;
    }

    private static JFreeChart createChart(OHLCDataset dataset, double[] sma21, double[] btcRatios, double[] btcRatiosSma21, String titleSuffix) {
        JFreeChart chart = ChartFactory.createCandlestickChart(
                titleSuffix + " Index",
                "Date",
                "Price",
                dataset,
                false);

        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDomainPannable(true);
        plot.setRangePannable(true);

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));

        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setAutoRangeIncludesZero(false);

        CandlestickRenderer renderer = new CandlestickRenderer();
        plot.setRenderer(renderer);

        // Add SMA series
        addLineSeries(plot, sma21, "21-day SMA", Color.GRAY);

        // Add BTC Ratio series
        addLineSeries(plot, btcRatios, "BTC Ratio", Color.BLUE);

        // Add BTC Ratio SMA series
        addLineSeries(plot, btcRatiosSma21, "21-day SMA of BTC Ratio", Color.ORANGE);

        return chart;
    }

    private static void addLineSeries(XYPlot plot, double[] values, String seriesName, Color color) {
        double[][] data = new double[2][values.length];
        for (int i = 0; i < values.length; i++) {
            data[0][i] = i;
            data[1][i] = values[i];
        }
        DefaultHighLowDataset dataset = new DefaultHighLowDataset(seriesName, data);
        StandardXYItemRenderer renderer = new StandardXYItemRenderer();
        renderer.setSeriesPaint(0, color);
        plot.setDataset(plot.getDatasetCount(), dataset);
        plot.setRenderer(plot.getRendererCount(), renderer);
    }
}
Leave a Comment