Untitled

 avatar
unknown
plain_text
a year ago
4.3 kB
5
Indexable
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 java.util.*;
import java.util.stream.Collectors;

public class PriceWeightedIndexCalculator {

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

    public static void calculatePriceWeightedIndex(List<String> tokens, String exchangeId) {
        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()) {
                Map<Date, List<OHLCV>> groupedData = new HashMap<>();

                // Concatenate data frames by grouping OHLCV data by date
                for (Map<Date, OHLCV> dataFrame : dataFrames) {
                    for (Map.Entry<Date, OHLCV> entry : dataFrame.entrySet()) {
                        groupedData.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).add(entry.getValue());
                    }
                }

                // Calculate the average OHLCV values for each date
                Map<Date, OHLCV> averageData = groupedData.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> calculateAverageOHLCV(entry.getValue())
                        ));

                // Now you can use averageData for further processing or plotting
                System.out.println("Calculated Price Weighted Index:");
                averageData.forEach((date, ohlcv) -> System.out.println(date + " -> " + ohlcv));
            } else {
                System.out.println("No data fetched for tokens");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static OHLCV calculateAverageOHLCV(List<OHLCV> ohlcvList) {
        double open = ohlcvList.stream().mapToDouble(ohlcv -> ohlcv.getOpen().doubleValue()).average().orElse(0);
        double high = ohlcvList.stream().mapToDouble(ohlcv -> ohlcv.getHigh().doubleValue()).average().orElse(0);
        double low = ohlcvList.stream().mapToDouble(ohlcv -> ohlcv.getLow().doubleValue()).average().orElse(0);
        double close = ohlcvList.stream().mapToDouble(ohlcv -> ohlcv.getClose().doubleValue()).average().orElse(0);
        double volume = ohlcvList.stream().mapToDouble(ohlcv -> ohlcv.getVolume().doubleValue()).average().orElse(0);

        return new OHLCV(null, open, high, low, close, volume);
    }
}

--
Explanation
Data Fetching: Fetches OHLCV data for each token using the XChange library and stores it in a list of maps, where each map represents a token's OHLCV data keyed by date.

Concatenation and Grouping:

Merges the individual token data maps into a single map (groupedData), where each date maps to a list of OHLCV entries.
Calculation of Averages:

Computes the average OHLCV values for each date using the calculateAverageOHLCV method.
Output: The resulting averageData map contains the average OHLCV data for each date, which can be used for further processing or plotting.

This approach mirrors the Pandas functionality in Java, combining, grouping, and averaging data appropriately. Let me know if you need further adjustments or additional features!
Editor is loading...
Leave a Comment