Based on the provided web console logs and the WebSocketManager.tsx code, several issues can be identified that lead to the repeated WebSocket connection errors:
-
Frequent WebSocket Re-connections:
- The
useEffect responsible for managing the WebSocket connection depends on chartSymbol and chartTimeframe. This causes the WebSocket to disconnect and reconnect every time these states change, which is unnecessary and leads to connection instability.
-
Attempting to Send Messages on a Closed or Not-yet-Open Socket:
- Subscription and unsubscription messages are being sent during the reconnection process without ensuring that the WebSocket is fully open, resulting in errors like
Socket is not connected.
-
Redundant State Management:
- Both
wsRef and ws states are used to manage the WebSocket instance, potentially causing confusion and redundancy.
-
Lack of Exponential Backoff for Reconnection Attempts:
- The reconnection logic uses a fixed interval (
RECONNECT_INTERVAL), which isn't optimal for handling connection failures gracefully.
Solutions and Improvements
-
Decouple WebSocket Connection from Subscription Management:
- Problem: The
useEffect for WebSocket connection is dependent on chartSymbol and chartTimeframe, causing unnecessary reconnections.
- Solution: Modify the
useEffect to depend only on isClient, ensuring the WebSocket connection is established once during the component's lifecycle. Handle subscriptions separately without reconnecting the WebSocket.
-
Manage Subscriptions Independently:
- Problem: Subscriptions are managed within the WebSocket connection logic, leading to message sends during reconnection attempts.
- Solution: Use separate
useEffect hooks or functions to manage subscriptions, ensuring messages are only sent when the WebSocket is open.
-
Simplify WebSocket State Management:
- Problem: Using both
wsRef and ws can lead to redundant or conflicting state updates.
- Solution: Utilize only
wsRef for mutable WebSocket references, removing the ws state unless it's necessary for triggering re-renders.
-
Implement Exponential Backoff for Reconnection:
- Problem: A fixed reconnection interval can cause rapid, repeated attempts to reconnect, exacerbating connection issues.
- Solution: Implement an exponential backoff strategy to space out reconnection attempts more effectively.
-
Ensure Safe Message Sending:
- Problem: Sending messages like subscribe/unsubscribe without confirming the WebSocket is open can lead to errors.
- Solution: Queue messages or utilize event listeners to ensure messages are only sent when the WebSocket is in the
OPEN state.
-
Error Handling and Logging Enhancements:
- Improve logging to provide more context about WebSocket states and errors, aiding in debugging.
Refactored WebSocketManager.tsx Code
Below is the refactored code addressing the above issues:
// src/components/WebSocketManager.tsx
"use client";
import React, { useEffect, useState, useCallback, useRef } from "react";
import dynamic from 'next/dynamic';
import {
BarData,
WebSocketMessage,
MT5AccountInfo,
ConnectionStatus,
WebSocketSubscription
} from "../lib/types";
import { fetchConfig } from '../lib/api';
// Dynamic Imports with Proper Loading States
const Chart = dynamic(
() => import("./Chart"),
{
ssr: false,
loading: () => (
<div className="flex items-center justify-center h-[500px] bg-gray-50 rounded">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto mb-4"></div>
<p className="text-gray-500">Loading chart...</p>
</div>
</div>
)
}
);
const TradingForm = dynamic(
() => import("./TradingForm"),
{
ssr: false,
loading: () => (
<div className="animate-pulse space-y-4">
<div className="h-12 bg-gray-200 rounded"></div>
<div className="h-32 bg-gray-200 rounded"></div>
</div>
)
}
);
const AccountStatus = dynamic(
() => import("./AccountStatus"),
{
ssr: false,
loading: () => (
<div className="animate-pulse space-y-2">
<div className="h-6 bg-gray-200 rounded w-3/4"></div>
<div className="h-4 bg-gray-200 rounded w-1/2"></div>
</div>
)
}
);
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || "ws://192.168.8.114:8005/ws";
const RECONNECT_BASE_INTERVAL = 1000; // Starting with 1 second
const RECONNECT_MAX_INTERVAL = 30000; // Max 30 seconds
const WebSocketManager: React.FC = () => {
// Client-side rendering flag
const [isClient, setIsClient] = useState(false);
// WebSocket Ref
const wsRef = useRef<WebSocket | null>(null);
// Reconnection logic
const reconnectAttemptsRef = useRef<number>(0);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
// Application state
const [historicalData, setHistoricalData] = useState<BarData[]>([]);
const [symbols, setSymbols] = useState<string[]>([]);
const [trades, setTrades] = useState<any[]>([]);
const [accountInfo, setAccountInfo] = useState<MT5AccountInfo | null>(null);
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>({
connected: false,
last_update: Math.floor(Date.now() / 1000),
message: "Initializing connection..."
});
// Chart control state
const [chartSymbol, setChartSymbol] = useState<string>("");
const [chartTimeframe, setChartTimeframe] = useState<string>("");
const [availableSymbols, setAvailableSymbols] = useState<string[]>([]);
const [availableTimeframes, setAvailableTimeframes] = useState<string[]>([]);
const [chartError, setChartError] = useState<string | null>(null);
const [configLoading, setConfigLoading] = useState(true);
// Refs for data management
const latestDataRef = useRef<BarData[]>([]);
const currentSubscriptionRef = useRef<WebSocketSubscription | null>(null);
// Add new state for config loading
const [configLoaded, setConfigLoaded] = useState(false);
// Set client-side rendering flag
useEffect(() => {
setIsClient(true);
}, []);
// WebSocket message handler
const handleWebSocketMessage = useCallback((event: MessageEvent) => {
try {
const message = JSON.parse(event.data) as WebSocketMessage;
switch (message.action) {
case 'historical_data':
if (message.data && Array.isArray(message.data)) {
console.log("Received historical data:", message.data.length, "bars");
setHistoricalData(message.data as BarData[]);
latestDataRef.current = message.data as BarData[];
setChartError(null);
}
break;
case 'ohlc_update':
if (message.data && !Array.isArray(message.data)) {
const updateData = message.data as BarData;
console.log("Received OHLC update for:", message.symbol);
setHistoricalData(prevData => {
const newData = [...prevData];
const lastIndex = newData.length - 1;
if (lastIndex >= 0 && newData[lastIndex].time === updateData.time) {
// Update existing candle
newData[lastIndex] = updateData;
} else {
// Add new candle
newData.push(updateData);
// Optional: Limit the number of candles to prevent memory issues
if (newData.length > 1000) {
newData.shift();
}
}
latestDataRef.current = newData;
return newData;
});
}
break;
case 'account_update':
if (message.account_info) {
console.log("Received account update");
setAccountInfo(message.account_info);
setConnectionStatus(prev => ({
...prev,
last_update: Math.floor(Date.now() / 1000)
}));
}
break;
case 'connection_status':
if (message.status) {
console.log("Received connection status update:", message.status);
setConnectionStatus(message.status);
if (!message.status.connected) {
setAccountInfo(null);
// Optionally, handle UI changes for disconnection
}
}
break;
case 'error':
console.error("Received error message:", message.error);
setChartError(message.error || 'Unknown error occurred');
break;
default:
console.warn("Unknown message action:", message.action);
break;
}
} catch (error) {
console.error('Error processing WebSocket message:', error);
setChartError('Failed to process data');
}
}, []);
// Function to connect WebSocket
const connectWebSocket = useCallback(() => {
if (wsRef.current && (wsRef.current.readyState === WebSocket.OPEN || wsRef.current.readyState === WebSocket.CONNECTING)) {
console.log("WebSocket already connected or connecting");
return;
}
try {
console.log("Initiating WebSocket connection...");
const socket = new WebSocket(WS_URL);
wsRef.current = socket;
setConnectionStatus(prev => ({
...prev,
message: "Connecting...",
connected: false
}));
socket.onopen = () => {
console.log("WebSocket connected successfully");
setConnectionStatus({
connected: true,
last_update: Math.floor(Date.now() / 1000),
message: "Connected"
});
reconnectAttemptsRef.current = 0; // Reset reconnection attempts
// Re-subscribe to current subscription if exists
if (currentSubscriptionRef.current) {
subscribeToSymbol(currentSubscriptionRef.current.symbol, currentSubscriptionRef.current.timeframe);
}
// Request initial data if symbol and timeframe are set
if (chartSymbol && chartTimeframe) {
const message: WebSocketMessage = {
action: 'get_data',
symbol: chartSymbol,
timeframe: chartTimeframe,
};
socket.send(JSON.stringify(message));
}
};
socket.onmessage = handleWebSocketMessage;
socket.onclose = (event) => {
console.log("WebSocket disconnected:", event.reason);
setConnectionStatus({
connected: false,
last_update: Math.floor(Date.now() / 1000),
message: `Disconnected: ${event.reason || 'No reason provided'}`
});
wsRef.current = null;
// Attempt to reconnect with exponential backoff
const reconnectDelay = Math.min(RECONNECT_BASE_INTERVAL * Math.pow(2, reconnectAttemptsRef.current), RECONNECT_MAX_INTERVAL);
console.log(`Reconnecting in ${reconnectDelay / 1000} seconds...`);
reconnectTimeoutRef.current = setTimeout(() => {
reconnectAttemptsRef.current += 1;
connectWebSocket();
}, reconnectDelay);
};
socket.onerror = (error) => {
console.error("WebSocket error:", error);
setChartError('WebSocket connection error');
// The onclose handler will handle reconnection
};
} catch (error) {
console.error("Failed to create WebSocket connection:", error);
setChartError('Failed to establish WebSocket connection');
}
}, [WS_URL, chartSymbol, chartTimeframe, handleWebSocketMessage]);
// Initialize WebSocket once
useEffect(() => {
if (!isClient) return;
connectWebSocket();
return () => {
console.log("Cleaning up WebSocket connection...");
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
}
if (wsRef.current) {
if (currentSubscriptionRef.current) {
const unsubscribeMessage: WebSocketMessage = {
action: 'unsubscribe',
symbol: currentSubscriptionRef.current.symbol,
timeframe: currentSubscriptionRef.current.timeframe,
};
wsRef.current.send(JSON.stringify(unsubscribeMessage));
}
wsRef.current.close();
wsRef.current = null;
}
};
}, [isClient, connectWebSocket]);
// Configuration loading
useEffect(() => {
if (!isClient || configLoaded) return;
let isComponentMounted = true;
const loadConfig = async () => {
try {
console.log("Loading configuration...");
const config = await fetchConfig();
if (!isComponentMounted) return;
setAvailableSymbols(config.symbols);
setAvailableTimeframes(config.timeframes);
// Set initial values if not already set
if (!chartSymbol && config.symbols.length > 0) {
setChartSymbol(config.symbols[0]);
}
if (!chartTimeframe && config.timeframes.length > 0) {
setChartTimeframe(config.timeframes[0]);
}
setSymbols(config.symbols);
setConfigLoading(false);
setConfigLoaded(true);
} catch (error) {
console.error('Failed to load configuration:', error);
if (isComponentMounted) {
setChartError('Failed to load configuration');
setConfigLoading(false);
}
}
};
loadConfig();
return () => {
isComponentMounted = false;
};
}, [isClient, chartSymbol, chartTimeframe, configLoaded]);
// Subscribe to a symbol and timeframe
const subscribeToSymbol = useCallback((symbol: string, timeframe: string) => {
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
console.warn('Cannot subscribe: WebSocket is not connected');
return;
}
try {
// Unsubscribe from previous subscription if any
if (currentSubscriptionRef.current &&
(currentSubscriptionRef.current.symbol !== symbol ||
currentSubscriptionRef.current.timeframe !== timeframe)) {
console.log(`Unsubscribing from ${currentSubscriptionRef.current.symbol}:${currentSubscriptionRef.current.timeframe}`);
const unsubscribeMessage: WebSocketMessage = {
action: 'unsubscribe',
symbol: currentSubscriptionRef.current.symbol,
timeframe: currentSubscriptionRef.current.timeframe,
};
wsRef.current.send(JSON.stringify(unsubscribeMessage));
}
// Subscribe to the new symbol and timeframe
console.log(`Subscribing to ${symbol}:${timeframe}`);
const subscribeMessage: WebSocketMessage = {
action: 'subscribe',
symbol,
timeframe,
};
wsRef.current.send(JSON.stringify(subscribeMessage));
currentSubscriptionRef.current = { symbol, timeframe };
} catch (error) {
console.error('Error during subscription change:', error);
setChartError('Failed to change subscription');
}
}, []);
// Chart symbol change handler
const handleChartSymbolChange = useCallback((newSymbol: string) => {
console.log(`Changing symbol to ${newSymbol}`);
setChartError(null);
setChartSymbol(newSymbol);
if (wsRef.current?.readyState === WebSocket.OPEN) {
try {
// Request historical data for the new symbol
const historyMessage: WebSocketMessage = {
action: 'get_data',
symbol: newSymbol,
timeframe: chartTimeframe,
};
wsRef.current.send(JSON.stringify(historyMessage));
// Update subscription
subscribeToSymbol(newSymbol, chartTimeframe);
} catch (error) {
console.error('Error changing symbol:', error);
setChartError(`Failed to request data for ${newSymbol}`);
}
} else {
setChartError('WebSocket connection not available');
}
}, [chartTimeframe, subscribeToSymbol]);
// Chart timeframe change handler
const handleChartTimeframeChange = useCallback((newTimeframe: string) => {
console.log(`Changing timeframe to ${newTimeframe}`);
setChartError(null);
setChartTimeframe(newTimeframe);
if (wsRef.current?.readyState === WebSocket.OPEN) {
try {
// Request historical data for the new timeframe
const historyMessage: WebSocketMessage = {
action: 'get_data',
symbol: chartSymbol,
timeframe: newTimeframe,
};
wsRef.current.send(JSON.stringify(historyMessage));
// Update subscription
subscribeToSymbol(chartSymbol, newTimeframe);
} catch (error) {
console.error('Error changing timeframe:', error);
setChartError(`Failed to request data for timeframe ${newTimeframe}`);
}
} else {
setChartError('WebSocket connection not available');
}
}, [chartSymbol, subscribeToSymbol]);
// Handle new trades
const handleNewTrade = useCallback((trade: any) => {
setTrades(prevTrades => [...prevTrades, trade]);
console.log("Trade executed:", trade);
}, []);
// Separate useEffect to handle subscription changes
useEffect(() => {
if (!isClient || !configLoaded) return;
if (chartSymbol && chartTimeframe) {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
subscribeToSymbol(chartSymbol, chartTimeframe);
const historyMessage: WebSocketMessage = {
action: 'get_data',
symbol: chartSymbol,
timeframe: chartTimeframe,
};
wsRef.current.send(JSON.stringify(historyMessage));
}
}
}, [isClient, configLoaded, chartSymbol, chartTimeframe, subscribeToSymbol]);
// Don't render anything during SSR
if (!isClient) {
return null;
}
// Render component
return (
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">Trading Platform</h1>
<AccountStatus
accountInfo={accountInfo}
connectionStatus={connectionStatus}
/>
{configLoading ? (
<div className="text-center py-4">
<p>Loading configuration...</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="md:col-span-2">
{chartError && (
<div className="mb-4 p-2 bg-red-100 border border-red-400 text-red-700 rounded">
{chartError}
</div>
)}
{historicalData.length > 0 ? (
<Chart
symbol={chartSymbol}
timeframe={chartTimeframe}
historicalData={historicalData}
trades={trades}
availableSymbols={availableSymbols}
availableTimeframes={availableTimeframes}
onSymbolChange={handleChartSymbolChange}
onTimeframeChange={handleChartTimeframeChange}
/>
) : (
<div className="flex items-center justify-center h-[500px] bg-gray-50 rounded">
<p className="text-gray-500">Loading data...</p>
</div>
)}
</div>
<div>
<TradingForm
symbols={symbols}
onTradeExecuted={handleNewTrade}
disabled={!connectionStatus.connected}
/>
</div>
</div>
)}
</div>
);
};
export default WebSocketManager;
Key Changes and Explanations
-
Decoupled WebSocket Connection Management:
- The
useEffect responsible for establishing the WebSocket connection now only depends on isClient and invokes the connectWebSocket function once.
- This ensures that the WebSocket connection is maintained throughout the component's lifecycle, regardless of changes to
chartSymbol or chartTimeframe.
-
Separate Subscription Handling:
- Introduced a separate
useEffect that listens for changes in chartSymbol and chartTimeframe to manage subscriptions.
- This
useEffect sends subscription and unsubscription messages without affecting the WebSocket connection.
-
Exponential Backoff for Reconnection:
- Implemented an exponential backoff strategy using
RECONNECT_BASE_INTERVAL and RECONNECT_MAX_INTERVAL.
- This prevents rapid, successive reconnection attempts, allowing the system to recover gracefully from transient network issues.
-
Simplified WebSocket State Management:
- Removed the redundant
ws state and relied solely on wsRef to manage the WebSocket instance.
- This reduces complexity and potential state synchronization issues.
-
Enhanced Error Handling:
- Added default case handling in the WebSocket message handler to log unknown message actions.
- Clearer error messages and state updates to aid in debugging and improving user experience.
-
Queueing Messages (Optional Improvement):
- While not implemented above, consider adding a message queue to handle cases where messages need to be sent before the WebSocket is fully open. This ensures that messages aren't lost if they're dispatched during the connection phase.
-
Optimized Cleanup Logic:
- The cleanup function now ensures that pending reconnection attempts are cleared, and the current subscription is properly unsubscribed before closing the WebSocket.
Additional Recommendations
-
Use WebSocket Libraries:
-
Implement Heartbeats or Pings:
- To detect and handle stale connections proactively, implement heartbeat messages or pings that ensure the connection remains active.
-
User Feedback on Connection Status:
- Enhance the UI to provide clearer feedback to users about the connection status, such as displaying warnings when disconnected and indicating reconnection attempts.
-
Version Control and Testing:
- Before deploying the refactored code, ensure thorough testing under various network conditions to validate the stability and reliability of the WebSocket connections and subscription management.
By implementing these changes, the WebSocket connection should become more stable, reducing or eliminating the Socket is not connected errors observed in the web console. This will lead to a more reliable and responsive trading platform for users.