### Install Dependencies and Start StonkQuest Application Source: https://github.com/aditikilledar/stonksquest/blob/main/README.md This snippet details the steps required to clone the repository, navigate into the project directory, install necessary dependencies (NES.css and project-specific ones), and finally start the StonkQuest application. It assumes Node.js and Git are already installed. ```bash git clone [repository-url] cd my-stonks npm install nes.css npm install npm start ``` -------------------------------- ### React Router Setup for StonkQuest Navigation Source: https://context7.com/aditikilledar/stonksquest/llms.txt Configures the main application router using react-router-dom to manage navigation between different game scenarios and the home page. It defines routes for home, various scenario pages, and potential future routes like 'test'. ```tsx import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import Home from './components/home'; import ScenarioOne from './scenarios/ScenarioOne'; import ScenarioTwo from './scenarios/ScenarioTwo'; function App() { return ( } /> } /> } /> } /> } /> } /> ); } export default App; ``` -------------------------------- ### Portfolio State Management Interfaces and Logic in StonkQuest Source: https://context7.com/aditikilledar/stonksquest/llms.txt Defines TypeScript interfaces for managing stock and portfolio data, including wallet balance, cash, and stock shares. It also includes example state initialization, total portfolio value calculation, and profit calculation logic for the game. ```typescript interface Stock { shares: number; } interface PortfolioI { wallet: number; // Remaining bank funds cash: number; // Cash from sold stocks stocks: Stock[]; // Array of stock holdings } // Initialize portfolio with $1000 const [portfolio, setPortfolio] = useState({ wallet: 1000, cash: 0, stocks: [{ shares: 0 }, { shares: 0 }, { shares: 0 }] }); // Calculate total portfolio value const totalPortfolioValue = portfolio.stocks.reduce((total, stock, index) => { const stockValue = stock.shares * (prices[index][day] || 0); return total + stockValue; }, 0).toFixed(2); // Calculate profit const investmentMoneyLeft = Math.max(portfolio.wallet, 0); const profit = Math.max( Number(portfolio.cash) - (1000 - Number(investmentMoneyLeft)), -9999 ); ``` -------------------------------- ### Contextual Hint System in React TSX Source: https://context7.com/aditikilledar/stonksquest/llms.txt Implements a day-range based contextual hint system for players. It uses a predefined array of hints, each associated with a start and end day. The system displays a relevant hint based on the current game day and allows the player to close it. Dependencies include React's useState hook. ```tsx const hints = [ { dayStart: 0, dayEnd: 10, hint: "Monitor the housing market closely. If prices fall, consider buying undervalued stocks." }, { dayStart: 11, dayEnd: 27, hint: "Mortgage defaults may lead to stock price drops. Hold off on buying bank stocks." }, { dayStart: 28, dayEnd: 35, hint: "During market panic, consider buying stocks that are undervalued." } ]; const [currentHint, setCurrentHint] = useState(null); const requestHint = () => { const dayHint = hints.find(hint => hint.dayStart <= day && day <= hint.dayEnd); setCurrentHint(dayHint ? dayHint.hint : "Consider watching for opportunities."); }; const closeHint = () => { setCurrentHint(null); }; // Hint display { currentHint && (

Hint: {currentHint}

) } ``` -------------------------------- ### Simulate Tech Boom/Bust Phases in TypeScript Source: https://context7.com/aditikilledar/stonksquest/llms.txt This code models a 200-day 'Tech Boom or Bust' scenario focused on the technology sector. It uses React hooks to manage the simulation day and stock prices, applying different growth and volatility factors across distinct phases (boom, slowdown, high volatility, stabilization). It depends on `day` and `setPrices` state variables. ```tsx const TechBoomOrBustScenario: React.FC = () => { const [day, setDay] = useState(0); const [prices, setPrices] = useState([ [150], // Tech Innovators [200], // Global Digi Inc. [100] // EcoTech Solutions ]); const timelineMessages = [ { day: 30, message: "AI advancements fuel tech stock growth!" }, { day: 60, message: "Data privacy laws are announced, increasing compliance costs." }, { day: 100, message: "Mixed earnings season: some stocks soar, others plunge." } ]; // Tech boom/bust phases useEffect(() => { if (day > 0) { setPrices((prevPrices) => prevPrices.map((priceSeries) => { const previousPrice = priceSeries[day - 1]; let newPrice; if (day <= 30) { // Strong growth: +3% to +8% newPrice = previousPrice * (1 + Math.random() * 0.05 + 0.03); } else if (day > 30 && day <= 60) { // Slowdown: -1.5% to +2% newPrice = previousPrice * (1 + Math.random() * 0.02 - 0.015); } else if (day > 60 && day <= 100) { // High volatility: ±10% const volatilityFactor = Math.random() < 0.5 ? 1 : -1; newPrice = previousPrice * (1 + volatilityFactor * Math.random() * 0.1); } else { // Stabilization: -1.5% to +3% newPrice = previousPrice * (1 + Math.random() * 0.03 - 0.015); } return [...priceSeries, newPrice]; })); } }, [day]); // Extended duration const isGameOver = day >= 200; const isProfitMade = Number(totalPortfolioValue) > 1000; }; ``` -------------------------------- ### Home Component for Scenario Selection in StonkQuest Source: https://context7.com/aditikilledar/stonksquest/llms.txt Implements the home screen component for StonkQuest, providing a user interface for selecting different stock market simulation scenarios. It uses the useNavigate hook from react-router-dom to handle navigation to selected scenarios. ```tsx import React from 'react'; import { useNavigate } from 'react-router-dom'; const Home: React.FC = () => { const navigate = useNavigate(); return (

StonkQuest

Practice Stock Market Scenarios

); }; export default Home; ``` -------------------------------- ### Manage Stock Buy/Sell Transactions (TypeScript) Source: https://context7.com/aditikilledar/stonksquest/llms.txt Implements logic for buying and selling stocks, managing the user's wallet and cash. The `handleBuy` function checks for sufficient funds and prioritizes deducting from the wallet before using cash. `handleSell` updates cash and stock quantities. ```tsx const handleBuy = (index: number) => { const price = prices[index][day]; // Check if sufficient funds available if (portfolio.wallet + portfolio.cash >= price) { setPortfolio((prevPortfolio) => { let newWallet = prevPortfolio.wallet; let newCash = prevPortfolio.cash; // Deduct from wallet first, then cash if (newWallet >= price) { newWallet -= price; } else { const remainingAmount = price - newWallet; newWallet = 0; newCash -= remainingAmount; } const updatedStocks = prevPortfolio.stocks.map((stock, i) => i === index ? { shares: stock.shares + 1 } : stock ); return { ...prevPortfolio, wallet: newWallet, cash: newCash, stocks: updatedStocks, }; }); } }; const handleSell = (index: number) => { const price = prices[index][day] || 0; const sharesToSell = 1; if (portfolio.stocks[index].shares >= sharesToSell) { setPortfolio((prevPortfolio) => ({ ...prevPortfolio, cash: prevPortfolio.cash + (price * sharesToSell), stocks: prevPortfolio.stocks.map((stock, i) => i === index ? { ...stock, shares: stock.shares - sharesToSell } : stock ) })); } }; ``` -------------------------------- ### Simulate IPO Volatility in TypeScript Source: https://context7.com/aditikilledar/stonksquest/llms.txt This code simulates the high volatility of an Initial Public Offering (IPO) stock over an 80-day period. It uses React's useEffect hook to update stock prices daily, applying a ±10% fluctuation to the IPO stock and a ±3% fluctuation to regular stocks. It depends on `day` and `setPrices` from the component's state. ```tsx const stockSymbols = ["Global BankCorp", "SafeHold Realty Trust", "IPO TechCorp"]; const stockInfo = [ { title: "IPO TechCorp", description: "High volatility! New and exciting tech startup. Great promise, significant risks due to lack of track record." } ]; // IPO-specific price volatility at day 3 useEffect(() => { if (day > 0 && day <= 80) { setPrices((prevPrices) => prevPrices.map((priceSeries, index) => { const previousPrice = priceSeries[day - 1]; let newPrice; if (index === 2) { // IPO stock (index 2) // High volatility: ±10% newPrice = previousPrice * (1 + (Math.random() - 0.5) * 0.1); } else { // Regular stocks: ±3% newPrice = previousPrice * (1 + (Math.random() - 0.5) * 0.03); } return [...priceSeries, newPrice]; })); } }, [day]); ``` -------------------------------- ### Scenario One: Market Crash Game Logic in React TSX Source: https://context7.com/aditikilledar/stonksquest/llms.txt Defines the game logic for 'Scenario One: Market Crash', simulating the 2008 financial crisis. It includes stock information relevant to the scenario and checks for game over conditions based on the number of days passed and profit made. This component renders a game over overlay with win/loss status and a play again button. Dependencies include React. ```tsx const ScenarioOne: React.FC = () => { const stockInfo = [ { title: "Global BankCorp", description: "Medium Risk. International banking institution undergoing restructuring." }, { title: "SafeHold Realty Trust", description: "Good performer! Premier REIT with stable YoY growth." }, { title: "GreenEnergy Innovations Inc.", description: "High Risk! Renewable energy company with unstable management." } ]; // Win condition: Net gain > 0 after 80 days const isGameOver = day >= 80; const isProfitMade = Number(profit) > 0; return (
{isGameOver && (

GAME OVER

{isProfitMade ? 'YOU WIN' : 'YOU LOSE'}

)}
); }; ``` -------------------------------- ### Stock Information Dialog in React Source: https://context7.com/aditikilledar/stonksquest/llms.txt Implements an interactive dialog component to display detailed stock information using React hooks. It manages the dialog's visibility state and renders company details based on user interaction. Dependencies include React's useState hook. ```tsx const [activeDialog, setActiveDialog] = useState(null); const stockInfo = [ { title: "TechWave Solutions", description: "Medium Risk. A rising star in the software and AI sector, with strong growth but facing increasing competition." } ]; const openDialog = (index: number) => setActiveDialog(index); const closeDialog = () => setActiveDialog(null); // Render dialog {activeDialog === index && (

{stockInfo[index].title}

{stockInfo[index].description}

)} ``` -------------------------------- ### Real-Time Stock Price Charts in React TSX Source: https://context7.com/aditikilledar/stonksquest/llms.txt Renders real-time stock price line charts using react-chartjs-2 and Chart.js. It requires importing necessary Chart.js components and registering them. The `createChartData` function formats price data into a structure compatible with Chart.js, and the component maps over stock data to display individual charts. Dependencies include react-chartjs-2, chart.js, and React. ```tsx import { Line } from 'react-chartjs-2'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js'; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend ); const createChartData = (priceSeries: number[]) => ({ labels: Array.from({ length: day + 1 }, (_, i) => (i + 1).toString()), datasets: [ { label: 'Stock Price', data: priceSeries, fill: false, borderColor: 'green', }, ], }); // Render chart for each stock { prices.map((priceSeries, index) => { const currentPrice = priceSeries[day]?.toFixed(2) || "0.00"; return (

{stockSymbols[index]} ${currentPrice}

); }); } ``` -------------------------------- ### Simulate Stock Prices with Dynamic Volatility (TypeScript) Source: https://context7.com/aditikilledar/stonksquest/llms.txt Simulates daily stock price updates for multiple stocks. It uses React's useState and useEffect hooks to manage the day count and price series, applying different volatility levels based on the current day in the simulation. The simulation pauses based on external state. ```tsx const [day, setDay] = useState(0); const [prices, setPrices] = useState([ [100], // Stock A initial price [120], // Stock B initial price [80] // Stock C initial price ]); // Auto-increment day every 500ms when not paused useEffect(() => { if (!paused) { const interval = setInterval(() => setDay((prevDay) => prevDay + 1), 500); return () => clearInterval(interval); } }, [paused]); // Update prices based on scenario phase useEffect(() => { if (day > 0 && day <= 80) { setPrices((prevPrices) => prevPrices.map((priceSeries) => { const previousPrice = priceSeries[day - 1]; let newPrice; if (day < 10) { // Early phase: slight decline (-2%) newPrice = previousPrice * (1 - Math.random() * 0.02); } else if (day < 27) { // Crisis begins: moderate decline (-1%) newPrice = previousPrice * (1 - Math.random() * 0.01); } else if (day < 35) { // Recovery signs: slight growth (+0.5%) newPrice = previousPrice * (1 + Math.random() * 0.005); } else { // Full recovery: strong growth (+3%) newPrice = previousPrice * (1 + Math.random() * 0.03); } return [...priceSeries, newPrice]; })); } }, [day]); ``` -------------------------------- ### Scenario Two: Mergers & Acquisitions Price Updates in React TSX Source: https://context7.com/aditikilledar/stonksquest/llms.txt Handles dynamic stock price updates for 'Scenario Two: Mergers & Acquisitions' using React's useEffect hook. The code simulates market reactions to merger rumors, announcements, and integration challenges over a 60-day period. Price adjustments are based on the current day and the specific stock's role in the merger. Dependencies include React's useEffect and useState hooks. ```tsx const timelineMessages = [ { day: 10, message: "Rumors suggest TechWave Solutions might merge with a larger tech firm!" }, { day: 20, message: "Breaking News: TechWave Solutions officially announces a merger with Urban AgroGrowth." }, { day: 40, message: "Concerns over integration challenges are impacting the merged company's performance." }, { day: 60, message: "The merged company reports either strong synergies or mounting issues." } ]; // Price updates favor merger target useEffect(() => { if (day > 0 && day <= 60) { setPrices(prevPrices => prevPrices.map((priceSeries, index) => { const previousPrice = priceSeries[day - 1]; let newPrice; if (day < 10) { // Pre-merger rumors: target stock rises newPrice = index === 0 ? previousPrice * (1 + Math.random() * 0.02) : previousPrice * (1 - Math.random() * 0.01); } else if (day < 20) { // Post-announcement spike: target stock +5% newPrice = index === 0 ? previousPrice * (1 + Math.random() * 0.05) : previousPrice * (1 + Math.random() * 0.01); } else if (day < 40) { // Integration concerns: volatility newPrice = previousPrice * (1 + Math.random() * 0.03 - 0.015); } else { // Final outcome phase: target performs well newPrice = index === 0 ? previousPrice * (1 + Math.random() * 0.04) : previousPrice * (1 + Math.random() * 0.01 - 0.005); } return [...priceSeries, newPrice]; })); } }, [day]); ``` -------------------------------- ### Implement Timeline-Based Market Alert System (TypeScript) Source: https://context7.com/aditikilledar/stonksquest/llms.txt Features a system for displaying scenario-specific market event alerts triggered on predefined days. It uses React state to manage alert messages and track shown alerts, pausing the simulation when an alert is active. Alerts are closed via a button click. ```tsx const timelineMessages = [ { day: 10, message: "Housing market weakens as home prices start to fall." }, { day: 27, message: "Mortgage defaults rise, hitting banks with losses." }, { day: 35, message: "A major company, Lehman Brothers, collapses, triggering panic." }, { day: 42, message: "Global markets plunge as fears of recession grow." }, { day: 50, message: "Government bailouts aim to stabilize the market." }, { day: 60, message: "Early signs of recovery as market stabilizes." } ]; const [alertMessage, setAlertMessage] = useState(null); const [shownAlerts, setShownAlerts] = useState>(new Set()); const checkForAlert = () => { const alert = timelineMessages.find(event => day < event.day); if (alert && !shownAlerts.has(alert.day)) { setAlertMessage(alert.message); setPaused(true); // Pause game when alert shown setShownAlerts(new Set(shownAlerts).add(alert.day)); } }; const handleCloseAlert = () => { setAlertMessage(null); setIsResumeEnabled(true); }; // Display alert overlay { alertMessage && (

Alert: {alertMessage}

) } ``` -------------------------------- ### Simulate Earnings Report Impact on Stock Prices in TypeScript Source: https://context7.com/aditikilledar/stonksquest/llms.txt This code simulates stock price behavior during a 40-day earnings report season. It uses React's useEffect hook to adjust prices based on predefined events like earnings beats, misses, and general market volatility. The logic differentiates price movements based on specific days and stock indices. It relies on the `day` state variable and the `setPrices` function. ```tsx const timelineMessages = [ { day: 10, message: "Anticipation builds ahead of TechWave Solutions's quarterly earnings report." }, { day: 20, message: "TechWave Solutions's earnings beat expectations, driving stock prices higher." }, { day: 30, message: "Urban AgroGrowth's earnings report reveals a surprising revenue drop." }, { day: 40, message: "AeroNex Industries reports mixed earnings, causing volatility." } ]; // Earnings-driven price changes useEffect(() => { if (day > 0 && day <= 40) { setPrices((prevPrices) => prevPrices.map((priceSeries, index) => { const previousPrice = priceSeries[day - 1]; let newPrice; if (day < 10) { // Pre-earnings stability newPrice = previousPrice * (1 + Math.random() * 0.01); } else if (day < 20) { // TechWave beats expectations: +5% newPrice = index === 0 ? previousPrice * (1 + Math.random() * 0.05) : previousPrice * (1 - Math.random() * 0.01); } else if (day < 30) { // Urban AgroGrowth misses: -3% newPrice = index === 1 ? previousPrice * (1 - Math.random() * 0.03) : previousPrice * (1 + Math.random() * 0.01); } else if (day < 40) { // AeroNex volatility: ±5% newPrice = index === 2 ? previousPrice * (1 + Math.random() * 0.05 - 0.025) : previousPrice * (1 + Math.random() * 0.01); } return [...priceSeries, newPrice]; })); } }, [day]); // Shorter scenario: 40 days const isGameOver = day >= 40; ``` -------------------------------- ### Game State Reset on Tab Hidden in React Source: https://context7.com/aditikilledar/stonksquest/llms.txt Resets the game state when the browser tab's visibility changes to 'hidden', preventing potential cheating. It utilizes React's useEffect hook to add and remove a 'visibilitychange' event listener. The reset function updates game variables like day, portfolio, and alerts. ```tsx const resetGame = () => { setDay(0); setPortfolio({ wallet: 1000, cash: 0, stocks: [{ shares: 0 }, { shares: 0 }, { shares: 0 }] }); setPaused(false); setShownAlerts(new Set()); }; useEffect(() => { const handleVisibilityChange = () => { if (document.visibilityState === 'hidden') { resetGame(); } }; window.addEventListener('visibilitychange', handleVisibilityChange); return () => { window.removeEventListener('visibilitychange', handleVisibilityChange); }; }, []); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.