A real-time cryptocurrency trading dashboard built with React 19, TypeScript, and Redux Toolkit for learning purposes. This is a course project designed to demonstrate how modern web technologies work together in a financial application. While robust and well-structured, there's plenty of room for improvement and enhancement.
- Bitfinex API Integration: Direct WebSocket API v2 connection for live market data
- Redux Thunk Async Operations: Professional async subscription management
- Interactive Candlestick Charts: Highcharts with zoom, navigation, and technical analysis
- Live Order Book: Real-time bid/ask spreads with market depth visualization
- Trade Feed: Animated real-time trade history with color-coded buy/sell indicators
- Market Overview: Comprehensive ticker grid with price changes and mini charts
- Handler-Based Processing: Modular WebSocket message handlers for maintainability
- Memory Management: Configurable limits preventing memory leaks
- Connection Monitoring: Real-time latency tracking and diagnostics
- Environment Configuration: Flexible deployment settings via .env
- Comprehensive Testing: Vitest with 80%+ coverage and handler unit tests
- Type Safety: Enhanced TypeScript strict mode configuration
- Responsive Design: Adaptive grid layout for all screen sizes
- Dark Theme: Professional trading interface with smooth animations
- Component Library: Reusable UI components with consistent styling
- Loading States: Animated loading indicators and skeleton screens
- Update Highlighting: Visual feedback for real-time data changes
- Frontend: React 19, TypeScript 5.9, Vite 7.2
- State Management: Redux Toolkit 2.0 with Redux Thunk
- API Integration: Bitfinex WebSocket API v2
- Styling: Styled Components 6.1 with custom theme system
- Charts: Highcharts 12.4 & Highcharts React
- Data Grid: AG Grid Community 34.3
- Testing: Vitest 2.1 with React Testing Library and comprehensive handler tests
- Type Safety: Enhanced TypeScript strict mode with noUncheckedIndexedAccess
- Code Quality: ESLint 9.39.1, Prettier 3.6.2 (available via npm scripts, not enforced)
- Build Tool: Vite 7.2 with optimized production builds
- Data Processing: Lodash 4.17, Luxon 3.7, Numeral 2.0
- Custom Hooks: useGridResize, useLatest, usePrevious, useThrottle, usePerformanceMonitor
- Performance Monitoring: Real-time FPS, memory usage, and data processing latency tracking
# Clone repository
git clone <repository-url>
cd cryptoapp
# Install dependencies
npm install# Create environment file
cp .env.example .env
# Configure settings (optional)
# VITE_BITFINEX_WS_URL=wss://api-pub.bitfinex.com/ws/2
# VITE_MAX_TRADES=1000
# VITE_LOG_LEVEL=info# Start development server
npm run dev
# Run tests (optional)
npm run test
# Open browser
# http://localhost:5173# Build optimized version
npm run build
# Preview production build
npm run preview- AI-Accelerated Development - How senior engineers use AI to build real-time UIs faster
- Memory-Bounded Arrays Deep Dive - Critical concept for real-time systems
- slice() vs splice() Explained - Memory management techniques
- Architecture Overview - Project structure and organization
- API Integration - WebSocket implementation details
- Performance Features - Optimization strategies
src/
management
βββ core/ # Core utilities and components
β βββ components/ # Reusable UI components
β β βββ AnimatedCube/ # 3D loading animations
β β βββ Diagnostics/ # Connection monitoring
β β βββ LineChart/ # Mini price charts
β β βββ Loading/ # Loading states
β β βββ Stale/ # Stale data indicators
β β βββ TrendIndicator/ # Price trend arrows
β β βββ UpdateHighlight/ # Value change animations
β β βββ Widget/ # Container components
β βββ hooks/ # Custom React hooks
β β βββ useGridResize.ts
β β βββ useLatest.ts
β β βββ usePrevious.ts
β β βββ useThrottle.ts
β β βββ usePerformanceMonitor.ts # Performance monitoring hook
β βββ transport/ # WebSocket infrastructure
β β βββ handlers/ # Message processing handlers
β β β βββ bookHandler.ts
β β β βββ candlesHandler.ts
β β β βββ subscriptionHandlers.ts
β β β βββ tickerHandler.ts
β β β βββ tradesHandler.ts
β β βββ types/ # WebSocket type definitions
β β β βββ ActionTypes.ts
β β β βββ Channels.ts
β β β βββ ConnectionProxy.ts
β β β βββ ConnectionStatus.ts
β β β βββ SubscribeMsg.ts
β β βββ Connection.ts
β β βββ WsConnectionProxy.ts
β β βββ wsMiddleware.ts
β β βββ staleMonitor.ts
β β βββ slice.ts
β β βββ selectors.ts
β βββ utils.ts # Core utility functions
β βββ utils.test.ts # Core utilities tests
βββ services/ # Service layer
β βββ performanceTracker.ts # Performance metrics service
βββ modules/ # Feature modules (Domain-driven design)
β βββ ag-grid/ # Data grid formatters
β β βββ formatter.ts
β β βββ formatter.test.ts
β βββ app/ # Application bootstrap
β β βββ slice.ts
β βββ book/ # Order book & depth chart
β β βββ components/
β β β βββ Book/
β β β βββ DepthChart/
β β βββ types/
β β βββ selectors.ts
β β βββ slice.ts
β βββ candles/ # Candlestick charts
β β βββ components/
β β βββ types/
β β βββ selectors.ts
β β βββ slice.ts
β β βββ utils.ts
β βββ common/ # Shared components
β β βββ AnimatedContent/
β βββ PerformanceDashboard/ # Performance monitoring dashboard
β β βββ PerformanceDashboard.tsx
β βββ redux/ # Store configuration
β β βββ store.ts
β βββ reference-data/ # Currency pair management
β β βββ selectors.ts
β β βββ slice.ts
β β βββ utils.ts
β βββ selection/ # Selected pair state
β β βββ selectors.ts
β β βββ slice.ts
β βββ tickers/ # Price tickers & market data
β β βββ components/
β β β βββ Market/
β β β βββ Ticker/
β β β βββ Tickers/
β β βββ types/
β β βββ selectors.ts
β β βββ slice.ts
β βββ trades/ # Trade history
β βββ components/
β βββ types/
β βββ selector.ts
β βββ slice.ts
βββ theme/ # Styling system
β βββ fonts/ # Font files (Fira Sans, Material Icons)
β βββ fonts.css # Font definitions
β βββ Highchart.ts # Chart theme configuration
β βββ style.ts # Theme configuration
βββ App.styled.ts # Main app styling
βββ App.tsx # Main application
βββ GithubLink.tsx # GitHub repository link
βββ index.css # Global styles
βββ index.tsx # Application entry point
βββ react-app-env.d.ts # React type definitions
βββ serviceWorker.ts # Service worker registration
βββ setupTests.ts # Test configuration
- WebSocket API v2: Direct connection to
wss://api-pub.bitfinex.com/ws/2 - Handler-Based Processing: Modular handlers for trades, tickers, candles, and book data
- Auto-Reconnection: Exponential backoff with connection recovery
- Redux Thunk Orchestration: Async subscription management with staggered timing
- Subscription Management: Channel lifecycle with stale detection
- Rate Limiting: 2-second intervals between subscriptions to respect API limits
- Professional Candlestick Charts: Highcharts with OHLC data visualization
- Interactive Navigation: Zoom, pan, and range selection
- Market Depth Charts: Order book visualization with bid/ask curves
- Mini Charts: Embedded price trends in ticker components
- Real-time Updates: Smooth data streaming without chart rebuilds
- Dark Theme Integration: Consistent styling across all chart types
- Live Order Book: Real-time bid/ask spreads with price aggregation
- Trade Feed: Chronological trade history with buy/sell indicators
- Market Overview: Multi-currency ticker grid with performance metrics
- Price Alerts: Visual highlighting for significant price movements
- Data Validation: Runtime type checking for all financial data
- Memory Management: Environment-configurable limits for trades (1000) and candles (5000)
- Handler Architecture: Modular message processing for maintainability
- Order Book Batching: 50ms batching for high-frequency updates to prevent AG Grid performance issues
- Connection Monitoring: Real-time latency tracking and diagnostics
- Stale Detection: Heartbeat-based monitoring (20s timeout) with visual indicators
- Memoized Selectors: Optimized data access preventing unnecessary re-renders
- Connection Diagnostics: WebSocket health monitoring with auto-reconnection (5 attempts, exponential backoff)
- Comprehensive Testing: Vitest with handler unit tests and 80%+ coverage
- Type Safety: Enhanced TypeScript strict mode with advanced compiler options
- Environment Configuration: Flexible deployment via environment variables
- Handler Testing: Individual unit tests for each WebSocket message handler
- Code Quality: ESLint and Prettier available via npm scripts (manual execution)
- Documentation: Extensive API documentation and architecture guides
Create .env file for configuration:
# API Configuration
VITE_BITFINEX_WS_URL=wss://api-pub.bitfinex.com/ws/2
# Performance Tuning
VITE_MAX_TRADES=1000
VITE_MAX_CANDLES=5000
# Logging
VITE_LOG_LEVEL=info// Modular message handlers
export const handleTradesData = (parsedData: any[], subscription: any, dispatch: AppDispatch) => {
const currencyPair = subscription.request.symbol.slice(1)
if (Array.isArray(parsedData[1])) {
// Snapshot data with memory management
const trades = parsedData[1].map(transformTrade).sort((a, b) => a.timestamp - b.timestamp)
dispatch(tradesSnapshotReducer({ currencyPair, trades }))
} else {
// Single trade update
const trade = transformTrade(parsedData[1])
dispatch(tradesUpdateReducer({ currencyPair, trade }))
}
}
// Store configuration with handler middleware
const store = configureStore({
reducer: {
app: appBootstrapSlice.reducer,
trades: tradesSlice.reducer,
subscriptions: subscriptionsSlice.reducer,
// ... other reducers
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
thunk: { extraArgument: { connection } },
}).concat(createWsMiddleware(connection)),
})// src/theme/style.ts
const Palette = {
BackgroundColor: "#1f2936",
Positive: "#00AD08", // Green for gains
Negative: "#FF264D", // Red for losses
Bid: "#00AD08", // Buy orders
Ask: "#FF264D", // Sell orders
Orange: "#FFA41B", // Accent color
White: "#FFF",
Border: "#424242",
}
// Font system with Fira Sans
// Custom fonts: Fira Sans (Regular, Bold, Light, Medium, Italic variants)
// Material Icons for UI elementsnpm run dev- Start development server with hot reloadnpm run preview- Preview production build locally
npm run test- Run unit tests with Vitestnpm run test:ui- Run tests with interactive UInpm run test:coverage- Generate test coverage report
npm run build- Production build (TypeScript + Vite optimization)npm run lint- Run ESLint with TypeScript supportnpm run format- Format code with Prettier
# Run full quality check
npm run lint && npm run test && npm run build- CandlesChart: Professional candlestick charts with Highcharts integration
- Market: Real-time market data with performance metrics
- Tickers: Responsive grid with mini charts and trend indicators
- Trades: Live trade feed with color-coded buy/sell animations
- Book: Order book with real-time bid/ask spread visualization
- DepthChart: Market depth curves with interactive price levels
- Diagnostics: WebSocket connection monitoring and health checks
- Latency: Real-time latency monitoring with performance alerts
- PerformanceDashboard: Real-time performance metrics display
- AnimatedContent: Smooth transitions and loading states
- UpdateHighlight: Value change animations for price updates
- Widget: Consistent container components with titles and styling
- useGridResize: Responsive grid layout handling
- useThrottle: Performance optimization for high-frequency updates
- usePrevious: State comparison for change detection
- usePerformanceMonitor: Real-time performance metrics tracking
- Configurable Limits: Environment variables control data retention (MAX_TRADES=1000, MAX_CANDLES=5000)
- Automatic Cleanup: Reducers prevent unbounded array growth
- Staggered Subscriptions: 2-second intervals prevent API overload
- Handler-Based Processing: Modular WebSocket message handling for maintainability
- Connection Monitoring: Built-in latency tracking via Diagnostics and Latency components
- Performance Monitoring: Real-time metrics via PerformanceDashboard and usePerformanceMonitor hook
- Type Safety: Enhanced TypeScript strict mode prevents runtime errors
- Testing Coverage: Comprehensive Vitest test suite with handler unit tests
- Unit Tests: 80%+ coverage for critical business logic
- Integration Tests: WebSocket message handling and Redux flows
- Component Tests: UI behavior and user interactions
- Performance Tests: Memory usage and render time validation
βββ slice.test.ts # Redux state management
βββ selectors.test.ts # Data selection logic
βββ handlers.test.ts # WebSocket message processing
βββ middleware.test.ts # Redux middleware integration
βββ formatter.test.ts # Data formatting utilities
βββ utils.test.ts # Core utility functions
- Node.js 24+ (LTS recommended)
- npm 11+ or yarn 3+
- Git for version control
# Clone and setup
git clone <repository-url>
cd cryptoapp
npm install
# Environment configuration
cp .env.example .env
# Edit .env with your settings
# Start development
npm run dev# Run tests during development
npm run test:watch
# Check code quality
npm run lint
npm run format
# Build and test production
npm run build
npm run preview- WebSocket Health: Connection status tracking via
ConnectionStatusenum - UI Latency: Real-time UI thread responsiveness monitoring (every 2 seconds)
- Network Latency: WebSocket round-trip time via latency monitoring
- Stale Detection: Heartbeat-based monitoring detecting inactive subscriptions after 20 seconds
- Visual Indicators: Stale overlays on Book, DepthChart, Trades, Candles, and Market components
- Auto-Reconnection: Exponential backoff with up to 5 reconnection attempts
// Stale Monitor - checks every 5 seconds
const STALE_TIMEOUT_MS = 20000 // 20 seconds without heartbeat = stale
const STALE_CHECK_INTERVAL_MS = 5000 // Check every 5 seconds
export const startStaleMonitor = (getState: () => RootState, dispatch: AppDispatch) => {
const intervalId = setInterval(() => {
const state = getState()
const now = Date.now()
Object.keys(state.subscriptions).forEach((key) => {
const channelId = Number(key)
if (isNaN(channelId)) return
const subscription = state.subscriptions[channelId]
if (!subscription) return
const { lastUpdate, isStale } = subscription
if (lastUpdate && !isStale && now - lastUpdate > STALE_TIMEOUT_MS) {
dispatch(markSubscriptionStale({ channelId }))
}
})
}, STALE_CHECK_INTERVAL_MS)
return () => clearInterval(intervalId)
}
// Heartbeat handling - resets stale flag
if (Array.isArray(parsedData) && parsedData[1] === "hb") {
const [channelId] = parsedData
const subscription = store.getState().subscriptions[channelId]
if (subscription?.isStale) {
store.dispatch(updateStaleSubscription({ channelId }))
}
return
}
// UI Components with stale indicators
const Book = ({ orders, isStale }: Props) => {
return (
<Container>
{isStale && <Stale />}
<AgGridReact rowData={orders} />
</Container>
)
}MIT License - see LICENSE file for details.
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Write tests for new functionality
- Run quality checks (
npm run lint && npm run test) - Commit with conventional commits
- Push and create Pull Request
- TypeScript: Strict mode with enhanced type checking
- Testing: Minimum 80% coverage for new features
- Performance: No regressions in bundle size or render times
- Documentation: Update README and inline docs
Built with β€οΈ for the crypto trading community
For learning purposes only β’ No responsibility accepted for use of this software
This software is provided strictly for learning and educational purposes.
It is distributed βas isβ, without warranties of any kind, express or implied, including but not limited to fitness for a particular purpose or nonβinfringement.
The authors and contributors do not accept any responsibility or liability for any use, misuse, or outcomes resulting from this software.
By using this code, you acknowledge that you assume full responsibility for any consequences.
