# Project export: traider

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: Trade smarter not harder! Upgrade your financial literacy with traider
- Devpost: https://devpost.com/software/traider
- GitHub: https://github.com/ajagtapdev/traider
- Demo: https://traider-omega.vercel.app/
- Video: https://www.youtube.com/embed/CUTdrkfdz1M?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Context: Best AI Employee Workflow ($2.5k Cash + $2.5k Context API Credits))
- Team: 4 GitHub contributor(s) — Aarush (36 commits), vera chuang (25 commits), Mahika Calyanakoti (13 commits), janani (6 commits)

## Devpost submission (written by the team)

### Inspiration

Finance isn’t a subject commonly taught thoroughly in schools, yet it plays a crucial role in everyone’s lives. Many people, especially students, grow up without exposure to financial concepts, making it challenging for them to navigate real-world financial decisions. This lack of financial knowledge can lead to overwhelming debt, poor savings habits, and financial stress. In our lives, we have seen that these knowledge gaps in finance can cause enormous hurdles when entering college, internships, or the corporate world as young adults struggle to manage their growing debt and earnings.

### What it does

traider is an educational platform that provides beginner investors with mock trading simulations and instantaneous AI-powered feedback for their trades. Scraping REAL historical and current stock data from Yahoo Finance, traders can engage with accurate market data and place their trades over a user-specified simulation duration beginning at a specified start date. Unlike models trained on outdated datasets, our product offers real, relevant market and economic data based on the stock ticker and current date in the simulation, which we then synthesize with NVIDIA to supplement young traders with more robust information to fuel their financial decision-making. This allows users to make informed trades using accurate and up-to-date market information. Our product stands out from other trading simulations in that it allows students to pick any timeframe in the past to put their trading skills to the test. Further, our supplemental market events information provides a more detailed painting of the financial landscape during the simulation, encouraging informed investing. Our dynamic and colorful data insights allow students to examine takeaways, while our AI-powered feedback for each executed trade promotes healthy learning and detailed mistake analysis. The leaderboard and financial calculator features offer a social and educational playground for students to explore the world of trading while gamifying finance like never before.

### How we built it

Frontend: Next.js Tailwind Vercel/v0: We ran multiple versions of v0 to fine-tune and perfect out front end while asking for abstract animations for the background and generated complex containers for the simulator page Shadcn: Awesome built-in Next.js UI library which provided interactive graphic cards for buttons and pop-outs Figma Canva Radix UI Lucid React Backend: NVIDIA: We used NVIDIA and NVIDIA Cloud Compute to test the model. We used NVIDIA bev dev on a T4 GPU Cloud Instance to run a Jupyter notebook through Ubuntu Linux to fine-tune Lama 70b on financial prediction data Vercel Hosting Fast API Perplexity: We used it for the AI stock trading feedback simulator OpenAI: Used NVIDIA llama-70B to generate responsive and instantaneous feedback on stock exchanges. Additionally, provided a section for students to ask questions about the stock market and other financial questions Google Search API: Scrape relevant market and economic events given a stock ticker and a date. Once we scanned financial news websites for economic data, we passed it through NVIDIA using llama 70B to get the best possible market consensus on a stock ticker and synthesize that information to display to users. This enhanced their decision-making process as they decided on how to place trades.

### Challenges we ran into

Finding an accurate LLM to provide users feedback on their trades Providing a layout for the various data visualizations in an aesthetically pleasing and non-overwhelming manner Handling massive amounts of stock data from Yahoo Finance and parsing through it to calculate daily portfolio values with complex mathematical calculations Picking up new technology and integrating with databases with which we have no prior experience, such as Convex Handling the dynamic animations on the homepage Combining the v0 code with preexisting code and integrating the frontend with the backend Real-time data handling: stock and trading information datasets led to rate limits we faced when making our API calls Finding a logo that would encompass our product. We spent a lot of time ideating different designs on Figma

### Accomplishments we're proud of

Backend: We were excited to be able to integrate and leverage AI models, such as Perplexity and Llama 70B, NVIDIA Brev, and cloud computing, for numerous features of our trading simulation. These included providing young investors instantaneous feedback on their trades, parsing through and summarizing market data with Google Search API and Llama 70B, and offering an AI-powered chatbot that answers users' questions and concerns regarding finance and trading. We were also proud to utilize a database technology that was new to us, Convex, to store user information. Through Clerk, we could also set up secure user authentication through Google sign-in. Additionally, we leveraged the Yahoo! Finance API to consolidate and display financial stock data for any time frame the user needed, allowing the user to see detailed stock information, such as high, low, open, close, volume, and more. These complex calls and technology integrations allowed for a seamless user experience and analytical trading dashboard. Frontend: We are proud of our dynamic homepage UI and the detailed and analytical simulator page UI. Their seamless and intuitive interfaces make them easy to use for our young target audience. We paid close attention to the color scheme, ensuring that it aligns with our brand identity and creates a visually cohesive and inviting interface. The result is a user-friendly design that is both functional and appealing, providing an enjoyable experience for users of all experience levels. Additionally, the components we are most proud of are the Homepage for its nifty abstract animations, which make the page more exciting. The home page’s color palette is also bright, giving it a more vibrant feel since it is marketed towards students to encourage them to learn more about finance. Another page we are proud of is the trading simulation and portfolio analytics page. The UI is attractive and enhances the theme. Many of the boxes and the pop-out form offer interactive and dynamic components. We were also proud to be able to offer various features on our page in just 36 hours of coding, from financial calculators to a leaderboard to data visualizations regarding portfolio analytics. We thoroughly enjoyed building this engaging product and integrating the technical backend with an appealing front end.

### What we learned

Through developing this project, we learned about the complexity of designing scalable backend architectures, handling real-time data processing, and optimizing system performance. We learned the importance of efficient database structuring to maintain data integrity while ensuring fast retrieval. Additionally, we also deepened our understanding of financial market mechanics, from order execution to portfolio management, and the challenges involved in simulating a fair and realistic trading environment. Most importantly, we gained valuable experience working collaboratively and iterating design choices to build the most reliable user-centric platform.

### What's next

Next mission for traider is to bring it to the real market with users of all age groups who are students to try our product out. We also plan on implementing more robust features, such as fine-tuning an LLM on trades and historical stock data to provide more tailored insights to users, developing a more social aspect of the platform to allow young investors to share their accomplishments with their networks, and integrating voice-based AI-powered chat support for our younger client base. We would also aim to build AI-generated weekly quizzes and maintain performance metrics and streaks to keep our users rewarded and engaged on a daily. Additionally, we would love to implement cryptocurrency in our platform.

## README (from the GitHub repository)

# 📈 traider - High-Performance AI-Powered Stock Trading Simulator

## 🚀 Inspiration  
Finance isn’t a subject commonly taught thoroughly in schools, yet it plays a crucial role in everyone’s lives. Furthermore, professional trading tools are often inaccessible or too complex for beginners. We created **traider** to bridge this gap, providing a risk-free environment that combines **high-performance C++ analytics** with **AI-driven insights** to help users master the markets.

---

## 🎯 What It Does  
**traider** is a next-generation educational platform that leverages a **hybrid C++/Python architecture** to deliver professional-grade trading simulations:

- 🚀 **High-Performance C++ Core** – Backtesting and technical analysis executed with bare-metal speed.
- 📊 **Real-Time Simulation** – Trade using historical & current data with millisecond-latency processing.
- 🤖 **AI-Powered Feedback** – Instantaneous trade analysis using **Llama 70B** on **NVIDIA Cloud Compute**.
- 📈 **Advanced Technical Indicators** – Real-time calculation of SMA, EMA, RSI, VWAP, and Bollinger Bands using our custom C++ engine.
- 📰 **Market Sentiment Analysis** – AI synthesis of financial news to inform trading decisions.
- 🏆 **Gamified Learning** – Compete on leaderboards and track portfolio performance metrics like Sharpe Ratio and Max Drawdown.

**traider** differentiates itself by running its heavy-lifting simulation logic in **C++**, ensuring accuracy and scalability, while using Python and AI for high-level reasoning and user interaction.

---

## 🛠️ How We Built It  

### 🔹 Core Engine (C++)
The heart of **traider** is a high-performance C++ extension (`traider_cpp`) exposed to Python via **Pybind11**. This layer handles all compute-intensive tasks:
- **Backtesting Engine**: Simulates trading strategies over historical data with O(n) efficiency.
- **Technical Indicators**: Optimized implementations of SMA, EMA, RSI, VWAP, and Bollinger Bands.
- **Data Processing**: Fast normalization and manipulation of OHLCV (Open, High, Low, Close, Volume) market data.
- **Portfolio Analytics**: Real-time calculation of risk metrics like Sharpe Ratio, variance, and returns.

### 🔹 Backend (Python & AI)
Our Python backend acts as the orchestration layer, integrating the C++ engine with modern AI capabilities:
- **FastAPI** – High-performance API server bridging the frontend and the C++ core.
- **NVIDIA Cloud Compute** – Hosting **Llama 3.3 70B** for deep semantic analysis of market news.
- **Google Search API** – Real-time financial news scraping.
- **Yahoo Finance API** – Source for raw historical market data.

### 🔹 Frontend
- **Next.js** – React framework for a responsive, interactive dashboard.
- **Tailwind CSS & ShadCN** – Modern, clean UI components.
- **Recharts** – Visualizing the high-frequency data streams from our backend.
- **Convex & Clerk** – Real-time database and secure authentication.

---

## ⚡ Challenges We Faced  
- **C++/Python Integration**: Developing a seamless interface between the C++ simulation engine and the Python backend using Pybind11.
- **Memory Management**: Ensuring zero-copy data transfer where possible to maintain high performance.
- **Cross-Platform Compilation**: configuring the build system (`setup.py` / `CMake`) to work reliably across different environments.
- **AI Hallucination Control**: Fine-tuning prompts for the Llama 70B model to ensure financial advice remained grounded in data.
- **Real-Time Data Sync**: coordinating the C++ calculation pipeline with live frontend updates.

---

## 🏆 Accomplishments We're Proud Of  
### 🔹 System Architecture
- Built a **hybrid execution environment** where C++ handles the math and Python handles the logic.
- Achieved **significant performance gains** in backtesting speed compared to pure Python implementations.
- Successfully integrated **NVIDIA's Llama 70B** for context-aware financial commentary.

### 🔹 Product Quality
- Designed a **professional-grade dashboard** that abstracts away the complexity of the underlying C++ engine.
- Created a robust educational tool that offers both **quantitative rigor** and **qualitative insights**.

---

## 📚 What We Learned  
- **Systems Programming**: The importance of memory safety and type strictness when building financial engines.
- **Foreign Function Interfaces (FFI)**: How to effectively bridge high-level and low-level languages.
- **Financial Engineering**: Deepened our knowledge of technical analysis algorithms and portfolio theory.
- **Scalable Architecture**: Designing a system that leverages the best tools for each specific job (C++ for speed, AI for reasoning).

---

## Screenshots
![image](https://github.com/user-attachments/assets/6130bbbe-776c-4c00-a901-3e43c6684e36)
![image](https://github.com/user-attachments/assets/46d866d7-dc41-4405-83ad-c7bb2ad005b6)


## Detected evidence (automated analysis)

Indexed codebase: 62 recognized source files, 200 KB.
- C (language) — detected in the code
- C++ (language) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (78 of 78)

```
.gitattributes
.gitignore
api/index.py
app/about/page.tsx
app/api/chat/route.ts
app/api/search/route.ts
app/api/stock-data/route.ts
app/calculator/page.tsx
app/globals.css
app/layout.tsx
app/leaderboard/page.tsx
app/page.tsx
app/simulator/page.tsx
backend/__init__.py
backend/cpp/backtesting/backtest_engine.cpp
backend/cpp/backtesting/backtest_engine.h
backend/cpp/core/trading_engine.cpp
backend/cpp/core/trading_engine.h
backend/cpp/data/data_processor.cpp
backend/cpp/data/data_processor.h
backend/cpp/indicators/technical_indicators.cpp
backend/cpp/indicators/technical_indicators.h
backend/cpp/main_bindings.cpp
backend/cpp/portfolio/portfolio_analytics.cpp
backend/cpp/portfolio/portfolio_analytics.h
backend/cpp/utils/math_utils.cpp
backend/cpp/utils/math_utils.h
backend/requirements.txt
backend/server.py
backend/setup.py
backend/ticker_names.py
backend/traider_cpp.cp311-win_amd64.pyd
backend/traider_cpp.cp311-win_amd64.pyd.old
components.json
components/Calculator.tsx
components/chatbot.tsx
components/Contexts.tsx
components/header.tsx
components/Leaderboard.tsx
components/sidebar.tsx
components/stock-ticker-dropdown.tsx
components/trading-simulator.tsx
components/ui/breadcrumb.tsx
components/ui/button.tsx
components/ui/card.tsx
components/ui/chart.tsx
components/ui/dialog.tsx
components/ui/input.tsx
components/ui/label.tsx
components/ui/popover.tsx
components/ui/radio-group.tsx
components/ui/scroll-area.tsx
components/ui/select.tsx
components/ui/separator.tsx
components/ui/sheet.tsx
components/ui/sidebar.tsx
components/ui/skeleton.tsx
components/ui/table.tsx
components/ui/tooltip.tsx
eslint.config.mjs
hooks/use-mobile.tsx
hooks/useGuestUser.ts
lib/rate-limit.ts
lib/supabaseClient.ts
lib/utils.ts
next.config.ts
package.json
past.jsonl
postcss.config.mjs
public/backend/ticker_name.csv
README.md
requirements.txt
runtime.txt
sample.jsonl
tailwind.config.js
tailwind.config.ts
tsconfig.json
vercel.json
```

### Dependencies

- backend/requirements.txt: fastapi, html5lib, openai, pandas, pybind11@>=2.11.0, pydantic, python-dotenv, requests, requests_html, setuptools@>=61.0, uvicorn, wheel, yahoo_fin
- package.json: @clerk/clerk-react@^5.22.13, @clerk/clerk-sdk-node@^5.1.6, @eslint/eslintrc@^3, @radix-ui/react-dialog@^1.1.6, @radix-ui/react-label@^2.1.2, @radix-ui/react-popover@^1.1.6, @radix-ui/react-radio-group@^1.2.3, @radix-ui/react-scroll-area@^1.2.3, @radix-ui/react-select@^2.1.6, @radix-ui/react-separator@^1.1.2, @radix-ui/react-slot@^1.1.2, @radix-ui/react-tooltip@^1.1.8, @supabase/supabase-js@^2.86.2, @types/node@^20, @types/papaparse@^5.3.15, @types/react@^19, @types/react-dom@^19, class-variance-authority@^0.7.1, clerk@^0.8.3, clsx@^2.1.1, eslint@^9, eslint-config-next@15.1.7, framer-motion@^12.4.3, lucide-react@^0.475.0, next@15.1.9, openai@^4.85.1, papaparse@^5.5.2, postcss@^8, radix-ui@^1.1.3, react@^19.0.0, react-dom@^19.0.0, recharts@^2.15.1, tailwind-merge@^3.0.1, tailwindcss@^3.4.1, tailwindcss-animate@^1.0.7, typescript@^5
- requirements.txt: fastapi, html5lib, openai, pandas, pybind11@>=2.11.0, pydantic, python-dotenv, requests, requests_html, setuptools@>=61.0, uvicorn, wheel, yahoo_fin

### Recent commits (newest first)

- Merge pull request #3 from ajagtapdev/vercel/dependencies-for-react-flight-7lesmi
- Update dependencies for React Flight RCE advisory
- scope fix
- lint fixes
- surfacing analytics
- lint fixes
- deployment fix
- Merge branch 'master' of https://github.com/ajagtapdev/traider
- db switch
- Update .gitattributes
- config changes
- fixes
- remove venv, build artifacts and pycache from git tracking
- deployment fix
- Merge branch 'master' of https://github.com/ajagtapdev/traider
- backend fixes
- Merge pull request #2 from ajagtapdev/homepage
- Merge pull request #1 from ajagtapdev/master
- Update README.md
- prod v1.0.0

## Key source files (fetched from GitHub, selected and truncated for size)

### requirements.txt

```
yahoo_fin
pandas
requests_html
html5lib
fastapi
uvicorn
pybind11>=2.11.0
setuptools>=61.0
wheel
requests
python-dotenv
openai
pydantic


```

### package.json

```
{
  "name": "traider",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@clerk/clerk-react": "^5.22.13",
    "@clerk/clerk-sdk-node": "^5.1.6",
    "@radix-ui/react-dialog": "^1.1.6",
    "@radix-ui/react-label": "^2.1.2",
    "@radix-ui/react-popover": "^1.1.6",
    "@radix-ui/react-radio-group": "^1.2.3",
    "@radix-ui/react-scroll-area": "^1.2.3",
    "@radix-ui/react-select": "^2.1.6",
    "@radix-ui/react-separator": "^1.1.2",
    "@radix-ui/react-slot": "^1.1.2",
    "@radix-ui/react-tooltip": "^1.1.8",
    "@supabase/supabase-js": "^2.86.2",
    "class-variance-authority": "^0.7.1",
    "clerk": "^0.8.3",
    "clsx": "^2.1.1",
    "framer-motion": "^12.4.3",
    "lucide-react": "^0.475.0",
    "next": "15.1.9",
    "openai": "^4.85.1",
    "papaparse": "^5.5.2",
    "radix-ui": "^1.1.3",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "recharts": "^2.15.1",
    "tailwind-merge": "^3.0.1",
    "tailwindcss-animate": "^1.0.7"
  },
  "devDependencies": {
    "@eslint/eslintrc": "^3",
    "@types/node": "^20",
    "@types/papaparse": "^5.3.15",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "eslint": "^9",
    "eslint-config-next": "15.1.7",
    "postcss": "^8",
    "tailwindcss": "^3.4.1",
    "typescript": "^5"
  }
}

```

### backend/requirements.txt

```
yahoo_fin
pandas
requests_html
html5lib
fastapi
uvicorn
pybind11>=2.11.0
setuptools>=61.0
wheel
requests
python-dotenv
openai
pydantic

```

### api/index.py

```python
import os
import sys

# Add the project root to sys.path to allow importing from backend
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from backend.server import app


```

### app/layout.tsx

```typescript
import type React from "react";
import type { Metadata } from "next";
import "./globals.css";

export const metadata: Metadata = {
  title: "traider",
  description: "learn your trades with AI",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        {children}
      </body>
    </html>
  );
}

```

### app/page.tsx

```typescript
"use client";

import type React from "react";

import Link from "next/link";
import { Button } from "@/components/ui/button";
import { LineChart, PieChart, BarChart } from "lucide-react";
import Header from "@/components/header";
import {
  motion,
  useMotionValue,
  useTransform,
  useAnimation,
} from "framer-motion";
import { useEffect, useState } from "react";

const fadeIn = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0 },
  transition: { duration: 0.5 },
};

const staggerContainer = {
  animate: {
    transition: {
      staggerChildren: 0.2,
    },
  },
};

const draw = {
  hidden: { pathLength: 0, opacity: 0 },
  visible: (i: number) => {
    const delay = i * 0.1; // Reduced delay between elements
    return {
      pathLength: 1,
      opacity: 1,
      transition: {
        pathLength: { delay, type: "spring", duration: 0.8, bounce: 0 }, // Reduced duration
        opacity: { delay, duration: 0.01 },
      },
    };
  },
};

const pulse = {
  scale: [1, 1.1, 1],
  transition: {
    duration: 2,
    repeat: Number.POSITIVE_INFINITY,
    ease: "easeInOut",
  },
};

export default function Home() {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const rotateX = useTransform(y, [-100, 100], [30, -30]);
  const rotateY = useTransform(x, [-100, 100], [-30, 30]);

  const controls = useAnimation();

  useEffect(() => {
    const updateDimensions = () => {
      setDimensions({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };
    updateDimensions();
    window.addEventListener("resize", updateDimensions);
    controls.start("visible");
    return () => window.removeEventListener("resize", updateDimensions);
  }, [controls]);

  function handleMouse(event: React.MouseEvent<HTMLDivElement>) {
    const rect = event.currentTarget.getBoundingClientRect();
    x.set(event.clientX - rect.left - rect.width / 2);
    y.set(event.clientY - rect.top - rect.height / 2);
  }

  return (
    <div className="min-h-screen bg-[#FDF6E9] overflow-hidden">
      <Header />
      <main>
        <section
          className="relative min-h-screen flex items-center justify-center overflow-hidden"
          onMouseMove={handleMouse}
        >
          <motion.div
            className="absolute inset-0"
            style={{
              rotateX: rotateX,
              rotateY: rotateY,
              perspective: 1000,
            }}
          >
            <motion.svg
              className="w-full h-full"
              viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
              initial="hidden"
              animate={controls}
            >
              {/* Grid pattern */}
              {Array.from({ length: 20 }).map((_, i) => (
                <motion.line
                  key={`horizontal-${i}`}
                  x1="0"
                  y1={i * (dimensions.height / 20)}
                  x2={dimensions.width}
                  y2={i * (dimensions.height / 20)}
                  stroke="#509048"
                  strokeWidth="0.5"
                  variants={draw}
                  custom={i * 0.5} // Adjust the multiplier to speed up or slow down the sequence
                  whileHover={{ stroke: "#FDA4AF", strokeWidth: 2 }}
                />
              ))}
              {Array.from({ length: 20 }).map((_, i) => (
                <motion.line
                  key={`vertical-${i}`}
                  x1={i * (dimensions.width / 20)}
                  y1="0"
                  x2={i * (dimensions.width / 20)}
                  y2={dimensions.height}
                  stroke="#FDA4AF"
                  strokeWidth="0.5"
                  variants={draw}
                  custom={i * 0.5 + 10} // Offset to start after horizontal lines
                  whileHover={{ stroke: "#509048", strokeWidth: 2 }}
                />
              ))}

              {/* Abstract financial patterns */}
              <motion.path
                d={`M ${dimensions.width * 0.1} ${dimensions.height * 0.3} Q ${dimensions.width * 0.15} ${dimensions.height * 0.05} ${dimensions.width * 0.2} ${dimensions.height * 0.3} T ${dimensions.width * 0.3} ${dimensions.height * 0.3} T ${dimensions.width * 0.4} ${dimensions.height * 0.3} T ${dimensions.width * 0.5} ${dimensions.height * 0.3}`}
                stroke="#509048"
                strokeWidth="2"
                fill="none"
                variants={draw}
                custom={20} // Reduced delay
                whileHover={{ stroke: "#FDA4AF" }}
              />
              <motion.path
                d={`M ${dimensions.width * 0.7} ${dimensions.height * 0.6} Q ${dimensions.width * 0.8} ${dimensions.height * 0.4} ${dimensions.width * 0.9} ${dimensions.height * 0.6} T ${dimensions.width} ${dimensions.height * 0.6}`}
                stroke="#FDA4AF"
                strokeWidth="2"
                fill="none"
                variants={draw}
                custom={21} // Reduced delay
                whileHover={{ stroke: "#509048" }}
              />

              {/* Animated circles */}
              <motion.circle
                cx={dimensions.width * 0.15}
                cy={dimensions.height * 0.15}
                r={dimensions.width * 0.05}
                stroke="#509048"
                strokeWidth="2"
                fill="none"
                variants={draw}
                custom={22} // Reduced delay
                whileHover={{ stroke: "#FDA4AF" }}
              />
              <motion.circle
                cx={dimensions.width * 0.85}
                cy={dimensions.height * 0.85}
                r={dimensions.width * 0.1}
                stroke="#FDA4AF"
                strokeWidth="2"
                fill="none"
                variants={draw}
                custom={23} // Reduced delay
                whileHover={{ stroke: "#509048" }}
              />

              {/* Pulsing el
[truncated — 5491 more characters]
```

### backend/server.py

```python
from fastapi import FastAPI, HTTPException
from yahoo_fin.stock_info import get_data
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime, timedelta
import requests
from openai import OpenAI
import os
from dotenv import load_dotenv
from pydantic import BaseModel
from typing import List, Dict, Optional
import sys

# Try to import the C++ extension
try:
    import traider_cpp
    CPP_AVAILABLE = True
    print("C++ extension loaded successfully")
except ImportError as e:
    CPP_AVAILABLE = False
    print(f"Warning: C++ extension not available: {e}")

# Load environment variables from .env.local
load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), "../.env.local"))

NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY")
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
CX = "c293cecd2186844b3"  # Ensure this CSE is configured to search news sites!

# NVIDIA API Setup
client = OpenAI(
    base_url="https://integrate.api.nvidia.com/v1",
    api_key=NVIDIA_API_KEY
)

app = FastAPI()

# CORS middleware settings
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Dictionary to store the last request timestamp and response per ticker
news_cache: Dict[str, Dict] = {}

COOLDOWN_PERIOD = timedelta(seconds=15)  # 15-second cooldown

@app.get("/stock-data")
def get_stock_data(ticker: str, startDate: str, endDate: str):
    try:
        start_date_obj = datetime.strptime(startDate, "%Y-%m-%d")
        end_date_obj = datetime.strptime(endDate, "%Y-%m-%d")

        # Clamp future end dates to "today" to prevent Yahoo Finance API errors
        today = datetime.today()
        if end_date_obj > today:
            end_date_obj = today

        stock_data = get_data(
            ticker,
            start_date=start_date_obj,
            end_date=end_date_obj,
            index_as_date=False  # DataFrame will have a 'date' column
        )
        if stock_data is None or stock_data.empty:
            return []

        # Rename 'close' => 'price' for clarity
        stock_data.rename(columns={"close": "price"}, inplace=True)

        # Convert relevant columns to a list of dictionaries
        records = stock_data[
            ["date", "open", "high", "low", "price", "adjclose", "volume"]
        ].to_dict(orient="records")

        return records
    except Exception as e:
        print(f"Error fetching stock data: {e}")
        return []

def get_stock_news(ticker, date):
    """
    Fetches news articles related to a stock ticker on a specific date.
    """
    query = f"{ticker} stock news"
    url = "https://www.googleapis.com/customsearch/v1"
    
    formatted_date = date.replace("-", "")
    
    params = {
        "q": query,
        "cx": CX,
        "key": GOOGLE_API_KEY,
        "num": 5,
        "sort": f"date:r:{formatted_date}:{formatted_date}"
    }
    
    response = requests.get(url, params=params)
    data = response.json()
    
    if "error" in data:
        print("Google API Error:", data["error"])
        return []
    
    return [item.get("snippet", "") for item in data.get("items", [])]

def summarize_news_with_nvidia(news_list):
    """Uses NVIDIA model to summarize stock news into bullet points focused on external conditions."""
    combined_text = " ".join(news_list)
    
    prompt = (
        "Summarize the following stock news into 2-4 concise bullet points. "
        "Focus solely on external conditions, events, and market sentiments that could have influenced the company during this time period. "
        "Ensure all points are relevant to the stock's context, but do not include any direct numerical data or mention that the stock price went up or down. "
        "Avoid making any direct predictions about the stock's performance. "
        "Return only the bullet points and nothing else. "
        f"News: {combined_text}"
    )
    
    completion = client.chat.completions.create(
        model="meta/llama-3.3-70b-instruct",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.2,
        max_tokens=300
    )
    summary_text = completion.choices[0].message.content
    return [line.strip() for line in summary_text.split("\n") if line.strip()]

class StockNewsRequest(BaseModel):
    ticker: str
    date: str

@app.get("/search", response_model=List[str])
async def get_stock_news_route(ticker: str, date: str):
    """
    Endpoint to fetch stock news based on ticker and date, and return summarized points.
    Uses a 15-second cooldown per ticker to prevent excessive API calls.
    """
    now = datetime.now()
    
    # Check cooldown for the ticker
    if ticker in news_cache:
        last_request_time = news_cache[ticker]["timestamp"]
        if now - last_request_time < COOLDOWN_PERIOD:
            print(f"Returning cached news for {ticker} (cooldown active)")
            return news_cache[ticker]["response"]

    news_results = get_stock_news(ticker, date)
    if not news_results:
        return ["No news articles found"]

    bullet_points = summarize_news_with_nvidia(news_results)

    # Cache the result with a timestamp
    news_cache[ticker] = {
        "timestamp": now,
        "response": bullet_points
    }

    return bullet_points

# --- C++ Integration Endpoints ---

class TechnicalIndicatorsRequest(BaseModel):
    ticker: str
    period: int = 20

@app.post("/technical-indicators")
def get_technical_indicators(request: TechnicalIndicatorsRequest):
    """
    Calculate technical indicators using the high-performance C++ engine.
    """
    if not CPP_AVAILABLE:
        raise HTTPException(status_code=501, detail="C++ extension not available")
    
    try:
        # Fetch data for enough history (e.g. 2 years to be safe for EMAs etc)
        end_date = datetime.now()
        start_date = end_date - timedelta(days=730)
        
        stock_data = get_data(
            request.ticker,
            start_date=start_date
[truncated — 6015 more characters]
```

### app/calculator/page.tsx

```typescript
"use client";

import { Sidebar } from "@/components/sidebar";
import Header from "@/components/header";
import Calculator from "@/components/Calculator";

const CalculatorPage = () => {
    return (
        <div className="flex h-screen overflow-hidden bg-gradient-to-br from-[#fdf6e9] to-[#fdf6e9]">
        <Sidebar />
        <div className="flex flex-1 flex-col overflow-hidden">
            <Header />
            <main className="flex-1 overflow-y-auto p-6">
            <Calculator />
            </main>
        </div>
        </div>
    );
};

export default CalculatorPage;
```

### app/leaderboard/page.tsx

```typescript
"use client";

import { Sidebar } from "@/components/sidebar";
import Header from "@/components/header";
import Leaderboard from "@/components/Leaderboard";

const LeaderboardPage = () => {
    return (
        <div className="flex h-screen overflow-hidden bg-gradient-to-br from-[#fdf6e9] to-[#fdf6e9]">
        <Sidebar />
        <div className="flex flex-1 flex-col overflow-hidden">
            <Header />
            <main className="flex-1 overflow-y-auto p-6">
            <Leaderboard />
            </main>
        </div>
        </div>
    );
};

export default LeaderboardPage;
```

### app/simulator/page.tsx

```typescript
"use client";

import { useState } from "react";
import { Sidebar, PortfolioMetrics } from "@/components/sidebar";
import Header from "@/components/header";
import TradingSimulator from "@/components/trading-simulator";
import { useGuestUser } from "@/hooks/useGuestUser";

const Simulator = () => {
  const { guestId, userId, isLoaded } = useGuestUser();
  const [metrics, setMetrics] = useState<PortfolioMetrics | null>(null);

  if (!isLoaded) {
    return <div className="min-h-screen flex items-center justify-center bg-[#FDF6E9]">Loading...</div>;
  }

  return (
    <div className="flex h-screen overflow-hidden bg-gradient-to-br from-[#fdf6e9] to-[#fdf6e9]">
      <Sidebar metrics={metrics} />
      <div className="flex flex-1 flex-col overflow-hidden">
        <Header />
        <main className="flex-1 overflow-y-auto p-6">
          <TradingSimulator 
            guestId={guestId!} 
            userId={userId} 
            onMetricsUpdate={setMetrics} 
          />
        </main>
      </div>
    </div>
  );
};



export default Simulator;

```

[53 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]