Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created June 29, 2025 02:17
Show Gist options
  • Save rokon12/ab6385ae9d8619b8d716062ab12613a9 to your computer and use it in GitHub Desktop.
Save rokon12/ab6385ae9d8619b8d716062ab12613a9 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-9.java
record TrendSignal(double price, String trend) {}
public static Gatherer<Double, ?, TrendSignal> trendDetection(int lookback) {
return Gatherer.of(
() -> new Object() {
List<Double> history = new ArrayList<>(); // 1️⃣ Price history buffer
},
(state, price, downstream) -> {
state.history.add(price); // 2️⃣ Add to history
if (state.history.size() >= lookback) { // 3️⃣ Enough data?
String trend = detectTrend(state.history); // 4️⃣ Analyze trend
downstream.push(new TrendSignal(price, trend)); // 5️⃣ Emit signal
if (state.history.size() > lookback) { // 6️⃣ Maintain window size
state.history.remove(0);
}
}
return true;
}
);
}
private static String detectTrend(List<Double> prices) {
double first = prices.get(0);
double last = prices.get(prices.size() - 1);
double change = (last - first) / first * 100; // Percentage change
if (change > 2) return "UPTREND ↑"; // 1️⃣ Significant rise
else if (change < -2) return "DOWNTREND ↓"; // 2️⃣ Significant fall
else return "SIDEWAYS →"; // 3️⃣ Relatively flat
}
// Example output:
// Price: $100.50 → SIDEWAYS →
// Price: $102.30 → UPTREND ↑
// Price: $98.75 → DOWNTREND ↓
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment