Okay, let's outline a robust plan to create a divergence finder in Rust, pulling data from PostgreSQL. Robustness here implies handling various divergence types, potential data issues, configuration, and performance considerations.
Project Name: rust_divergence_finder
Core Goal: Identify Bullish and Bearish divergences (Regular and Hidden) between Price data and Indicator data sourced from PostgreSQL.
High-Level Architecture:
- Configuration: Load database connection details and processing parameters.
- Data Ingestion: Connect to PostgreSQL and fetch historical price and indicator data for a given symbol and time range.
- Data Model: Represent price (candles) and indicator data in Rust structs.
- Data Processing:
- Align price and indicator data by timestamp.
- Identify potential swing points (peaks and troughs) in both price and indicator series.
- Analyze swing points over a defined lookback period to find divergence patterns.
- Divergence Definition: Implement logic for different divergence types.
- Output: Store identified divergences (e.g., back into the database, print to console, save to file).
- Error Handling: Gracefully handle database errors, data inconsistencies, and calculation errors.
- Performance: Optimize data fetching and processing for potentially large datasets.
Detailed Plan:
Phase 1: Project Setup and Data Foundation
-
Project Setup:
- Use
cargo new rust_divergence_finder.
- Add necessary dependencies in
Cargo.toml:
postgres: For PostgreSQL interaction.
chrono: For handling timestamps.
serde, serde_derive, serde_yaml or toml: For configuration loading.
tokio: For asynchronous operations (database I/O can benefit).
dotenv (Optional): For loading environment variables for credentials during development.
log, env_logger: For logging progress and errors.
- Potentially a financial analysis crate if available, but building the core logic (swing detection, divergence) manually offers more control and learning.
-
Configuration (src/config.rs):
- Define a struct
Config to hold:
- Database connection details (host, port, user, password, dbname).
- Processing parameters:
symbol: Trading symbol (e.g., "BTCUSD").
timeframe: Data timeframe (e.g., "1h", "1d").
start_time, end_time: Time range for data fetching.
indicator_name: Name of the indicator table/column to use (e.g., "rsi", "macd_hist").
indicator_period (if applicable, e.g., RSI period).
swing_window_size: The number of candles/indicator points on either side to consider for identifying a local peak/trough. This is a crucial hyperparameter.
divergence_lookback_periods: How far back (in candles/points) to look for a previous swing point when identifying a divergence relative to a current swing point.
price_field: Which price field to use for swing detection (e.g., "low" for bullish, "high" for bearish, or potentially "close").
output_method: How to output results (e.g., "console", "db").
- (If outputting to DB)
divergence_table_name: Table to store results.
- Implement a function
load_config() that reads a configuration file (e.g., config.yaml or Config.toml).
-
Data Models (src/data_models.rs):
- Define a
Candle struct: timestamp: DateTime<Utc>, open: f64, high: f64, low: f64, close: f64, volume: f64.
- Define an
IndicatorData struct: timestamp: DateTime<Utc>, value: f64, indicator_name: String. (Or create specific structs if indicators have multiple lines, e.g., MacdData with macd_line, signal_line, histogram). For simplicity, start with a single value per timestamp per indicator.
- Define a
DivergenceResult struct: symbol: String, timeframe: String, divergence_type: DivergenceType, start_timestamp: DateTime<Utc>, end_timestamp: DateTime<Utc>, start_price: f64, end_price: f64, start_indicator_value: f64, end_indicator_value: f64.
- Define an
enum DivergenceType: RegularBullish, HiddenBullish, RegularBearish, HiddenBearish.
-
Database Module (src/db.rs):
- Implement functions to connect to the database using connection details from
Config. Use tokio_postgres for async operations.
- Implement
fetch_candles(symbol, timeframe, start_time, end_time) -> Result<Vec<Candle>, Error>. Query your candles table.
- Implement
fetch_indicator_data(symbol, timeframe, indicator_name, start_time, end_time) -> Result<Vec<IndicatorData>, Error>. Query your indicator table. Ensure the query selects the correct column based on indicator_name.
- Implement
insert_divergence(divergence_result) -> Result<(), Error> if storing results in the DB.
Phase 2: Core Processing Logic
-
Data Alignment:
- Fetch both
Vec<Candle> and Vec<IndicatorData>.
- Align them based on timestamp. Assuming both tables use the same timestamp for the end of the candle/period, you can iterate through the candles and find the matching indicator data by timestamp.
- Create a combined structure or process them side-by-side. Handle cases where a timestamp exists in one dataset but not the other (e.g., skip the point, log a warning). A
HashMap<DateTime<Utc>, IndicatorData> built from the indicator vector can facilitate quick lookups during candle iteration.
-
Swing Point Detection (src/swing_detector.rs):
- This is a crucial and potentially complex part. A simple approach:
- A point (candle index
i) is a trough if the chosen price field (low for bullish detection) at i is less than the price field at i - j and i + j for all j from 1 to swing_window_size.
- A point (candle index
i) is a peak if the chosen price field (high for bearish detection) at i is greater than the price field at i - j and i + j for all j from 1 to swing_window_size.
- Implement
find_swing_points(data: &[f64], window_size: usize, swing_type: SwingType) where SwingType is Peak or Trough. This function should return a Vec<usize> of indices where swings are detected.
- Apply this to:
- The chosen price field (
low or high) from the Vec<Candle>.
- The
value field from the Vec<IndicatorData> (aligned to candles).
- Store detected swings as a list of
(index, timestamp, value).
-
Divergence Finding Logic (src/divergence_finder.rs):
-
Implement the core function, e.g., find_all_divergences(candles: &[Candle], indicator_values: &[f64], config: &Config) -> Result<Vec<DivergenceResult>, Error>.
-
Get the price series (e.g., lows) and the indicator series ().
Phase 3: Output and Refinement
-
Output Module (src/output.rs):
- Implement functions based on
config.output_method:
print_divergences(divergences: &[DivergenceResult]): Prints results to the console in a readable format.
save_divergences_to_db(divergences: &[DivergenceResult], db_client, table_name): Uses the db module to insert results into the database. Ensure the target table structure matches DivergenceResult.
-
Main Application Flow (src/main.rs):
- Initialize logging.
- Load configuration using
config::load_config(). Handle potential errors.
- Connect to the database using
db::connect_db(). Handle potential errors.
- Fetch candles using
db::fetch_candles(). Handle errors.
- Fetch indicator data using
db::fetch_indicator_data(). Handle errors.
- Perform data alignment (if not done within
fetch_indicator_data to return already-aligned data).
- Call
divergence_finder::find_all_divergences(). Handle errors.
- Output results using
output::print_divergences() or output::save_divergences_to_db() based on config. Handle errors.
- Ensure database connections are closed gracefully.
-
Error Handling:
- Use Rust's
Result type extensively. Define a custom error enum (AppError) to wrap potential errors from database operations, file loading, parsing, and calculation issues.
- Propagate errors up the call stack using
?.
- Handle errors appropriately in
main (e.g., print an error message and exit).
-
Testing:
- Write unit tests for smaller, isolated functions:
- Config loading.
- Swing detection (test with simple arrays having clear peaks/troughs).
- Divergence rule checks (test with hardcoded price/indicator values that match or don't match divergence criteria).
- Consider integration tests:
- Test database fetching with a mock or test database containing sample data.
- Test the full pipeline with a small, known dataset where you can manually verify the expected divergence results.
Phase 4: Refinement and Robustness
- Parameter Tuning: The
swing_window_size and divergence_lookback_periods are critical hyperparameters. The robustness of the finder heavily depends on choosing appropriate values. The code structure should allow easy modification of these parameters via the config file. Note in documentation that tuning is required.
- Data Gaps/Missing Data: Explicitly handle cases where indicator data doesn't align perfectly with candle data. Options: skip the timestamp, interpolate (more complex), require strict alignment. Starting with skipping is simpler.
- Edge Cases: Consider datasets with very few points, flat periods in price/indicator, or noisy data. The swing detection algorithm's behavior is key here.
- Floating Point Comparisons: Double-check that comparisons use an epsilon where necessary.
- Performance Optimization: If processing a large amount of data is slow, profile the application to identify bottlenecks. Potential areas: database queries, swing detection loops, divergence comparison loops. Could parallelize some parts if necessary (using
rayon).
- Extendability: Design the
DivergenceFinder module so it could potentially accept different swing detection algorithms or handle multiple indicators/divergence types more flexibly in the future.
Database Considerations:
- Data Structure: Ensure your
candles and indicators tables have a suitable structure, including at least a timestamp column (preferably indexed), symbol, timeframe, and the relevant price/indicator value columns.
- Indexing: Add indexes to
timestamp, symbol, and timeframe columns in your data tables for faster fetching.
Key Challenges:
- Swing Point Identification: Defining and reliably finding meaningful peaks and troughs in noisy financial data is difficult and depends heavily on the
swing_window_size parameter. Different window sizes will yield different swing points and thus different divergence signals.
- Parameter Sensitivity: The results will be highly sensitive to
swing_window_size and divergence_lookback_periods.
- Data Alignment: Ensuring perfect timestamp alignment between candles and indicator data from different sources/tables is crucial.
This plan provides a solid foundation. Start by implementing the data models, configuration loading, and database fetching. Then tackle the swing detection and finally the core divergence logic. Build and test incrementally. Good luck!