Please read my plan and add more to it for maximum improvement: Project: Rust Divergence Finder
Goal: To create a Rust application that ingests candle and indicator data from PostgreSQL, identifies various types of price/indicator divergences, and outputs these findings.
Core Principles:
Robustness: Error handling, efficient data processing, testability, clear logging.
Flexibility: Support for multiple indicators and configurable divergence parameters.
Performance: Leverage Rust's strengths for efficient computation, especially with time-series data.
Maintainability: Well-structured code, clear separation of concerns.
I. Planning & Design Phase
A. Understanding Divergences
Regular (Classic) Divergence:
Bullish: Price makes Lower Lows (LL), Indicator makes Higher Lows (HL). Suggests weakening downtrend, potential reversal up.
Bearish: Price makes Higher Highs (HH), Indicator makes Lower Highs (LH). Suggests weakening uptrend, potential reversal down.
Hidden (Continuation) Divergence:
Bullish: Price makes Higher Lows (HL), Indicator makes Lower Lows (LL). Suggests continuation of uptrend.
Bearish: Price makes Lower Highs (LH), Indicator makes Higher Highs (HH). Suggests continuation of downtrend.
Exaggerated Divergence (Optional, less common):
Price makes double bottom/top, indicator makes a higher low / lower high. Can be treated as a weaker form of regular divergence. For now, focus on the main 4.
B. Data Requirements
Candles: Timestamp, Open, High, Low, Close, Volume (optional but good).
Indicators: Timestamp, Value(s). Examples:
RSI: Single value.
MACD: MACD line, Signal line, Histogram. Divergence can be sought on any of these.
Example data structure: Candle Data:
symbol, 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, last_updated
Price series to use for comparison (e.g., Close, High, Low).
Parameters for peak/trough detection (e.g., window size or prominence).
Parameters for divergence validation (e.g., max number of bars between extrema).
Output options (DB table, log level, file paths).
II. Development Plan
A. Setup & Dependencies (Cargo.toml)
toml
[dependencies]
tokio = { version = "1", features = ["full"] } # Async runtime
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "macros", "chrono", "decimal", "json"] } # Async SQL
chrono = { version = "0.4", features = ["serde"] } # Timestamps
serde = { version = "1", features = ["derive"] } # Serialization/Deserialization
serde_json = "1" # For config if using JSON
config = "0.13" # For config file handling (supports TOML, JSON, YAML etc.)
thiserror = "1" # For custom error types
anyhow = "1" # For simple error handling in main/higher levels
log = "0.4"
env_logger = "0.10" # Or tracing
clap = { version = "4", features = ["derive"] } # CLI arguments
# Potentially for calculations if not pre-calculated (but problem states data IS from PG)
# rust_decimal = "1" # For precise financial calculations if needed
B. Core Data Structures (src/models.rs)
rust
use chrono::{DateTime, Utc};
use serde::Deserialize;
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Candle {
pub timestamp: DateTime<Utc>,
pub open: f64, // Or rust_decimal::Decimal
pub high: f64,
pub low: f64,
pub close: f64,
pub volume: Option<f64>,
// Potentially symbol, timeframe if not passed contextually
}
// Generic way to handle different indicator structures
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct IndicatorPoint {
pub timestamp: DateTime<Utc>,
pub value: f64, // The specific value we're checking for divergence (e.g., RSI value, MACD histogram)
// pub symbol: String, // If fetching generically
// pub timeframe: String, // If fetching generically
}
// Combined data point for easier processing
#[derive(Debug, Clone)]
pub struct TimeSeriesPoint {
pub timestamp: DateTime<Utc>,
pub price_high: f64, // Usually candle high for bearish divergence detection
pub price_low: f64, // Usually candle low for bullish divergence detection
pub price_close: f64, // Often used as a general price reference
pub indicator_value: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub enum DivergenceType {
RegularBullish,
RegularBearish,
HiddenBullish,
HiddenBearish,
}
#[derive(Debug, Clone)]
pub struct Extremum {
pub index: usize, // Index in the TimeSeriesPoint Vec
pub timestamp: DateTime<Utc>,
pub value: f64,
pub is_peak: bool, // true for peak, false for trough
}
#[derive(Debug, Clone, sqlx::FromRow)] // If storing to DB
pub struct Divergence {
pub symbol: String,
pub timeframe: String,
pub indicator_name: String,
pub divergence_type: DivergenceType, // Might need custom sqlx mapping for enum
pub start_time: DateTime<Utc>,
pub end_time: DateTime<Utc>,
pub price_start: f64,
pub price_end: f64,
pub indicator_start: f64,
pub indicator_end: f64,
}
C. Configuration Module (src/config.rs)
Define a struct mirroring your config.toml (or other format).
E. Data Alignment and Preparation (Part of Processing Engine)
Fetch candles for a symbol/timeframe.
Fetch indicator data for the chosen indicator(s) for the same symbol/timeframe.
Crucial Step: Align candles and indicator data by timestamp.
Use a HashMap<DateTime<Utc>, Candle> and HashMap<DateTime<Utc>, IndicatorValue> for efficient lookup.
Iterate through sorted timestamps and create TimeSeriesPoint structs. Handle missing data points (e.g., if an indicator value is missing for a candle timestamp). Decide on a strategy: skip, interpolate (careful!), or error. Skipping is safest initially.
Result: Vec<TimeSeriesPoint> sorted by time.
F. Peak/Trough Detection (src/analysis/extrema.rs)
Input: &[TimeSeriesPoint] and window_size: usize (config).
Output: (Vec<Extremum>, Vec<Extremum>) for (price peaks, price troughs) and (Vec<Extremum>, Vec<Extremum>) for (indicator peaks, indicator troughs).
Algorithm:
A simple approach: A point i is a peak if value[i] is greater than value[i-window_size ... i-1] AND value[i-1 ... i+window_size]. Similar for troughs.
Consider edge cases (start/end of data).
Store index, timestamp, value, and type (peak/trough).
One function for price (using price_high for peaks, price_low for troughs) and one for indicator (using indicator_value).
G. Divergence Identification Logic (src/analysis/divergence.rs)
Input:
Vec<Extremum> for price peaks.
Vec<Extremum> for price troughs.
Vec<Extremum> for indicator peaks.
Vec<Extremum> for indicator troughs.
max_bars_between_extrema: usize (config).
The original Vec<TimeSeriesPoint> (to get full candle data if needed).
Output: Vec<Divergence>.
Algorithm Outline (Example for Regular Bullish):
Iterate through price_troughs (let current be P_trough2, previous be P_trough1).
Iterate through indicator_troughs (let current be I_trough2, previous be I_trough1).
Conditions for Regular Bullish Divergence:
P_trough2.value < P_trough1.value (Lower Low in Price)
I_trough2.value > I_trough1.value (Higher Low in Indicator)
Temporal Alignment:
P_trough1.index must be before P_trough2.index.
I_trough1.index must be before I_trough2.index.
The indices of corresponding extrema should be close: abs(P_trough1.index - I_trough1.index) < N and abs(P_trough2.index - I_trough2.index) < N (where N is a small configurable number, e.g., 2-3 bars, or ensure they are the closest valid extrema).
The distance between the two price troughs (and indicator troughs) should be within max_bars_between_extrema: (P_trough2.index - P_trough1.index) <= max_bars_between_extrema.
No Conflicting Extrema: There should be no lower price trough between P_trough1 and P_trough2, and no lower indicator trough between I_trough1 and I_trough2. (This is implicitly handled if you iterate through consecutive identified extrema, but needs careful thought if you allow skipping extrema).
If all conditions met, create a Divergence struct.
Loop through configured symbols and timeframes (potentially concurrently using tokio::spawn and futures::future::join_all).
For each symbol/timeframe/indicator configuration:
a. Fetch candles.
b. Fetch corresponding indicator data.
c. Align data into Vec<TimeSeriesPoint>. Handle errors if data is insufficient or misaligned.
d. Detect price extrema (highs for bearish, lows for bullish).
e. Detect indicator extrema.
f. Identify divergences.
g. Store/Log found divergences.
Handle errors gracefully at each step using Result and anyhow/thiserror.
I. Output/Reporting
Log found divergences to console (using log crate).
Store divergences in a dedicated PostgreSQL table.
Add a unique constraint on (symbol, timeframe, indicator_name, divergence_type, start_time, end_time) to prevent duplicates if re-running.
Optionally, write to CSV/JSON files.
III. Robustness & Best Practices
Comprehensive Error Handling: Use Result<T, E> extensively. Define custom error types with thiserror for domain-specific errors (e.g., DataAlignmentError, InsufficientDataError). Use anyhow for simpler error propagation in main or high-level functions.
Logging: Use tracing or log crate. Log key events, errors, and summary statistics.
Testing:
Unit Tests: For peak/trough detection logic with mock data. For divergence rule implementations with mock extrema.
Integration Tests: With a test PostgreSQL database. Test data fetching, alignment, and full divergence detection pipeline. Use sqlx::test macro.
Concurrency: Use tokio to process multiple symbol/timeframe pairs concurrently if I/O bound (DB queries).
futures::stream::StreamExt::for_each_concurrent can be useful.
Data Validation: Check for empty datasets, consistency.
Idempotency: If storing results in DB, ensure re-running the finder doesn't create duplicate entries (e.g., using ON CONFLICT DO NOTHING or checking existence before insert).
Code Organization: Use modules (mod) effectively.
Performance Profiling: If performance becomes an issue, use tools like perf (Linux) or Instruments (macOS), and Rust's criterion for benchmarking critical sections.
Database Migrations: If schema changes, use a tool like sqlx-cli migrate.
IV. Future Enhancements
More Sophisticated Peak/Trough Detection:
ZigZag-like logic.
Filtering by volume confirmation.
Consider using libraries that might offer this (though implementing it yourself is a good learning exercise).
Divergence Scoring/Strength: Some divergences are stronger than others (e.g., based on the angle of divergence, number of bars, volume confirmation).
Real-time Processing: Adapt to listen for new candles/indicator updates and process incrementally.
Visualization: Integrate with a charting library or output data for external visualization tools.
Machine Learning: Train a model to classify or predict based on identified divergences.
Support for more indicator types without code changes: More dynamic indicator configuration.
Backtesting Framework Integration: Feed identified divergences into a backtester.
Getting Started Steps:
Project Setup:cargo new divergence_finder --bin and add dependencies.
PostgreSQL Setup: Create your database and tables for candles and at least one indicator (e.g., RSI). Populate with some sample data.
Configuration: Create a config.toml file. Implement src/config.rs.
Models: Implement src/models.rs.
DB Layer: Implement src/db.rs to fetch candles and one indicator. Test it.
Alignment: Implement logic to merge candle and indicator data into Vec<TimeSeriesPoint>.
Extrema Detection: Implement src/analysis/extrema.rs. Test with various patterns.
Divergence Logic: Implement src/analysis/divergence.rs for one type (e.g., Regular Bullish) first. Test thoroughly. Then add others.
Main Orchestration: Wire everything up in src/main.rs.
Output: Implement logging and DB storage for results.
Your plan for the Rust Divergence Finder project is already very detailed and well-structured, covering the essential aspects of design, implementation, and best practices. However, there are several areas where we can enhance it further to maximize improvement, robustness, flexibility, performance, and maintainability. Below, I’ll provide additions and refinements to your plan, organized by section, with a focus on practical improvements, advanced features, and long-term scalability.
General Enhancements to Core Principles
To ensure the project is future-proof and maximally improved, let’s refine and expand the core principles:
Robustness:
Add input validation for all external data (e.g., candles, indicators) to ensure data integrity (e.g., non-negative prices, valid timestamps).
Implement circuit breakers for database connections to handle transient failures gracefully.
Add monitoring and alerting hooks (e.g., metrics collection) to track system health in production.
Flexibility:
Support pluggable indicator logic to allow users to define custom indicators without modifying the core codebase (e.g., via a plugin system or scripting).
Enable dynamic timeframes (e.g., custom timeframes like 2h, 3h) by aggregating lower timeframes if needed.
Add support for multi-asset class processing (e.g., stocks, forex, crypto) by abstracting data models.
Performance:
Use parallel processing not just for symbols/timeframes but also for indicator calculations within a single symbol/timeframe (e.g., using rayon for CPU-bound tasks).
Implement caching for frequently accessed data (e.g., candles for overlapping timeframes) using an in-memory store like redis or a local cache.
Optimize database queries with indexing and batching to reduce I/O overhead.
Maintainability:
Adopt domain-driven design (DDD) principles to further separate concerns (e.g., separate domain logic, infrastructure, and application layers).
Use feature flags to enable/disable experimental features (e.g., new divergence types) without affecting stable code.
Instead of nested loops over all extrema, consider iterating through price extrema and then finding corresponding indicator extrema within a reasonable window.
A common approach is to iterate through the data once:
Find all price peaks/troughs.
Find all indicator peaks/troughs.
Then, iterate (e.g., with two pointers or nested loops with constraints) through these lists of extrema to find pairs that satisfy divergence conditions.
For example, for Regular Bullish: Iterate i from 0 to price_troughs.len() - 2. Let pt1 = price_troughs[i], pt2 = price_troughs[i+1].
Then search for it1 and it2 in indicator_troughs such that it1 is "close" to pt1 and it2 is "close" to pt2 in time, and they satisfy the value conditions.
Implement API versioning for output data to ensure backward compatibility if the schema changes.
I. Planning & Design Phase Enhancements
A. Understanding Divergences
Add Divergence Strength Metrics: Introduce a scoring system for divergences based on factors like:
Angle of Divergence: Steeper divergences (price vs. indicator) are often stronger signals.
Volume Confirmation: Divergences with increasing volume are more significant.
Time Span: Divergences over a longer period (more bars) may indicate stronger trends.
Indicator Magnitude: Larger differences in indicator values (e.g., RSI moving from 30 to 40 vs. 30 to 32) can indicate stronger signals.
Store these metrics in the Divergence struct for later analysis or filtering.
Support for Divergence Patterns: Beyond regular, hidden, and exaggerated divergences, consider:
Triple Divergences: When three consecutive peaks/troughs show divergence, indicating an even stronger signal.
Converging Divergences: When multiple indicators (e.g., RSI and MACD) show divergence simultaneously, increasing confidence in the signal.
False Positive Mitigation: Add logic to filter out weak or noisy divergences, such as:
Divergences occurring in low-volatility periods (e.g., using ATR to measure volatility).
Divergences that are immediately invalidated by subsequent price action (e.g., a bullish divergence followed by a sharp drop).
B. Data Requirements
Extended Candle Data: Include additional fields in the Candle struct to support advanced analysis:
atr: Average True Range for volatility filtering.
vwap: Volume-Weighted Average Price for additional price context.
is_complete: A boolean flag to indicate whether the candle is finalized (important for real-time processing).
Indicator Metadata: Add metadata to indicator data to support dynamic processing:
parameters: Store the parameters used to calculate the indicator (e.g., RSI period, MACD fast/slow/signal periods) to ensure consistency and traceability.
normalization: For indicators like RSI, store whether the value is normalized (e.g., 0-100) to handle comparisons correctly.
Data Quality Checks: Implement checks for:
Missing data (e.g., gaps in timestamps).
Outliers (e.g., extreme price spikes that may indicate data errors).
Data staleness (e.g., ensure candles and indicators are up-to-date for real-time use).
C. System Architecture
Your architecture diagram is solid, but we can enhance it to support scalability and real-time processing:
Event Stream: Add support for real-time data ingestion using a message queue (e.g., Kafka, RabbitMQ) for processing live market data.
Cache Layer: Use Redis or an in-memory cache to store frequently accessed data (e.g., recent candles) to reduce database load.
Metrics Collection: Integrate with Prometheus (or similar) to monitor performance metrics (e.g., query latency, divergence detection rate).
Distributed Processing: Design the system to scale horizontally by running multiple instances of the processing engine, each handling a subset of symbols/timeframes.
D. Configuration
Dynamic Configuration Updates: Allow configuration to be reloaded at runtime (e.g., via a file watcher or HTTP endpoint) without restarting the application.
Validation: Add validation for configuration parameters (e.g., ensure peak_trough_window is positive, max_bars_between_extrema is reasonable).
Environment Overrides: Support environment variables to override config file settings (e.g., for database credentials in production).
Secrets Management: Store sensitive data (e.g., database credentials) in a secure vault (e.g., HashiCorp Vault) or environment variables, not in the config file.
Default Configurations: Provide sensible defaults for all parameters to make the application easier to use out of the box.
II. Development Plan Enhancements
A. Setup & Dependencies (Cargo.toml)
Add the following dependencies to support the enhanced features:
toml
[dependencies]
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "macros", "chrono", "decimal", "json"] }
chrono = { version = "0.4", features = ["serde"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
config = "0.13"
thiserror = "1"
anyhow = "1"
log = "0.4"
env_logger = "0.10"
clap = { version = "4", features = ["derive"] }
# New dependencies for enhanced features
rayon = "1.7" # For parallel processing of CPU-bound tasks
redis = { version = "0.23", features = ["tokio-comp"] } # For caching
prometheus = "0.13" # For metrics collection
tokio-stream = "0.1" # For stream processing
kafka = "0.9" # For real-time event streaming (optional)
notify = "5.1" # For watching config file changes
validator = { version = "0.16", features = ["derive"] } # For config validation
rust_decimal = "1" # For precise financial calculations
tracing = "0.1" # For advanced logging and observability
tracing-subscriber = "0.3" # For tracing configuration
[dev-dependencies]
criterion = "0.5" # For benchmarking
testcontainers = "0.14" # For integration tests with Dockerized PostgreSQL
[[bench]]
name = "divergence_benchmarks"
harness = false
B. Core Data Structures (src/models.rs)
Enhance the data structures to support the new features:
Batching: Fetch and store data in batches to reduce the number of database round-trips.
Circuit Breaker: Use a circuit breaker pattern to handle transient database failures:
rust
use sqlx::{PgPool, Postgres, Transaction};
use tokio::time::{timeout, Duration};
use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::Result;
pub struct DbClient {
pool: PgPool,
circuit_open: AtomicBool,
}
impl DbClient {
pub async fn new(database_url: &str) -> Result<Self> {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(10)
.idle_timeout(Duration::from_secs(30))
.connect(database_url)
.await?;
Ok(Self {
pool,
circuit_open: AtomicBool::new(false),
})
}
pub async fn fetch_candles(
&self,
symbol: &str,
timeframe: &str,
start_date: DateTime<Utc>,
end_date: DateTime<Utc>,
) -> Result<Vec<Candle>> {
if self.circuit_open.load(Ordering::SeqCst) {
return Err(anyhow::anyhow!("Database circuit breaker is open"));
}
let query = sqlx::query_as::<_, Candle>(
r#"
SELECT * FROM candles
WHERE symbol = $1 AND timeframe = $2 AND timestamp BETWEEN $3 AND $4
ORDER BY timestamp
"#,
)
.bind(symbol)
.bind(timeframe)
.bind(start_date)
.bind(end_date);
match timeout(Duration::from_secs(5), query.fetch_all(&self.pool)).await {
Ok(Ok(candles)) => Ok(candles),
Ok(Err(e)) => {
self.circuit_open.store(true, Ordering::SeqCst);
Err(e.into())
}
Err(_) => {
self.circuit_open.store(true, Ordering::SeqCst);
Err(anyhow::anyhow!("Database query timed out"))
}
}
}
pub async fn store_divergences(&self, divergences: &[Divergence]) -> Result<()> {
if divergences.is_empty() {
return Ok(());
}
let mut tx: Transaction<Postgres> = self.pool.begin().await?;
for divergence in divergences {
sqlx::query(
r#"
INSERT INTO divergences (
symbol, timeframe, indicator_name, divergence_type, start_time, end_time,
price_start, price_end, indicator_start, indicator_end, strength_score,
volume_confirmed, created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT DO NOTHING
"#,
)
.bind(&divergence.symbol)
.bind(&divergence.timeframe)
.bind(&divergence.indicator_name)
.bind(&divergence.divergence_type)
.bind(&divergence.start_time)
.bind(&divergence.end_time)
.bind(&divergence.price_start)
.bind(&divergence.price_end)
.bind(&divergence.indicator_start)
.bind(&divergence.indicator_end)
.bind(&divergence.strength_score)
.bind(&divergence.volume_confirmed)
.bind(Utc::now())
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(())
}
}
Notes:
Use timeout to prevent queries from hanging indefinitely.
Implement a simple circuit breaker to avoid overwhelming the database during outages.
Use transactions for batch inserts to ensure atomicity.
E. Data Alignment and Preparation
Interpolation Strategy: Instead of just skipping missing data, consider linear interpolation for small gaps (e.g., 1-2 bars) in indicator data, but log a warning.
Data Normalization: Normalize indicator values if needed (e.g., scale MACD histogram to a 0-100 range for comparison with RSI).
Caching: Cache aligned TimeSeriesPoint data in Redis for frequently accessed symbol/timeframe pairs to avoid redundant processing.
F. Peak/Trough Detection (src/analysis/extrema.rs)
Enhance the peak/trough detection algorithm for accuracy and robustness:
Advanced Detection Methods:
Use Savitzky-Golay filtering or Gaussian smoothing to reduce noise in the data before detecting extrema.
Implement ZigZag logic to filter out minor fluctuations and focus on significant peaks/troughs.
Use volume-weighted extrema to prioritize peaks/troughs with high volume.
Strength Scoring: Calculate a strength score for each extremum based on:
Prominence: How much the peak/trough stands out from surrounding data.
Volume: Higher volume increases strength.
Volatility: Lower ATR (volatility) may indicate weaker extrema.
rust
use rust_decimal::Decimal;
use rayon::prelude::*;
pub fn find_extrema(data: &[TimeSeriesPoint], window_size: usize) -> (Vec<Extremum>, Vec<Extremum>) {
let mut peaks = Vec::new();
let mut troughs = Vec::new();
data.par_iter().enumerate().for_each(|(i, point)| {
if i < window_size || i >= data.len() - window_size {
return;
}
let is_peak = (i - window_size..i)
.chain(i + 1..i + window_size + 1)
.all(|j| point.price_high >= data[j].price_high);
let is_trough = (i - window_size..i)
.chain(i + 1..i + window_size + 1)
.all(|j| point.price_low <= data[j].price_low);
let strength = calculate_strength(&data[i - window_size..i + window_size + 1], i - window_size);
if is_peak {
peaks.push(Extremum {
index: i,
timestamp: point.timestamp,
value: point.price_high,
is_peak: true,
strength,
});
}
if is_trough {
troughs.push(Extremum {
index: i,
timestamp: point.timestamp,
value: point.price_low,
is_peak: false,
strength,
});
}
});
(peaks, troughs)
}
fn calculate_strength(window: &[TimeSeriesPoint], center_idx: usize) -> f64 {
let center = &window[window.len() / 2];
let prominence = window
.iter()
.map(|p| (p.price_high - p.price_low).to_f64().unwrap())
.sum::<f64>()
/ window.len() as f64;
let volume_factor = center.volume.map_or(1.0, |v| v.to_f64().unwrap().log10().max(1.0));
let atr_factor = center.atr.map_or(1.0, |a| 1.0 / a.to_f64().unwrap().max(1.0));
prominence * volume_factor * atr_factor
}
Notes:
Use rayon for parallel processing of extrema detection.
Add a calculate_strength function to quantify the significance of extrema.
G. Divergence Identification Logic (src/analysis/divergence.rs)
Enhance the divergence detection logic for accuracy and flexibility:
For Regular Bullish Triple: Price makes three lower lows, while the indicator makes three higher lows.
Similar logic for other types.
Strength Scoring: Calculate a strength score for each divergence based on:
Angle of Divergence: Use the slope of the line connecting price extrema vs. indicator extrema.
Volume Confirmation: Check if volume is increasing during the divergence period.
Time Span: Longer divergences (more bars) are stronger.
Indicator Magnitude: Larger changes in indicator values indicate stronger signals.
False Positive Filtering: Filter out divergences that:
Occur in low-volatility periods (e.g., ATR below a threshold).
Are immediately invalidated by subsequent price action (e.g., a bullish divergence followed by a sharp drop).
rust
use rust_decimal::Decimal;
pub fn find_divergences(
price_peaks: Vec<Extremum>,
price_troughs: Vec<Extremum>,
indicator_peaks: Vec<Extremum>,
indicator_troughs: Vec<Extremum>,
max_bars_between_extrema: usize,
min_strength_score: f64,
) -> Vec<Divergence> {
let mut divergences = Vec::new();
// Regular Bullish Divergence
for i in 0..price_troughs.len().saturating_sub(1) {
let pt1 = &price_troughs[i];
let pt2 = &price_troughs[i + 1];
if pt2.value < pt1.value {
if let Some((it1, it2)) = find_matching_indicator_troughs(
&indicator_troughs,
pt1,
pt2,
max_bars_between_extrema,
) {
if it2.value > it1.value {
let strength_score = calculate_divergence_strength(pt1, pt2, it1, it2);
if strength_score >= min_strength_score {
divergences.push(Divergence {
id: None,
symbol: "BTCUSDT".to_string(), // Replace with actual symbol
timeframe: "1h".to_string(), // Replace with actual timeframe
indicator_name: "RSI".to_string(), // Replace with actual indicator
divergence_type: DivergenceType::RegularBullish,
start_time: pt1.timestamp,
end_time: pt2.timestamp,
price_start: pt1.value,
price_end: pt2.value,
indicator_start: it1.value,
indicator_end: it2.value,
strength_score,
volume_confirmed: check_volume_confirmation(pt1, pt2),
created_at: Utc::now(),
});
}
}
}
}
}
// Add similar logic for other divergence types (Regular Bearish, Hidden Bullish, etc.)
// Add logic for triple divergences
divergences
}
fn find_matching_indicator_troughs(
indicator_troughs: &[Extremum],
pt1: &Extremum,
pt2: &Extremum,
max_bars_between_extrema: usize,
) -> Option<(&Extremum, &Extremum)> {
let mut it1 = None;
let mut it2 = None;
for it in indicator_troughs {
if it.timestamp >= pt1.timestamp && it.timestamp <= pt2.timestamp {
if it1.is_none() && it.index >= pt1.index && it.index <= pt1.index + 3 {
it1 = Some(it);
}
if it.index >= pt2.index && it.index <= pt2.index + 3 {
it2 = Some(it);
}
}
}
if let (Some(it1), Some(it2)) = (it1, it2) {
if (pt2.index - pt1.index) <= max_bars_between_extrema {
return Some((it1, it2));
}
}
None
}
fn calculate_divergence_strength(
pt1: &Extremum,
pt2: &Extremum,
it1: &Extremum,
it2: &Extremum,
) -> f64 {
let price_slope = (pt2.value - pt1.value).to_f64().unwrap() / (pt2.index - pt1.index) as f64;
let indicator_slope = (it2.value - it1.value).to_f64().unwrap() / (it2.index - it1.index) as f64;
let angle_score = (price_slope - indicator_slope).abs();
let time_span_score = (pt2.index - pt1.index) as f64 / 10.0;
let extremum_strength_score = (pt1.strength + pt2.strength) / 2.0;
angle_score * time_span_score * extremum_strength_score
}
fn check_volume_confirmation(pt1: &Extremum, pt2: &Extremum) -> bool {
// Placeholder: Implement logic to check if volume is increasing
true
}
Notes:
Add a min_strength_score parameter to filter out weak divergences.
Implement calculate_divergence_strength to quantify divergence significance.
Add placeholder logic for volume confirmation (to be implemented based on actual volume data).
H. Main Application Logic (src/main.rs)
Enhance the main logic to support concurrency, metrics, and real-time processing:
rust
use tokio::sync::Semaphore;
use prometheus::{Registry, Counter, Gauge};
use tracing::{info, error};
use tracing_subscriber;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Initialize tracing
tracing_subscriber::fmt::init();
// Initialize metrics
let registry = Registry::new();
let divergence_counter = Counter::new("divergences_detected_total", "Total divergences detected")?;
let processing_time_gauge = Gauge::new("processing_time_seconds", "Time taken to process data")?;
registry.register(Box::new(divergence_counter.clone()))?;
registry.register(Box::new(processing_time_gauge.clone()))?;
// Load configuration
let config_manager = ConfigManager::new("config.toml")?;
let config = config_manager.get_config().await;
// Initialize database client
let db_client = DbClient::new(&config.database_url).await?;
// Process tasks concurrently
let semaphore = Arc::new(Semaphore::new(10)); // Limit concurrent tasks
let mut handles = Vec::new();
for task in config.process_tasks {
let permit = semaphore.clone().acquire_owned().await?;
let db_client = db_client.clone();
let divergence_counter = divergence_counter.clone();
let processing_time_gauge = processing_time_gauge.clone();
let handle = tokio::spawn(async move {
let start_time = Utc::now();
info!("Processing {} on {}", task.symbol, task.timeframe);
// Fetch and process data
let candles = db_client.fetch_candles(&task.symbol, &task.timeframe, start_date, end_date).await?;
for indicator in task.indicators {
let indicator_data = db_client.fetch_indicator_data(&indicator, &task.symbol, &task.timeframe, start_date, end_date).await?;
let time_series = align_data(candles.clone(), indicator_data)?;
let (price_peaks, price_troughs) = find_extrema(&time_series, config.divergence_params.peak_trough_window);
let (indicator_peaks, indicator_troughs) = find_extrema(&time_series, config.divergence_params.peak_trough_window);
let divergences = find_divergences(
price_peaks,
price_troughs,
indicator_peaks,
indicator_troughs,
config.divergence_params.max_bars_between_extrema,
config.divergence_params.min_strength_score,
);
// Store results
db_client.store_divergences(&divergences).await?;
divergence_counter.inc_by(divergences.len() as f64);
// Log results
for div in divergences {
info!("Found divergence: {:?}", div);
}
}
let processing_time = Utc::now().signed_duration_since(start_time).num_milliseconds() as f64 / 1000.0;
processing_time_gauge.set(processing_time);
drop(permit);
Ok::<(), anyhow::Error>(())
});
handles.push(handle);
}
// Wait for all tasks to complete
for handle in handles {
handle.await??;
}
Ok(())
}
Notes:
Use a Semaphore to limit concurrent database connections.
Integrate Prometheus metrics to track the number of divergences detected and processing time.
Use tracing for structured logging.
I. Output/Reporting
Enhance the output system to support advanced use cases:
Metrics Output: Expose Prometheus metrics via an HTTP endpoint (e.g., /metrics).
Alerting: Add support for sending alerts (e.g., via email, Slack, or webhook) when significant divergences are detected.
Visualization Data: Output data in a format suitable for visualization tools (e.g., JSON for Plotly, CSV for Excel).
API Output: Add an optional REST or gRPC API to serve divergence results to external applications.
III. Robustness & Best Practices Enhancements
Advanced Error Handling: Use tracing to log detailed error contexts, including stack traces and request IDs for debugging.
Testing:
Add property-based tests using proptest to test divergence logic with randomly generated data.
Use testcontainers to spin up a Dockerized PostgreSQL instance for integration tests.
Add load tests to ensure the system can handle high volumes of data.
Concurrency: Use tokio::select! to handle real-time updates and batch processing concurrently.
Performance Profiling: Use tracing spans to measure the performance of individual components (e.g., data fetching, extrema detection).
Security: Sanitize all user inputs (e.g., symbol names, timeframes) to prevent SQL injection or other attacks.
Documentation: Use cargo doc to generate comprehensive API documentation, and add a README.md with setup instructions, examples, and architecture diagrams.
IV. Future Enhancements (Expanded)
Real-time Processing:
Use a message queue (e.g., Kafka) to ingest real-time candle and indicator updates.
Implement incremental processing to update extrema and divergences as new data arrives.
Machine Learning Integration:
Train a model to predict the success rate of divergences based on historical data.
Use features like divergence strength, volume, ATR, and market conditions as inputs.
Backtesting Framework:
Integrate with a backtesting library (e.g., backtest-rs) to evaluate the profitability of trading strategies based on detected divergences.
Add support for transaction costs, slippage, and risk management.
Visualization:
Integrate with a Rust-based plotting library (e.g., plotters) to generate charts of divergences.
Output data in a format compatible with external tools like TradingView or Grafana.
Cloud Deployment:
Containerize the application using Docker for easy deployment.
Add support for Kubernetes to scale the processing engine horizontally.
Use a managed database service (e.g., AWS RDS) for production.
Plugin System:
Allow users to define custom indicators and divergence types via a plugin system (e.g., using dlopen for dynamic loading of Rust libraries).
Support scripting languages (e.g., Lua, Python) for rapid prototyping of new logic.
Getting Started Steps (Enhanced)
Project Setup: Add a Dockerfile and docker-compose.yml to set up a local development environment with PostgreSQL and Redis.
PostgreSQL Setup: Use sqlx-cli to manage database migrations and seed the database with realistic test data.
Configuration: Add a sample config.toml file with comments explaining each parameter.
Models: Add unit tests for serialization/deserialization of data structures.
DB Layer: Add integration tests using testcontainers to verify database interactions.
Alignment: Add benchmarks using criterion to measure the performance of data alignment.
Extrema Detection: Add property-based tests to ensure the extrema detection logic is robust.
Divergence Logic: Add a test suite with known divergence patterns to verify correctness.
Main Orchestration: Add a CLI option to run in "dry-run" mode (log results without storing them).
Output: Add a simple HTTP server to expose Prometheus metrics.
Refine & Test: Set up a CI/CD pipeline (e.g., GitHub Actions) to run tests, benchmarks, and linters on every commit.
Conclusion
These enhancements significantly improve the Rust Divergence Finder by adding advanced features, improving performance, ensuring robustness, and preparing the system for production use. The additions focus on scalability, real-time processing, advanced analytics, and developer experience, making the project not only functional but also a strong foundation for future growth. Let me know if you'd like to dive deeper into any specific area!