Of course! Let's design a robust, scalable plan for building a Divergence Finder in Rust that reads candle and indicator data from PostgreSQL, processes it, and detects various types of divergences.
I'll break it down into:
- 📚 Requirements
- 🏛️ System Architecture
- 🛠️ Core Components
- 🔍 Divergence Detection Logic
- 🗄️ Database Interaction
- 🧪 Testing Strategy
- 🚀 Future Enhancements
📚 Requirements
- Language: Rust
- Database: PostgreSQL
- Input: Candlestick data (OHLCV) + Indicator data (e.g., RSI, MACD, etc.)
- Output: Detected divergences (bullish, bearish, hidden bullish, hidden bearish)
- Performance: Should handle large datasets efficiently
- Extensibility: Easy to add new indicators or divergence types
🏛️ System Architecture
+------------------+
| PostgreSQL |
| (Candles + |
| Indicators) |
+--------+---------+
|
v
+--------+---------+
| Data Fetcher |
| (Rust SQL client)|
+--------+---------+
|
v
+--------+---------+
| Data Processor |
| (Structs, Models)|
+--------+---------+
|
v
+--------+---------+
| Divergence Engine|
| (Detection Logic)|
+--------+---------+
|
v
+--------+---------+
| Output / Storage |
| (Save to DB/File)|
+------------------+
🛠️ Core Components
1. Data Models
Define Rust structs for:
struct Candle {
timestamp: chrono::NaiveDateTime,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
struct Indicator {
timestamp: chrono::NaiveDateTime,
rsi: Option<f64>,
macd: Option<f64>,
macd_signal: Option<f64>,
// Add more indicators as needed
}
2. Database Layer
Use sqlx or tokio-postgres for async database access.
Example:
use sqlx::postgres::PgPoolOptions;
async fn fetch_candles(pool: &sqlx::PgPool, symbol: &str, timeframe: &str) -> Result<Vec<Candle>, sqlx::Error> {
sqlx::query_as!(
Candle,
r#"
SELECT timestamp, open, high, low, close, volume
FROM candles
WHERE symbol = $1 AND timeframe = $2
ORDER BY timestamp ASC
"#,
symbol,
timeframe
)
.fetch_all(pool)
.await
}
Similarly for indicators.
3. Divergence Types
You need to detect:
| Type | Price Action | Indicator Action |
|---|
| Bullish Divergence | Lower Low | Higher Low |
| Bearish Divergence | Higher High | Lower High |
| Hidden Bullish | Higher Low | Lower Low |
| Hidden Bearish | Lower High | Higher High |
🔍 Divergence Detection Logic
1. Find Swing Points
First, find local highs and lows in price and indicator.
Example:
fn find_local_extrema(data: &[f64], window: usize) -> Vec<Option<bool>> {
let mut extrema = vec![None; data.len()];
for i in window..(data.len() - window) {
let is_high = data[i] > data[i - window..i].iter().cloned().fold(f64::MIN, f64::max)
&& data[i] > data[i + 1..=i + window].iter().cloned().fold(f64::MIN, f64::max);
let is_low = data[i] < data[i - window..i].iter().cloned().fold(f64::MAX, f64::min)
&& data[i] < data[i + 1..=i + window].iter().cloned().fold(f64::MAX, f64::min);
if is_high {
extrema[i] = Some(true);
} else if is_low {
extrema[i] = Some(false);
}
}
extrema
}
true = local high
false = local low
None = neither
2. Match Price and Indicator Extremes
- For each swing point in price, find corresponding swing point in indicator.
- Compare the direction of price vs indicator.
Example:
fn detect_divergence(
price_extrema: &[Option<bool>],
indicator_extrema: &[Option<bool>],
prices: &[f64],
indicators: &[f64],
) -> Vec<Divergence> {
let mut divergences = Vec::new();
for i in 1..price_extrema.len() {
if let (Some(price_type), Some(indicator_type)) = (price_extrema[i], indicator_extrema[i]) {
if price_type == indicator_type {
// Both are highs or both are lows
let prev_price = prices[i - 1];
let curr_price = prices[i];
let prev_indicator = indicators[i - 1];
let curr_indicator = indicators[i];
if price_type {
// Highs
if curr_price > prev_price && curr_indicator < prev_indicator {
divergences.push(Divergence::Bearish(i));
} else if curr_price < prev_price && curr_indicator > prev_indicator {
divergences.push(Divergence::HiddenBearish(i));
}
} else {
// Lows
if curr_price < prev_price && curr_indicator > prev_indicator {
divergences.push(Divergence::Bullish(i));
} else if curr_price > prev_price && curr_indicator < prev_indicator {
divergences.push(Divergence::HiddenBullish(i));
}
}
}
}
}
divergences
}
Define:
enum Divergence {
Bullish(usize),
Bearish(usize),
HiddenBullish(usize),
HiddenBearish(usize),
}
🗄️ Database Interaction
You can store detected divergences back into PostgreSQL:
async fn save_divergence(pool: &sqlx::PgPool, divergence: &DivergenceRecord) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
INSERT INTO divergences (symbol, timeframe, timestamp, divergence_type)
VALUES ($1, $2, $3, $4)
"#,
divergence.symbol,
divergence.timeframe,
divergence.timestamp,
divergence.divergence_type
)
.execute(pool)
.await?;
Ok(())
}
🧪 Testing Strategy
- Unit tests for:
- Local extrema detection
- Divergence detection
- Integration tests:
- Fetching data from PostgreSQL
- Saving divergence results
- Backtesting:
- Run divergence detection on historical data and validate results manually or statistically.
🚀 Future Enhancements
- Add support for more indicators (Stochastic RSI, CCI, etc.)
- Add multi-timeframe divergence detection
- Add real-time streaming divergence detection
- Visualize divergences on charts (e.g., using Plotters crate)
- Parallelize processing using
tokio or rayon
- Add a REST API to query divergences
📦 Crates You Will Need
sqlx (async PostgreSQL client)
tokio (async runtime)
serde (serialization)
chrono (date/time handling)
rayon (parallel processing, optional)
plotters (for visualization, optional)
📋 Summary
✅ Fetch candles and indicators from PostgreSQL
✅ Find local highs/lows in price and indicator
✅ Compare swing points to detect divergences
✅ Save results back to database
✅ Make it modular, extensible, and efficient
Would you like me to also generate a sample project structure (folder layout) and a basic Cargo.toml for you? 🚀
If yes, just say "yes"!