As a frontend developer, implement the Navbar section for the Signup page. This component (Navbar.css) uses useState for mobileOpen and dropdownOpen state, renders primaryLinks (Dashboard, Signals, Scanner, Chart, Backtest) and moreLinks (Gainers, Losers, Sectors, AI Score, Risk, Trades, Alerts) arrays. Includes TrendingUp and ChevronDown lucide icons, a 'More' dropdown toggle with aria-expanded, a hamburger menu button with three span elements, and CTA buttons for Log In (/Login) and Get Started (/Signup). Note: this component likely already exists from previous pages — reuse if available.
As a frontend developer, implement the SectorPerformanceGrid section for the Sectors page. This section renders an interactive grid of sector cards using `SECTOR_DEFS` (9 sectors: banking, IT, pharma, auto, energy, FMCG, metals, realty, etc.) each with: `id`, `name`, `index`, `icon`, `iconClass`, `symbol`, `stocks` array, `baseChange`, `basePrice`, `baseVolume`, `bullish`/`bearish` counts, and `sparkBase` 7-point price array. State hooks include `useState` and `useEffect` with `useCallback`. Each card displays a sparkline chart rendered from `sparkBase` data, bullish/bearish stock count bars, sector icon with `iconClass` color variants, live price/change simulation, and volume display. Uses Framer Motion `motion` and `AnimatePresence` for card entrance animations. Imports both `SectorPerformanceGrid.css` and `TVChartModal.css` (TV chart modal integration for clicking into a sector chart). Clicking a sector card likely opens a `TVChartModal` overlay with the sector's `symbol`.
As a frontend developer, implement the SectorDetailsTable section for the Sectors page. This is the most complex section, featuring a full sortable/expandable sector table using `SECTORS_DATA` (10+ sector rows: banking, IT, pharma, auto, etc.). Each row includes: `advances`/`declines` counts, `change` %, `topStock` (symbol/price/change), `volume` with `volumeRating` badge (HIGH/MED/LOW), `strength` bar (0–100), live VWAP, `dayHigh`/`dayLow`, ATR, `delivery` %, `buyVol`/`sellVol` ratio bar, `instBuy`/`instSell` institutional flow bar, and `aiNote` text. State includes `useState`, `useEffect`, `useCallback` for sort column, sort direction, search, expanded row, and live price simulation. Imports lucide-react icons: `TrendingUp`, `TrendingDown`, `Search`, `BarChart2`, `Zap`, `ChevronUp`, `ChevronDown`, `X`, `ExternalLink`, `Activity`, `Brain`. Uses `SortIcon` sub-component (imports `SortIcon.css`). Framer Motion `AnimatePresence` animates expanded row details panel. `Brain` icon triggers AI note display in expanded panel. Imports `SectorDetailsTable.css`.
As a frontend developer, implement the TopStocksBySector section for the Sectors page. This section renders per-sector top stock lists with `SECTORS` (8 sector tabs: banking, IT, pharma, auto, FMCG, energy, metal, realty) and `SECTOR_STOCKS` map containing 5 stocks per sector, each with: `symbol`, `name`, `basePrice`, `baseChange`, `baseVolume`, `delivery`, `vwap`, `dayHigh`, `dayLow`, `atr`. State hooks: `useState` for `activeSector`, `useEffect` + `useCallback` + `useRef` for live price simulation intervals. Sector tab bar uses `SECTORS` array to switch the active sector. Stock rows display live-updating price, change %, volume, delivery %, VWAP comparison indicator, day high/low range bar, and ATR value. Framer Motion `motion` and `AnimatePresence` animate stock list transitions when switching sectors. Imports `TopStocksBySector.css`.
As a Backend Developer, define SQLAlchemy ORM models and Alembic migrations for all core entities: User (id, email, password_hash, created_at, is_active), Alert (id, user_id, symbol, sector, type, status, trigger_condition, entry, sl, target, created_at), Trade (id, user_id, symbol, side, entry_price, exit_price, qty, sl, target, status, pnl, entry_time, exit_time, exit_reason, rr, setup_score), BacktestResult (id, user_id, strategy, watchlist, timeframe, start_date, end_date, capital, win_rate, profit_factor, max_drawdown, total_trades, metrics_json), UserSettings (id, user_id, capital, risk_pct, max_drawdown, notification_channels_json). Run `alembic init` and generate initial migration. Use MySQL/MariaDB as per SRD tech stack.
As a DevOps Engineer, add Redis to the docker-compose and Kubernetes chart. Configure Redis as the caching layer for: Fyers API responses (10s TTL for quotes/breadth, 60s for sectors), session store for JWT refresh tokens, WebSocket connection registry, backtest job state. Install redis-py and add cache decorator utility in the FastAPI app. Set REDIS_URL env var. Add redis service to docker-compose.yml and a Redis StatefulSet/Deployment to the k8s Helm chart. Ensure redis persistence (appendonly yes) for session data.
As a DevOps Engineer, centralize all environment variable configuration: create .env.example documenting all required vars (FYERS_CLIENT_ID, FYERS_SECRET_KEY, FYERS_REDIRECT_URI, DATABASE_URL, REDIS_URL, JWT_SECRET_KEY, JWT_ALGORITHM, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_CLIENT_SECRET, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, LITELLM_API_KEY, OPENAI_API_KEY). Create Kubernetes Secrets manifests for sensitive values. Update docker-compose.yml env_file reference. Add a startup validation in FastAPI (check all required env vars on boot, fail fast with clear error message). Document Fyers OAuth2 setup flow in README.
As a Frontend Developer, implement the global theme and design system. Create a CSS custom properties file (variables.css) defining all SRD colors: --primary #1A73E8, --primary-light #4A90E2, --secondary #FF6F61, --accent #FFD700, --highlight #FFA500, --bg #F5F5F5, --surface rgba(255,255,255,0.8), --text #333333, --text-muted #777777, --border rgba(0,0,0,0.1). Implement dark mode via a data-theme='dark' attribute on :root with overridden values. Create DarkModeContext + useDarkMode() hook with localStorage persistence. Add a dark mode toggle button in DashboardSidebar and Navbar. Create shared utility CSS classes (e.g. .text-up, .text-down, .badge-buy, .badge-sell) used across pages. Import variables.css as the first stylesheet in the app entry point.
As a Backend Developer, implement the WebSocket relay server that bridges the Fyers API V3 WebSocket feed to frontend clients. Create ws://backend/ws/market endpoint using FastAPI WebSocket support. Subscribe to Fyers live tick feed for all active NSE symbols. Broadcast tick payloads {symbol, ltp, open, high, low, close, volume, change, changePct, buyVol, sellVol, oi} to all connected frontend clients. Implement connection pooling, symbol subscription management (subscribe/unsubscribe messages from clients), and automatic reconnection to Fyers on disconnect. This task extends the Fyers API V3 integration (task 18450547) with the dedicated WebSocket relay layer. Depends on Fyers integration task.
As a Backend Developer, implement a lightweight API endpoint to support TradingView Advanced Chart Widget symbol resolution: GET /api/chart/symbol/{symbol} (returns TradingView-compatible symbol string for a given NSE symbol, e.g. NSE:RELIANCE for RELIANCE-EQ), GET /api/chart/indicators (returns default indicator config: EMA 20/50/200, VWAP, Volume). This enables the frontend to map Fyers symbols to TradingView symbols dynamically on click without page reload. Also expose GET /api/chart/default-config returning the standard chart configuration object (chart type, timeframe, indicators). Depends on Fyers integration.
As a Frontend Developer, implement the Landing page (v4) frontend sections: Hero section with animated stock ticker, Features overview, Platform stats strip (pulling from GET /api/public/stats), Market preview strip showing top 5 gainers/losers (pulling from GET /api/public/market-preview), Testimonials, CTA sections, and Footer. Use framer-motion for parallax scroll interactions and smooth transitions as per the SRD signature design concept. Integrate with the public API endpoints once available. Note: depends on Build Landing Page API task (temp_id: build-landing-api equivalent: 6ef61275).
As a Tech Lead, verify the end-to-end integration between the watchlist star toggles in GainersTable, LosersTable, and CandidateDetails frontend components and the User Watchlist API (GET /api/user/watchlist, POST /api/user/watchlist, DELETE /api/user/watchlist/{symbol}). Ensure starred symbols are persisted via the API, watchlist state is loaded on page mount after auth, and un-starring correctly calls the DELETE endpoint. This is a subset of the broader User Settings Persistence integration (task 9214ad24) focused specifically on watchlist CRUD flows. Depends on User Settings API (81c6bf07) and relevant frontend section tasks.
As a Backend Developer, execute the initial Alembic migration to create all tables (User, Alert, Trade, BacktestResult, UserSettings) in the MySQL/MariaDB database. Verify migration runs cleanly in the docker-compose environment and the Kubernetes init-container pattern. Add a seed script (seed.py) for development that inserts a test user and sample trades to enable frontend development without real Fyers credentials. Document migration commands in README. Depends on DB models task (b1e05bed).
As a Backend Developer, implement the Fyers API V3 OAuth2 authorization code flow as a dedicated setup endpoint: GET /api/fyers/auth/url (returns the Fyers authorization URL for the browser redirect), GET /api/fyers/auth/callback (handles the redirect, exchanges auth_code for access_token, stores token in Redis with TTL matching expiry). Implement token refresh logic that automatically re-authenticates when the token expires (Fyers tokens expire daily). Expose GET /api/fyers/auth/status endpoint to check if a valid token is available. This is a prerequisite for all Fyers data endpoints. App ID: BYIJFTPDWO-100, Secret ID must be stored as FYERS_SECRET_KEY env var. Depends on Redis caching (dfabfd55) and env vars (8e302583) tasks.
As a Backend Developer, implement application health and readiness endpoints for Kubernetes probes and CI/CD gates: GET /api/health (liveness probe: returns {status: ok, timestamp}), GET /api/ready (readiness probe: checks DB connection, Redis ping, Fyers token validity, returns per-dependency status and overall ready: true|false). Add a GET /api/metrics endpoint (Prometheus-compatible basic metrics: request_count, error_rate, active_ws_connections, fyers_token_valid). These endpoints are unauthenticated and required by the k8s deployment chart. Depends on Redis (dfabfd55) and DB models (b1e05bed).
As a frontend developer, implement the SignupHero section for the Signup page. Uses framer-motion with containerVariants (staggerChildren: 0.1) and fadeUp variant (opacity 0→1, y 18→0, duration 0.45). Renders two decorative accent blobs (sh-accent-blob, sh-accent-blob--2) as aria-hidden. Displays an eyebrow badge ('Free 14-Day Trial — No Credit Card Required') with sh-eyebrow-dot, an h1 headline with sh-headline-accent span for 'Paisa Banao', a subheadline paragraph, and VALUE_PROPS array of 3 items (📡 Real-time Scanner, 🤖 AI-Powered Signals, 🔔 Instant Alerts) rendered with dangerouslySetInnerHTML for bold text. Ends with a divider containing 'Create your free account below' text flanked by sh-divider-line spans. All children are motion.div elements animated in sequence.
As a frontend developer, implement the SignupForm section for the Signup page. Uses useState for form (email, password, confirmPassword, terms), touched (per-field), showPassword, showConfirm, submitting, and submitted state. Implements getPasswordStrength() scoring (length≥8, uppercase, digit, special char) with STRENGTH_LABELS ('Weak','Fair','Good','Strong') and STRENGTH_CLASS (sf-sl-weak/fair/good/strong). Uses useCallback for handleChange and handleBlur. Inline validation errors object covers all four fields with regex email check and password match. handleSubmit triggers setTouched all-true, guards on isValid, sets submitting with 1400ms fake async delay, then sets submitted. Renders lucide icons: Mail, Lock, Eye, EyeOff, Check, X, AlertCircle, CheckCircle, User. Shows per-field showErr/showOk helpers. On success renders sf-success-state with Check icon, 'Account Created!' h2. Password and confirm fields have toggle visibility buttons. Terms checkbox with error state.
As a frontend developer, implement the SignupTrust section for the Signup page. Renders a BADGES array of 5 items (Shield/blue, Zap/yellow, TrendingUp/green, Lock/coral, Bell/orange) each with dynamic inline styles for iconBg and iconColor via lucide icons at size 18 strokeWidth 2.2. Below a sgt-divider, renders TESTIMONIALS array of 3 items (Rajesh K., Priya S., Amit V.) each with 5 star ratings using sgt-star spans, a quote paragraph, and an avatar with initials and dynamic avatarBg color (blue, coral, green). Includes sgt-label heading 'Why traders choose Paisa Banao Strategy Pro'. Fully static/presentational — no state or animations.
As a frontend developer, implement the Footer section for the Signup page. Uses TrendingUp, Twitter, Linkedin, Send, Youtube lucide icons. Renders platformLinks, tradingLinks, marketLinks nav columns and a socials array of 4 items. Features a live market ticker (ftr-ticker-track) with loopTickers = [...tickers, ...tickers] doubling a 6-item array (NIFTY, RELIANCE, TCS, HDFCBANK, INFY, SBIN) with up/down directional classes for CSS animation. Includes ftr-glow decorative element, ftr-brand with tagline, dynamic year via new Date().getFullYear(), and ftr-logo-mark with TrendingUp icon. Note: this component likely already exists from previous pages — reuse if available.
As a frontend developer, implement the LoginHero section for the Login page. This is a static presentational section (no state hooks) that renders decorative background layers (lh-grid, lh-glow-1/2/3 divs with aria-hidden), a 'Live Market Access' badge with an animated dot (lh-badge-dot), an animated chart strip of 12 bars generated via Array.from({ length: BAR_COUNT }) each rendered as a lh-bar div with CSS animation, an h1 headline with an accented span for 'Automated Setups', a subheadline paragraph, three VALUE_BULLETS rendered with icon and text spans, and a STATS row of three metrics (1500+ Stocks Scanned, 92% Accuracy, <50ms Latency) with dividers between them using React.Fragment.
As a frontend developer, implement the LoginForm section for the Login page. This interactive form component manages multiple useState hooks: email, password, rememberMe, showPassword, loading, formError, emailError, and passwordError. It includes inline validation functions validateEmail (regex-based) and validatePassword (min 6 chars) triggered on blur via handleEmailBlur and handlePasswordBlur. The handleSubmit async handler prevents default, runs full validation, sets loading state, simulates a 1200ms auth delay via Promise/setTimeout, then redirects to /Dashboard on success or sets a formError on failure. The form renders a TrendingUp icon header, an AlertCircle-based lf-form-error alert div (role='alert'), an email input with Mail icon and error class toggle (lf-input--error), a password input with Lock icon and Eye/EyeOff toggle for showPassword, a remember me checkbox, a forgot password link, and a submit button that shows a loading spinner when loading is true. ShieldCheck and CheckCircle icons are also imported for trust indicators.
As a frontend developer, implement the LoginSignupPrompt section for the Login page. This is a minimal static presentational component with no state hooks. It renders an lsp-root wrapper containing an lsp-inner div with a paragraph ('Don't have an account?') and an anchor link labeled 'Create one for free' pointing to /Signup with className lsp-link.
As a Backend Developer, implement authentication REST API endpoints using FastAPI: POST /api/auth/register (user signup with email/password hashing via bcrypt), POST /api/auth/login (JWT access + refresh token generation), POST /api/auth/logout (token invalidation), POST /api/auth/refresh (token rotation), GET /api/auth/me (current user profile). Include input validation with Pydantic models, rate limiting on login endpoint, and proper HTTP error responses. Note: depends on database models task (temp_id: backend-db-models).
As a Backend Developer, implement the Fyers API V3 integration layer in FastAPI. Create a FyersClient service class handling: OAuth2 token generation and refresh flow, REST endpoints proxied at /api/fyers/v3/quotes, /api/fyers/v3/market/breadth, /api/fyers/v3/market/gainers, /api/fyers/v3/market/history (OHLCV), /api/fyers/v3/market/depth. Implement a WebSocket relay server at ws://localhost/ws/market that subscribes to Fyers WebSocket feed and broadcasts tick data to all connected frontend clients. Handle reconnection logic, token expiry, and error propagation. Store Fyers credentials in environment variables (FYERS_CLIENT_ID, FYERS_SECRET_KEY, FYERS_REDIRECT_URI).
As a Backend Developer, implement risk management API endpoints: GET /api/risk/settings (returns user's capital, risk_pct, max_drawdown settings), PUT /api/risk/settings (update risk parameters with validation: capital ≥ 10000, risk_pct 0.1-5, drawdown 1-20), GET /api/risk/calculate?capital=X&entry=X&sl=X&target=X (server-side position sizing: max_risk, risk_per_share, position_size, total_cost, profit_potential, rr_ratio, capital_used_pct), GET /api/risk/summary (aggregate open risk: total_capital_deployed, total_capital_at_risk, max_loss_pct, open_positions_count, aggregate_rr, utilization_pct). Persist settings in UserSettings DB model. Depends on DB models task.
As a DevOps Engineer, implement CI/CD pipeline using GitHub Actions (or equivalent): build and test workflow triggered on push/PR to main branch running backend pytest suite and frontend lint/build checks. Build Docker images for frontend and backend, tag with git SHA, and push to container registry. Implement staging deployment workflow that applies k8s manifests to staging namespace. Implement production deployment workflow (manual trigger) with rollback capability. Add health check gates between stages. Configure environment-specific secrets (staging vs prod) via repository secrets. Add pre-commit hooks for linting (ruff for Python, eslint for React).
As a Backend Developer, implement lightweight public (unauthenticated) API endpoints to power the Landing page with real data: GET /api/public/stats (returns live platform stats: stocks_scanned, active_signals, win_rate, avg_rr for the hero section), GET /api/public/market-preview (returns top 5 gainers and top 5 losers with basic fields for the landing page preview strip, cached with 30s Redis TTL). These endpoints must not require authentication and should be served behind rate limiting. Depends on Fyers integration and Redis caching.
As a Tech Lead, verify the end-to-end integration between the Landing page frontend sections (Hero, Stats Strip, Market Preview Strip) and the public API backend (GET /api/public/stats, GET /api/public/market-preview). Ensure the stats strip displays live platform metrics from the API, the market preview strip shows real top 5 gainers/losers replacing any static data, CTA buttons route correctly to /Login and /Signup, and the page loads within performance budgets without auth. Verify rate limiting on public endpoints does not degrade UX.
As a Frontend Developer, implement a minimal admin/setup page at /setup/fyers that allows the app operator to initiate the Fyers OAuth2 flow: display GET /api/fyers/auth/status (Connected/Not Connected), render a 'Connect Fyers Account' button that redirects to GET /api/fyers/auth/url, and show the callback success/error state after redirect. This page should be protected and only accessible to admin users. Also add a Fyers connection status indicator in DashboardSidebar (green dot = connected, red = not connected). Depends on Fyers OAuth2 backend task.
As a DevOps Engineer, generate VAPID public/private key pair for browser Web Push notifications and add them to the environment configuration. Update .env.example with VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY. Expose GET /api/push/vapid-public-key endpoint (unauthenticated) so the frontend Service Worker can retrieve the VAPID public key for push subscription registration. Document the web-push library setup (pywebpush or similar) and the browser Push Notification permission request flow. Depends on env vars task (8e302583).
As a DevOps Engineer, implement structured JSON logging across the FastAPI backend using Python structlog or loguru: log all API requests (method, path, status_code, latency_ms, user_id), WebSocket connection events (connect, disconnect, symbol subscriptions), Fyers API calls (endpoint, latency, cache_hit), and signal state transitions. Configure log level via LOG_LEVEL env var. In Kubernetes, ensure logs are stdout/stderr for collection by the cluster log aggregator. Add a correlation ID (X-Request-ID header) propagated through all log entries for request tracing. Depends on env vars task (8e302583).
As a frontend developer, implement the DashboardSidebar section for the Dashboard page. Build the collapsible sidebar using `ds-root`, `ds-root--collapsed`, and `ds-root--mobile-open` CSS class variants driven by `useState` hooks for `collapsed`, `mobileOpen`, and `activeHref`. Implement the `NavGroup` component that renders nav items from MARKET_MENU, ANALYSIS_MENU, TOOLS_MENU, and BOTTOM_ACTIONS arrays with icon glyphs (⊞, ⊡, ⊟, ◈, etc.), active-state highlighting via `ds-nav__item--active`, and badge rendering for Signals (count=5) and Alerts (count=3) via `ds-nav__badge` and `ds-nav__badge--count`. Include the mobile header bar with hamburger toggle (☰/✕), user profile section, and `framer-motion` AnimatePresence transitions. Handle navigation via `handleNavigate` which updates `activeHref` and closes mobile sidebar when `window.innerWidth < 768`. Note: this component may already exist from a previous page — reuse if available. Imports `NavGroup.css` and `DashboardSidebar.css`.
As a Backend Developer, implement the auto scanner API endpoints: GET /api/scanner/run (triggers the 09:25 AM scan logic — fetches top 20 gainers/losers from Fyers V3, applies Paisa Banao setup detection algorithm, returns top 5 candidates with symbol, sector, ltp, gap_pct, volume, rel_volume, strength_score), GET /api/scanner/candidates (returns current session candidates with full metadata), GET /api/scanner/setup/{symbol} (returns Paisa Banao BUY/SELL setup details for a symbol including signal candle data, entry, sl, targets, validity status). Implement the core Paisa Banao strategy detection logic: first-candle color check, ignore-3-candles rule, lowest-volume signal candle detection on 5-min OHLCV data, auto-update of entry/SL if lower-volume candle appears, validity until 11:00 AM. Depends on Fyers integration task.
As a Backend Developer, implement market data REST endpoints that proxy and enrich Fyers V3 data: GET /api/market/sentiment (advance/decline counts, ratio, market status Bullish/Bearish/Neutral), GET /api/market/breadth (advancing/declining/unchanged totals, A-D ratio, breadth percentage), GET /api/market/gainers?limit=50 (top gainers with ltp, gap_pct, volume, rel_vol, strength, sector), GET /api/market/losers?limit=50 (top losers with same fields), GET /api/market/sectors (sector performance: name, bullish_count, bearish_count, strength_pct, change_pct, top_stock), GET /api/market/quotes?symbols=NSE:RELIANCE-EQ,... (batch quote endpoint). All endpoints must be sub-200ms using Redis caching with 10-second TTL. Depends on Fyers integration.
As a Backend Developer, implement the AI scoring engine API endpoints: GET /api/ai/score/{symbol} (returns overall score 0-100 and breakdown: volume_pattern, market_breadth, relative_strength, gap_pct, sector_strength sub-scores, plus ai_explanation text via LiteLLM/GPT routing), GET /api/ai/scores?min_score=70 (bulk scored setups list filtered by threshold), GET /api/ai/institutional/{symbol} (institutional buy/sell detector: inst_buy_score, inst_sell_score, signal label STRONG_BUYING to STRONG_SELLING derived from volume spike, rel_vol, delivery_pct, VWAP position, momentum), POST /api/ai/explain (body: {symbol, context}) uses LiteLLM to route to GPT-5.4 generating natural-language explanation of stock movement. Integrate Langchain for prompt templating. Depends on Fyers integration and DB models.
As a Backend Developer, implement the backtesting engine API: POST /api/backtest/run (body: strategy, watchlist, timeframe, start_date, end_date, capital, risk_percent, trail_sl, compound_positions, filter_score — runs Paisa Banao strategy simulation on historical 5-min OHLCV data fetched from Fyers V3 history endpoint, returns job_id), GET /api/backtest/status/{job_id} (polling endpoint returning progress and partial results), GET /api/backtest/results/{job_id} (full results: win_rate, profit_factor, max_drawdown, avg_rr, total_trades, equity_curve array, drawdown_array, trade_log array with entry/exit/pnl per trade, metrics breakdown). Run computation in FastAPI BackgroundTasks. Store results in BacktestResult DB model. Depends on Fyers integration and DB models.
As a Backend Developer, implement trade management REST API: GET /api/trades?status=open|closed&timeframe=today|week|month (paginated trade list with filters), GET /api/trades/{id} (trade detail with P&L, RR, timeline), POST /api/trades (manually add trade), PUT /api/trades/{id} (update entry/sl/target/status), DELETE /api/trades/{id} (close/delete trade), GET /api/trades/summary (aggregate P&L: total_pnl, realized_pnl, unrealized_pnl, active_trades_count, win_rate, profit_factor), GET /api/trades/history?page=1&limit=20 (paginated history with sort). Implement real-time P&L computation using latest Fyers tick prices for open trades via the WebSocket relay. Depends on DB models and Fyers integration.
As a Frontend Developer, implement global authentication state management and route protection: create AuthContext (React Context + useReducer) storing user, accessToken, isAuthenticated, isLoading. Implement useAuth() hook. Create ProtectedRoute HOC that redirects unauthenticated users to /Login. Implement tokenService utility for storing/refreshing JWT access tokens (axios interceptor that auto-refreshes on 401). Create apiClient (axios instance) with base URL, auth header injection, and error handling. Wire LoginForm and SignupForm to POST /api/auth/login and /api/auth/register. On login success store tokens and redirect to /Dashboard. Implement logout clearing tokens and redirecting to /Login.
As a Frontend Developer, implement a global WebSocket service for real-time market data: create useMarketSocket() custom hook that connects to ws://backend/ws/market, handles reconnection with exponential backoff (max 5 retries), parses incoming tick messages ({symbol, ltp, change, volume, ...}), and dispatches to a MarketDataContext (React Context + useReducer) keyed by symbol. Create useSignalSocket() hook connecting to ws://backend/ws/signals for live signal status updates. Expose useStockPrice(symbol) convenience hook returning latest tick for a symbol. Ensure WebSocket connections are shared (single connection per namespace) and components subscribe/unsubscribe via context. This service enables real-time price flashes across GainersTable, LosersTable, ScannerHeader, DashboardLiveSignals, etc.
As a Backend Developer, implement user settings persistence API: GET /api/user/settings (returns all user preferences: capital, risk_pct, max_drawdown, notification_channels, ai_score_threshold, dark_mode, watchlist), PUT /api/user/settings (batch update any subset of settings with validation), GET /api/user/watchlist (returns user's watchlisted symbols), POST /api/user/watchlist (add symbol), DELETE /api/user/watchlist/{symbol} (remove symbol). Uses UserSettings ORM model. Required to support RiskCapitalInput persistence, AlertsSettings save, and Watchlist features across pages. Depends on DB models and auth API.
As a Backend Developer, implement the Google OAuth2 consent flow required by the Export API's POST /api/export/sheets endpoint: GET /api/google/auth/url (returns Google OAuth2 consent URL with Drive/Sheets scopes), GET /api/google/auth/callback (exchanges auth_code for Google tokens, stores encrypted refresh token in UserSettings), GET /api/google/auth/status (returns whether the user has connected their Google account). This prerequisite enables /api/export/sheets to use the stored Google refresh token to create spreadsheets in the user's Drive. Requires GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET env vars (already in 8e302583). Depends on DB models (b1e05bed) and auth API (beabb412).
As a Frontend Developer, implement a minimal Service Worker to enable browser Push Notifications: register the Service Worker on app load, call GET /api/push/vapid-public-key to retrieve the VAPID key, use PushManager.subscribe() to create a push subscription, POST the subscription object to POST /api/push/subscribe (new endpoint to store subscription in DB), and handle push events in the Service Worker to display browser notifications when alerts trigger. This enables the browser notification channel in NotificationChannels and AlertsSettings. Depends on VAPID setup (backend-notification-vapid-setup).
As a Backend Developer, implement browser push subscription management endpoints: POST /api/push/subscribe (stores the browser PushSubscription object in DB linked to user_id), DELETE /api/push/subscribe (removes subscription on unsubscribe/logout), GET /api/push/vapid-public-key (returns VAPID public key, unauthenticated). Integrate push dispatch into the alerts notification service so when an alert fires it calls web-push send_notification() for all active browser subscriptions for that user. Depends on DB models (b1e05bed), auth API (beabb412), and VAPID keys (backend-notification-vapid-setup).
As a Backend Developer, implement rate limiting middleware for the FastAPI application to comply with financial data regulations and protect against abuse: use slowapi (or fastapi-limiter with Redis) to apply per-IP and per-user rate limits. Public endpoints (/api/public/*): 30 req/min. Auth endpoints (/api/auth/login, /register): 5 req/min per IP. Market data endpoints: 120 req/min per user. AI endpoints (/api/ai/*): 30 req/min per user (LLM cost protection). Return 429 with Retry-After header on limit exceeded. Log rate limit events. Depends on Redis (dfabfd55) and auth API (beabb412).
As a frontend developer, implement the DashboardMarketSentiment section for the Dashboard page. Render a `dms-root` section containing a header with an `h2` heading 'Market Sentiment' and a bullish status dot badge (`dms-status--bullish`). Implement a staggered card grid using `framer-motion` `motion.div` with `containerVariants` (staggerChildren: 0.08) and `cardVariants` (opacity 0→1, y 12→0, duration 0.35) for the four METRICS: Advances (1283), Declines (716), Adv/Dec Ratio (1.79), and Breadth % (28.4%). Each `dms-card` displays label, value, directional sub-text with ▲/▼ icons via `dms-card-sub--up/down`, and a progress bar (`dms-bar-wrap` / `dms-bar-fill`) for ratio and breadth cards at `barPct` width. Render a live `timeStr` timestamp via `toLocaleTimeString('en-IN')` in the `dms-updated` footer. Imports `DashboardMarketSentiment.css`.
As a frontend developer, implement the DashboardMarketStatus section for the Dashboard page. Manage `useState` hooks for `status` (bullish/bearish/neutral), `advances`, `declines`, `adRatio`, `lastUpdated`, `spinning`, and `showRefreshed`. Implement `STATUS_STATES` config mapping each status to label, icon (↗/↘/↔), and CSS class variants (`dms-banner--bullish/bearish/neutral`, `dms-icon-wrap--*`, `dms-status--*`). Build `refreshData` using `useCallback` that triggers a 600ms `setTimeout`, randomly selects a status using weighted probabilities (0.55/0.25/0.2), recalculates advances/declines/adRatio per status branch, updates `lastUpdated` via `toLocaleTimeString` with `timeZone: 'Asia/Kolkata'`, and shows a 1800ms 'refreshed' flash. Use `framer-motion` `AnimatePresence` with `mode='wait'` keyed on `status` for animated banner transitions between status states. A spinning refresh button triggers `refreshData` with guard against double-calls. Imports `DashboardMarketStatus.css`.
As a frontend developer, implement the DashboardScannerCandidates section for the Dashboard page. Render paginated scanner candidates from `ALL_CANDIDATES` array (20 stocks with symbol, sector, ltp, gapPct, volume, relVolume, strength fields) using `ITEMS_PER_PAGE=5`. Implement pagination state with `useState` and `useRef`, along with `useCallback`-wrapped handlers and a `useEffect` for side-effects. Render `CandidateCard` components using `cardVariants` framer-motion animations. Implement `getStrengthClass(score)` returning 'high'/'mid'/'low' thresholds at 80/50, and `formatVolume(n)` formatting to 'Cr'/'L' suffixes using Indian locale (`toLocaleString('en-IN')`). Use `AnimatePresence` for card enter/exit transitions. Style strength indicators per grade and display gap percentage with directional coloring. Imports `CandidateCard.css` and `DashboardScannerCandidates.css`.
As a frontend developer, implement the DashboardLiveSignals section for the Dashboard page. Render a signals list from the `SIGNALS` array (10 entries with id, symbol, sector, setup BUY/SELL, entry, current, pnlPercent, status Active/At Risk/Closed, rrRatio, timestamp, stopLoss, target, volume, strength, chartUrl). Implement `useMemo`-based filtering/sorting logic to support filter tabs and `useState` for active filter state. Use `framer-motion` `AnimatePresence` for signal card enter/exit transitions. Display PnL coloring based on `pnlPercent` positive/negative values, status badges for Active/At Risk/Closed states, BUY/SELL setup direction indicators, and strength scores. Include `chartUrl` navigation links to `/Chart?symbol=SYMBOL`. Handle the large JSX surface area (19252 chars) with component decomposition for signal cards. Imports `DashboardLiveSignals.css`.
As a frontend developer, implement the DashboardSectorAnalysis section for the Dashboard page. Render 8 sectors from the `SECTORS` array (IT, Pharma, Banking, Oil & Gas, Automobile, FMCG, Metals, Power with perf%, candidates count, positive bool). Implement `useState` view toggle between 'cards' and 'chart' modes, toggled via `dsa-toggle-btn` / `dsa-toggle-btn--active` buttons with SVG grid icons. Compute `topSector` by sorting descending perf and `maxAbsPerf` for proportional bar width scaling. In cards view render sector cards with performance coloring (positive/negative). In chart view render horizontal bar chart with bars proportionally sized to `Math.abs(perf) / maxAbsPerf`. Use `framer-motion` `AnimatePresence` for view transition animations. Display SVG rect-icon group in `dsa-icon` header. Imports `DashboardSectorAnalysis.css`.
As a frontend developer, implement the DashboardGainersLosers section for the Dashboard page. Render tabbed GAINERS (8 stocks) and LOSERS (8 stocks) lists with `useState` tab toggle. Implement `StockRow` component using `motion.div` with `rowVariants` (hidden: opacity 0, x -12 → visible: opacity 1, x 0 with `custom={index}` stagger delay of `i * 0.04`, exit: x 12). Implement `getRankClass(index)` returning `dgl-row__rank--gold/silver/bronze/default` for top 3, `getRankIcon(index)` returning medal emojis 🥇🥈🥉 for top 3 ranks, and `getChangeClass(change)` returning `dgl-row__change--highlight` for abs >= 4, `--gain` for positive, `--loss` for negative. Format change values with sign via `formatChange`. Each row navigates to `/Chart?symbol=` on click. Use `AnimatePresence` for list transition between gainers/losers tabs. Imports `DashboardGainersLosers.css`.
As a frontend developer, implement the DashboardAIScoring section for the Dashboard page. Render AI-scored setups from `SETUPS` array (9 entries with aiScore, confidence, symbol, type Buy/Sell, entry/sl/target, sector, ltp). Implement `ScoreBadge` component using `getScoreGrade(score)` returning 'high'/'mid'/'low' at thresholds 70/30, applying `dai-score-badge--high/mid/low` CSS classes. Implement `Tooltip` component with `useState` for `visible` toggled via `onMouseEnter/Leave` and `onFocus/Blur`, rendering a `dai-tooltip-bubble` span. Build `SetupCard` as a `motion.div` with `layout` prop, `initial={{ opacity: 0, y: 16 }}` animation displaying grade-classed card borders. Implement filtering/sorting controls using `useState`, `useMemo`, and `useCallback`. Import lucide-react icons: `Sparkles`, `TrendingUp`, `TrendingDown`, `ChevronDown`, `Shield`. Use `AnimatePresence` for list animations. Imports `DashboardAIScoring.css`.
As a frontend developer, implement the DashboardRiskManagement section for the Dashboard page. Manage `useState` for `capital` (default 10000), `stopLossPercent` (1.0), `targetPercent` (2.5), `activePreset` (null), and `applied` (false). Implement four `useMemo` derived calculations: `riskAmount = capital * (stopLossPercent/100)`, `rewardAmount = capital * (targetPercent/100)`, `riskRewardRatio = targetPercent/stopLossPercent`, and `positionSize = capital / (stopLossPercent/100)`, all rounded to 2 decimal places. Implement `useCallback`-wrapped handlers: `handleCapitalChange`, `handleSLChange`, `handleTargetChange` (each resets `activePreset`), `handlePreset` applying one of four PRESETS (Conservative/Moderate/Aggressive/High Risk with preset capital/sl/target values), `handleApply` showing 2800ms applied flash, and `handleReset` returning to defaults. Compute `rrLabel` as 'Good' (>=2) or 'Low'. Render a `drm-grid` layout with input fields, preset buttons with `activePreset` highlight, calculated output metrics, and apply/reset action buttons. Header includes `drm-section-tag`, `drm-title`, and `drm-subtitle`. Imports `DashboardRiskManagement.css`.
As a frontend developer, implement the ScannerHeader section for the Scanner page. This section uses framer-motion containerVariants/itemVariants with staggerChildren (0.08s) for entrance animation. It manages `scanning` (bool), `lastScan` (string), and `scanCount` (number, init 1847) state via useState. A useEffect runs setInterval every 60000ms to update lastScan via getLastScanLabel() which computes relative time from a fixed 09:25 AM scan time. The `handleManualScan` function triggers a 2200ms scanning animation then increments scanCount. The JSX renders: sh-title-group with ScanSearch lucide icon + h1 'Scanner' + subtitle 'NSE Intraday · Paisa Banao Strategy Pro'; sh-status badge using SCAN_STATUS.active; sentiment display using SENTIMENT_MAP (Bullish/Bearish/Neutral) with adv/dec counts; RefreshCw icon button that triggers handleManualScan with spinning state; Clock icon showing lastScan label; Activity and BarChart2 icons for market breadth. SENTIMENT_MAP drives tone classes (bullish/bearish/neutral) on the status container. Note: Navbar/Sidebar may already exist from Dashboard page — reuse DashboardSidebar component if applicable.
As a frontend developer, implement the GainersHeader section for the Gainers page. Build the animated header using framer-motion with containerVariants (staggerChildren: 0.09) and itemVariants/chipVariants for entrance animations. Implement the STATS array (5 chips: Top Gainers, Live NSE Data, Volume Tracked, Sectors, AI Score Enabled) each with Lucide icons (TrendingUp, Activity, BarChart2, Layers, Star) and distinct CSS classes (gh-chip-gain, gh-chip-vol, gh-chip-sector, gh-chip-ai). Add the live timestamp using useState/useEffect with setInterval (1s tick) calling formatTimestamp() with en-IN locale formatting. Include decorative background blobs (gh-bg-accent, gh-bg-accent-2) as aria-hidden divs, the gh-icon-wrap TrendingUp icon, h1 title with highlighted span, descriptive paragraph referencing Fyers API V3, and the gh-status-badge live indicator with gh-live-dot pulse animation. Import GainersHeader.css for all styling.
As a frontend developer, implement the LosersPageHeader section for the Losers page. Build the `LosersPageHeader` component using `useState` and `useEffect` to drive a live clock (`setInterval` every 1000ms) displaying `HH:MM:SS IST`. Render a breadcrumb nav with links to `/Dashboard` and `/Scanner` and a current `Top Losers` crumb. Use `framer-motion` with `containerVariants` (staggerChildren: 0.08) and `cardVariants` (opacity/y with easeOut) plus `titleVariants` for the title block entrance. Render four stat cards from the `STATS` array: 'Total Losers Today' (TrendingDown icon, red), 'Avg. Loss Percentage' (BarChart2, orange, with 'High Selling Pressure' badge), 'Market Sentiment' (Activity, blue, with `getSentimentClass` for Bearish/Bullish/Neutral badge), and 'Weakest Sector' (AlertTriangle, gold, with '-4.81% avg drop' badge). Apply CSS classes from `LosersPageHeader.css` including `lph-root`, `lph-inner`, `lph-meta`, `lph-breadcrumb`, `lph-timestamp`, `lph-live-dot`, and stat-specific classes like `lph-stat-icon--red`, `lph-stat-value--red`.
As a frontend developer, implement the SectorsHero section for the Sectors page. This section renders a full hero with: (1) `useState` hooks for `activeFilter`, `sortBy`, `search`, and `lastUpdated`; (2) a real-time clock via `setInterval` in `useEffect` updating `lastUpdated` every second; (3) `getMarketStatus(18, 7)` logic returning 'bullish'/'bearish'/'neutral'; (4) a `MarketBadge` sub-component displaying status with animated `sh-badge-indicator` dot; (5) a `SearchIcon` SVG sub-component; (6) `FILTER_OPTIONS` tab pills ('All Sectors', 'Bullish', 'Bearish', 'Neutral') with `activeFilter` state toggle; (7) a `SORT_OPTIONS` dropdown (6 options including strength, change, volume, name sorts); (8) `MARKET_STATS` stat bar showing Advancing/Declining/Unchanged/Sectors Tracked/A-D Ratio with colored cls variants (up/down/amber/blue); (9) Framer Motion `motion.div` on the title row with `initial={{ opacity: 0, y: -10 }}` and `animate={{ opacity: 1, y: 0 }}` at 0.38s ease-out; (10) `sh-eyebrow` branding row with `sh-eyebrow-dot`. Imports `SectorsHero.css`. Note: DashboardSidebar may already exist from Dashboard page.
As a frontend developer, implement the ChartSidebar section for the Chart page. Build the animated aside component using framer-motion with containerVariants (staggerChildren: 0.06) and itemVariants (opacity/x slide-in). Implement: (1) Search bar with useState('') for searchVal and lucide-react Search icon; (2) Favorites panel showing RELIANCE, HDFCBANK, TCS, INFY with price/change/dir color coding and activeStock state via handleFavClick; (3) Watchlist panel with BAJFINANCE, TATAMOTORS, WIPRO, SBIN, ADANIENT rows showing sector, ltp, chg with up/down color classes; (4) Related Setups panel with buy/sell type badges and AI score values (91, 88, 84, 79); (5) NAV_VIEWS side navigation with lucide icons (BarChart2, Activity, BookOpen, Star, Bell) linking to /Chart, /Signals, /Backtest, /AI Score, /Alerts; (6) STOCK_METRICS row showing Gap %, Volume, Rel Vol, Strength. Apply ChartSidebar.css styles. Depends on Dashboard page's DashboardSidebar task for layout reference.
As a frontend developer, implement the SignalsHeader section for the Signals page. Build the animated header using framer-motion with containerVariants (staggerChildren: 0.08) and itemVariants (opacity/y fade-in, duration 0.28). Render the sh-eyebrow div with an animated sh-live-dot pulse indicator and 'Live · NSE Intraday' label. Display the h1 with sh-title-accent span for 'Live Trading Signals'. Map over the STATS array (3 items: Active Signals with Activity icon in blue, Win Rate 78.4% with TrendingUp in green, Avg RR Ratio 1:2.6 with BarChart2 in orange) rendering each as an sh-stat card with lucide icon, sh-stat-value, and sh-stat-label. Nested motion.div for stats row uses its own containerVariants/itemVariants stagger. Import SignalsHeader.css for sh-root, sh-inner, sh-top, sh-stats layout styles.
As a frontend developer, implement the AlertsHeader section for the Alerts page. Render the `ah-root` section with breadcrumb navigation using `Home` and `ChevronRight` icons linking back to `/Dashboard`. Build the `ah-main` block containing a title row with a `Bell` icon and the 'Alerts & Notifications' heading, a description paragraph, and an `ah-actions` row with a `Plus`-icon 'Create Alert' primary button, a `Settings`-icon secondary button, and an animated 'Live Monitoring' live badge with a pulsing `ah-live-dot`. Below, render the `ah-stats` group mapping the static STATS array (Active=12, Triggered=5, Paused=3, Total=20) into `ah-stat` divs with color-classed values. Apply AlertsHeader.css styles. Note: DashboardSidebar may already exist from Dashboard page.
As a frontend developer, implement the BacktestHeader section for the Backtest page. This section renders a breadcrumb nav (Dashboard → Trades → Backtest) using ChevronRight icons from lucide-react, a title block with 'Strategy Backtesting' heading (with bh-title-accent span), a subtitle referencing Paisa Banao NSE 5-minute historical data, and a 'New Backtest' CTA button with PlusCircle icon using useRef(ctaRef). A quick stats strip renders three bh-stat-chip elements showing Avg Win Rate (68.4%), Profit Factor (2.87), and Last Run date using BarChart3, TrendingUp, and Clock icons. All elements use framer-motion fadeUp animation with staggered delays (0, 0.08, 0.14, 0.2). Component may already exist from earlier pages — check for reuse.
As a frontend developer, implement the BacktestParameters section for the Backtest page. This section manages extensive form state via useState hooks: activeTab ('quick'/'advanced'), strategy (STRATEGIES array with 6 options including paisa_banao_buy/sell, rsi_divergence, volume_breakout, gap_reversal, moving_avg_cross), watchlist (WATCHLIST_OPTIONS covering nifty50/100/500/bank/custom/all_nse), timeframe (TIMEFRAMES: 5min/15min/hourly/daily/weekly), startDate, endDate, capital (number), riskPercent, activePreset, trailSL (boolean toggle), compoundPositions (boolean toggle), filterScore (boolean toggle). Renders 4 preset cards (Conservative/Moderate/Aggressive/Custom) via PRESETS array with handlePresetApply logic that auto-sets risk/capital/timeframe. handleReset restores all defaults. Includes Run Backtest (Play icon) and Reset (RotateCcw icon) action buttons. Uses Zap, Settings, TrendingUp icons from lucide-react. This is a complex interactive form with no backend call — pure frontend state.
As a frontend developer, implement the BacktestResults section for the Backtest page. This section renders a bsr-grid of metric cards using two static data arrays: METRICS (4 items: total_return +34.82%, win_rate 62.8%, profit_factor 2.47, max_drawdown 11.20%) and TRADE_COUNT_METRICS (total_trades 432 with wins/losses split). Each card uses framer-motion motion.div with cardVariants (hidden/visible with staggered delay i*0.08) triggered by whileInView with viewport margin '-60px'. Cards use dynamic CSS class modifiers bsr-card--positive/negative/neutral/info and bsr-card-icon--gold/blue/orange. Icons from lucide-react: TrendingUp, TrendingDown, Minus, Target, ShieldAlert, BarChart3, PieChart, Award, Crosshair, Calendar. Header includes a bsr-period-badge with Calendar icon showing 'May 2025 – Jun 2026'.
As a frontend developer, implement the BacktestMetrics section for the Backtest page. This section renders a searchable, sortable metrics table using useState and useMemo hooks. METRICS_DATA contains 12 rows (Consecutive Wins/Losses, Average Win/Loss %, Win/Loss Ratio, Recovery Factor, Sharpe/Sortino/Calmar Ratios, Best/Worst Trade, Avg Trade Duration). Features: Search input filtering metric names (Search icon), column sort via ArrowUpDown icon cycling through asc/desc/none per column (COLUMNS: Metric, Value, Category, Bar), animated bar visualization per row, Download button for export. METRIC_TOOLTIPS object maps metric names to explanatory strings shown via Info icon hover. AnimatePresence from framer-motion handles row enter/exit animations. getValueClass() applies bm-value--positive/negative/neutral CSS classes based on value prefix.
As a frontend developer, implement the BacktestChart section for the Backtest page. This section uses react-chartjs-2 Line component with ChartJS registered modules: LineElement, PointElement, LinearScale, TimeScale, CategoryScale, Filler, Tooltip, Legend. Equity curve data is generated by generateEquityData() using a random-walk simulation (drift=0.0008, vol=0.012) over 252 trading days from 2025-12-01 producing equity and drawdown arrays. State: zoomDays (useState(0)) controls data slicing. ZOOM_PRESETS array provides 1M/3M/6M/1Y/All buttons (days: 22/66/132/252/0). useMemo hooks compute equityData, drawdownData (sliced by zoomDays), equityNet (% and abs change), and maxDD (minimum drawdown in window). Two chart refs: equityChartRef and ddChartRef. Icons: TrendingUp, TrendingDown, BarChart3, ZoomIn, ZoomOut, Maximize, Calendar. AnimatePresence handles chart panel transitions. Chart options factory builds common config for both equity and drawdown Line charts.
As a frontend developer, implement the BacktestTrades section for the Backtest page. This section renders a paginated, sortable, filterable trades log table using useState and useMemo. TRADES_DATA contains 14+ sample trade records with fields: num, entryDate, entryPrice, exitDate, exitPrice, shares, pnlAmount, pnlPercent, duration, result (win/loss). State hooks: sort column/direction toggled via ChevronUp/ChevronDown icons, search query (Search icon), result filter (win/loss/all), current page for pagination. useMemo computes filtered and sorted trade rows. RotateCcw icon resets all filters. ListOrdered icon in header. FileX icon displayed when no trades match filters (empty state). AnimatePresence with motion.div handles row enter/exit animations. PnL values use conditional CSS classes for positive/negative coloring. Pagination controls render page numbers and prev/next navigation.
As a frontend developer, implement the BacktestExport section for the Backtest page. This section manages async export/share actions via useState: activeId (tracks in-flight action), status ({type, message, actionId}), shareLink (string|null), copied (boolean). EXPORT_ACTIONS array defines 3 actions: csv (Download icon, primary variant), sheets (FileSpreadsheet icon, secondary variant), share (Share2 icon, outline variant), each with statusMessages for pending/success/error states. handleAction (useCallback) simulates async export with 1800ms setTimeout, sets pending status, then success; for 'share' action sets MOCK_SHARE_LINK. Auto-clears success status after 5s via nested setTimeout. handleCopyLink uses navigator.clipboard.writeText with setCopied(true) reverting after 2200ms. AnimatePresence renders status banner with CheckCircle2/AlertCircle/Loader2 icons. Share link panel with ExternalLink and Copy icons appears conditionally when shareLink is set. Icons: Download, FileSpreadsheet, Share2, Copy, CheckCircle2, AlertCircle, Loader2, ExternalLink.
As a Backend Developer, implement live signals REST and WebSocket endpoints: GET /api/signals (returns all active signals with symbol, direction, entry, sl, risk, target1, target2, qty, volume_score, setup_quality, status), POST /api/signals/{id}/close (manually close a signal), GET /api/signals/{id} (detail with chart annotations), WebSocket /ws/signals (push signal status updates: Waiting→Triggered→Target Hit/Breakeven/Closed in real time as Fyers tick data flows in). Implement status transition logic: mark Triggered when LTP crosses entry, Target Hit when LTP crosses target, SL Hit when LTP crosses sl, Breakeven when 1:2 RR achieved triggering 50% book + SL move logic. Store signals in DB (Trade model). Depends on scanner and Fyers integration.
As a Backend Developer, implement data export endpoints: GET /api/export/signals/csv?from=X&to=X (streams CSV of signals for the date range with headers: symbol, direction, entry, sl, target1, target2, qty, volume_score, setup_quality, status, entry_time, exit_time, pnl), GET /api/export/trades/csv?from=X&to=X (trade history CSV export), POST /api/export/sheets (OAuth2 Google Sheets export: creates a new sheet in the user's Drive and populates it with signal data, returns sheet URL). Use Python csv module for CSV generation and Google API Python client for Sheets. Add GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET env vars. Depends on DB models and trades API.
As a Tech Lead, verify the end-to-end integration between the authentication frontend (LoginForm, SignupForm, LoginSignupPrompt) and the Auth API backend (POST /api/auth/login, /api/auth/register). Ensure JWT tokens are stored correctly, ProtectedRoute redirects work, the AuthContext is populated after login, and logout clears state and tokens. Verify that all protected pages (/Dashboard, /Scanner, /Signals, /Trades, /Risk, /Alerts, /Backtest, /AI Score, /Chart) redirect to /Login when unauthenticated. Test token refresh flow on 401 responses.
As a Tech Lead, verify the end-to-end integration between the Fyers WebSocket relay backend (ws://backend/ws/market) and the frontend Global WebSocket Service (useMarketSocket, MarketDataContext, useStockPrice). Ensure: the backend relay successfully subscribes to Fyers V3 live tick feed and rebroadcasts tick payloads, the frontend hook connects after auth and dispatches ticks to MarketDataContext, useStockPrice(symbol) returns the latest LTP for a given symbol causing price flash animations, and symbol subscription/unsubscription messages from the frontend are handled by the relay. Test with NSE equity symbols (NSE:RELIANCE-EQ format). Depends on Fyers WebSocket Relay (a828093a), Global WebSocket Service (4f52cee3), and Fyers OAuth2 flow (backend-fyers-oauth-flow).
As a Backend Developer, implement the scheduled auto-scanner job that runs automatically at 09:25 AM IST on trading days: use APScheduler (or Celery Beat) to schedule the Paisa Banao scan logic from /api/scanner/run, persist results to the DB (Trade model candidates table or a dedicated ScanResult model), and broadcast the scan completion event via the /ws/signals WebSocket so the Scanner page's RealTimeUpdates feed receives the event without user action. Add a GET /api/scanner/last-run endpoint returning last run timestamp and candidate count. Depends on Scanner API (6fcc057a), Fyers integration (18450547), and DB models (b1e05bed).
As a frontend developer, implement the ScannerFilters section for the Scanner page. This section manages `searchVal`, `sector` (default 'All Sectors' from 12-item SECTORS array), `volumeSpike` (bool toggle), `scoreThreshold` (number, default 70), `viewMode` ('grid'|'list'), and `showToast` (bool) state. A toastTimer ref handles the 2400ms save confirmation toast via handleSave(). Active filter chips are computed dynamically from state and rendered with AnimatePresence for enter/exit animations — each chip has a removeChip(key) handler. The clearAll() function resets all filters to defaults. The JSX renders: sf-search-wrap with Search lucide icon + text input for symbol search; sf-select-wrap with TrendingUp icon + native select for sector; a volume spike toggle button with CheckCircle icon; a score threshold range slider with fillPct (0–100) CSS variable for track fill styling; LayoutGrid/List toggle buttons for viewMode; Bookmark icon button for save with toast notification; RotateCcw icon button for clearAll. The `onFiltersChange` prop callback is invoked when filters update. AnimatePresence wraps the chips row for smooth add/remove transitions.
As a frontend developer, implement the ScannerStats section for the Scanner page. This is a static display section with no local state. It renders a 5-card grid from the STATS array: 'Total Candidates Scanned' (ScanLine icon, value '1,487', meta 'NSE cash stocks · today'), 'Active Setups' (Layers icon, value '23', meta '14 Buy · 9 Sell'), 'Top Sector' (Tag icon, value 'Banking' with sst-sector-badge containing dot + text), 'Avg Strength Score' (BarChart2 icon, value '78.4'), 'Scan Coverage' (Percent icon, value '87%' with isCoverage=true for a progress bar). Each card uses framer-motion with cardVariants — hidden (opacity 0, y 14) to visible with staggered delay (i * 0.07s), triggered by whileInView with viewport once:true. Each card has sst-card--{cardVariant} class (primary/warning/accent/highlight/success) and sst-icon-wrap--{iconVariant} for color theming. The section heading includes ScanLine icon, 'Scanner Summary' title, and 'Last updated: 09:25 AM' sub-label.
As a frontend developer, implement the RealTimeUpdates section for the Scanner page. State: `feed` (array, init INITIAL_FEED of 8 events), `newRowIds` (Set for highlight tracking), `spinning` (bool), `lastRefreshed` (string). Module-level mutable vars: `nextId` (init 100) and `incomingIdx` (init 0) for cycling INCOMING_EVENTS (6 events). A useEffect sets up a setInterval that every ~3s appends the next INCOMING_EVENTS entry to feed (max ~20 rows, oldest pruned), adds its id to newRowIds, then removes it from newRowIds after 1200ms highlight window. The RefreshCw icon button triggers `spinning` for a CSS spin animation + manual feed refresh. Activity icon shows live indicator. Each feed row renders: timestamp (time field), action label styled by actionType ('new'/'confirmed'/'cancelled'/'updated') via getActionIconClass(), symbol text, BUY/SELL badge, entry price, and score badge styled by getScoreClass() (rtu-score--high/mid/low for ≥85/≥70/else). AnimatePresence wraps feed rows for enter (y: -12, opacity 0) → visible → exit animations. useCallback wraps the refresh handler. A useRef may be used for the interval cleanup.
As a frontend developer, implement the GainersFilterBar section for the Gainers page. Build a two-row filter control bar using useState hooks for search (string), sector (default 'All Sectors'), period (default '1D'), sortBy (default 'gain'), and sortDir (default 'desc'). Render a text search input with Search Lucide icon (maxLength 12, aria-label). Render a sector dropdown from SECTORS array (14 options including Banking & Finance, IT, Pharma, etc.) with ChevronDown icon. Render PERIODS toggle buttons (1D, 5D, 1M, 3M, 1Y) and SORT_OPTIONS buttons (Gain %, Volume, LTP) with ArrowUpDown/ArrowUp/ArrowDown icons toggled via handleSortToggle. Derive activeTags array from non-default state values and render them with AnimatePresence using tagVariants (spring stiffness 340, damping 22). Implement removeTag useCallback to reset individual filters and handleReset to clear all. Include RefreshCw icon on reset button and Activity/Layers icons for sector/period labels. Import GainersFilterBar.css.
As a frontend developer, implement the `LosersFilterBar` component for the Losers page. Manage five pieces of state via `useState`: `search` (text input for symbol search e.g. RELIANCE), `sector` (dropdown from 11-item SECTORS array defaulting to 'All Sectors'), `period` (tab group from PERIOD_TABS: Today/1W/1M), `lossRange` (range slider 1–30 defaulting to 10, with dynamic `lossPercent` label and `lossFill` computed fill width), and `volumeFilter` (chip group from VOLUME_CHIPS: Any/1L/5L/10L). Compute `activeCount` as the count of non-default filters and show it in the clear button badge. Implement `handleClear` to reset all state to defaults. Use `framer-motion` `fadeIn` variants with custom stagger index (`custom` prop) on each animated row. Render a sector dropdown with ChevronDown, Check icons from lucide-react for active option, and a Filter icon with active count badge. Apply CSS classes from `LosersFilterBar.css` including `lfb-root`, `lfb-inner`, `lfb-row1`, `lfb-search-wrap`, `lfb-period-tabs`, `lfb-period-tab`, `lfb-active`.
As a frontend developer, implement the `LosersMetrics` component for the Losers page. Use `useState` (`animated`) and `useRef` (`rootRef`) with an `IntersectionObserver` (threshold 0.12) to trigger entrance animations only when the section scrolls into view, then disconnect. Register `ChartJS` with `ArcElement`, `Tooltip`, `Legend` and render a `Doughnut` chart from `react-chartjs-2` using `SECTOR_DISTRIBUTION` data (7 sectors: IT, Banking, Auto, Pharma, Metal, FMCG, Others with hex colors), configured with `cutout: '68%'`, hidden legend, and custom tooltip label callback. Render a custom legend grid below the donut. Render 4 summary metric cards from `METRICS` array (Avg Loss, Total Volume, Sectors Hit, Market Breadth) using `cardVariants` with custom stagger delay. Render `TOP_LOSING_SECTORS` (5 sectors) as animated horizontal bars using `barVariants` (opacity/x with stagger), with dynamic width computed from `loss / max * 100%`. Apply CSS from `LosersMetrics.css` including `lm-root`, `lm-inner`, metric value classes `loss`, `primary`, `gold`, and bearish badge styling.
As a frontend developer, implement the ChartHeader section for the Chart page. Build a header component with three core behaviors: (1) Live price simulation via setInterval every 2000ms using useRef(priceRef) to accumulate delta (Math.random() - 0.48) * 3.5, clamped to [2750, 2950], updating price/prevPrice state for flash animation classes (chh-price-flash-up / chh-price-flash-down); (2) Timeframe selector for ['1m','5m','15m','1h','Daily'] with activeTimeframe useState('5m') and active styling; (3) Alert and Export buttons triggering toast notifications via useRef timers (toastTimerRef, exportTimerRef) with 2800ms auto-dismiss and AnimatePresence; (4) Market open/closed status computed from current hour/minutes (09:15–15:30); (5) OHLCV stats row (open, high, low, volume, prevClose) and change/changePct display with TrendingUp/TrendingDown lucide icons. Apply ChartHeader.css with formatPrice en-IN locale formatting.
As a frontend developer, implement the ChartIndicators section for the Chart page. Build a panel of four indicator cards defined in the INDICATORS array (volume_profile, order_flow, relative_strength, strength_index), each rendered with one of three mini-visualization sub-components: (1) Sparkline — SVG-based line+area chart using genSparkPoints() to map values to (x,y) coordinates, buildPath() for the line, buildArea() for filled area, with trend-keyed CSS classes (ci-sparkline-fill--up/down/neutral) and a terminal dot; (2) VolumeBars — proportional bar chart divs with ci-bar--up/down coloring, last bar adopting the trend; (3) GaugeBar — horizontal progress track with ci-gauge-fill--up/down/neutral and percentage label. Each card shows label, value, delta, and sub text. Wrap card entries with framer-motion for stagger animation. Apply ChartIndicators.css.
As a frontend developer, implement the ChartAnalysis section for the Chart page. Build a tabbed analysis panel with three tabs controlled by useState: (1) 'Setup Details' tab rendering SETUP_METRICS grid (Entry Level ₹2,845.50, Stop Loss ₹2,810.00, Target 1/2, Risk:Reward 1:2.8, AI Score 91/100 with aiBar progress bar) using ca-val-primary/danger/success/gold CSS classes; (2) 'Trade Analysis' tab showing TRADE_HISTORY rows (buy/sell type badges, entry/exit prices, win/loss result, pnl color), WIN_STATS summary row (68% win rate, 34 trades, 2.4× profit factor, ₹8,240 avg profit), and BACKTEST_ROWS table with positive/negative coloring; (3) 'Market Context' tab rendering SECTORS horizontal bar chart (IT Services, Banking, Energy, FMCG, Pharma, Metals with pos/neg direction), RELATED stocks list (TCS, INFY, WIPRO, HCLTECH with change %), and BREADTH advancing/declining/unchanged gauge bars. Tab panel transitions use panelVariants with AnimatePresence (opacity 0→1, y 6→0, 0.22s). Apply ChartAnalysis.css.
As a frontend developer, implement the SignalsFiltersBar section for the Signals page. Build a controlled filter bar using useState for six filter fields: search (text), timeframe (pill buttons from TIMEFRAMES array: All/5m/15m/1h), status (pill buttons from STATUSES: All/Buy/Sell/Closed), sector (select dropdown from SECTORS array with 11 options), strengthMin (range slider, default 60), and aiScoreMin (range slider, default 70). Use useMemo to compute activeCount of non-default filters and display a badge. Implement handleClear() to reset all filters to DEFAULTS. Apply dynamic linear-gradient CSS custom property to range slider tracks via strengthTrack and aiTrack inline styles. Wrap entire bar in motion.div with opacity/y fade-in animation (duration 0.28). Include sfb-search-wrap with Search lucide icon, sfb-divider, sfb-filter-block rows, and a clear button that appears when activeCount > 0 with X icon. Import SignalsFiltersBar.css.
As a frontend developer, implement the SignalsChartViewer section for the Signals page. This is a complex canvas-based chart component using useState, useEffect, useRef, and useCallback. Implement generateCandles() to produce OHLCV candle arrays with configurable timeframe intervals (5m/15m/1h in ms). Implement computeBB() for Bollinger Bands (period=20, stdDevMult=2) returning {mid, upper, lower} per candle and computeMA() for moving averages. Build renderChart() as the core canvas renderer using devicePixelRatio scaling, drawing price candles, volume bars (showVolume toggle), BB bands (showBB toggle), MA lines (showMA toggle), and signal overlays (entry/SL/target lines) for DEMO_SIGNAL (RELIANCE BUY at 2845.50, SL 2810, targets 2920/2975, aiScore 94). Include toolbar controls using lucide icons: Maximize2/Minimize2 for fullscreen toggle, ZoomIn/ZoomOut for zoom, X to close, BarChart2 for volume, Brain for BB/MA overlays, ChevronRight for panel expand. Use AnimatePresence for panel transitions. Import SignalsChartViewer.css with scv- BEM classes.
As a frontend developer, implement the SignalsTradePanel section for the Signals page. Build a two-panel grid layout (stp-grid) using useState for: capital (default 500000), activeRisk (default 1, from RISK_OPTIONS array: 0.5%/1%/2%/5%), entryPrice (2845.50), stopLossPrice (2810.00), riskSet (boolean), showCloseModal (boolean), tradeClosed (boolean), and showToast (null|'risk'|'success'). Left panel (Risk Management, ShieldCheck icon): render RISK_OPTIONS as pill buttons, capital/entry/SL inputs, compute riskAmount = capital * (activeRisk/100), slDistance = entryPrice - stopLossPrice, positionSize = floor(riskAmount/slDistance), positionValue = positionSize * entryPrice. handleSetRisk() sets riskSet=true and triggers 'risk' toast for 3s. Right panel (Active Trade, TrendingUp icon): display ACTIVE_TRADE object (RELIANCE BUY, entry 2845.50, current 2891.25, SL 2810, pnl +4575 INR / +1.61%, rrAchieved 1.3). Render AUTO_CLOSE_TARGETS (4 rows: 1:1 move SL, 1:2 close 50%, 1:3 close 25%, 1:5 exit full) as CheckCircle2/Circle indicator rows. Show pnlFillPercent progress bar (min(100, rrAchieved/5*100)). Implement showCloseModal with XCircle confirmation dialog via AnimatePresence, handleConfirmClose() triggers 'success' toast 3.5s. Use formatINR() for en-IN locale formatting. Import SignalsTradePanel.css with stp- BEM classes.
As a frontend developer, implement the SignalsExportSection section for the Signals page. Build an export controls bar using useState for fromDate (initialized to THIRTY_DAYS_AGO = Date.now() - 30 days ISO string) and toDate (TODAY ISO string), plus toast/toastVisible state for feedback. Render ses-top row with a Calendar lucide icon label and a ses-date-group with two date inputs (from/to) with min/max constraints (fromDate max=toDate, toDate min=fromDate max=TODAY). Render ses-actions with three motion.button elements using whileTap scale:0.96: ses-btn--csv (Download icon, 'Export CSV', handleCSV shows toast 'CSV export started — file will download shortly'), ses-btn--sheets (Sheet icon, 'Google Sheets', handleSheets shows 'Opening Google Sheets export wizard…'), ses-btn--email (Mail icon, showToast 'Signal report queued — email will arrive within 2 min'). Use AnimatePresence with useCallback showToast helper (2800ms auto-hide). Include an Info icon tooltip area and CheckCircle success indicator. Import SignalsExportSection.css with ses- BEM classes.
As a frontend developer, implement the AlertsFilters section for the Alerts page. Use `useState` hooks for `search`, `activeTypes` (array), `status`, and `sector`. Render a top row with a `Search`-icon text input for symbol/sector/keyword search, a status toggle group (All / Active / Inactive) with `alf-status-btn--active` class, and a styled `<select>` dropdown for SECTORS (10 options) with a `ChevronDown` icon overlay. Below, render TYPE_CHIPS (Buy, Sell, Risk, General) as toggle chips using `toggleType` toggling `activeTypes` array, each with its own color class (`alf-chip--buy`, etc.). Show a `clearAll` button with `X` icon when `activeFilterCount > 0`, computing count from active types, non-default status/sector, and non-empty search. Apply AlertsFilters.css styles.
As a frontend developer, implement the AlertsSettings section for the Alerts page. Build a multi-card settings grid using `useState` for: `frequency` (realtime/1min/5min/15min/digest radio options), `soundEnabled` toggle, `dndEnabled` toggle with `dndStart`/`dndEnd` time inputs (20:00–09:00), `weekendsOff` toggle, `grouping` radio selection (none/stock/type/sector with hint text), and `thresholds` object (aiScore=75, volumeSpike=150, gapPercent=2) with range sliders via `handleThreshold` callback. Implement a custom `Toggle` component rendering a checkbox with `as-toggle-track` and `as-toggle-thumb` spans. Wire the `Save Settings` button to `handleSave` which cycles `toastState` through hidden→show→out→hidden with 2200ms/2500ms timeouts, swapping `Save` icon for `Check` icon and label to 'Saved!' during the toast. Apply AlertsSettings.css styles.
As a frontend developer, implement the NotificationChannels section for the Alerts page using `framer-motion` (`motion`, `AnimatePresence`). Render 3 channel cards from the CHANNELS array (Telegram connected with @paisa_alerts_bot, WhatsApp connected with +91 number, Browser Notifications disconnected). Each card shows: `ChannelIcon` component (Send/MessageCircle/Bell by id), connected status badge with `CheckCircle`/`XCircle`, identifier, last alert info with type label, today's alert count, a collapsible step-by-step instructions accordion toggled via `openInstructions` state using `ChevronDown`, a `Zap` test button calling `handleTest` (fires `toast` state for 3s), a `Unlink` disconnect button calling `handleDisconnect` (updates channel to disconnected state), and a `LinkIcon`/`Plus` connect button calling `handleConnect` opening `modalChannel`. Implement the connect modal with `AnimatePresence` fade animation and `handleModalConfirm` to set channel connected. Show global toast via `AnimatePresence`. Apply NotificationChannels.css styles.
As a frontend developer, implement the AIScoreHeader section for the AI Score page. Build the `AIScoreHeader` component using `framer-motion` with `containerVariants` (staggerChildren: 0.08), `fadeUp`, and `pillVariants` animation configs. Render a breadcrumb nav with links to /Dashboard and /Scanner. Render the title row with a `Brain` (lucide-react, size 26) icon badge featuring an `ash-icon-pulse` animated dot, an `ash-live-badge` with a pulsing `ash-live-dot` and 'Live' text, and subtitle 'NSE Paisa Banao Strategy — Intelligent Setup Scoring Engine'. Render a description row with an `Info` icon (size 16) explaining the 0–100 multi-factor scoring and threshold of 70 for high-conviction. Render the five `scoreComponents` pills array (Volume Pattern/BarChart2, Market Breadth/Activity, Relative Strength/TrendingUp, Gap %/Zap, Sector Strength/Layers) each with `pillVariants` animation, icon, and label. All child elements use `motion.*` with `fadeUp` or `pillVariants` variants. CSS classes: `ash-root`, `ash-inner`, `ash-breadcrumb`, `ash-title-row`, `ash-description-row`. Note: this is the entry-point section for the AI Score page — include page-level dependency on Chart page tasks.
As a frontend developer, implement the RiskHeader section for the Risk page. Build a section component using `useState` (tooltipOpen) and `useRef` (wrapRef) with a `useEffect` that adds a `mousedown` document listener to close the tooltip when clicking outside. Render a breadcrumb nav with links to /Dashboard and /Trades and a current 'Risk Management' label. Implement an `rh-header-row` containing a title group with an `rh-page-tag` badge ('Capital Protection'), an `<h1>` with accented 'Risk Management & Position Sizing' text, and a descriptive paragraph with a 'Learn risk fundamentals →' link. Add a help button (HelpCircle / X from lucide-react) that toggles the tooltip open state and exposes `aria-expanded`. Animate the tooltip panel with `framer-motion` `AnimatePresence` using opacity/y/scale enter-exit transitions (duration 0.2, easeOut). Import RiskHeader.css for all styling. Note: Navbar/Footer components may already exist from previous pages.
As a Backend Developer, implement alerts CRUD and notification dispatch API: GET /api/alerts (list user alerts with filters: status, type, sector), POST /api/alerts (create alert with symbol, type, trigger_condition, entry/sl/target), PUT /api/alerts/{id} (update threshold or status), DELETE /api/alerts/{id} (delete alert), POST /api/alerts/{id}/snooze (snooze alert), POST /api/alerts/test?channel=telegram|whatsapp|browser (send test notification). Implement notification dispatch service: Telegram Bot API integration (TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID env vars), browser Push Notifications via Web Push protocol (VAPID keys), WhatsApp via Twilio or WhatsApp Business API. Fire notifications when signals transition state (Triggered, Target Hit, SL Hit, Breakeven). Depends on DB models and signals API.
As a Tech Lead, verify the end-to-end integration between the Dashboard frontend sections (DashboardMarketSentiment, DashboardMarketStatus, DashboardGainersLosers, DashboardSectorAnalysis, DashboardLiveSignals, DashboardScannerCandidates) and the Market Data API backend (GET /api/market/sentiment, /api/market/breadth, /api/market/gainers, /api/market/losers, /api/market/sectors) and Signals API (GET /api/signals). Ensure real-time data replaces all mock data, WebSocket price updates flow to live signals, and advance/decline counts render correctly. Verify API error states display gracefully in each section.
As a Tech Lead, verify the end-to-end integration between the Backtest frontend sections (BacktestHeader, BacktestParameters, BacktestResults, BacktestChart, BacktestMetrics, BacktestTrades, BacktestExport) and the Backtest API backend (POST /api/backtest/run, GET /api/backtest/status/{job_id}, GET /api/backtest/results/{job_id}, GET /api/export/trades/csv). Ensure BacktestParameters Run button POSTs to /api/backtest/run, a loading/progress state polls /api/backtest/status, BacktestResults/BacktestChart/BacktestMetrics/BacktestTrades all populate from /api/backtest/results, and BacktestExport CSV button downloads from /api/export/trades/csv. Replace all static mock equity data with real results.
As a Tech Lead, verify the end-to-end integration between the Sectors frontend sections (SectorsHero, SectorPerformanceGrid, TopStocksBySector, SectorDetailsTable) and the Market Data API backend (GET /api/market/sectors). Ensure SectorsHero market stats row (Advancing/Declining/Unchanged) populates from GET /api/market/breadth, SectorPerformanceGrid replaces static SECTOR_DEFS with live API sector data, TopStocksBySector fetches per-sector stock lists from GET /api/market/gainers?sector=banking&limit=5 style queries, and SectorDetailsTable sortable rows load from live API with real inst_buy/inst_sell scores from /api/ai/institutional/{symbol}. Verify sparkline data uses real 5-min OHLCV history.
As a Tech Lead, verify the end-to-end integration between the Global WebSocket Service frontend (useMarketSocket, useSignalSocket, MarketDataContext, useStockPrice) and the backend WebSocket relay endpoints (/ws/market, /ws/signals). Ensure: single shared WebSocket connection is established on app load after auth, tick data flows into MarketDataContext and causes price flash animations in GainersTable, LosersTable, DashboardLiveSignals, TradesActivePositions, and ScannerHeader, signal status transitions broadcast via /ws/signals update SignalsChartViewer and TradesActivePositions in real-time, and reconnection logic recovers gracefully from network drops. Verify no duplicate connections are opened when navigating between pages.
As a Tech Lead, verify the end-to-end integration between the Frontend Auth Middleware (AuthContext, ProtectedRoute, tokenService, apiClient) and the Auth API backend (POST /api/auth/login, /api/auth/register, /api/auth/refresh, /api/auth/logout, GET /api/auth/me). Confirm JWT access token auto-refresh via axios interceptor on 401 works correctly, ProtectedRoute correctly blocks all pages (/Dashboard, /Scanner, /Signals, /Trades, /Risk, /Alerts, /Backtest, /AI Score, /Chart) for unauthenticated users, and the WebSocket connections established by useMarketSocket and useSignalSocket include auth token headers. Verify logout clears both tokens and MarketDataContext, and WebSocket connections are cleanly closed on logout.
As a Backend Developer, implement the background job that monitors active signals for validity and auto-expiry: at 11:00 AM IST mark all 'Waiting' signals as 'Expired' (Paisa Banao setup validity window closes), continuously check open signals against live Fyers tick data every 5 seconds for SL/Target hits and status transitions (Triggered → Target Hit / SL Hit / Breakeven), emit status change events via /ws/signals WebSocket. Implement the 50% close + SL-to-breakeven logic when 1:2 RR is achieved. Run as FastAPI BackgroundTask or APScheduler job. Depends on Live Signals API (51809010), Fyers WebSocket Relay (a828093a), and DB models (b1e05bed).
As a frontend developer, implement the TopCandidates section for the Scanner page. This section uses INITIAL_CANDIDATES array (12 stocks: RELIANCE, HDFCBANK, TCS, INFY, BAJFINANCE, TATAMOTORS, SUNPHARMA, HINDUNILVR, TATASTEEL, LT, ICICIBANK, WIPRO) each with id, symbol, exchange, sector, sectorLabel, ltp, gap%, volume, relVol, and score fields. State: `sortKey` (column key), `sortDir` (asc/desc), `selected` (candidate id), `viewMode` ('grid'|'table'). COLUMNS array drives table headers. SortIcon component renders ArrowUpDown/ArrowUp/ArrowDown lucide icons based on active sort. getScoreClass() maps score to 'green'/'yellow'/'red' classes; getRVolClass() maps relVol to 'high'/'mid'/'low'. symInitials() extracts first 3 chars for avatar. AnimatePresence + framer-motion handle row/card enter animations. Imports both ScoreBar.css and TopCandidates.css. Renders Download button (lucide Download icon) for CSV export, LayoutGrid/Table2 view toggle buttons. In grid mode: candidate cards with sector badge, score bar, gap% colored by direction. In table mode: sortable columns with sticky header. Clicking a candidate sets selected state for CandidateDetails integration.
As a frontend developer, implement the GainersTable section for the Gainers page. Build the main data table using useState hooks for selectedStock, expandedRow, sortConfig, and live tick simulation via useEffect/useRef. Implement generateStocks() which maps 50 NSE symbols from the SECTORS object (RELIANCE, TCS, HDFCBANK, etc.) generating realistic mock FYERS API V3 payloads with fields: rank, symbol, sector, ltp, gainPct, prevLtp, volume, rvol, strength, buyScore, sellScore, dayHigh, dayLow, vwap, atr, deliveryPct, relVol, buyVol, sellVol, marketPart. Use fmtVol() for volume formatting (Cr/L suffix). Render a sortable table with columns for Rank, Symbol/Sector, LTP with gain flash animation, Gain %, Volume, RVol, Strength bar, Buy/Sell score mini-bars, and an expand chevron. Implement an expandable DetailPanel (importing DetailPanel.css) showing dayHigh/dayLow/VWAP/ATR/deliveryPct/buyVol/sellVol/marketPart. Add TrendingUp/TrendingDown/BarChart2/Zap/Activity/ExternalLink Lucide icons. Use AnimatePresence for row expansion. Import GainersTable.css and DetailPanel.css.
As a frontend developer, implement the `LosersTable` component for the Losers page. Use `useState` and `useMemo` to manage sorting, pagination, and row expansion over a 20+ row `LOSERS_DATA` array (fields: id, symbol, abbr, sector, ltp, gap, loss, volume, relVol, strength). Implement column sorting by clicking headers with sort direction toggling. Derive displayed rows via `useMemo` applying sort order. Use `framer-motion` `AnimatePresence` for row enter/exit animations on the table body. Each row should render: a rank badge, symbol with two-letter `abbr` avatar, sector label, LTP price, gap% and loss% values (styled red), volume and relative volume (relVol), and a strength progress bar. Support row click to expand detail panel. Apply CSS classes from `LosersTable.css` including grid-based table layout, hover row highlights, red-colored loss values, and responsive column visibility.
As a frontend developer, implement the ChartCanvas section for the Chart page. This is the most complex section — a fully custom Canvas 2D charting engine with: (1) generateCandleData() producing 80 realistic OHLCV bars starting at price 2845 with 5-min intervals from 2026-06-23T09:15:00; (2) calcEMA(data, period) using exponential smoothing (k = 2/(period+1)) for EMA9 and EMA21 overlays; (3) calcBB(data, 20, 2) for Bollinger Bands computing rolling mean and std deviation; (4) generateAnnotations() placing BUY markers at candle indices [12,34,58] and SELL at [22,47,70]; (5) useState for activeTimeframe ('5m'), chartType ('Candles'/'Line'), showEMA9, showEMA21, showBB, showVol, hovered tooltip, zoomOffset, visibleCount (60); (6) mainCanvasRef rendered via useRef with canvas drawing logic for candlesticks, line chart, volume bars, EMA/BB overlays, tooltip on hover; (7) toolbar controls for TIMEFRAMES ['1m','3m','5m','15m','30m','1h','1D'] and CHART_TYPES; (8) loading state transitions with AnimatePresence. Apply ChartCanvas.css.
As a frontend developer, implement the AlertsList section for the Alerts page. Render 8 static alert rows from `ALERTS_DATA` (RELIANCE, TCS, HDFCBANK, BAJFINANCE, INFY, SBIN, TATAMOTORS, ADANIENT) each with symbol, sector, type badge (Buy/Sell/Risk/General with `getTypeClass` color mapping), status badge (`getStatusLabel` mapping: active/triggered/snoozed/expired), trigger condition string, created date, and entry/SL/target price columns. Implement sort controls using SORT_OPTIONS (Date, Type, Status) with `useState` for `sortKey` and `sortAsc`, calling `sortAlerts` utility. Render per-row action icons: `Eye` (view), `Pencil` (edit), `Trash2` (delete), `BellOff` (snooze). Mark `critical: true` rows (HDFCBANK, BAJFINANCE, ADANIENT) with a critical indicator. Use `ChevronDown` for sort direction toggle. Apply AlertsList.css styles.
As a frontend developer, implement the AIScoreFilters section for the AI Score page. Build the `AIScoreFilters` component with local state: `threshold` (useState 60), `showBelow` (useState false), `direction` (useState 'All'), `dateFrom` (useState getWeekAgoStr()), `dateTo` (useState getTodayStr()), `applied` (useState false), plus `useId()` for the toggle. Render a custom range slider with `asf-slider-fill-bar` and `asf-slider-native` — the fill bar width is set via `style={{ width: fillPercent }}` and the native input uses an inline linear-gradient. Render direction toggle buttons (All/Buy/Sell) using `getDirBtnActiveClass()` and `getDirectionChipClass()` helper functions. Render date-range inputs for `dateFrom` and `dateTo`. Render an `AnimatePresence`-wrapped active-filter chips row displaying a threshold chip ('Score ≥ N') and direction chip when not 'All'. Implement `handleApply` (sets applied: true) and `handleReset` (restores all defaults) callbacks. CSS classes: `asf-root`, `asf-inner`, `asf-filter-row`, `asf-group--slider`, `asf-slider-wrapper`, `asf-dir-btn`, `asf-chip`, `asf-chip--green`, `asf-chip--red`.
As a frontend developer, implement the OverallScoreCard section for the AI Score page. Build the component with real-time WebSocket integration via the custom `useNiftyScoreStream` hook that connects to `wss://socket.fyers.in/trade/live-data`, sends a SUB_DATA subscription for `NSE:NIFTY50-INDEX` and `NSE:NIFTYBANK-INDEX`, and derives an AI score via the formula `Math.max(20, Math.min(100, Math.round(50 + changePct * 8)))`. On mount, also call `fetchMarketBreadth()` which hits `/api/fyers/v3/market/breadth?exchange=NSE&segment=CM` to compute a `breadthScore` from advances/total * 60, plus `setupsScanned` and `aboveThreshold` counts. Implement WebSocket auto-reconnect with a 4000ms setTimeout stored in `reconnRef`. Use `getScoreCategory(score)` to return 'green'/'yellow'/'red' and `getStatusLabel(score)` for 'High Confidence'/'Moderate'/'Low Confidence'. Animate the displayed score with `framer-motion`. Display the overall score gauge/card, status label, setupsScanned and aboveThreshold stats. CSS: `OverallScoreCard.css`.
As a frontend developer, implement the ScoreComponentBreakdown section for the AI Score page. Build the component with a `fetchLiveScoreComponents()` async function that fires three parallel FYERS V3 requests via `Promise.all`: `/api/fyers/v3/market/breadth`, `/api/fyers/v3/market/gainers?exchange=NSE&segment=CM&limit=50`, and `/api/fyers/v3/quotes?symbols=NSE:NIFTY50-INDEX,NSE:NIFTYBANK-INDEX`. Derive five scores: Volume Pattern (avgRvol of top 50 gainers clamped to 4x, mapped to 0–100), Market Breadth (adRatio * 100), Relative Strength (50 + niftyChangePct * 8, clamped 0–100), Gap % (avg abs gap% of gainers, mapped), Sector Strength (derived). Render each of the five `COMPONENT_META` rows (volume/breadth/rs/gap/sector) with emoji icon, name, animated progress bar, numeric score, `scoreLabel()` text ('Excellent'/'Strong'/'Moderate'/'Weak'/'Poor'), and `scoreTier()` CSS class ('high'/'medium'/'low'). Animate bars with `framer-motion`. Poll or fetch on mount via `useEffect`. CSS: `ScoreComponentBreakdown.css`.
As a frontend developer, implement the ScoreThresholdSelector section for the AI Score page. Build the component with local state for selected threshold. Render four tier cards from the `TIERS` array (Elite 90–100 🏆, High 80–89 🚀, Medium 60–79 📊, Low 40–59 ⚠️) — each card shows the tier icon, label, range, `count`, animated `barPct` progress bar, and `desc`. Render the five `PRESETS` quick-select buttons (Elite/High/Medium/Low/All) with colored dot indicators from `dotColor`. Use `getMatchingCount(threshold)` to display the number of matching setups. Use `AnimatePresence` to animate the `getExplanationText(threshold)` explanation panel that returns rich JSX with strong tags describing threshold behavior (Elite=highest conviction, High=active intraday, Medium=swing, Low=caution with risk mgmt, All=all scanned). Apply `tier-elite`, `tier-high`, `tier-medium`, `tier-low` CSS classes per tier. CSS: `ScoreThresholdSelector.css`.
As a frontend developer, implement the ScoreDistributionChart section for the AI Score page. Register Chart.js modules — `CategoryScale`, `LinearScale`, `BarElement`, `ArcElement`, `Tooltip`, `Legend` — via `Chart.register()`. Build `fetchScoreDistribution()` which calls `/api/fyers/v3/market/gainers?exchange=NSE&segment=CM&limit=200`, computes a per-stock AI score using the formula `(changePct/10)*35 + (rvol/4)*30 + buyRatio*25 + (tradeNum/50)*10`, buckets into 5 histogram ranges (0–20/20–40/40–60/60–80/80–100) using `HIST_META`, and derives tier counts (highCount ≥75, medCount 45–74, lowCount <45), total, and avgScore. Render a `Bar` chart (`react-chartjs-2`) with `HIST_COLORS` palette and histogram labels from `HIST_META`. Render a `Doughnut` chart for the three `TIER_META` tiers (High Quality 75–100 #1A73E8, Medium Quality 45–74 #FFD700, Low Quality 0–44 #FF6F61). Render a stats row with avgScore, total scanned, and tier counts. Animate section entry with `fadeUp` framer-motion custom delay variants (i * 0.1). CSS: `ScoreDistributionChart.css`.
As a frontend developer, implement the RiskCapitalInput section for the Risk page. Build a component with `useState` for `capital` (default 500000) and `inputValue` (default '5,00,000'). Implement `useMemo`-driven `getValidationState` that returns idle/error/warn/valid states with thresholds MIN_CAPITAL=10000, MAX_CAPITAL=50000000, WARN_THRESHOLD=100000. Render a currency input that strips non-numeric characters on change, formats using `toLocaleString('en-IN')`, and handles focus/blur formatting. Implement six QUICK_AMOUNTS preset buttons (50K, 1L, 2L, 5L, 10L, 25L) via `handleQuickAmount` callback. Derive and display `maxPositionSize` (capital×0.05), `dailyRiskLimit` (capital×0.02), and `availableLots` (capital÷25000) as live metric cards. Render a status badge (rci-badge with dot) reflecting valid/warn/error states using CheckCircle, AlertTriangle, AlertCircle, Info, ZapOff from lucide-react. Use `framer-motion` for animated transitions. Import RiskCapitalInput.css.
As a frontend developer, implement the RiskParameters section for the Risk page. Define PROFILES array (conservative/moderate/aggressive) each with riskPct, positionPct, stopLossPct, rr values, and RR_OPTIONS array with five ratio presets. Use `useState` for activeProfile (default 'moderate'), riskPercent (2), positionSize (5), stopLossPct (1), riskRewardRatio (2), customEnabled (false), customStopLoss ('1.0'), and tilt ({x,y}). Implement 3D card tilt effect via `useRef` (cardRef) and `handleMouseMove`/`handleMouseLeave` callbacks that calculate dx/dy offset from card center and apply 4× intensity tilt. Implement `selectProfile` callback that sets all state fields from profile data and disables custom mode. Build a dynamic `sliderGradient` via `useMemo` that transitions green→blue→orange→red across the riskPercent range (0.25–4). Render profile selector cards with Check icon for active state, a custom risk percent range slider with computed gradient, position size slider, RR_OPTIONS toggle buttons, and a custom stop-loss input toggled by customEnabled. Use AnimatePresence for custom panel transitions. Import RiskParameters.css.
As a frontend developer, implement the RiskCalculator section for the Risk page. Use `useState` for capital (500000), entryPrice (2845.50), stopLoss (2810.00), targetPrice (2920.00), and riskPercent (1). Build a `useMemo`-powered `results` object computing: maxRisk (capital×rp/100), riskPerShare (|entry−sl|), positionSize (min of floor(maxRisk/riskPerShare) and floor(capital/entry)), totalCost, grossProfit, profitPotential, rrRatio, capitalUsedPercent. Render five number inputs for all trade parameters and a presetRiskLevels quick-select row [0.5, 1, 1.5, 2, 3]. Display computed result cards for Max Risk, Position Size, Total Cost, Profit Potential, and R:R Ratio using ShieldAlert, Coins, TrendingUp, Target, Percent icons from lucide-react. Animate result cards with `cardVariants` (opacity/y, 0.35s easeOut) and value changes with `valueMotion` (spring stiffness 300, damping 25). Format currency using `toLocaleString('en-IN')`. Use AnimatePresence for conditional warning panels (AlertTriangle, Info). Import RiskCalculator.css.
As a frontend developer, implement the PositionRiskSummary section for the Risk page. Use static SUMMARY_DATA object containing total_capital_deployed (485000), total_capital_at_risk (19400), max_loss_percentage (4.0), open_positions_count (7), aggregate_rr (2.85), risk_per_trade_pct (1.0), max_daily_loss_pct (5.0), and a position_sizes array for 7 stocks (RELIANCE, TCS, HDFCBANK, INFY, ICICIBANK, SBIN, BAJFINANCE). Implement `getRiskLevel` helper mapping percentage thresholds to safe/moderate/high/critical levels. Build a `ThermometerGauge` sub-component with vertical fill bar, TICK_POINTS at 0/25/50/75/100%, a fill div sized by `fillPct` with risk-level CSS modifier classes, and a bulb element at the bottom. Render MetricCard sub-components with `framer-motion` animate (opacity/y, 0.4s easeOut) and whileHover (y: −2) for metrics like aggregate R:R, risk per trade, and daily loss limit. Display a horizontal position-size bar chart for each symbol using their percentage allocations. Use Wallet, ShieldAlert, Percent, BarChart3, Target, AlertTriangle, CheckCircle2 icons. Use `useState` and `useEffect` as needed for animated entry. Import PositionRiskSummary.css.
As a frontend developer, implement the RiskAlerts section for the Risk page. Define ALERT_DEFINITIONS array with four alert types: capital_loss (TrendingDown icon, default 2%, step 0.5, range 0.5–20), max_drawdown (AlertTriangle icon, default 5%, step 1, range 1–50), position_size (BarChart3 icon, default 10%, step 1, range 1–50), and rr_deviation (Target icon, default 2:1, step 0.5, range 0.5–10). Define CHANNELS array with browser (Globe icon), telegram (Send icon), and whatsapp (MessageCircle icon). Use `useState` initializing `alerts` map via reducer over ALERT_DEFINITIONS (each entry: {enabled: true, value: defaultValue}), `channel` (default 'browser'), and `toast` (null). Implement `toggleAlert` and `updateThreshold` callbacks updating the alerts map immutably. Implement `showToast` callback that sets toast state and auto-clears after 3000ms. Implement `handleTestAlert` that triggers a success toast naming the selected channel. Render alert cards with enable/disable toggles and numeric threshold inputs (with unit labels). Render channel selector tabs. Show AnimatePresence-driven toast notification (CheckCircle / XCircle icons) at the bottom. Import RiskAlerts.css.
As a frontend developer, implement the TradesHeader section for the Trades page. This section renders a top-level navigation and filter bar using `useState` for `refreshing` and `lastRefreshed` state, and `useCallback` for the `handleRefresh` handler (900ms simulated refresh with timestamp update). Render the `Activity` icon from lucide-react alongside the 'Trade Manager' title and 'Paisa Banao Strategy Pro — NSE Intraday Positions' subtitle. Implement a view toggle group with 'Active Positions' and 'Trade History' buttons that call `onViewChange`. Render a `motion.span`-wrapped `RefreshCw` icon with spin animation during refresh. Implement STATUS_FILTERS (all, open, closed, partial, target, sl) with color classes (active-green, active-red, active-gold) and TIMEFRAME_FILTERS (today, week, month, 3m, all) as pill button groups calling `onStatusChange` and `onTimeframeChange`. Apply TradesHeader.css styles. This is the entry section for the Trades page and depends on the Risk page's RiskHeader task for page-level chaining.
As a Tech Lead, verify the end-to-end integration between the Signals frontend sections (SignalsHeader, SignalsFiltersBar, SignalsChartViewer, SignalsTradePanel, SignalsExportSection) and the Signals API backend (GET /api/signals, WebSocket /ws/signals, GET /api/export/signals/csv). Ensure live signal status transitions (Waiting→Triggered→Target Hit) update the UI in real time via WebSocket, filter controls correctly query the API, SignalsTradePanel risk calculations use real position sizing from /api/risk/calculate, and CSV export triggers /api/export/signals/csv download. Verify TradePanel auto-close targets update when 1:2 RR is achieved.
As a Tech Lead, verify the end-to-end integration between the export frontend sections (SignalsExportSection, BacktestExport) and the Export API backend (GET /api/export/signals/csv, GET /api/export/trades/csv, POST /api/export/sheets). Ensure SignalsExportSection CSV button triggers /api/export/signals/csv with from/to date params and downloads the file correctly in the browser, BacktestExport CSV button triggers /api/export/trades/csv, Google Sheets export opens the OAuth2 consent flow and returns the sheet URL, and the share link panel displays the correct sheet URL. Verify date range params are correctly passed and that error states (e.g., no data in range) are shown gracefully in the UI.
As a Tech Lead, verify the end-to-end integration of the browser push notification flow: frontend Service Worker registers and subscribes via VAPID (GET /api/push/vapid-public-key + POST /api/push/subscribe), the NotificationChannels 'Test' button triggers POST /api/alerts/test?channel=browser and the backend dispatches a real browser push notification, the Service Worker displays the notification correctly in the OS notification tray, and permission request UI flows are handled gracefully (denied state shown in NotificationChannels). Depends on PWA Service Worker (frontend-pwa-service-worker), Push Subscription API (backend-push-subscription-api), and Alerts API (05b2a5ba).
As a frontend developer, implement the CandidateDetails section for the Scanner page. This section renders a detail panel for a selected candidate from CANDIDATES array (RELIANCE, INFY, BAJFINANCE with full metadata). State: `activeTab` for tab switching and `watchlisted` (bool) via useState. The JSX renders: header with symbol, name, sector badge, cap label, ltp with change amount/percent colored by `dir` ('up'/'down'), TrendingUp/TrendingDown lucide icons; Star icon button for watchlist toggle; Bell icon for alert setup; a 52-week high/low range bar with current price marker; stats grid showing PE, marketCap, volume, relVol (relVol uses Layers icon, volume uses Activity icon); AI score total (Zap icon) with circular score display; breakdown bars for 5 AI dimensions (volume, momentum, breakout, sector, rratio) each with label, score/max, and animated width bar; news card with Newspaper icon showing source, headline, and time from the `news` object; ChevronRight icon for navigation to full chart. AnimatePresence wraps the panel for slide-in/out transitions when selected candidate changes. All candidate data is static mock — no API calls.
As a frontend developer, implement the GainersPagination section for the Gainers page. Build the pagination control bar with useState hooks for currentPage (default 1), perPage (default 50), and flashKey (for result count flash animation). Implement getPageNumbers(currentPage, totalPages) with delta=2 logic producing ellipsis ('...') entries for large page counts. Render PER_PAGE_OPTIONS select (25, 50, 100) with handlePerPageChange useCallback that resets to page 1 and increments flashKey. Render a results info span showing startResult–endResult of TOTAL_RESULTS (500) animated with framer-motion key-based opacity flash. Render prev/next buttons using custom SVG ChevronLeft/ChevronRight components with useCallback handlers (handlePrev, handleNext) clamped to [1, totalPages]. Render individual page number buttons using AnimatePresence with btnVariants (scale 0.8→1, duration 0.18). Add useEffect to clamp currentPage when totalPages shrinks. Import GainersPagination.css.
As a frontend developer, implement the ScoredSetupsTable section for the AI Score page. Build the component with `useState` for sort column/direction, search query, pagination, and selected row for the detail panel. Use `useMemo` to filter and sort the `SETUPS` array (4 stocks: RELIANCE, HDFCBANK, TCS, INFY) by overallScore, symbol, sector, etc. Render a toolbar with a `Search` icon input, `Download` button, and `SlidersHorizontal` filters button. Render a sortable table with columns for Symbol, Sector, Setup Type (Buy/Sell chip colored green/red via `TrendingUp`/`TrendingDown` icons), Overall Score (colored score badge), Volume/Breadth/Strength/Gap/Sector sub-scores, LTP, Change%, RelVol, Delivery%, VWAP, Recommendation badge. Use `ArrowUpDown`/`ArrowUp`/`ArrowDown` icons for sort indicators. Implement `AnimatePresence`-animated DetailPanel drawer/modal on row click showing `aiText`, `orderFlow` buy/sell vol bars, `instBuy`/`instSell` percentages, ATR, day high/low, and an `ExternalLink` for TradingView. Render pagination with `ChevronLeft`/`ChevronRight`. Import both `ScoredSetupsTable.css` and `DetailPanel.css`. Icons: `Eye`, `AlertTriangle`, `CheckCircle`, `Zap`, `Activity`.
As a frontend developer, implement the TradesActivePositions section for the Trades page. Initialize 6 mock trades (RELIANCE, TCS, INFY, HDFCBANK, BAJFINANCE, TATAMOTORS) via `useState(INITIAL_TRADES)`. Implement `calcPnL` (side-aware BUY/SELL diff × qty), `fmtINR` (₹K formatting with +/- prefix), and `fmtPrice` (en-IN locale). Manage `confirmClose` state for a two-step close confirmation dialog and `watchlisted` state (object keyed by trade id) toggled by `handleWatchlist`. Filter visible trades based on `activeStatus` prop — show all trades for 'all'/'open', empty array otherwise. Render a header with the live count badge and animated 'Live' dot. For each trade card, render TrendingUp/TrendingDown icon based on side, entry/current price, qty, entry time, SL/target, computed P&L with color class, and action buttons using Edit3, X, Bookmark, Plus icons from lucide-react. Include the confirm-close modal overlay. Apply TradesActivePositions.css styles.
As a frontend developer, implement the TradesPnLSummary section for the Trades page. Render 6 metric cards (Total P&L, Realized P&L, Unrealized P&L, Active Trades, Win Rate, Profit Factor) each with label, value, sub-label, and a badge with type 'up' or 'warn'. Apply per-card accent classes (tps-card--green, tps-card--accent, tps-card--blue, tps-card--teal) and value color classes (tps-card-value--green, tps-card-value--accent, tps-card-value--blue). Implement `SparklineCanvas` component using `useRef` and `useEffect`: draw a bezier-smoothed sparkline on a DPR-scaled canvas with a green linear gradient fill (rgba 26,165,100) and a solid line. Provide SPARKLINE_DATA keyed by timeframe ('today', 'week', 'month') with 12 data points each. Use `framer-motion` for card entrance animations. Apply TradesPnLSummary.css styles.
As a frontend developer, implement the TradesHistoryTable section for the Trades page. Manage `useState` for search query, sort column/direction, current page, and expanded row id. Use `useMemo` to derive filtered + sorted trade rows from the TRADES array (10 entries: RELIANCE, INFY, HDFCBANK, BAJFINANCE, TCS, SBIN, TATAMOTORS, etc.) based on search input and sort state. Render a search bar with the `Search` icon. Implement a sortable table header using `ArrowUpDown`, `ChevronUp`, `ChevronDown` icons for sort indicators across columns (symbol, entryDate, entryTime, entryPrice, exitPrice, qty, duration, exitReason, rr, setupScore). For each row render exit reason badges (TP=green, SL=red, Manual=gold), RR value with color, and a setup score pill. Implement expandable row detail using `AnimatePresence` and `motion.div` showing trade notes and tags (tp1, tp2, sl, breakout, reversal, manual). Render pagination controls with `ChevronLeft`/`ChevronRight` and page count. Include a `FileText` export button in the header. Apply TradesHistoryTable.css styles.
As a frontend developer, implement the TradesRiskPanel section for the Trades page. Manage `useState` for `collapsed`, `editing`, and `saved` flags, and editable fields: `capital` (₹5,00,000), `riskPct` (1%), `maxDrawdown` (5%). Maintain draft state (`draftCapital`, `draftRisk`, `draftDrawdown`) for the inline edit form. Compute derived values: `riskPerTrade` (capital × riskPct / 100), `maxDrawdownAmt`, `totalOpenRisk` (sum of OPEN_TRADES riskAmt for RELIANCE, TCS, INFY), and `utilizationPct` (clamped 0–100). Apply `utilClass` (safe/warn/danger) and `utilColor` (#1A73E8/#FFA500/#e03030) based on utilization thresholds (70%/90%). Implement `handleEdit`, `handleApply` (with validation: capital ≥ 10000, riskPct 0.1–5, drawdown 1–20), and `handleReset`. Render risk-per-trade slider with CSS `--pct` custom property and a drawdown slider similarly. Display the OPEN_TRADES breakdown table with sym, type, riskAmt, riskPct, allocation bar. Render collapse toggle with `ChevronUp`, edit mode with `Edit2`/`Check`/`RotateCcw` icons, shield header with `ShieldCheck`, and risk alerts with `AlertTriangle`/`TrendingUp` icons. Apply TradesRiskPanel.css styles.
As a Tech Lead, verify the end-to-end integration between the Alerts frontend sections (AlertsHeader, AlertsList, AlertsFilters, NotificationChannels, AlertsSettings) and the Alerts API backend (GET/POST/PUT/DELETE /api/alerts, POST /api/alerts/test). Ensure AlertsList loads from GET /api/alerts replacing static data, create/edit/delete actions call the respective API endpoints, NotificationChannels test button calls POST /api/alerts/test?channel=X and shows real success/failure feedback, and AlertsSettings save persists to PUT /api/risk/settings or a dedicated user settings endpoint. Verify browser push notification permission request flow works end-to-end.
As a Tech Lead, verify the end-to-end integration between the Risk frontend sections (RiskHeader, RiskCapitalInput, RiskParameters, RiskCalculator, PositionRiskSummary, RiskAlerts) and the Risk API backend (GET/PUT /api/risk/settings, GET /api/risk/calculate, GET /api/risk/summary). Ensure RiskCapitalInput persists capital to PUT /api/risk/settings, RiskCalculator fetches computed values from GET /api/risk/calculate replacing client-side useMemo calculations with server-authoritative results, PositionRiskSummary loads from GET /api/risk/summary, and RiskAlerts test button calls POST /api/alerts/test. Verify validation rules match between frontend and backend.
As a Tech Lead, verify the end-to-end integration between the Gainers page (GainersHeader, GainersFilterBar, GainersTable, GainersPagination) and Losers page (LosersPageHeader, LosersFilterBar, LosersTable, LosersMetrics) frontend sections and the Market Data API backend (GET /api/market/gainers, GET /api/market/losers). Ensure GainersTable and LosersTable replace all mock generateStocks() data with live API responses, WebSocket price flashes work for live LTP updates via useStockPrice() hook, pagination and filter controls pass query params to the API (sector, period, limit), and clicking a stock row correctly opens the stock detail panel with real institutional score data from /api/ai/institutional/{symbol}.
As a Tech Lead, verify the end-to-end integration between the Chart page frontend sections (ChartHeader, ChartCanvas, ChartSidebar, ChartAnalysis, ChartIndicators) and the backend APIs (GET /api/chart/symbol/{symbol}, GET /api/fyers/v3/market/history for OHLCV, WebSocket /ws/market for live tick, GET /api/ai/institutional/{symbol}, POST /api/ai/explain). Ensure: TradingView widget receives correct NSE symbol string from /api/chart/symbol, ChartSidebar watchlist stock clicks dynamically update the TradingView symbol without page reload, ChartAnalysis institutional scores come from /api/ai/institutional, AI explanation text from /api/ai/explain, and ChartIndicators live data from WebSocket tick stream. Verify symbol click events across GainersTable, LosersTable, ScannerCandidates, and SignalsTable all correctly route to /Chart and trigger the same dynamic symbol update flow.
As a Tech Lead, verify the end-to-end integration of the symbol click flow across all pages: clicking any stock row/card in GainersTable, LosersTable, TopCandidates, CandidateDetails, ScoredSetupsTable, DashboardGainersLosers, DashboardLiveSignals, ChartSidebar, and TopStocksBySector correctly routes to /Chart?symbol=SYMBOL, the Chart page calls GET /api/chart/symbol/{symbol} to resolve the TradingView-compatible symbol string, and the TradingView Advanced Chart Widget updates dynamically without page reload. Ensure ChartHeader shows live OHLCV data for the selected symbol via WebSocket tick stream. Verify the stock detail panel (ChartSidebar) populates all fields (LTP, Change%, Volume, RelVol, Delivery%, VWAP, Day High/Low, ATR, Sector) from the Fyers data relay. Depends on TradingView Symbol API (93e34967) and Fyers WebSocket Relay (a828093a).
As a Tech Lead, verify the end-to-end integration between the Scanner frontend sections (ScannerHeader, ScannerStats, ScannerFilters, TopCandidates, CandidateDetails, RealTimeUpdates) and the Scanner API backend (GET /api/scanner/run, /api/scanner/candidates, /api/scanner/setup/{symbol}) and WebSocket signal feed (/ws/signals). Ensure the manual scan button triggers GET /api/scanner/run, candidate data populates from live API replacing all mock data, RealTimeUpdates feed is driven by WebSocket events, and CandidateDetails fetches real setup data from /api/scanner/setup/{symbol}. Verify sector filter and score threshold filters work against real API data.
As a Tech Lead, verify the end-to-end integration between the AI Score frontend sections (AIScoreHeader, OverallScoreCard, ScoreComponentBreakdown, ScoreDistributionChart, AIScoreFilters, ScoredSetupsTable, ScoreThresholdSelector) and the AI Scoring API backend (GET /api/ai/scores, GET /api/ai/score/{symbol}, GET /api/ai/institutional/{symbol}, POST /api/ai/explain). Ensure OverallScoreCard replaces its WebSocket mock with real Fyers data via the backend relay, ScoreComponentBreakdown fetches from /api/market/breadth and /api/market/gainers proxied through the backend, ScoredSetupsTable loads from /api/ai/scores?min_score=threshold, and DetailPanel ai_explanation text comes from /api/ai/explain. Verify threshold filter updates the API query parameter.
As a Tech Lead, verify the end-to-end integration between the Trades frontend sections (TradesHeader, TradesPnLSummary, TradesRiskPanel, TradesActivePositions, TradesHistoryTable) and the Trades API backend (GET /api/trades, GET /api/trades/summary, PUT /api/trades/{id}, WebSocket /ws/signals for live P&L). Ensure TradesPnLSummary populates from GET /api/trades/summary, TradesActivePositions loads open trades from GET /api/trades?status=open with real-time P&L updates via WebSocket, TradesHistoryTable paginates from GET /api/trades/history, and TradesRiskPanel risk settings persist via PUT /api/risk/settings. Verify two-step close confirmation calls PUT /api/trades/{id} with status=closed.
As a Tech Lead, verify the end-to-end integration between user settings frontend components (RiskCapitalInput, TradesRiskPanel, AlertsSettings, ScoreThresholdSelector) and the User Settings API (GET/PUT /api/user/settings, GET/POST/DELETE /api/user/watchlist). Ensure: RiskCapitalInput capital value persists to /api/user/settings on apply, TradesRiskPanel risk parameters persist correctly, AlertsSettings frequency/threshold/DND settings save and reload on next login, ScoreThresholdSelector selected threshold persists across sessions, and watchlist star toggles in GainersTable/CandidateDetails correctly call /api/user/watchlist endpoints. Verify settings are loaded on app init after auth and populate the correct component states.
No comments yet. Be the first!