Skip to content

davthecodercom/Financial-RustAndAndroid

Repository files navigation

High-Performance Financial Graphics with Rust & Kotlin

A complete high-performance financial charting application built with Rust (for technical indicators) and Kotlin/Jetpack Compose (for UI). Features real-time cryptocurrency price data from Binance WebSocket API with blazing-fast native calculations.

πŸ—οΈ Architecture Overview

This project demonstrates a hybrid Rust/Kotlin architecture for maximum performance:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Jetpack Compose UI Layer                  β”‚
β”‚  β€’ Candlestick Charts  β€’ Volume Bars  β€’ RSI Indicators      β”‚
β”‚  β€’ Real-time Updates   β€’ Smooth Animations                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  Binance WebSocket Service                   β”‚
β”‚  β€’ Real-time BTC/USDT Data  β€’ Connection Management         β”‚
β”‚  β€’ Trade Stream Processing  β€’ State Flow Integration        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Kotlin Business Layer                     β”‚
β”‚  β€’ Data Models  β€’ Business Logic  β€’ Data Processing        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚  TechnicalIndicators (Hybrid) β”‚
              β”‚  β€’ JNI Bridge                 β”‚
              β”‚  β€’ Native + Kotlin Fallback   β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                          β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚                                   β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Rust Native     β”‚              β”‚  Kotlin Fallback  β”‚
β”‚  (Primary)       β”‚              β”‚  (Backup)         β”‚
β”‚  β€’ 2-5x Faster   β”‚              β”‚  β€’ Pure Kotlin    β”‚
β”‚  β€’ Zero GC       β”‚              β”‚  β€’ Always Works   β”‚
β”‚  β€’ SIMD Optimizedβ”‚              β”‚  β€’ Safe Fallback  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Key Features

Performance

  • πŸ¦€ Rust-Powered Calculations: Technical indicators implemented in Rust for 2-5x performance boost
  • Zero Garbage Collection: Native Rust code eliminates GC pauses during calculations
  • SIMD Optimizations: Compiler auto-vectorization for tight computational loops
  • Optimized for Large Datasets: Handles 1000+ candlesticks smoothly at 60 FPS
  • Hybrid Architecture: Automatic fallback to Kotlin if native library unavailable
  • Clean Architecture: Well-organized code following best practices
  • πŸ“Š Benchmarked: Comprehensive performance testing suite included (see benchmarks)

Technical Indicators

  • Simple Moving Average (SMA): 20-period and 50-period
  • Exponential Moving Average (EMA): 12-period and 26-period
  • Relative Strength Index (RSI): 14-period with visual zones
  • MACD: Moving Average Convergence Divergence with signal line and histogram

Real-time Data Integration

  • Binance WebSocket: Live BTC/USDT trade data from Binance API
  • Real-time Price Updates: Actual market data streaming via WebSocket
  • Connection Management: Automatic connection handling and cleanup
  • State Flow Integration: Reactive data flow using Kotlin StateFlow

UI Features

  • Interactive Charts: Swipe to pan through historical data
  • Live Price Updates: Real-time price data from Binance WebSocket
  • Toggle Indicators: Enable/disable indicators on the fly
  • Dark Theme: Material Design 3 dark theme
  • Responsive Layout: Scrollable dashboard with multiple chart types
  • Visual Feedback: Color-coded bullish/bearish candles and indicators

πŸ“¦ Project Structure

RustAndAndroid/
β”œβ”€β”€ rust/                                 # πŸ¦€ Rust implementation
β”‚   β”œβ”€β”€ Cargo.toml                       # Rust dependencies & config
β”‚   β”œβ”€β”€ .cargo/config.toml               # Android NDK linker settings
β”‚   └── src/
β”‚       β”œβ”€β”€ lib.rs                       # JNI bindings for Kotlin interop
β”‚       └── indicators.rs                # Native indicator algorithms
β”‚
β”œβ”€β”€ app/src/
β”‚   β”œβ”€β”€ main/
β”‚   β”‚   β”œβ”€β”€ java/com/davthecoder/financial/
β”‚   β”‚   β”‚   β”œβ”€β”€ MainActivity.kt          # Financial dashboard UI
β”‚   β”‚   β”‚   β”œβ”€β”€ BinanceWebSocketService.kt # Real-time Binance WebSocket
β”‚   β”‚   β”‚   β”œβ”€β”€ Indicators.kt            # Data processing layer
β”‚   β”‚   β”‚   β”œβ”€β”€ TechnicalIndicators.kt   # Hybrid Rust/Kotlin indicators
β”‚   β”‚   β”‚   β”œβ”€β”€ FinanceCharts.kt         # Compose chart components
β”‚   β”‚   β”‚   └── ui/theme/                # App theming
β”‚   β”‚   └── jniLibs/                     # Compiled Rust libraries
β”‚   β”‚       β”œβ”€β”€ arm64-v8a/
β”‚   β”‚       β”œβ”€β”€ armeabi-v7a/
β”‚   β”‚       β”œβ”€β”€ x86_64/
β”‚   β”‚       └── x86/
β”‚   β”œβ”€β”€ test/                            # Unit tests (JVM)
β”‚   β”‚   └── BenchmarkTest.kt             # Kotlin-only benchmarks
β”‚   └── androidTest/                     # Instrumented tests (Device)
β”‚       └── BenchmarkInstrumentedTest.kt # Rust vs Kotlin benchmarks
β”‚
β”œβ”€β”€ build-rust.sh                        # Rust build script
β”œβ”€β”€ run-benchmarks.sh                    # Automated benchmark runner
β”œβ”€β”€ RUST_MIGRATION.md                    # Detailed Rust integration docs
β”œβ”€β”€ BENCHMARKING.md                      # Benchmark how-to guide
β”œβ”€β”€ BENCHMARK_REPORT.md                  # Detailed performance analysis
β”œβ”€β”€ BENCHMARK_SUMMARY.md                 # Quick benchmark reference
└── README.md                            # This file

πŸ› οΈ Prerequisites

Before building this project, ensure you have the following installed:

Android Development Environment

  • Android Studio: Latest stable version (Hedgehog or newer recommended)
  • Android SDK: API Level 26 or higher
  • Android NDK: Version 21 or higher (for Rust compilation)
  • JDK: Version 11 or higher

Rust Toolchain (Required for building native libraries)

  • Rust: Install from rustup.rs
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  • Android Targets: Install after Rust setup
    rustup target add aarch64-linux-android
    rustup target add armv7-linux-androideabi
    rustup target add x86_64-linux-android
    rustup target add i686-linux-android

πŸ”¨ Building the Project

Step 1: Build Rust Libraries

# Compile Rust for all Android architectures and copy to jniLibs
./build-rust.sh

This will:

  • βœ… Compile Rust code for arm64-v8a, armeabi-v7a, x86_64, x86
  • βœ… Copy .so libraries to app/src/main/jniLibs/
  • βœ… Verify Android NDK configuration

Step 2: Build Android App

# Via command line:
./gradlew assembleDebug

# Or via Android Studio: Build > Make Project

Step 3: Run on Device/Emulator

# Via command line:
./gradlew installDebug

# Or via Android Studio: Run > Run 'app'

Note: If you skip Step 1, the app will automatically fall back to pure Kotlin implementations (slightly slower but fully functional)

βœ… Verification

After building, verify everything is working correctly:

Android App Builds Without Errors

./gradlew assembleDebug

Should complete with BUILD SUCCESSFUL

App Runs and Displays Charts

  • Launch the app on a device/emulator
  • Verify you see:
    • βœ… Financial Chart Demo header
    • βœ… Current BTC/USDT price card with real-time updates
    • βœ… Indicators toggles (SMA 20, SMA 50, EMA 12, RSI, Volume)
    • βœ… Candlestick chart with price data
    • βœ… Volume chart (if enabled)
    • βœ… RSI indicator chart (if enabled)

Indicators Working

  • Toggle indicators on/off and verify:
    • βœ… Lines appear/disappear on the chart
    • βœ… No crashes or errors
    • βœ… Charts remain smooth and responsive

Real-time Updates

  • Watch the price card update every 2 seconds
  • Verify the last candlestick updates dynamically

πŸ’‘ How It Works

1. Technical Indicators (Rust Native + Kotlin Fallback)

The TechnicalIndicators.kt object provides a hybrid implementation:

object TechnicalIndicators {
    private var useNative = true

    init {
        try {
            System.loadLibrary("financial_indicators") // Load Rust library
        } catch (e: UnsatisfiedLinkError) {
            useNative = false // Fall back to Kotlin
        }
    }

    // Native Rust methods (via JNI)
    @JvmStatic
    private external fun calculateSMANative(data: FloatArray, period: Int): FloatArray

    // Public API with automatic fallback
    fun calculateSMA(data: FloatArray, period: Int): FloatArray {
        return if (useNative) {
            try {
                calculateSMANative(data, period) // πŸ¦€ Rust (2-3x faster)
            } catch (e: Exception) {
                calculateSMAKotlin(data, period)  // Fallback
            }
        } else {
            calculateSMAKotlin(data, period)      // Pure Kotlin
        }
    }

    // Similar pattern for EMA, RSI, MACD...
}

Rust Implementation (rust/src/indicators.rs):

pub fn calculate_sma(data: &[f32], period: usize) -> Vec<f32> {
    // Highly optimized, zero-allocation hot path
    // SIMD auto-vectorization by compiler
    // No garbage collection overhead
}

2. Real-time Data Integration

BinanceWebSocketService.kt provides live cryptocurrency data from Binance:

class BinanceWebSocketService {
    val connectionState: StateFlow<ConnectionState>
    val tradeData: StateFlow<TradeData?>
    
    suspend fun connect() {
        // Connects to Binance WebSocket and streams BTC/USDT trades
        // Updates tradeData flow with real-time prices
    }
    
    suspend fun disconnect() {
        // Cleanly closes WebSocket connection
    }
}

3. Data Processing Layer

Indicators.kt provides a clean data processing API:

object Indicators {
    fun calculateSMA(data: FloatArray, period: Int): FloatArray {
        return TechnicalIndicators.calculateSMA(data, period) // Uses Rust or Kotlin
    }

    fun processChartData(candles: List<CandleStick>): ChartData {
        val closePrices = candles.map { it.close }.toFloatArray()

        // All calculations use Rust if available (2-5x faster)
        val sma20 = calculateSMA(closePrices, 20)
        val sma50 = calculateSMA(closePrices, 50)
        val rsi = calculateRSI(closePrices, 14)
        val macdData = calculateMACD(closePrices, 12, 26, 9)

        return ChartData(candles, sma20, sma50, rsi, macdData, ...)
    }
}

4. Compose UI Components

FinanceCharts.kt renders charts using Canvas for smooth 60 FPS performance:

@Composable
fun CandlestickChart(chartData: ChartData, ...) {
    Canvas(modifier = ...) {
        // Direct drawing to Canvas for maximum performance
        chartData.candles.forEach { candle ->
            drawCandlestick(candle, ...)
        }
    }
}

5. Financial Dashboard

MainActivity.kt orchestrates everything:

  • Connects to Binance WebSocket for real-time data
  • Processes indicators using Rust (with Kotlin fallback)
  • Updates UI in real-time with live price data at 60 FPS
  • Handles user interactions (toggle indicators, pan charts)
  • Zero-latency indicator calculations thanks to native Rust

🎨 Customization

Adding New Indicators

  1. Implement in Rust (rust/src/indicators.rs):
pub fn calculate_bollinger_bands(
    data: &[f32],
    period: usize,
    std_dev: f32
) -> Vec<f32> {
    // Native implementation
    // Returns [upper, middle, lower, ...]
}
  1. Add JNI Binding (rust/src/lib.rs):
#[no_mangle]
pub extern "C" fn Java_com_davthecoder_financial_TechnicalIndicators_calculateBollingerBandsNative(
    env: JNIEnv,
    _class: JClass,
    data: JFloatArray,
    period: i32,
    std_dev: f32,
) -> jfloatArray {
    // JNI marshaling
}
  1. Update Kotlin (TechnicalIndicators.kt):
@JvmStatic
private external fun calculateBollingerBandsNative(
    data: FloatArray, period: Int, stdDev: Float
): FloatArray

fun calculateBollingerBands(data: FloatArray, period: Int, stdDev: Float): FloatArray {
    return if (useNative) {
        try {
            calculateBollingerBandsNative(data, period, stdDev)
        } catch (e: Exception) {
            calculateBollingerBandsKotlin(data, period, stdDev)
        }
    } else {
        calculateBollingerBandsKotlin(data, period, stdDev)
    }
}
  1. Build and Test:
./build-rust.sh
./gradlew assembleDebug

See RUST_MIGRATION.md for detailed documentation.

Styling Charts

Modify ChartColors in FinanceCharts.kt:

object ChartColors {
    val bullish = Color(0xFF26A69A)  // Customize colors
    val bearish = Color(0xFFEF5350)
    // ...
}

πŸ§ͺ Testing

Unit Tests

# Run unit tests
./gradlew test

# Run with coverage
./gradlew testDebugUnitTest

Instrumented Tests (Android)

./gradlew connectedAndroidTest

Performance Benchmarks

# Run comprehensive benchmark suite
./run-benchmarks.sh

# View detailed results
cat BENCHMARK_REPORT.md        # Full analysis
cat BENCHMARK_SUMMARY.md       # Quick reference
cat BENCHMARKING.md            # How-to guide

The benchmark suite tests:

  • βœ… SMA, EMA, RSI, MACD performance
  • βœ… Rust vs Kotlin comparison
  • βœ… Real-world data patterns (BTC prices)
  • βœ… Multiple dataset sizes (100 to 10,000 points)
  • βœ… Full chart processing scenarios

See BENCHMARKING.md for detailed instructions.

πŸ” Debugging

Debugging Kotlin Code

  1. Set breakpoints in any Kotlin file (TechnicalIndicators.kt, MainActivity.kt, etc.)
  2. Click the Debug button in Android Studio
  3. Inspect variables and step through code as normal

Debugging Rust Code

For debugging native Rust code:

  1. Add println!() or log!() statements in Rust
  2. View output in Android Logcat
  3. For advanced debugging, use lldb with Android NDK

Verifying Native Library Usage

Check logcat on app startup:

# If Rust library loaded successfully:
adb logcat | grep "TechnicalIndicators"
# Should show: Using native Rust implementation

# If fallback to Kotlin:
# Should show: Failed to load native library, using Kotlin fallback

Performance Profiling

Use Android Studio Profiler to analyze:

  • CPU usage during indicator calculations
  • Memory allocation patterns
  • UI rendering performance

πŸ“š Further Reading

Rust & JNI

Android & Kotlin

Technical Analysis

Project Documentation

🀝 Contributing

Contributions are welcome! Areas for improvement:

  • Rust Indicators: Additional technical indicators (Bollinger Bands, Stochastic, etc.)
  • Performance: Benchmarking suite comparing Rust vs Kotlin implementations
  • Testing: Comprehensive unit tests for Rust and Kotlin code
  • Features:
    • Pinch-to-zoom gesture support
    • Multiple cryptocurrency pairs support
    • Historical data persistence (Room, SQLite)
    • Custom indicator builder
  • Infrastructure:
    • CI/CD for automated Rust builds
    • Cross-compilation for iOS (via Rust)
    • WebSocket reconnection logic

πŸ“„ License

This project is provided as-is for educational and demonstration purposes.

πŸ™ Acknowledgments

  • Rust Team: For an incredible systems programming language with zero-cost abstractions
  • Kotlin Team: For an excellent modern programming language
  • Android Team: For Jetpack Compose and modern Android development
  • JNI Community: For making native interop possible and well-documented
  • Financial Analysis Community: For standardized indicator algorithms
  • Binance: For providing free WebSocket API access

πŸ‘¨β€πŸ’» Developer

David Cruz Anaya
🌐 www.davthecoder.com


Built with ❀️ using Rust πŸ¦€, Kotlin, and Jetpack Compose

For questions or issues, please open a GitHub issue.

πŸš€ Quick Start Summary

# 1. Install Rust and Android targets
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android

# 2. Build Rust libraries
./build-rust.sh

# 3. Build and run Android app
./gradlew installDebug

# 4. Enjoy blazing-fast technical indicators! πŸ”₯

About

Financial code using rust and kotlin+compose

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published