### Install Dependencies and Run Development Server (Bash) Source: https://github.com/investlab-app/web/blob/main/README.md Commands to install project dependencies using pnpm and start the development server. Assumes Node.js and pnpm are installed. ```bash pnpm install pnpm dev ``` -------------------------------- ### Run End-to-End Tests with Playwright (Bash) Source: https://github.com/investlab-app/web/blob/main/README.md Command to run all end-to-end tests using Playwright. Assumes Playwright is installed and configured, with test files in the 'e2e/' directory. ```bash pnpm test:e2e ``` -------------------------------- ### Configure API Client (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Configures the auto-generated API client with the base URL for connecting to the InvestLab backend. Authentication is handled automatically using Clerk tokens. This setup ensures all subsequent API calls use the specified base URL. ```typescript import { client } from '@/client/client.gen'; // Configure the base URL for API requests client.setConfig({ baseUrl: 'http://localhost:8000' }); // All API functions automatically use this configuration // Authentication is handled automatically via Clerk tokens ``` -------------------------------- ### Run Unit Tests with Vitest (Bash) Source: https://github.com/investlab-app/web/blob/main/README.md Command to execute unit tests using Vitest. Requires Vitest to be configured in the project. ```bash pnpm test ``` -------------------------------- ### Run Prettier Formatter (Bash) Source: https://github.com/investlab-app/web/blob/main/README.md Command to run Prettier for code formatting. Standardizes code style across the project. Requires Prettier to be configured. ```bash pnpm format ``` -------------------------------- ### Run ESLint Linter (Bash) Source: https://github.com/investlab-app/web/blob/main/README.md Command to run ESLint for code linting. Ensures code adheres to defined coding standards. Requires ESLint to be configured. ```bash pnpm lint ``` -------------------------------- ### Create Market Order with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Executes an immediate buy or sell order at the current market price. It uses React Query mutations and toasts for user feedback. Dependencies include '@tanstack/react-query', '@/client/@tanstack/react-query.gen', and 'sonner'. Input is a ticker symbol, and output is a UI button that triggers the order. ```typescript import { useMutation, useQueryClient } from '@tanstack/react-query'; import { ordersMarketCreateMutation } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; function BuyStockButton({ ticker }: { ticker: string }) { const queryClient = useQueryClient(); const mutation = useMutation({ ...ordersMarketCreateMutation(), onSuccess: () => { toast.success('Order executed successfully'); queryClient.invalidateQueries({ queryKey: ['orders'] }); queryClient.invalidateQueries({ queryKey: ['statistics'] }); }, onError: (error) => { toast.error(`Order failed: ${error.message}`); } }); const handleBuy = () => { mutation.mutate({ body: { ticker: ticker, volume: '10', is_buy: true } }); }; return ( ); } ``` -------------------------------- ### Create Trading Strategy with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Allows users to build and create automated trading strategies using a graph-based flow system. It utilizes `@tanstack/react-query` for mutations and state management, and `sonner` for notifications. The function takes strategy details including name, raw graph data, and activation status as input, and outputs success or error messages. ```typescript import { useMutation, useQueryClient } from '@tanstack/react-query'; import { graphLangCreateMutation } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; import { useNavigate } from '@tanstack/react-router'; function CreateStrategy() { const queryClient = useQueryClient(); const navigate = useNavigate(); const mutation = useMutation({ ...graphLangCreateMutation(), onSuccess: (data) => { toast.success('Strategy created successfully'); queryClient.invalidateQueries({ queryKey: ['graph_lang'] }); navigate({ to: `/strategies/${data.id}` }); }, onError: (error) => { toast.error(`Failed to create strategy: ${error.message}`); } }); const handleCreate = () => { // Example: Create a strategy that buys AAPL when price drops below $150 const strategyGraph = { nodes: [ { id: '1', type: 'price_check', data: { ticker: 'AAPL', operator: 'below', threshold: 150 } }, { id: '2', type: 'buy_action', data: { ticker: 'AAPL', volume: '10' } } ], edges: [ { id: 'e1-2', source: '1', target: '2' } ] }; mutation.mutate({ body: { name: 'Buy AAPL Dip', raw_graph_data: strategyGraph, active: true, repeat: true } }); }; return ( ); } ``` -------------------------------- ### Live Stock Price Tracking Hooks (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Provides hooks (`useLivePrices` and `useLivePrice`) for tracking real-time stock prices via WebSocket integration. `useLivePrices` tracks multiple tickers, returning an object of prices, while `useLivePrice` tracks a single ticker, returning its current price or undefined while loading. ```typescript import { useLivePrices, useLivePrice } from '@/features/shared/hooks/use-live-prices'; // Track multiple stock prices function PortfolioView() { const prices = useLivePrices('AAPL', 'GOOGL', 'MSFT'); return (
{Object.entries(prices).map(([ticker, price]) => (
{ticker}: ${price.toFixed(2)}
))}
); } // Track a single stock price function SingleStock() { const price = useLivePrice('AAPL'); if (price === undefined) { return
Loading...
; } return
AAPL: ${price.toFixed(2)}
; } ``` -------------------------------- ### WebSocket Provider and Hooks for Real-time Data (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Implements a WebSocket provider for subscribing to real-time market data events. Includes a hook (`useWS`) to subscribe to specific ticker events and process incoming JSON messages. This enables live updates for various application components. ```typescript import { WSProvider } from '@/features/shared/providers/ws-provider'; import { useWS } from '@/features/shared/hooks/use-ws'; // Wrap your app with the WebSocket provider function App() { return ( ); } // Subscribe to specific ticker events function StockMonitor() { const { lastJsonMessage } = useWS(['AAPL', 'GOOGL', 'MSFT']); useEffect(() => { if (lastJsonMessage) { console.log('Received update:', lastJsonMessage); // Handle real-time price updates } }, [lastJsonMessage]); return
Monitoring stocks...
; } ``` -------------------------------- ### Fetch Paginated Instrument List with TanStack Query (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Queries a paginated list of trading instruments using TanStack Query. It allows specifying page number, page size, search parameters, and ordering. The hook fetches data and handles loading and error states, rendering a list of instrument names and tickers. ```typescript import { useQuery } from '@tanstack/react-query'; import { instrumentsListOptions } from '@/client/@tanstack/react-query.gen'; function InstrumentsList() { const { data, isLoading, error } = useQuery({ ...instrumentsListOptions({ query: { page: 1, page_size: 20, search: 'Apple', ordering: '-market_cap' } }) }); if (isLoading) return
Loading instruments...
; if (error) return
Error: {error.message}
; return ( ); } ``` -------------------------------- ### Create Price Alert - TypeScript React Source: https://context7.com/investlab-app/web/llms.txt Implements a price alert creation component that allows users to set threshold-based notifications for stock price movements. Uses TanStack React Query mutations to post alert data with configurable notification channels (email, push, websocket). Includes success/error toast notifications and query invalidation for real-time updates. ```typescript import { useMutation, useQueryClient } from '@tanstack/react-query'; import { pricesPriceAlertCreateMutation } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; function PriceAlertCreator({ ticker }: { ticker: string }) { const [threshold, setThreshold] = useState('150.00'); const [thresholdType, setThresholdType] = useState<'above' | 'below'>('above'); const queryClient = useQueryClient(); const mutation = useMutation({ ...pricesPriceAlertCreateMutation(), onSuccess: () => { toast.success('Price alert created'); queryClient.invalidateQueries({ queryKey: ['price-alerts'] }); }, onError: (error) => { toast.error(`Failed to create alert: ${error.message}`); } }); const handleCreate = () => { mutation.mutate({ body: { instrument_ticker: ticker, threshold_type: thresholdType, threshold_value: threshold, notification_config: { is_email: true, is_push: true, is_websocket: true } } }); }; return (
setThreshold(e.target.value)} />
); } ``` -------------------------------- ### Fetch Portfolio Statistics - TypeScript React Source: https://context7.com/investlab-app/web/llms.txt Retrieves and displays comprehensive portfolio performance metrics including total value, invested amount, total gains/losses, and today's performance. Uses TanStack React Query to fetch dual data sources (stats and account value) and conditionally renders a dashboard grid with color-coded gain/loss indicators. ```typescript import { useQuery } from '@tanstack/react-query'; import { statisticsStatsOptions, statisticsCurrentAccountValueOptions } from '@/client/@tanstack/react-query.gen'; function PortfolioDashboard() { const { data: stats } = useQuery(statisticsStatsOptions()); const { data: accountValue } = useQuery(statisticsCurrentAccountValueOptions()); if (!stats || !accountValue) return
Loading...
; const gainColor = stats.total_gain >= 0 ? 'text-green-600' : 'text-red-600'; const gainPercentage = accountValue.gain_percentage?.toFixed(2) || '0.00'; return (

Total Value

${stats.total_value.toLocaleString()}

Total Invested

${stats.invested.toLocaleString()}

Total Gain/Loss

${stats.total_gain.toLocaleString()} ({gainPercentage}%)

Today's Gain/Loss

${stats.todays_gain.toLocaleString()}

); } ``` -------------------------------- ### Fetch Market News (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Retrieves and displays the latest market news articles, optionally filtered by a stock ticker. It utilizes TanStack Query for asynchronous data fetching and displays loading or no-data states. Dependencies include '@tanstack/react-query' and type-safe API client definitions. ```typescript import { useQuery } from '@tanstack/react-query'; import { newsListOptions } from '@/client/@tanstack/react-query.gen'; function StockNews({ ticker }: { ticker?: string }) { const { data, isLoading } = useQuery({ ...newsListOptions({ query: { ticker: ticker, number_of_news: 10, order: 'desc', sort: 'published_utc' } }) }); if (isLoading) return
Loading news...
; if (!data || data.length === 0) return
No news available
; return (
{data.map((article) => (
{article.image_url && ( {article.title} )}

{article.title}

{article.description}

{article.author} {new Date(article.published_utc || '').toLocaleDateString()} {article.publisher && ( {article.publisher.name} )}
{article.insights && article.insights.length > 0 && (
{article.insights.map((insight, idx) => ( {insight.ticker}: {insight.sentiment} ))}
)}
))}
); } ``` -------------------------------- ### Create Limit Order with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Places a limit order that executes only at a specified price or better. This function utilizes React Query mutations and 'sonner' for notifications. It requires ticker, volume, and limit price as inputs, and provides a form for order submission. Dependencies include '@tanstack/react-query', '@/client/@tanstack/react-query.gen', and 'sonner'. ```typescript import { useMutation } from '@tanstack/react-query'; import { ordersLimitCreateMutation } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; function LimitOrderForm({ ticker }: { ticker: string }) { const [limitPrice, setLimitPrice] = useState('100.00'); const [volume, setVolume] = useState('5'); const mutation = useMutation({ ...ordersLimitCreateMutation(), onSuccess: () => { toast.success('Limit order placed successfully'); }, onError: (error) => { toast.error(`Failed to place order: ${error.message}`); } }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); mutation.mutate({ body: { ticker: ticker, volume: volume, is_buy: true, limit_price: limitPrice } }); }; return (
setVolume(e.target.value)} placeholder="Volume" /> setLimitPrice(e.target.value)} placeholder="Limit Price" />
); } ``` -------------------------------- ### Toggle Instrument Watchlist (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Manages adding or removing instruments from a user's watchlist. It uses TanStack Query for data fetching and mutations, and Sonner for displaying user feedback. It depends on the '@tanstack/react-query' library and type-safe API client definitions. ```typescript import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { investorsMeWatchedTickersListOptions, investorsMeWatchedTickersPartialUpdateMutation } from '@/client/@tanstack/react-react-query.gen'; import { toast } from 'sonner'; function WatchlistToggle({ instrumentId, ticker }: { instrumentId: string; ticker: string }) { const queryClient = useQueryClient(); const { data: watchlist } = useQuery(investorsMeWatchedTickersListOptions()); const isWatched = watchlist?.some(item => item.ticker === ticker) || false; const mutation = useMutation({ ...investorsMeWatchedTickersPartialUpdateMutation(), onSuccess: () => { const message = isWatched ? 'Removed from watchlist' : 'Added to watchlist'; toast.success(message); queryClient.invalidateQueries({ queryKey: ['investors', 'me', 'watched-tickers'] }); }, onError: (error) => { toast.error(`Failed to update watchlist: ${error.message}`); } }); const handleToggle = () => { mutation.mutate({ path: { instrument_id: instrumentId }, body: { is_watched: !isWatched } }); }; return ( ); } ``` -------------------------------- ### Fetch Instrument Details with TanStack Query (TypeScript) Source: https://context7.com/investlab-app/web/llms.txt Fetches comprehensive details for a specific trading instrument using its ticker symbol via TanStack Query. It handles loading states and displays detailed information such as name, description, market, market capitalization, and contact details. ```typescript import { useQuery } from '@tanstack/react-query'; import { instrumentsDetailRetrieveOptions } from '@/client/@tanstack/react-query.gen'; function InstrumentDetails({ ticker }: { ticker: string }) { const { data, isLoading } = useQuery({ ...instrumentsDetailRetrieveOptions({ query: { ticker } }) }); if (isLoading) return
Loading...
; if (!data) return
Not found
; return (

{data.name} ({data.ticker})

{data.description}

Market: {data.market}

Market Cap: ${data.market_cap}

Exchange: {data.primary_exchange}

Employees: {data.total_employees?.toLocaleString()}

Address: {data.address.address1}, {data.address.city}, {data.address.state}

Website: {data.homepage_url}

); } ``` -------------------------------- ### Deposit Virtual Funds with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Allows users to add virtual funds to their trading account using paper money. This function leverages `@tanstack/react-query` for mutations and state updates, and `sonner` for notifications. It takes an amount as input and invalidates relevant queries upon successful deposit. ```typescript import { useMutation, useQueryClient } from '@tanstack/react-query'; import { investorsDepositCreateMutation } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; function DepositFunds() { const [amount, setAmount] = useState('1000.00'); const queryClient = useQueryClient(); const mutation = useMutation({ ...investorsDepositCreateMutation(), onSuccess: (data) => { toast.success(`Deposited $${data.amount}`); queryClient.invalidateQueries({ queryKey: ['investors', 'me'] }); queryClient.invalidateQueries({ queryKey: ['statistics'] }); setAmount('1000.00'); }, onError: (error) => { toast.error(`Deposit failed: ${error.message}`); } }); const handleDeposit = () => { mutation.mutate({ body: { amount: amount } }); }; return (

Add Virtual Funds

setAmount(e.target.value)} placeholder="Amount" />
); } ``` -------------------------------- ### Fetch Transaction History - TypeScript React Source: https://context7.com/investlab-app/web/llms.txt Displays detailed transaction history for selected securities with per-position analytics. Renders position cards with quantity, market value, and gain/loss metrics, along with a transaction table showing buy/sell entries with dates, quantities, and share prices. Supports filtering by transaction type and ticker symbols. ```typescript import { useQuery } from '@tanstack/react-query'; import { statisticsTransactionsHistoryListOptions } from '@/client/@tanstack/react-query.gen'; function TransactionHistory() { const { data, isLoading } = useQuery({ ...statisticsTransactionsHistoryListOptions({ query: { type: 'both', tickers: ['AAPL', 'GOOGL'] } }) }); if (isLoading) return
Loading transactions...
; if (!data) return
No transactions found
; return (
{data.map((position) => (

{position.name} ({position.symbol})

Quantity: {position.quantity}

Market Value: ${position.market_value.toLocaleString()}

= 0 ? 'text-green-600' : 'text-red-600'}> Gain/Loss: ${position.gain.toFixed(2)} ({position.gain_percentage?.toFixed(2)}%)

Transaction History

{position.history.map((entry, idx) => ( ))}
Date Type Quantity Price
{new Date(entry.timestamp).toLocaleDateString()} {entry.is_buy ? 'BUY' : 'SELL'} {entry.quantity} ${entry.share_price.toFixed(2)}
))}
); } ``` -------------------------------- ### Fetch Price History with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Retrieves historical price bars for a given ticker symbol for the past month. This function uses React Query for data fetching and displays the data in a table. It requires a ticker symbol as input. Dependencies include '@tanstack/react-query' and '@/client/@tanstack/react-query.gen'. Output is a chart component displaying price history. ```typescript import { useQuery } from '@tanstack/react-query'; import { pricesBarsOptions } from '@/client/@tanstack/react-query.gen'; function StockChart({ ticker }: { ticker: string }) { const endDate = new Date(); const startDate = new Date(); startDate.setMonth(startDate.getMonth() - 1); const { data, isLoading } = useQuery({ ...pricesBarsOptions({ query: { ticker: ticker, interval: 'DAY', interval_multiplier: 1, start_date: startDate.toISOString().split('T')[0], end_date: endDate.toISOString().split('T')[0] } }) }); if (isLoading) return
Loading chart...
; if (!data) return
No data
; return (

{ticker} - Last 30 Days

{data.map((bar) => ( ))}
Date Open High Low Close Volume
{bar.timestamp} ${bar.open} ${bar.high} ${bar.low} ${bar.close} {bar.volume}
); } ``` -------------------------------- ### Update Strategy Activation Status with TypeScript Source: https://context7.com/investlab-app/web/llms.txt Enables or disables the execution of automated trading strategies. This function uses `@tanstack/react-query` for partial updates and invalidation of queries, along with `sonner` for user feedback. It accepts a strategy ID and its current activation status, and toggles the 'active' property. ```typescript import { useMutation, useQueryClient } from '@tanstack/react-query'; import { graphLangPartialUpdateMutation, graphLangRetrieveQueryKey } from '@/client/@tanstack/react-query.gen'; import { toast } from 'sonner'; function StrategyToggle({ strategyId, currentActive }: { strategyId: string; currentActive: boolean }) { const queryClient = useQueryClient(); const mutation = useMutation({ ...graphLangPartialUpdateMutation(), onSuccess: (data) => { const message = data.active ? 'Strategy activated' : 'Strategy deactivated'; toast.success(message); queryClient.invalidateQueries({ queryKey: graphLangRetrieveQueryKey({ path: { id: strategyId } }) }); }, onError: (error) => { toast.error(`Failed to update strategy: ${error.message}`); } }); const handleToggle = () => { mutation.mutate({ path: { id: strategyId }, body: { active: !currentActive } }); }; return ( ); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.