Complete API endpoint documentation for StockViewer.
- Overview
- Dataset Endpoints
- Indicator Endpoints
- Strategy Endpoints
- Group Endpoints
- Backtest Endpoints
- Backtest History Endpoints
- Validation Endpoints
- Error Handling
- Rate Limiting
StockViewer uses Next.js API Routes for all backend functionality.
Base URL: http://localhost:3000/api (development)
Response Format: JSON
Authentication: None (local application)
Common Headers:
Content-Type: application/json
Accept: application/json
List all available stock datasets with metadata.
Request:
GET /api/datasetsResponse:
{
"datasets": [
{
"name": "000001_stock_zh_a_hist.csv",
"symbol": "000001",
"datasource": "stock_zh_a_hist",
"firstDate": "2000-01-01",
"lastDate": "2024-01-15",
"rowCount": 5000,
"columns": ["date", "open", "high", "low", "close", "volume", "SMA_20", "RSI_14"]
}
]
}Response Fields:
name(string): CSV filenamesymbol(string): Stock symboldatasource(string): Data source identifierfirstDate(string): Earliest date in datasetlastDate(string): Latest date in datasetrowCount(number): Number of rowscolumns(string[]): Available columns (OHLC + indicators)
Status Codes:
200 OK: Success500 Internal Server Error: Failed to read datasets
Get complete data for a specific dataset.
Request:
GET /api/dataset/000001_stock_zh_a_hist.csvResponse:
{
"name": "000001_stock_zh_a_hist.csv",
"data": [
{
"date": "2024-01-01",
"open": 10.0,
"high": 10.5,
"low": 9.8,
"close": 10.2,
"volume": 1000000,
"turnover": 10200000,
"amplitude": 7.0,
"change_pct": 2.0,
"change_amount": 0.2,
"turnover_rate": 0.5,
"SMA_20": 10.15,
"RSI_14": 65.5
}
],
"columns": ["date", "open", "high", "low", "close", "volume", "SMA_20", "RSI_14"]
}Response Fields:
name(string): Dataset filenamedata(object[]): Array of data rowscolumns(string[]): Column names
Status Codes:
200 OK: Success404 Not Found: Dataset doesn't exist500 Internal Server Error: Failed to read file
Add a new stock or update existing stock data.
Request:
POST /api/add-dataset
Content-Type: application/json
{
"symbol": "000001",
"startDate": "1900-01-01",
"endDate": "2024-12-31",
"datasource": "stock_zh_a_hist"
}Request Fields:
symbol(string, required): 6-digit stock codestartDate(string, optional): Start date (YYYY-MM-DD), default:1900-01-01endDate(string, optional): End date (YYYY-MM-DD), default: todaydatasource(string, optional): Data source, default:stock_zh_a_hist
Response:
{
"success": true,
"message": "Stock data fetched and saved successfully",
"filename": "000001_stock_zh_a_hist.csv",
"rowCount": 5000
}Status Codes:
200 OK: Stock added/updated successfully400 Bad Request: Missing or invalid parameters500 Internal Server Error: Failed to fetch or save data
Process:
- Fetch data from aktools API
- Save to CSV file
- Apply all existing indicators
- Return success with metadata
Delete a dataset by name.
Request:
DELETE /api/datasets?name=000001_stock_zh_a_hist.csvQuery Parameters:
name(string, required): Dataset filename to delete
Response:
{
"success": true,
"message": "Dataset deleted successfully"
}Status Codes:
200 OK: Dataset deleted400 Bad Request: Missing name parameter404 Not Found: Dataset not found500 Internal Server Error: Failed to delete file
List all custom indicators.
Request:
GET /api/indicatorsResponse:
{
"indicators": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "SMA_20",
"description": "20-day Simple Moving Average",
"pythonCode": "def calculate(data):\n return data['close'].rolling(20).mean()",
"outputColumn": "SMA_20",
"dependencies": [],
"isGroup": false,
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
]
}Response Fields:
id(string): Unique UUIDname(string): Display namedescription(string): DescriptionpythonCode(string): Calculation codeoutputColumn(string): Column name (Custom Python only)groupName(string): Group name (MyTT Group only)expectedOutputs(string[]): Output names (MyTT Group only)dependencies(string[]): Indicator dependenciesisGroup(boolean): True for MyTT Group indicatorscreatedAt(string): Creation timestamp (ISO-8601)updatedAt(string): Last update timestamp (ISO-8601)
Status Codes:
200 OK: Success500 Internal Server Error: Failed to read indicators
Create a new indicator.
Request:
POST /api/indicators
Content-Type: application/json
{
"name": "SMA_20",
"description": "20-day Simple Moving Average",
"pythonCode": "def calculate(data):\n return data['close'].rolling(20).mean()",
"outputColumn": "SMA_20",
"isGroup": false
}Request Fields (Custom Python):
name(string, required): Indicator namedescription(string, required): DescriptionpythonCode(string, required): Calculation codeoutputColumn(string, required): Column nameisGroup(boolean, required): Must befalse
Request Fields (MyTT Group):
name(string, required): Indicator namedescription(string, required): DescriptionpythonCode(string, required): Calculation codegroupName(string, required): Group nameexpectedOutputs(string[], required): Output namesisGroup(boolean, required): Must betrue
Response:
{
"success": true,
"indicator": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "SMA_20",
...
}
}Status Codes:
201 Created: Indicator created successfully400 Bad Request: Validation failed500 Internal Server Error: Failed to save
Validation:
- Checks for dangerous imports (
os,subprocess, etc.) - Requires
calculatefunction - Detects dependencies automatically
Get a single indicator by ID.
Request:
GET /api/indicators/550e8400-e29b-41d4-a716-446655440000Response:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "SMA_20",
"description": "20-day Simple Moving Average",
"pythonCode": "def calculate(data):\n return data['close'].rolling(20).mean()",
"outputColumn": "SMA_20",
"dependencies": [],
"isGroup": false,
"createdAt": "2024-01-01T00:00:00.000Z"
}Status Codes:
200 OK: Success404 Not Found: Indicator not found500 Internal Server Error: Failed to read
Update an existing indicator.
Request:
PUT /api/indicators/550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json
{
"name": "SMA_20",
"description": "Updated description",
"pythonCode": "def calculate(data):\n return data['close'].rolling(20).mean()"
}Request Fields:
- Same as POST, but
isGroupandoutputColumn/groupNamecannot be changed
Response:
{
"success": true,
"indicator": {
"id": "550e8400-e29b-41d4-a716-446655440000",
...
"updatedAt": "2024-01-16T12:00:00.000Z"
}
}Status Codes:
200 OK: Updated successfully400 Bad Request: Validation failed404 Not Found: Indicator not found500 Internal Server Error: Failed to save
Delete an indicator.
Request:
DELETE /api/indicators/550e8400-e29b-41d4-a716-446655440000?cascade=falseQuery Parameters:
cascade(boolean, optional): Iftrue, delete dependent indicators too. Default:false
Response:
{
"success": true,
"message": "Indicator deleted successfully"
}Response (with dependents, cascade=false):
{
"success": false,
"error": "Cannot delete indicator",
"dependents": ["SMA_Deviation", "Buy_Signal"]
}Status Codes:
200 OK: Deleted successfully400 Bad Request: Has dependents and cascade not set404 Not Found: Indicator not found500 Internal Server Error: Failed to delete
Apply an indicator to selected stocks.
Request:
POST /api/apply-indicator
Content-Type: application/json
{
"indicatorId": "550e8400-e29b-41d4-a716-446655440000",
"datasetNames": ["000001_stock_zh_a_hist.csv", "600000_stock_zh_a_hist.csv"]
}Request Fields:
indicatorId(string, required): Indicator UUIDdatasetNames(string[], required): CSV filenames to apply to
Response:
{
"success": true,
"message": "Indicator applied to 2 dataset(s) successfully",
"results": [
{
"dataset": "000001_stock_zh_a_hist.csv",
"success": true
},
{
"dataset": "600000_stock_zh_a_hist.csv",
"success": true
}
]
}Status Codes:
200 OK: Applied successfully (even if some failed)400 Bad Request: Missing parameters500 Internal Server Error: Complete failure
Process:
- Load indicator code
- For each dataset:
- Load CSV data
- Execute Python code
- Add indicator column(s)
- Save updated CSV
- Return individual results
List all trading strategies.
Request:
GET /api/strategiesResponse:
{
"strategies": [
{
"id": "strategy-uuid",
"name": "MACD Crossover",
"description": "Buy on golden cross, sell on death cross",
"pythonCode": "def calculate(data, parameters):\n ...",
"parameters": {},
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
]
}Status Codes:
200 OK: Success500 Internal Server Error: Failed to read strategies
Create a new strategy.
Request:
POST /api/strategies
Content-Type: application/json
{
"name": "MACD Crossover",
"description": "Buy on golden cross, sell on death cross",
"pythonCode": "def calculate(data, parameters):\n signals = []\n # ... logic ...\n return signals",
"parameters": {
"short_window": 10,
"long_window": 30
}
}Request Fields:
name(string, required): Strategy namedescription(string, required): DescriptionpythonCode(string, required): Signal generation codeparameters(object, optional): Default parameters
Response:
{
"success": true,
"strategy": {
"id": "strategy-uuid",
...
}
}Status Codes:
201 Created: Strategy created400 Bad Request: Validation failed500 Internal Server Error: Failed to save
Get a single strategy.
Request:
GET /api/strategies/strategy-uuidResponse:
{
"id": "strategy-uuid",
"name": "MACD Crossover",
...
}Status Codes:
200 OK: Success404 Not Found: Strategy not found500 Internal Server Error: Failed to read
Update a strategy.
Request:
PUT /api/strategies/strategy-uuid
Content-Type: application/json
{
"name": "MACD Crossover v2",
"description": "Updated strategy",
"pythonCode": "...",
"parameters": {...}
}Response:
{
"success": true,
"strategy": {...}
}Status Codes:
200 OK: Updated successfully400 Bad Request: Validation failed404 Not Found: Strategy not found500 Internal Server Error: Failed to save
Delete a strategy.
Request:
DELETE /api/strategies/strategy-uuidResponse:
{
"success": true,
"message": "Strategy deleted successfully"
}Status Codes:
200 OK: Deleted successfully404 Not Found: Strategy not found500 Internal Server Error: Failed to delete
List all stock groups.
Request:
GET /api/groupsResponse:
{
"groups": [
{
"id": "group_1704067200000_abc123",
"name": "Tech Stocks",
"description": "Technology sector stocks",
"datasetNames": ["000001_stock_zh_a_hist.csv", "600000_stock_zh_a_hist.csv"],
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}
]
}Status Codes:
200 OK: Success500 Internal Server Error: Failed to read groups
Create a new group.
Request:
POST /api/groups
Content-Type: application/json
{
"name": "Tech Stocks",
"description": "Technology sector stocks",
"datasetNames": ["000001_stock_zh_a_hist.csv", "600000_stock_zh_a_hist.csv"]
}Request Fields:
name(string, required): Group namedescription(string, optional): DescriptiondatasetNames(string[], required): CSV filenames
Response:
{
"success": true,
"group": {
"id": "group_1704067200000_abc123",
...
}
}Status Codes:
201 Created: Group created400 Bad Request: Invalid parameters500 Internal Server Error: Failed to save
Update a group.
Request:
PUT /api/groups
Content-Type: application/json
{
"id": "group_1704067200000_abc123",
"name": "Tech Stocks Updated",
"description": "Updated description",
"datasetNames": ["000001_stock_zh_a_hist.csv"]
}Request Fields:
id(string, required): Group IDname(string, required): Updated namedescription(string, optional): Updated descriptiondatasetNames(string[], required): Updated dataset list
Response:
{
"success": true,
"group": {...}
}Status Codes:
200 OK: Updated successfully400 Bad Request: Invalid parameters404 Not Found: Group not found500 Internal Server Error: Failed to save
Delete a group.
Request:
DELETE /api/groups?id=group_1704067200000_abc123Query Parameters:
id(string, required): Group ID to delete
Response:
{
"success": true,
"message": "Group deleted successfully"
}Status Codes:
200 OK: Deleted successfully400 Bad Request: Missing ID parameter404 Not Found: Group not found500 Internal Server Error: Failed to delete
Run a backtest on single stock or group.
Request (Single Stock):
POST /api/backtest
Content-Type: application/json
{
"strategyId": "strategy-uuid",
"mode": "single",
"datasetName": "000001_stock_zh_a_hist.csv",
"initialCash": 100000,
"commission": 0.001,
"parameters": {},
"startDate": "2023-01-01",
"endDate": "2023-12-31"
}Request (Group):
POST /api/backtest
Content-Type: application/json
{
"strategyId": "strategy-uuid",
"mode": "group",
"groupId": "group_1704067200000_abc123",
"initialCash": 100000,
"commission": 0.001,
"parameters": {},
"startDate": "2023-01-01",
"endDate": "2023-12-31"
}Request Fields:
strategyId(string, required): Strategy UUIDmode(string, required):"single"or"group"datasetName(string, required if mode=single): CSV filenamegroupId(string, required if mode=group): Group IDinitialCash(number, optional): Starting capital, default: 100000commission(number, optional): Commission rate (0.001 = 0.1%), default: 0.001parameters(object, optional): Strategy parameters, default: {}startDate(string, optional): Filter start date (YYYY-MM-DD)endDate(string, optional): Filter end date (YYYY-MM-DD)
Response (Single Stock):
{
"success": true,
"results": {
"metrics": {
"totalReturn": 20000,
"totalReturnPct": 20.0,
"finalValue": 120000,
"initialValue": 100000,
"maxDrawdown": -5000,
"maxDrawdownPct": -10.0,
"sharpeRatio": 1.5,
"sortinoRatio": 2.0,
"calmarRatio": 2.0,
"winRate": 60.0,
"avgWin": 500,
"avgLoss": -300,
"profitFactor": 1.67,
"tradeCount": 20,
"wonTrades": 12,
"lostTrades": 8,
"avgSlippagePct": 0.5,
"totalSlippageCost": 200,
"sameDayTrades": 10,
"nextOpenTrades": 10
},
"equityCurve": [
{"date": "2023-01-01", "value": 100000},
{"date": "2023-01-02", "value": 101000},
...
],
"tradeMarkers": [
{
"signal_date": "2023-01-15",
"execution_date": "2023-01-16",
"date": "2023-01-16",
"type": "buy",
"price": 102.5,
"signal_price": 100.0,
"amount": 100,
"value": 10250,
"commission": 10.25,
"execution_mode": "next_open"
},
...
]
}
}Response (Group):
{
"success": true,
"results": {
"aggregated": {
"metrics": {
"totalReturn": 15000, // Mean across stocks
"totalReturnPct": 15.0,
...
}
},
"individual": [
{
"datasetName": "000001_stock_zh_a_hist.csv",
"success": true,
"metrics": {...}
},
{
"datasetName": "600000_stock_zh_a_hist.csv",
"success": true,
"metrics": {...}
}
]
}
}Status Codes:
200 OK: Backtest completed (even if strategy failed)400 Bad Request: Invalid parameters404 Not Found: Strategy, dataset, or group not found500 Internal Server Error: Execution error
Notes:
- Backtest can succeed but strategy can fail (check
results.success) - Group mode returns aggregated metrics + individual results
- Trade markers only in single stock mode
- Equity curve only in single stock mode
Retrieve all backtest history entries with optional filtering.
Request:
GET /api/backtest-history
GET /api/backtest-history?starred=true
GET /api/backtest-history?strategyId=abc123
GET /api/backtest-history?tags=optimized,finalQuery Parameters:
starred(optional): Filter by starred status (trueorfalse)strategyId(optional): Filter by strategy IDtags(optional): Comma-separated list of tags
Response:
{
"entries": [
{
"id": "hist-uuid-1",
"createdAt": "2024-01-15T10:30:00.000Z",
"strategyId": "strat-123",
"strategyName": "MA Crossover",
"strategyType": "single",
"target": {
"type": "single",
"datasetName": "平安银行"
},
"parameters": {
"initialCash": 100000,
"commission": 0.001,
"startDate": "2023-01-01",
"endDate": "2023-12-31",
"strategyParameters": {}
},
"result": {
"success": true,
"metrics": { ... },
"equityCurve": [ ... ],
"tradeMarkers": [ ... ]
},
"starred": false,
"notes": "Best performance so far",
"tags": ["optimized", "final"],
"summary": {
"totalReturn": 15000,
"totalReturnPct": 15.0,
"sharpeRatio": 1.8,
"tradeCount": 42,
"duration": 1234
}
}
]
}Status Codes:
200 OK: Success500 Internal Server Error: Database error
Get details of a specific backtest history entry.
Request:
GET /api/backtest-history/hist-uuid-1Response:
{
"entry": {
"id": "hist-uuid-1",
"createdAt": "2024-01-15T10:30:00.000Z",
"strategyId": "strat-123",
"strategyName": "MA Crossover",
"target": { ... },
"parameters": { ... },
"result": { ... },
"starred": false,
"notes": "...",
"tags": ["tag1"],
"summary": { ... }
}
}Status Codes:
200 OK: Success404 Not Found: Entry not found500 Internal Server Error: Database error
Update backtest history entry metadata (notes, tags, starred status).
Request:
PATCH /api/backtest-history/hist-uuid-1
Content-Type: application/json
{
"starred": true,
"notes": "Updated notes about this backtest",
"tags": ["optimized", "final", "production"]
}Request Body:
starred(optional): Boolean to star/unstarnotes(optional): String with user notestags(optional): Array of tag strings
Response:
{
"entry": {
"id": "hist-uuid-1",
"starred": true,
"notes": "Updated notes about this backtest",
"tags": ["optimized", "final", "production"],
...
}
}Status Codes:
200 OK: Success404 Not Found: Entry not found500 Internal Server Error: Update error
Delete a backtest history entry.
Request:
DELETE /api/backtest-history/hist-uuid-1Response:
{
"success": true,
"message": "Backtest history entry deleted"
}Status Codes:
200 OK: Successfully deleted404 Not Found: Entry not found500 Internal Server Error: Deletion error
Re-execute a backtest with the same parameters as a previous run.
Request:
POST /api/backtest-history/hist-uuid-1/rerunResponse:
{
"result": {
"success": true,
"metrics": { ... },
"equityCurve": [ ... ],
"tradeMarkers": [ ... ],
"type": "single",
"datasetName": "平安银行",
"dateRange": { ... }
}
}Status Codes:
200 OK: Backtest completed successfully404 Not Found: Original entry not found400 Bad Request: Invalid parameters or strategy deleted500 Internal Server Error: Execution error
Notes:
- Creates a new history entry for the re-run
- Uses original strategy, target, and parameters
- Fails if original strategy has been deleted
- Returns same format as
/api/backtestendpoint
Validate indicator code before saving.
Request:
POST /api/validate-indicator
Content-Type: application/json
{
"pythonCode": "def calculate(data):\n return data['close'].rolling(20).mean()",
"isGroup": false
}Request Fields:
pythonCode(string, required): Code to validateisGroup(boolean, required): Indicator type
Response (Valid):
{
"valid": true,
"message": "Indicator code is valid",
"valueCount": 100
}Response (Invalid):
{
"valid": false,
"error": "Syntax Error in indicator code",
"details": "Line 2: invalid syntax"
}Status Codes:
200 OK: Validation completed (checkvalidfield)400 Bad Request: Missing parameters500 Internal Server Error: Validation process failed
Validation Checks:
- Security: Blocks dangerous imports
- Syntax: Checks Python syntax
- Structure: Requires
calculatefunction - Execution: Runs on sample data
- Output: Validates return type
Validate strategy code before saving.
Request:
POST /api/validate-strategy
Content-Type: application/json
{
"pythonCode": "def calculate(data, parameters):\n signals = []\n return signals"
}Request Fields:
pythonCode(string, required): Code to validate
Response (Valid):
{
"valid": true,
"message": "Strategy code is valid",
"signalCount": 5
}Response (Invalid):
{
"valid": false,
"error": "Strategy must define calculate(data, parameters) function"
}Status Codes:
200 OK: Validation completed400 Bad Request: Missing code parameter500 Internal Server Error: Validation failed
Validation Checks:
- Security: Blocks dangerous imports
- Syntax: Checks Python syntax
- Structure: Requires
calculate(data, parameters)function - Execution: Runs on sample data
- Signals: Validates signal format
All error responses follow this format:
{
"success": false,
"error": "Short error message",
"details": "Detailed error information (optional)",
"code": "ERROR_CODE (optional)"
}400 Bad Request:
- Missing required parameters
- Invalid parameter format
- Validation failures
404 Not Found:
- Resource doesn't exist (indicator, strategy, dataset, group)
500 Internal Server Error:
- File system errors
- Python execution failures
- JSON parsing errors
- Unexpected exceptions
Missing Parameter:
{
"success": false,
"error": "Missing required field: symbol"
}Validation Error:
{
"valid": false,
"error": "Security violation",
"details": "Code contains dangerous imports (os, subprocess, ...)"
}Python Execution Error:
{
"success": false,
"error": "Python execution failed",
"details": "Traceback (most recent call last):\n File ...\nKeyError: 'SMA_20'"
}Current: No rate limiting
Future Implementation:
- 60 requests per minute per IP (planned)
- Configurable via environment variables
- Headers:
X-RateLimit-Limit: 60 X-RateLimit-Remaining: 45 X-RateLimit-Reset: 1704067200
-
Error Handling:
- Always check
successfield - Handle both
erroranddetails - Log errors for debugging
- Always check
-
Validation:
- Validate code before creating indicators/strategies
- Show validation errors to users
- Don't assume validation passes
-
Large Datasets:
- Use date range filters for backtests
- Apply indicators in batches
- Consider pagination for large responses
-
Timeouts:
- Implement client-side timeouts (2-5 minutes)
- Show loading states during long operations
- Allow users to cancel long-running requests
-
Caching:
- Cache dataset lists
- Cache indicator/strategy lists
- Invalidate cache on create/update/delete
- Architecture - Understand how APIs work internally
- Indicators - Using indicator endpoints
- Backtesting - Using backtest endpoints
- Datasets & Groups - Using dataset/group endpoints
Need Help? Check individual feature documentation or the troubleshooting sections.