### 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 (
);
}
// 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
);
}
```
--------------------------------
### 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
);
}
```
--------------------------------
### 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
Date
Open
High
Low
Close
Volume
{data.map((bar) => (
{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.