Spaces:
Running
Running
Upload pages/index.js with huggingface_hub
Browse files4 unmodified lines567891011123 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931944 unmodified linesimport MarketChart from '../components/MarketChart'import SignalPanel from '../components/SignalPanel'import JsonUploadModal from '../components/JsonUploadModal'import { getKnowledgeBase, addKnowledgeBaseRules, removeCustomRule, clearAllCustomRules, getCustomRulesCount } from '../lib/knowledge-base'import { initializeMarket, getMarketTick, analyzeMarket } from '../lib/market-simulator'export default function Home() {const [knowledgeBase, setKnowledgeBase] = useState([])3 unmodified linesconst [isRunning, setIsRunning] = useState(false)const [isModalOpen, setIsModalOpen] = useState(false)const [customRulesCount, setCustomRulesCount] = useState(0)// Keep only last 50 points for chartconst MAX_DATA_POINTS = 50const chartRef = useRef(null)useEffect(() => {// Load Knowledge Baseconst kb = getKnowledgeBase()setKnowledgeBase(kb)setCustomRulesCount(getCustomRulesCount())// Initialize Market SimulatorinitializeMarket()}, [])useEffect(() => {let intervalif (isRunning) {interval = setInterval(() => {const tick = getMarketTick()setCurrentTick(tick)// Update Chart DatasetMarketData(prev => {const newData = [...prev, {time: new Date().toLocaleTimeString(),price: tick.price}]if (newData.length > MAX_DATA_POINTS) {return newData.slice(newData.length - MAX_DATA_POINTS)}return newData})// Analyze against Knowledge Baseconst newSignals = analyzeMarket(tick, knowledgeBase)if (newSignals.length > 0) {setSignals(newSignals)}}, 1000) // 1 second tick}return () => clearInterval(interval)}, [isRunning, knowledgeBase])const toggleSimulation = () => {setIsRunning(!isRunning)}const handleFileUpload = (event) => {const file = event.target.files[0]if (!file) returnconst reader = new FileReader()reader.onload = (e) => {try {const rules = JSON.parse(e.target.result)if (Array.isArray(rules)) {const added = addKnowledgeBaseRules(rules)setKnowledgeBase(getKnowledgeBase())setCustomRulesCount(getCustomRulesCount())}} catch (error) {console.error('Invalid JSON file:', error)}}reader.readAsText(file)}const handleTextUpload = (rules) => {addKnowledgeBaseRules(rules)setKnowledgeBase(getKnowledgeBase())setCustomRulesCount(getCustomRulesCount())}const handleRemoveRule = (ruleId) => {if (ruleId === 'all') {clearAllCustomRules()} else {removeCustomRule(ruleId)}setKnowledgeBase(getKnowledgeBase())setCustomRulesCount(getCustomRulesCount())}return (<><Head><title>AI Stock Trader | JSON Knowledge Base</title><meta name="description" content="Real-time stock trading simulation based on JSON knowledge base" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link rel="icon" href="/favicon.ico" /></Head><div className="min-h-screen bg-dark-900 flex flex-col"><Header /><main className="flex-grow container mx-auto px-4 py-6 space-y-6">{/* Control Bar */}<div className="flex flex-col md:flex-row justify-between items-center gap-4 bg-dark-800 p-4 rounded-xl border border-dark-700"><div><h2 className="text-lg font-bold text-white">Trading Dashboard</h2><p className="text-sm text-dark-400">Real-time analysis based on loaded JSON rules</p></div><div className="flex items-center space-x-4"><buttononClick={() => setIsModalOpen(true)}className="btn-secondary flex items-center space-x-2"><span>📄</span><span>Add JSON Rules</span></button><buttononClick={toggleSimulation}className={`px-6 py-2 rounded-lg font-medium transition-all ${isRunning? 'bg-danger/20 text-danger border border-danger hover:bg-danger/30': 'bg-success/20 text-success border border-success hover:bg-success/30'}`}>{isRunning ? 'Stop Simulation' : 'Start Live Feed'}</button></div></div>{/* Main Grid */}<div className="grid grid-cols-1 lg:grid-cols-4 gap-6">{/* Left Column: Knowledge Base (1/4 width) */}<div className="lg:col-span-1 h-[600px]"><KnowledgePanelrules={knowledgeBase}onUpload={handleFileUpload}onRemoveRule={handleRemoveRule}customRulesCount={customRulesCount}/></div>{/* Right Column: Trading Interface (3/4 width) */}<div className="lg:col-span-3 space-y-6">{/* Signals & Stats */}<SignalPanel signals={signals} marketData={currentTick} />{/* Chart */}<MarketChart data={marketData} />{/* Info Banner */}<div className="bg-primary-900/20 border border-primary-500/30 rounded-lg p-4 flex items-start space-x-3"><div className="text-primary-400 mt-1"><svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></div><div><h4 className="text-sm font-medium text-primary-300">How it works</h4><p className="text-sm text-dark-400 mt-1">This application loads trading strategies from a JSON knowledge base. You can add your own custom rules by uploading JSON files or pasting JSON directly. The system simulates real-time market data and compares current indicators (RSI, Volume, Price) against your rules to generate Long/Short signals automatically.</p></div></div></div></div></main></div><JsonUploadModalisOpen={isModalOpen}onClose={() => setIsModalOpen(false)}onUpload={handleTextUpload}/></>)}4 unmodified lines56789101112133 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031044 unmodified linesimport MarketChart from '../components/MarketChart'import SignalPanel from '../components/SignalPanel'import JsonUploadModal from '../components/JsonUploadModal'import AssetSelector from '../components/AssetSelector'import { getKnowledgeBase, addKnowledgeBaseRules, removeCustomRule, clearAllCustomRules, getCustomRulesCount } from '../lib/knowledge-base'import { fetchMarketData, calculateRSI } from '../lib/market-data'export default function Home() {const [knowledgeBase, setKnowledgeBase] = useState([])3 unmodified linesconst [isRunning, setIsRunning] = useState(false)const [isModalOpen, setIsModalOpen] = useState(false)const [customRulesCount, setCustomRulesCount] = useState(0)const [selectedAsset, setSelectedAsset] = useState('bitcoin')const [isLoading, setIsLoading] = useState(false)const MAX_DATA_POINTS = 50useEffect(() => {// Load Knowledge Baseconst kb = getKnowledgeBase()setKnowledgeBase(kb)setCustomRulesCount(getCustomRulesCount())}, [])// Real-time Data Fetching LoopuseEffect(() => {let intervalif (isRunning) {const fetchData = async () => {setIsLoading(true)try {const data = await fetchMarketData(selectedAsset)if (data && !data.error) {// Update Current Tickconst rsi = calculateRSI(data.history.map(h => h.price))const tick = {price: data.price,rsi: rsi,volume: data.volume,trend: data.trend,timestamp: data.timestamp}setCurrentTick(tick)// Update Chart DatasetMarketData(data.history)// Analyze against Knowledge Base// Note: We analyze the latest tick against rulesconst newSignals = analyzeTick(tick, knowledgeBase)if (newSignals.length > 0) {setSignals(newSignals)}}} catch (error) {console.error("Fetch error:", error)} finally {setIsLoading(false)}}// Initial fetchfetchData()// Poll every 10 seconds (CoinGecko free tier limit friendly)// For production, use WebSockets or a paid API with higher rate limitsinterval = setInterval(fetchData, 10000)}return () => clearInterval(interval)}, [isRunning, selectedAsset, knowledgeBase])// Helper to analyze a single tick against rules (extracted from lib for clarity)const analyzeTick = (data, kb) => {const signals = []kb.forEach(rule => {let match = falselet reason = ""if (rule.condition.includes("RSI < 30") && data.rsi < 30) {match = truereason = `RSI is ${data.rsi.toFixed(2)} (Oversold)`} else if (rule.condition.includes("RSI > 70") && data.rsi > 70) {match = truereason = `RSI is ${data.rsi.toFixed(2)} (Overbought)`} else if (rule.condition.includes("Volume") && data.volume > 2000000) {match = truereason = `Volume spike detected`}if (match) {signals.push({rule: rule.rule,action: rule.action === 'FOLLOW_TREND' ? (data.trend === 'UP' ? 'LONG' : 'SHORT') : rule.action,confidence: rule.confidence,reason: reason,isCustom
pages/index.js+67-157