Below is a detailed, step‐by‐step plan for building a robust divergence finder in Rust. This tool will load candle and indicator time‑series data from a PostgreSQL database and then process it to detect various types of divergences. The plan covers project setup, data ingestion, algorithm design for divergence detection, testing, and deployment considerations.
1. Define the Requirements and Scope
a. Divergence Types to Detect
-
Regular Bullish/Bearish Divergence:
– Regular Bullish: Price makes lower lows while the indicator makes higher lows.
– Regular Bearish: Price makes higher highs while the indicator makes lower highs.
-
Hidden Divergence:
– Hidden Bullish: Price forms a higher low while the indicator forms a lower low.
– Hidden Bearish: Price forms a lower high while the indicator forms a higher high.
b. Data Types
- Candles: Open, high, low, close, volume, and timestamp.
- Indicators: Any momentum oscillator or trend indicator with values correlated to each candle (with the same or interpolated timestamps).
c. Performance and Scalability:
- Handle large historical datasets efficiently.
- Ensure low latency for real‑time processing if needed.
- Support multithreading or asynchronous processing if required.
2. Overall System Architecture
-
Data Ingestion Layer:
- Connect to PostgreSQL.
- Query and fetch candle and indicator data.
- Convert the SQL rows into Rust structs and sort them by timestamp.
-
Preprocessing & Data Transformation:
- Validate data integrity (e.g., non‑null values, correct time series order).
- Optionally, merge or join candle and indicator data on timestamp.
- Normalize or smooth out the data if necessary for divergence detection.
-
Divergence Detection Engine:
- Identify key price turning points (peaks and troughs).
- Similarly, identify turning points in the indicator series.
- Compare these points to detect the required divergence patterns.
- Modularize the engine to support future additions of divergence types.
-
Output/Persistence Layer:
- Optionally persist the divergence results back to PostgreSQL or output via an API.
- Provide logging and reporting (e.g., console output, JSON files).
-
Testing and Monitoring Layer:
- Implement unit and integration tests.
- Set up logging for error monitoring and debugging.
3. Technology and Library Choices
4. Step‑by‑Step Implementation Plan
Step 1. Project Setup
- Initialize a New Cargo Project:
cargo new divergence_finder --bin
cd divergence_finder
- Add Dependencies in
Cargo.toml:
[dependencies]
postgres = "0.19" # or tokio-postgres if async is preferred
chrono = "0.4"
serde = { version = "1.0", features = ["derive"] }
# Optional for async & runtime
tokio = { version = "1", features = ["full"] }
- Set up configuration management:
- Use environment variables or a configuration file (e.g., using
config) for database connection details.
Step 2. Database Connection and Data Ingestion
-
Design Structs for Your Data:
#[derive(Debug)]
struct Candle {
time: chrono::NaiveDateTime,
open: f64,
high: f64,
low: f64,
close: f64,
volume: f64,
}
#[derive(Debug)]
struct IndicatorDatum {
time: chrono::NaiveDateTime,
value: f64,
}
-
Implement Database Functions:
- Write functions to connect to PostgreSQL.
- Execute SQL queries to get candle and indicator data.
- Transform rows into Rust structs.
Example sketch using postgres:
use postgres::{Client, NoTls};
fn load_candles(client: &mut Client) -> Result<Vec<Candle>, postgres::Error> {
let mut candles = Vec::new();
for row in client.query("SELECT time, open, high, low, close, volume FROM candle_table ORDER BY time", &[])? {
candles.push(Candle {
time: row.get("time"),
open: row.get("open"),
high: row.get("high"),
low: row.get("low"),
close: row.get("close"),
volume: row.get("volume"),
});
}
Ok(candles)
}
-
Data Merging/Alignment:
- Ensure that indicator data aligns with candle timestamps.
- Optionally join the data in SQL if it simplifies matching.
Step 3. Preprocessing and Data Transformation
Step 4. Designing the Divergence Detection Algorithms
A. Identifying Extremums (Peaks and Troughs):
-
Create helper functions to scan through a time series and find local maximums (peaks) and minimums (troughs).
-
Use a sliding window (e.g., check if a value is greater/less than its neighbors) to detect extremums.
Example pseudo‑code for peak detection:
fn find_peaks(data: &[f64]) -> Vec<usize> {
let mut peaks = Vec::new();
for i in 1..data.len()-1 {
if data[i] > data[i-1] && data[i] > data[i+1] {
peaks.push(i);
}
}
peaks
}
-
Repeat similarly for troughs.
B. Divergence Detection:
For each divergence type, compare pairs of extremums from the price series and the indicator series.
-
Regular Bullish Divergence:
- Identify two consecutive lows in price.
- Confirm that the later low is lower than the earlier low.
- In parallel, for the corresponding indicator values at these lows, check that the later indicator value is higher than the earlier one.
-
Regular Bearish Divergence:
- Identify two consecutive highs in price.
- Confirm that the later high is higher than the earlier high.
- For the indicator, ensure that the later value is lower than the earlier value.
-
Hidden Divergence Patterns:
Follow a similar strategy with inverted conditions:
- Hidden Bullish: Price shows a higher low while the indicator shows a lower low.
- Hidden Bearish: Price shows a lower high, while the indicator shows a higher high.
-
Function Signature Example:
enum DivergenceType {
RegularBullish,
RegularBearish,
HiddenBullish,
HiddenBearish,
}
struct Divergence {
start_time: chrono::NaiveDateTime,
end_time: chrono::NaiveDateTime,
divergence_type: DivergenceType,
price_start: f64,
price_end: f64,
indicator_start: f64,
indicator_end: f64,
}
fn detect_divergences(
candles: &[Candle],
indicators: &[IndicatorDatum]
) -> Vec<Divergence> {
let mut divergences = Vec::new();
// 1. Identify peaks/troughs positions for price and indicator.
// 2. For each candidate pair, compare price and indicator levels following the definitions.
// 3. Create Divergence instances if criteria match.
// 4. Handle different divergence types.
// NOTE: In practice consider aligning indices by timestamp.
divergences
}
-
Handling Alignment Issues:
Ensure correct matching of indicator data with candle extrema. You might need to:
- Use binary search (since the series is sorted) to find the closest timestamp.
- Apply interpolation if the series are offset.
Step 5. Integration and Modularization
-
Workflow Integration:
- Start the application.
- Open database connection and load data.
- Preprocess the data (sorting, cleaning).
- Run divergence detection.
- Output or store the detected divergence events.
-
Modular Design:
- Separate modules for database access (
db.rs), data models (models.rs), divergence detection (divergence.rs), and utilities (utils.rs).
- This separation makes unit testing and maintenance easier.
Step 6. Testing and Validation
-
Unit Testing:
- Create tests for the peak/trough detection logic using a small sample series.
- Test divergence detection with known scenarios and hard‑coded data.
-
Integration Testing:
- Use a test PostgreSQL database (or SQLite in a similar mode) to load sample data and verify the end‑to‑end processing.
-
Performance Testing:
- Benchmark the divergence finder on large datasets.
- Optimize if necessary (e.g., by parallelizing the divergence analysis).
Step 7. Logging, Error Handling, and Robustness
-
Error Handling:
- Use Rust’s error handling (Result, Option) properly.
- Check for database connection errors, data integrity issues, and out‑of‑bounds errors in array indexing.
-
Logging:
- Add logging (using crates like
env_logger or log) to capture errors and critical processing milestones.
-
Graceful Degradation:
- In case of partial failure (e.g., some data rows are bad), decide whether to skip, report, or stop processing.
Step 8. Deployment Considerations
Final Thoughts
This plan outlines the full lifecycle of a divergence finder from data ingestion, preprocessing, divergence detection algorithms, testing, and deployment. The key challenges will be:
- Correctly aligning candle and indicator data.
- Robustly detecting turning points in noisy financial data.
- Ensuring that the divergence detection logic comprehensively covers the different divergence patterns.
As you implement, iterate on the algorithms with real market data to fine‑tune the extremum detection and divergence conditions.
Happy coding in Rust!