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.
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 β
ββββββββββββββββββββ βββββββββββββββββββββ
- π¦ 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)
- 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
- 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
- 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
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
Before building this project, ensure you have the following installed:
- 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: 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
# Compile Rust for all Android architectures and copy to jniLibs
./build-rust.shThis will:
- β Compile Rust code for arm64-v8a, armeabi-v7a, x86_64, x86
- β
Copy
.solibraries toapp/src/main/jniLibs/ - β Verify Android NDK configuration
# Via command line:
./gradlew assembleDebug
# Or via Android Studio: Build > Make Project# 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)
After building, verify everything is working correctly:
./gradlew assembleDebugShould complete with BUILD SUCCESSFUL
- 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)
- Toggle indicators on/off and verify:
- β Lines appear/disappear on the chart
- β No crashes or errors
- β Charts remain smooth and responsive
- Watch the price card update every 2 seconds
- Verify the last candlestick updates dynamically
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
}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
}
}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, ...)
}
}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, ...)
}
}
}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
- 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, ...]
}- 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
}- 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)
}
}- Build and Test:
./build-rust.sh
./gradlew assembleDebugSee RUST_MIGRATION.md for detailed documentation.
Modify ChartColors in FinanceCharts.kt:
object ChartColors {
val bullish = Color(0xFF26A69A) // Customize colors
val bearish = Color(0xFFEF5350)
// ...
}# Run unit tests
./gradlew test
# Run with coverage
./gradlew testDebugUnitTest./gradlew connectedAndroidTest# 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 guideThe 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.
- Set breakpoints in any Kotlin file (TechnicalIndicators.kt, MainActivity.kt, etc.)
- Click the Debug button in Android Studio
- Inspect variables and step through code as normal
For debugging native Rust code:
- Add
println!()orlog!()statements in Rust - View output in Android Logcat
- For advanced debugging, use
lldbwith Android NDK
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 fallbackUse Android Studio Profiler to analyze:
- CPU usage during indicator calculations
- Memory allocation patterns
- UI rendering performance
- RUST_MIGRATION.md - Detailed Rust integration guide
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
This project is provided as-is for educational and demonstration purposes.
- 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
David Cruz Anaya
π www.davthecoder.com
Built with β€οΈ using Rust π¦, Kotlin, and Jetpack Compose
For questions or issues, please open a GitHub issue.
# 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! π₯