import React, { useState, useEffect } from 'react';
import { AlertCircle, Brain, TrendingUp, Activity, Play, Pause, RotateCcw, BookOpen, Calendar, Award, ArrowUp, ArrowDown, DollarSign } from 'lucide-react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area } from 'recharts';
const EmotionTradingAssistant = () => {
const [activeTab, setActiveTab] = useState('dashboard');
const [emotionScore, setEmotionScore] = useState(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentFrequency, setCurrentFrequency] = useState(null);
const [audioContext, setAudioContext] = useState(null);
const [oscillator, setOscillator] = useState(null);
const [journalEntries, setJournalEntries] = useState([]);
const [showWarning, setShowWarning] = useState(false);
const [checkinAnswers, setCheckinAnswers] = useState({
stress: 5,
sleep: 5,
eagerness: 5,
impatience: 5,
chasingLosses: 5
});
const [postTradeAnswers, setPostTradeAnswers] = useState({
followedPlan: '',
emotionsControl: '',
revengeTrade: '',
frequencyHelp: ''
});
// Mock trading data for dashboard
const [marketData] = useState([
{ time: '09:00', price: 42500, emotion: 75 },
{ time: '10:00', price: 42750, emotion: 72 },
{ time: '11:00', price: 42600, emotion: 68 },
{ time: '12:00', price: 43100, emotion: 65 },
{ time: '13:00', price: 42900, emotion: 70 },
{ time: '14:00', price: 43400, emotion: 78 },
{ time: '15:00', price: 43200, emotion: 80 },
{ time: '16:00', price: 43600, emotion: 82 }
]);
const [tradeStats] = useState({
todayPnL: 245.50,
winRate: 68,
totalTrades: 12,
emotionalScore: 75
});
const frequencies = {
stress: { hz: 528, name: "Stress Relief", purpose: "Calm your nervous system", color: "bg-blue-500" },
fear: { hz: 396, name: "Fear Release", purpose: "Reduces fear response", color: "bg-purple-500" },
revenge: { hz: 417, name: "Emotional Reset", purpose: "Clear negative patterns", color: "bg-orange-500" },
overconfidence: { hz: 741, name: "Clarity & Awareness", purpose: "Intuition and clarity", color: "bg-yellow-500" },
fatigue: { hz: 963, name: "Mental Activation", purpose: "Focus and energy", color: "bg-green-500" },
discipline: { hz: 639, name: "Balance & Harmony", purpose: "Emotional balance", color: "bg-pink-500" }
};
const calculateEmotionalScore = () => {
const { stress, sleep, eagerness, impatience, chasingLosses } = checkinAnswers;
// Better scoring - low stress is good, good sleep is good, etc.
const stressScore = (11 - stress) * 10; // Low stress = high score
const sleepScore = sleep * 10; // Good sleep = high score
const eagernessScore = eagerness <= 7 ? eagerness * 8 : (15 - eagerness) * 6; // Moderate eagerness is best
const impatienceScore = (11 - impatience) * 9; // Low impatience = high score
const chasingScore = (11 - chasingLosses) * 11; // Not chasing = high score
const totalScore = (stressScore + sleepScore + eagernessScore + impatienceScore + chasingScore) / 5;
const finalScore = Math.min(100, Math.round(totalScore));
let risk, bias, recommendation, recommendedFreq, winProbability, tradingTips, frequencyPlan;
if (finalScore >= 75) {
risk = 'optimal';
winProbability = Math.min(85, 65 + Math.round((finalScore - 75) / 2));
if (stress <= 3 && sleep >= 7) {
bias = 'β
Peak Mental Performance';
} else if (sleep >= 8) {
bias = 'β
Well-Rested & Focused';
} else {
bias = 'β
Balanced & Disciplined';
}
recommendation = `Excellent trading state! Your emotional discipline is strong. You have a ${winProbability}% probability of maintaining your edge today.`;
tradingTips = [
'β Your mind is clear - trust your analysis and stick to your strategy',
'β Take profit at your planned targets, avoid greed',
'β Keep position sizes normal as your risk management is solid',
'β Set a daily profit goal and stop when you reach it'
];
frequencyPlan = stress <= 2 ? 'discipline' : 'stress';
} else if (finalScore >= 55) {
risk = 'caution';
winProbability = Math.min(70, 45 + Math.round((finalScore - 55) / 2));
if (stress > 5) {
bias = 'β οΈ Stress Level Elevated';
frequencyPlan = 'stress';
} else if (impatience > 5) {
bias = 'β οΈ Slight Impatience Detected';
frequencyPlan = 'discipline';
} else if (sleep < 6) {
bias = 'β οΈ Fatigue May Affect Focus';
frequencyPlan = 'fatigue';
} else {
bias = 'β οΈ Mild Emotional Interference';
frequencyPlan = 'stress';
}
recommendation = `You can trade, but exercise caution. Current win probability: ${winProbability}%. Reduce risk and trade conservatively.`;
tradingTips = [
'β’ Reduce position size by 30-50% today',
'β’ Avoid trading during high volatility periods',
'β’ Take breaks every 30 minutes',
'β’ Set tighter stop losses than usual',
'β’ Skip marginal setups - only take A+ trades'
];
} else if (finalScore >= 35) {
risk = 'high';
winProbability = Math.max(25, 30 + Math.round((finalScore - 35) / 3));
if (chasingLosses > 6) {
bias = 'π΄ Revenge Trading Alert';
frequencyPlan = 'revenge';
} else if (stress > 7) {
bias = 'π΄ High Stress - Impaired Judgment';
frequencyPlan = 'stress';
} else if (impatience > 7) {
bias = 'π΄ FOMO & Impulsive Tendencies';
frequencyPlan = 'discipline';
} else {
bias = 'π΄ Multiple Emotional Red Flags';
frequencyPlan = 'stress';
}
recommendation = `High emotional risk detected (${winProbability}% success rate). Strong suggestion: Limit trading or take the day off. If you must trade, use minimal position sizes.`;
tradingTips = [
'β οΈ Reduce position size to 20% of normal',
'β οΈ Set a maximum of 2-3 trades for today',
'β οΈ Use demo account if possible',
'β οΈ Have a trusted trading buddy monitor you',
'β οΈ Use frequency therapy BEFORE trading'
];
setShowWarning(true);
} else {
risk = 'critical';
winProbability = Math.max(15, Math.round(finalScore / 2));
bias = 'π Critical Emotional State';
frequencyPlan = chasingLosses > 7 ? 'revenge' : 'stress';
recommendation = `STOP: Your emotional state is extremely compromised (${winProbability}% success rate). Trading today will likely result in losses. Take the day off, use healing frequencies, and come back tomorrow.`;
tradingTips = [
'π DO NOT TRADE TODAY - Your account is at serious risk',
'π Use frequency therapy for at least 15 minutes',
'π Take a walk, exercise, or meditate',
'π Review past trades that went well',
'π Come back tomorrow with fresh perspective'
];
setShowWarning(true);
}
setEmotionScore({
score: finalScore,
risk,
bias,
recommendation,
recommendedFreq: frequencyPlan,
winProbability,
tradingTips
});
};
const playFrequency = (freqKey) => {
if (isPlaying && currentFrequency === freqKey) {
stopFrequency();
return;
}
stopFrequency();
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gainNode = ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(frequencies[freqKey].hz, ctx.currentTime);
gainNode.gain.setValueAtTime(0.3, ctx.currentTime);
osc.connect(gainNode);
gainNode.connect(ctx.destination);
osc.start();
setAudioContext(ctx);
setOscillator(osc);
setCurrentFrequency(freqKey);
setIsPlaying(true);
};
const stopFrequency = () => {
if (oscillator) {
oscillator.stop();
setOscillator(null);
}
if (audioContext) {
audioContext.close();
setAudioContext(null);
}
setIsPlaying(false);
setCurrentFrequency(null);
};
const saveJournalEntry = () => {
const entry = {
date: new Date().toLocaleDateString(),
emotionScore: emotionScore?.score || 0,
risk: emotionScore?.risk || 'unknown',
frequencyUsed: currentFrequency ? frequencies[currentFrequency].name : 'None',
postTrade: postTradeAnswers,
timestamp: Date.now()
};
setJournalEntries([entry, ...journalEntries]);
setPostTradeAnswers({
followedPlan: '',
emotionsControl: '',
revengeTrade: '',
frequencyHelp: ''
});
alert('Journal entry saved!');
};
useEffect(() => {
return () => {
stopFrequency();
};
}, []);
return (
{/* Header */}
{/* Navigation Tabs */}
{[
{ id: 'dashboard', label: 'Trading Dashboard', icon: TrendingUp },
{ id: 'checkin', label: 'Daily Check-In', icon: Brain },
{ id: 'frequency', label: 'Frequency Therapy', icon: Activity },
{ id: 'posttrade', label: 'Post-Trade Review', icon: Calendar },
{ id: 'journal', label: 'Trading Journal', icon: BookOpen }
].map(tab => (
setActiveTab(tab.id)}
className={`flex items-center gap-2 px-6 py-3 rounded-lg font-semibold transition-all ${
activeTab === tab.id
? 'bg-purple-600 text-white shadow-lg shadow-purple-500/50'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
{tab.label}
))}
{/* Trading Dashboard Tab */}
{activeTab === 'dashboard' && (
{/* Stats Cards */}
Today's P&L
${tradeStats.todayPnL.toFixed(2)}
{tradeStats.winRate}%
8 wins / 4 losses
Total Trades
{tradeStats.totalTrades}
Today's session
Emotional Score
{tradeStats.emotionalScore}
π΅ Optimal State
{/* Charts */}
{/* Price Chart */}
{/* Emotional Score Chart */}
Your Emotional Stability
{/* Quick Actions */}
Quick Actions
setActiveTab('checkin')}
className="bg-white border-2 border-purple-300 text-gray-800 px-6 py-4 rounded-lg font-semibold hover:bg-purple-50 transition-all flex items-center justify-center gap-2"
>
Start Emotion Check-In
setActiveTab('frequency')}
className="bg-white border-2 border-pink-300 text-gray-800 px-6 py-4 rounded-lg font-semibold hover:bg-pink-50 transition-all flex items-center justify-center gap-2"
>
Use Frequency Therapy
setActiveTab('posttrade')}
className="bg-white border-2 border-blue-300 text-gray-800 px-6 py-4 rounded-lg font-semibold hover:bg-blue-50 transition-all flex items-center justify-center gap-2"
>
Log Trade Review
{/* Trading Tips */}
π§ Today's Mental Trading Tips
β
Your emotional score is optimal - maintain this state by taking breaks every 60 minutes
β’
Win rate above 65% indicates good emotional discipline - keep following your trading plan
βͺ
Consider using 528 Hz frequency during volatile market sessions for stress relief
)}
{/* Daily Check-In Tab */}
{activeTab === 'checkin' && (
Emotional Check-In Scanner
{!emotionScore ? (
{[
{ key: 'stress', label: 'How stressed do you feel? (1=Calm, 10=Very Stressed)' },
{ key: 'sleep', label: 'Did you sleep well? (1=Terrible, 10=Excellent)' },
{ key: 'eagerness', label: 'How eager are you to trade today? (1=Not at all, 10=Extremely)' },
{ key: 'impatience', label: 'Are you feeling impatient? (1=Very Patient, 10=Very Impatient)' },
{ key: 'chasingLosses', label: 'Are you chasing losses? (1=Not at all, 10=Definitely)' }
].map(question => (
))}
Analyze My Emotional State
) : (
{showWarning && emotionScore.risk === 'high' && (
β οΈ DO NOT TRADE TODAY
Your emotional profile indicates extremely high risk. Trading today may lead to significant losses. Take a break, use frequency therapy, and come back tomorrow.
)}
Emotional Score
{emotionScore.score}
Mental Risk Rating:
{emotionScore.risk === 'optimal' ? 'π΅ OPTIMAL' :
emotionScore.risk === 'caution' ? 'π‘ CAUTION' :
emotionScore.risk === 'critical' ? 'π CRITICAL' :
'π΄ HIGH RISK'}
Detected State:
{emotionScore.bias}
Win Probability Today:
= 70 ? 'text-green-600' :
emotionScore.winProbability >= 50 ? 'text-yellow-600' :
'text-red-600'
}`}>
{emotionScore.winProbability}%
= 70 ? 'bg-green-500' :
emotionScore.winProbability >= 50 ? 'bg-yellow-500' :
'bg-red-500'
}`}
style={{ width: `${emotionScore.winProbability}%` }}
>
{emotionScore.recommendation}
π Trading Tips for Today:
{emotionScore.tradingTips.map((tip, index) => (
{tip}
))}
π΅ Recommended Frequency Therapy:
{frequencies[emotionScore.recommendedFreq].name} ({frequencies[emotionScore.recommendedFreq].hz} Hz)
{frequencies[emotionScore.recommendedFreq].purpose}
{
setActiveTab('frequency');
playFrequency(emotionScore.recommendedFreq);
}}
className="w-full bg-purple-600 hover:bg-purple-700 text-white py-3 rounded-lg font-semibold transition-all flex items-center justify-center gap-2"
>
Start Frequency Therapy Now
{
setEmotionScore(null);
setShowWarning(false);
}}
className="w-full bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 rounded-lg font-semibold transition-all flex items-center justify-center gap-2"
>
Take Another Check-In
)}
)}
{/* Frequency Therapy Tab */}
{activeTab === 'frequency' && (
Frequency Correction Therapy
{Object.entries(frequencies).map(([key, freq]) => (
playFrequency(key)}
>
{freq.name}
{currentFrequency === key && isPlaying ? (
) : (
)}
{freq.hz} Hz
{freq.purpose}
{currentFrequency === key && isPlaying && (
)}
))}
{emotionScore && (
Recommended for you: {frequencies[emotionScore.recommendedFreq].name} ({frequencies[emotionScore.recommendedFreq].hz} Hz)
)}
π‘ How to Use:
β’ Click any frequency to start playing
β’ Listen for 2-5 minutes for optimal effect
β’ Use headphones for better results
β’ Combine with deep breathing for enhanced benefits
)}
{/* Post-Trade Review Tab */}
{activeTab === 'posttrade' && (
Post-Trade Emotional Review
Did you follow your trading plan?
setPostTradeAnswers({...postTradeAnswers, followedPlan: e.target.value})}
className="w-full bg-white border-2 border-gray-300 rounded-lg px-4 py-3 text-gray-800 focus:border-purple-500 focus:outline-none"
>
Select...
Yes, completely
Mostly, with minor deviations
Somewhat, broke several rules
No, ignored my plan
Did emotions control your trades?
setPostTradeAnswers({...postTradeAnswers, emotionsControl: e.target.value})}
className="w-full bg-white border-2 border-gray-300 rounded-lg px-4 py-3 text-gray-800 focus:border-purple-500 focus:outline-none"
>
Select...
No, I stayed disciplined
Slightly influenced
Significantly affected my decisions
Completely driven by emotions
Did you revenge trade after a loss?
setPostTradeAnswers({...postTradeAnswers, revengeTrade: e.target.value})}
className="w-full bg-white border-2 border-gray-300 rounded-lg px-4 py-3 text-gray-800 focus:border-purple-500 focus:outline-none"
>
Select...
No
Tempted but resisted
Once or twice
Multiple times
What frequency helped you most today?
setPostTradeAnswers({...postTradeAnswers, frequencyHelp: e.target.value})}
className="w-full bg-white border-2 border-gray-300 rounded-lg px-4 py-3 text-gray-800 focus:border-purple-500 focus:outline-none"
>
Select...
Didn't use any
{Object.entries(frequencies).map(([key, freq]) => (
{freq.name} ({freq.hz} Hz)
))}
Save to Trading Journal
)}
{/* Trading Journal Tab */}
{activeTab === 'journal' && (
Emotional Trading Journal
{journalEntries.length === 0 ? (
No journal entries yet. Complete a post-trade review to start building your journal.
) : (
{journalEntries.map((entry, index) => (
{entry.date}
Score: {entry.emotionScore}
Followed Plan:
{entry.postTrade.followedPlan}
Emotional Control:
{entry.postTrade.emotionsControl}
Revenge Trading:
{entry.postTrade.revengeTrade}
Frequency Used:
{entry.frequencyUsed}
))}
)}
)}
{/* Footer */}
π§ Remember: 90% of trading mistakes are emotional, not strategic
This tool is your psychological guardrail for better trading decisions
Visit Medihertz Blogs
{' '}for more healing frequency tools and wellness resources
);
};
export default EmotionTradingAssistant;