diff --git a/app/src/main/java/com/example/dcav2gui/TickerTracker.java b/app/src/main/java/com/example/dcav2gui/TickerTracker.java index 0ea9082..8118be6 100644 --- a/app/src/main/java/com/example/dcav2gui/TickerTracker.java +++ b/app/src/main/java/com/example/dcav2gui/TickerTracker.java @@ -1,8 +1,6 @@ package com.example.dcav2gui; -//import com.google.gson.Gson; import com.google.gson.JsonArray; -import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; @@ -15,87 +13,64 @@ import okhttp3.Response; public class TickerTracker { private static final String BINANCE_API_BASE_URL = "https://api.binance.com/api/v3/ticker/24hr"; private static final OkHttpClient httpClient = new OkHttpClient(); - //private static final Gson gson = new Gson(); + static int requestDepth = 722; + static String requestResolution = "15m"; - /** - * Retrieves price change percentages for a specific trading pair from Binance. - * - * @param symbol The trading pair symbol (e.g., "BTCUSDT") - * @return PriceChangeData object containing 24h, 7d, and 30d percentage changes - * @throws IOException If there's an error connecting to the Binance API - */ public static PriceChangeData getPriceChanges(String symbol) throws IOException { // Construct the API request URL for 24h change - Request request24h = new Request.Builder() - .url(BINANCE_API_BASE_URL + "?symbol=" + symbol.toUpperCase(Locale.ROOT)) + Request historicalRequest = new Request.Builder() + .url("https://api.binance.com/api/v3/klines?symbol=" + symbol.toUpperCase(Locale.ROOT) + "&interval=15m&limit=722") .build(); - // Send 24h request - try (Response response24h = httpClient.newCall(request24h).execute()) { - if (!response24h.isSuccessful()) { - throw new IOException("Unexpected code " + response24h); + try (Response historicalResponse = httpClient.newCall(historicalRequest).execute()) { + if (!historicalResponse.isSuccessful()) { + throw new IOException("Unexpected code " + historicalResponse); } - String responseBody24h = response24h.body().string(); - JsonObject jsonResponse = JsonParser.parseString(responseBody24h).getAsJsonObject(); + String historicalResponseBody = historicalResponse.body().string(); - // Extract current price - double currentPrice = jsonResponse.has("lastPrice") - ? jsonResponse.get("lastPrice").getAsDouble() - : 0.0; + double currentPrice = getCurrentPrice(historicalResponseBody); + double priceChangePercent24h = calculatePercentageChange(historicalResponseBody, 24); + double priceChangePercent7d = calculatePercentageChange(historicalResponseBody, 7*24); + double priceChangePercent30d = calculatePercentageChange(historicalResponseBody, 30*24); - // Extract 24h percentage change - double priceChangePercent24h = jsonResponse.has("priceChangePercent") - ? jsonResponse.get("priceChangePercent").getAsDouble() - : 0.0; + // Return the price change data + return new PriceChangeData( + symbol, + currentPrice, + priceChangePercent24h, + priceChangePercent7d, + priceChangePercent30d + ); + } + } - // Fetch historical data for 7d and 30d changes - Request historicalRequest = new Request.Builder() - .url("https://api.binance.com/api/v3/klines?symbol=" + symbol.toUpperCase(Locale.ROOT) + "&interval=1d&limit=30") - .build(); - - // Send historical data request - try (Response historicalResponse = httpClient.newCall(historicalRequest).execute()) { - if (!historicalResponse.isSuccessful()) { - throw new IOException("Unexpected code " + historicalResponse); - } - String historicalResponseBody = historicalResponse.body().string(); - - // Calculate 7d and 30d percentage changes - double priceChangePercent7d = calculatePercentageChange(historicalResponseBody, 7); - double priceChangePercent30d = calculatePercentageChange(historicalResponseBody, 30); - - // Return the price change data - return new PriceChangeData( - symbol, - currentPrice, - priceChangePercent24h, - priceChangePercent7d, - priceChangePercent30d - ); - } + private static double getCurrentPrice(String jsonKlineData) { + try { + // Parse the kline data + JsonArray klines = JsonParser.parseString(jsonKlineData).getAsJsonArray(); + return klines.get(requestDepth-1).getAsJsonArray().get(4).getAsDouble(); + } catch (Exception e) { + System.err.println("Error processing klines for price: " + e.getMessage()); + return 0.0; } } // Calculates the percentage change - private static double calculatePercentageChange(String jsonKlineData, int days) { + private static double calculatePercentageChange(String jsonKlineData, int hours) { try { - // Parse the kline data JsonArray klines = JsonParser.parseString(jsonKlineData).getAsJsonArray(); // Ensure we have enough data - if (klines == null || klines.size() < days) { + if (klines == null || klines.size() < hours) { return 0.0; } - // Get the opening price of the first day in the period - // Kline data structure: [Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore] - double firstOpenPrice = klines.get(0).getAsJsonArray().get(1).getAsDouble(); - - // Get the closing price of the last day in the period - double lastClosePrice = klines.get(days - 1).getAsJsonArray().get(4).getAsDouble(); + int backwards = 721; + double currentPrice = klines.get(backwards).getAsJsonArray().get(4).getAsDouble(); + double periodEndPrice = klines.get(backwards-hours-1).getAsJsonArray().get(1).getAsDouble(); // Calculate percentage change - return ((lastClosePrice - firstOpenPrice) / firstOpenPrice) * 100; + return ((currentPrice-periodEndPrice) / periodEndPrice * 100); } catch (Exception e) { System.err.println("Error calculating percentage change: " + e.getMessage()); return 0.0; @@ -126,10 +101,5 @@ public class TickerTracker { public double getPriceChangePercent7d() { return priceChangePercent7d; } public double getPriceChangePercent30d() { return priceChangePercent30d; } -// @Override -// public String toString() { -// return String.format("Symbol: %s\nPrice: %.2f%%\n24h Change: %.2f%%\n7d Change: %.2f%%\n30d Change: %.2f%%", -// symbol, currentPrice, priceChangePercent24h, priceChangePercent7d, priceChangePercent30d); -// } } } \ No newline at end of file diff --git a/app/src/main/java/com/example/dcav2gui/ui/home/HomeFragment.java b/app/src/main/java/com/example/dcav2gui/ui/home/HomeFragment.java index b27e6ff..d32d54f 100644 --- a/app/src/main/java/com/example/dcav2gui/ui/home/HomeFragment.java +++ b/app/src/main/java/com/example/dcav2gui/ui/home/HomeFragment.java @@ -137,6 +137,37 @@ public class HomeFragment extends Fragment { profitsToday.setText(R.string.profits_today_example); profitsThisMonth.setText(R.string.profits_this_month_example); + + //Load cached values + //Prices + pricePair1.setText(R.string.default_price_ticker_1); + pricePair2.setText(R.string.default_price_ticker_2); + pricePair3.setText(R.string.default_price_ticker_3); + + pricePair124hPercentage.setText(R.string.percentage_example); + pricePair17dPercentage.setText(R.string.percentage_example); + pricePair130dPercentage.setText(R.string.percentage_example); + + pricePair224hPercentage.setText(R.string.percentage_example); + pricePair27dPercentage.setText(R.string.percentage_example); + pricePair230dPercentage.setText(R.string.percentage_example); + + pricePair324hPercentage.setText(R.string.percentage_example); + pricePair37dPercentage.setText(R.string.percentage_example); + pricePair330dPercentage.setText(R.string.percentage_example); + + pricePair124hPercentage.setTextColor(Color.GREEN); + pricePair17dPercentage.setTextColor(Color.GREEN); + pricePair130dPercentage.setTextColor(Color.GREEN); + + pricePair224hPercentage.setTextColor(Color.GREEN); + pricePair27dPercentage.setTextColor(Color.GREEN); + pricePair230dPercentage.setTextColor(Color.GREEN); + + pricePair324hPercentage.setTextColor(Color.GREEN); + pricePair37dPercentage.setTextColor(Color.GREEN); + pricePair330dPercentage.setTextColor(Color.GREEN); + //Exchange status exchange1Status.setImageResource(R.drawable.ic_green_circle_48); exchange2Status.setImageResource(R.drawable.ic_green_circle_48); @@ -189,7 +220,7 @@ public class HomeFragment extends Fragment { log4Content.setText(R.string.log_example); // Let's fetch prices - fetchAndDisplayPriceData(); + //fetchAndDisplayPriceData(); // Setup task handler = new Handler();