Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

economics tab update

tilakpatel22aee81479ac42
diff --git a/README.md b/README.md
index 50586ca8e..c8fe15222 100644
--- a/README.md
+++ b/README.md
@@ -162,21 +162,6 @@ State-of-the-art financial intelligence platform with CFA-level analytics, AI au
---
-## 🔗 The Killer Feature: Cross-Domain Intelligence
-
-**Unlike traditional terminals where each module is isolated, Fincept Terminal lets you integrate data across ALL domains:**
-
-```
-Supply Chain Data → Portfolio Optimization
-Shipping Volumes → GDP Forecasts → Equity Positions
-Geopolitical Events → Currency Moves → Options Hedging
-Maritime Intelligence → Commodity Prices → Macro Strategies
-```
-
-**Build your own proprietary indicators by combining disparate data sources. Your competitive edge.**
-
----
-
## 📥 Download
**v3.0.11** | Windows • macOS • Linux
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
index 0f7f0f240..18d4098e2 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/adb_data.py
@@ -82,6 +82,22 @@ def _make_request(endpoint: str, params: Optional[Dict[str, Any]] = None, format
response = requests.get(url, params=params, timeout=TIMEOUT)
response.raise_for_status()
+ # Check if response is an XML error (ADB returns XML for errors even when JSON requested)
+ if response.text.strip().startswith('<?xml') or response.text.strip().startswith('<'):
+ # Extract error message from XML
+ import re
+ error_match = re.search(r'<com:Text>([^<]+)</com:Text>', response.text)
+ error_msg = error_match.group(1) if error_match else "Unknown API error"
+ return {
+ "data": [],
+ "metadata": {
+ "source": "Asian Development Bank (ADB) - Key Indicators Database",
+ "endpoint": endpoint,
+ "parameters": params
+ },
+ "error": f"ADB API Error: {error_msg}"
+ }
+
# Process response based on format
if format_type == "sdmx-json":
data = response.json()
@@ -171,7 +187,7 @@ def _parse_sdmx_data(sdmx_data: Dict[str, Any]) -> List[Dict[str, Any]]:
sdmx_data: Raw SDMX-JSON response
Returns:
- List of parsed data points
+ List of parsed data points with date and value
"""
if not sdmx_data or 'data' not in sdmx_data:
return []
@@ -179,41 +195,60 @@ def _parse_sdmx_data(sdmx_data: Dict[str, Any]) -> List[Dict[str, Any]]:
parsed_data = []
try:
- # Extract data from SDMX structure
- data_sets = sdmx_data.get('data', {}).get('dataSets', [])
- series = sdmx_data.get('data', {}).get('series', {})
- structure = sdmx_data.get('data', {}).get('structure', {})
+ data_section = sdmx_data.get('data', {})
+ datasets = data_section.get('datasets', [])
+ structures = data_section.get('structures', [])
- if not data_sets or not series:
+ if not datasets:
return parsed_data
- # Get series information
- for series_key, series_data in series.items():
- observations = series_data.get('observations', {})
- series_attributes = series_data.get('seriesAttributes', {})
-
- # Extract dimensions from series key
- dimensions = series_key.split(':') if ':' in series_key else [series_key]
-
- # Parse each observation
- for obs_key, obs_value in observations.items():
- if obs_value and len(obs_value) > 0:
- time_period = obs_key # Usually in format like "2020"
- value = obs_value[0] if isinstance(obs_value, list) else obs_value
-
- data_point = {
- "series_key": series_key,
- "time_period": time_period,
- "value": value,
- "dimensions": dimensions,
- "attributes": series_attributes
- }
- parsed_data.append(data_point)
+ # Extract time periods from structure
+ time_periods = []
+ if structures:
+ struct = structures[0]
+ obs_dims = struct.get('dimensions', {}).get('observation', [])
+ for od in obs_dims:
+ if od.get('id') == 'TIME_PERIOD':
+ time_periods = [v.get('value') or v.get('id') for v in od.get('values', [])]
+ break
+
+ # Parse datasets
+ for dataset in datasets:
+ series_dict = dataset.get('series', {})
+
+ for series_key, series_data in series_dict.items():
+ observations = series_data.get('observations', {})
+
+ # Parse each observation
+ for obs_idx, obs_value in observations.items():
+ if obs_value and len(obs_value) > 0:
+ # Get time period from index
+ idx = int(obs_idx)
+ time_period = time_periods[idx] if idx < len(time_periods) else str(2000 + idx)
+
+ # First element is the value
+ value = obs_value[0] if isinstance(obs_value, list) else obs_value
+
+ # Convert value to float
+ try:
+ numeric_value = float(value) if value is not None else None
+ except (ValueError, TypeError):
+ numeric_value = None
+
+ if numeric_value is not None:
+ data_point = {
+ "time_period": time_period,
+ "date": time_period,
+ "value": numeric_value,
+ "series_key": series_key
+ }
+ parsed_data.append(data_point)
+
+ # Sort by time period
+ parsed_data.sort(key=lambda x: x.get('time_period', ''))
except Exception as e:
- print(f"Error parsing SDMX data: {e}")
- # Return empty list if parsing fails
- pass
+ print(f"Error parsing SDMX data: {e}", file=sys.stderr)
return parsed_data
@@ -267,17 +302,21 @@ def get_dataflow_details(dataflow_code: str) -> Dict[str, Any]:
return result
-def get_population_data(economy: str = "all", start_period: Optional[str] = None, end_period: Optional[str] = None) -> Dict[str, Any]:
+def get_population_data(economy: str = "all", indicator: Optional[str] = None, start_period: Optional[str] = None, end_period: Optional[str] = None) -> Dict[str, Any]:
"""
Get population data for specified economy/economies
Args:
economy: Economy code (e.g., 'PHI', 'SGP', or 'all')
+ indicator: Optional indicator code (e.g., 'LP_PE_NUM_MOP' for total population)
start_period: Start year (e.g., '2010')
end_period: End year (e.g., '2020')
Returns: {"data": [...], "metadata": {...}, "error": None/error_msg}
"""
- # Build SDMX key: A.PPL_POP.FREQUENCY.all.ECONOMY
- sdmx_key = f"A..{economy}"
+ # Build SDMX key: A.INDICATOR.ECONOMY or A..ECONOMY for all indicators
+ if indicator:
+ sdmx_key = f"A.{indicator}.{economy}"
+ else:
+ sdmx_key = f"A..{economy}"
endpoint = f"data/ADB,PPL_POP/{sdmx_key}"
params = {}
@@ -296,10 +335,11 @@ def get_population_data(economy: str = "all", start_period: Optional[str] = None
if result['metadata']:
result['metadata']['economy'] = economy
result['metadata']['economy_name'] = ECONOMIES.get(economy, 'Unknown')
+ result['metadata']['indicator'] = indicator
result['metadata']['start_period'] = start_period
result['metadata']['end_period'] = end_period
result['metadata']['dataflow'] = 'PPL_POP'
- result['metadata']['description'] = f"Population data for {ECONOMIES.get(economy, economy)}"
+ result['metadata']['description'] = f"Population data for {ECONOMIES.get(economy, economy)}" + (f" - {indicator}" if indicator else "")
result['metadata']['total_records'] = len(result['data']) if isinstance(result['data'], list) else 0
return result
@@ -564,7 +604,7 @@ def main(args=None):
"get_dataflows",
"get_codelists",
"get_dataflow_details <dataflow_code>",
- "get_population <economy_code> [start_year] [end_year]",
+ "get_population <economy_code> [indicator] [start_year] [end_year]",
"get_gdp <economy_code> [indicator] [start_year] [end_year]",
"get_multiple_indicators <economy_code> <indicator1,indicator2,...> [start_year] [end_year]",
"get_multiple_economies <indicator> <economy1,economy2,...> [start_year] [end_year]",
@@ -574,7 +614,7 @@ def main(args=None):
],
"examples": [
"python adb_data.py get_dataflows",
- "python adb_data.py get_population PHI 2010 2020",
+ "python adb_data.py get_population PHI LP_PE_NUM_MOP 2010 2020",
"python adb_data.py get_gdp SGP NGDP_XDC 2015 2020",
"python adb_data.py get_multiple_indicators PHI NGDP_XDC,NGDPVA_XDC 2010 2020",
"python adb_data.py get_multiple_economies NGDP_XDC PHI,SGP,JPN 2015 2020",
@@ -601,9 +641,10 @@ def main(args=None):
elif command == "get_population":
economy = args[1] if len(args) + 1 > 2 else "all"
- start_period = args[2] if len(args) + 1 > 3 else None
- end_period = args[3] if len(args) + 1 > 4 else None
- result = get_population_data(economy, start_period, end_period)
+ indicator = args[2] if len(args) + 1 > 3 else None
+ start_period = args[3] if len(args) + 1 > 4 else None
+ end_period = args[4] if len(args) + 1 > 5 else None
+ result = get_population_data(economy, indicator, start_period, end_period)
elif command == "get_gdp":
economy = args[1] if len(args) + 1 > 2 else None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
index f532d3cfb..bce6f600f 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/cftc_data.py
@@ -187,6 +187,18 @@ class CFTCDataWrapper:
except:
return date_str
+ def _safe_int(self, value) -> int:
+ """Safely convert value to integer"""
+ if value is None:
+ return 0
+ try:
+ if isinstance(value, str):
+ # Remove commas and convert
+ return int(value.replace(',', ''))
+ return int(value)
+ except (ValueError, TypeError):
+ return 0
+
def _build_search_query(self, identifier: str) -> str:
"""Build search query for CFTC identifier"""
if not identifier or identifier.lower() == "all":
@@ -245,14 +257,20 @@ class CFTCDataWrapper:
# Build base URL
resource_id = self.reports_dict[report_type_key]
- date_range = f"Report_Date_as_YYYY_MM_DD between '{start_formatted}' AND '{end_formatted}'"
- base_url = f"{self.base_url}/resource/{resource_id}.json?$limit={limit}&$where={date_range}&$order=Report_Date_as_YYYY_MM_DD ASC"
+ # Build the where clause
+ where_clause = f"Report_Date_as_YYYY_MM_DD between '{start_formatted}' AND '{end_formatted}'"
# Add search filter if identifier is provided
search_query = self._build_search_query(identifier)
if search_query and search_query != "all":
- base_url += f" AND (UPPER(contract_market_name) like UPPER('{search_query}') OR UPPER(commodity) like UPPER('{search_query}') OR UPPER(cftc_contract_market_code) like UPPER('{search_query}') OR UPPER(commodity_group_name) like UPPER('{search_query}') OR UPPER(commodity_subgroup_name) like UPPER('{search_query}'))"
+ where_clause += f" AND (UPPER(contract_market_name) like UPPER('{search_query}') OR UPPER(commodity) like UPPER('{search_query}') OR UPPER(cftc_contract_market_code) like UPPER('{search_query}') OR UPPER(commodity_group_name) like UPPER('{search_query}') OR UPPER(commodity_subgroup_name) like UPPER('{search_query}'))"
+
+ # URL encode the where clause
+ import urllib.parse
+ encoded_where = urllib.parse.quote(where_clause)
+
+ base_url = f"{self.base_url}/resource/{resource_id}.json?$limit={limit}&$where={encoded_where}&$order=Report_Date_as_YYYY_MM_DD%20ASC"
# Make request
data = self._make_request(base_url)
@@ -590,15 +608,28 @@ class CFTCDataWrapper:
# Process trend data
trend_data = []
for record in cot_data:
+ # Handle different field names across report types
+ # Legacy reports use: noncomm_positions_long_all, comm_positions_long_all
+ # Disaggregated reports may use different naming
+ open_interest = self._safe_int(record.get("open_interest_all", 0))
+
+ # Commercial positions
+ comm_long = self._safe_int(record.get("comm_positions_long_all") or record.get("comm_long_all", 0))
+ comm_short = self._safe_int(record.get("comm_positions_short_all") or record.get("comm_short_all", 0))
+
+ # Non-commercial positions
+ noncomm_long = self._safe_int(record.get("noncomm_positions_long_all") or record.get("noncomm_long_all", 0))
+ noncomm_short = self._safe_int(record.get("noncomm_positions_short_all") or record.get("noncomm_short_all", 0))
+
trend_point = {
"date": record.get("report_date_as_yyyy_mm_dd"),
- "open_interest": record.get("open_interest_all", 0),
- "commercial_long": record.get("comm_long_all", 0),
- "commercial_short": record.get("comm_short_all", 0),
- "commercial_net": record.get("comm_long_all", 0) - record.get("comm_short_all", 0),
- "non_commercial_long": record.get("noncomm_long_all", 0),
- "non_commercial_short": record.get("noncomm_short_all", 0),
- "non_commercial_net": record.get("noncomm_long_all", 0) - record.get("noncomm_short_all", 0)
+ "open_interest": open_interest,
+ "commercial_long": comm_long,
+ "commercial_short": comm_short,
+ "commercial_net": comm_long - comm_short,
+ "non_commercial_long": noncomm_long,
+ "non_commercial_short": noncomm_short,
+ "non_commercial_net": noncomm_long - noncomm_short
}
trend_data.append(trend_point)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py
index ba850c574..a7bb3f837 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/econdb_data.py
@@ -176,7 +176,8 @@ async def get_economic_indicators(
# Build ticker symbol (e.g., GDPUS, CPICN)
ticker = f"{indicator}{country_code}"
- if transform and transform.lower() in TRANSFORMATIONS:
+ # Only add transform suffix if it's not "level" (level means no transformation)
+ if transform and transform.lower() in TRANSFORMATIONS and transform.lower() != "level":
ticker += f"~{transform.upper()}"
# Build URL
@@ -470,9 +471,10 @@ def main():
symbol = sys.argv[2]
country = sys.argv[3]
- start_date = sys.argv[4] if len(sys.argv) > 4 else None
- end_date = sys.argv[5] if len(sys.argv) > 5 else None
- transform = sys.argv[6] if len(sys.argv) > 6 else None
+ # Convert empty strings to None
+ start_date = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4].strip() else None
+ end_date = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5].strip() else None
+ transform = sys.argv[6] if len(sys.argv) > 6 and sys.argv[6].strip() else None
result = asyncio.run(get_economic_indicators(symbol, country, start_date, end_date, transform))
print(json.dumps(result, indent=2))
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/worldbank_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/worldbank_data.py
index 79d1e8c31..b98e70bb5 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/worldbank_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/worldbank_data.py
@@ -81,23 +81,40 @@ def _make_request(endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dic
# World Bank API returns array where first element contains metadata
if isinstance(data, list) and len(data) >= 2:
metadata = data[0] if data[0] else {}
- actual_data = data[1] if len(data) > 1 else []
+ actual_data = data[1] if len(data) > 1 and data[1] is not None else []
+
+ # Ensure actual_data is a list
+ if actual_data is None:
+ actual_data = []
return {
"data": actual_data,
"metadata": {
- "page": metadata.get("page", 1),
- "pages": metadata.get("pages", 1),
- "per_page": metadata.get("per_page", 50),
- "total": metadata.get("total", 0),
- "source": metadata.get("source", "World Bank"),
- "last_updated": metadata.get("lastupdated", datetime.now().isoformat())
+ "page": metadata.get("page", 1) if isinstance(metadata, dict) else 1,
+ "pages": metadata.get("pages", 1) if isinstance(metadata, dict) else 1,
+ "per_page": metadata.get("per_page", 50) if isinstance(metadata, dict) else 50,
+ "total": metadata.get("total", 0) if isinstance(metadata, dict) else 0,
+ "source": metadata.get("source", "World Bank") if isinstance(metadata, dict) else "World Bank",
+ "last_updated": metadata.get("lastupdated", datetime.now().isoformat()) if isinstance(metadata, dict) else datetime.now().isoformat()
},
"error": None
}
+ elif isinstance(data, list) and len(data) == 1:
+ # Single element response - check if it's metadata with message (no data found)
+ if isinstance(data[0], dict) and "message" in data[0]:
+ return {
+ "data": [],
+ "metadata": {"source": "World Bank", "last_updated": datetime.now().isoformat()},
+ "error": f"API message: {data[0].get('message', [{}])[0].get('value', 'No data available')}"
+ }
+ return {
+ "data": [],
+ "metadata": {"source": "World Bank", "last_updated": datetime.now().isoformat()},
+ "error": None
+ }
else:
return {
- "data": data,
+ "data": data if data is not None else [],
"metadata": {"source": "World Bank", "last_updated": datetime.now().isoformat()},
"error": None
}
@@ -249,6 +266,49 @@ def get_sources() -> Dict[str, Any]:
"error": f"Error fetching sources: {str(e)}"
}
+def get_all_indicators(per_page: int = 5000) -> Dict[str, Any]:
+ """
+ Get list of all available indicators from World Bank database
+
+ Args:
+ per_page: Number of results per page (default: 5000)
+
+ Returns:
+ JSON response with all indicator information
+ """
+ try:
+ endpoint = "indicators"
+ params = {"per_page": per_page}
+
+ result = _make_request(endpoint, params)
+
+ if result["error"]:
+ return result
+
+ # Enhance indicator data
+ enhanced_data = []
+ for indicator in result.get("data", []):
+ enhanced_indicator = {
+ "id": indicator.get("id"),
+ "name": indicator.get("name"),
+ "source": indicator.get("source"),
+ "sourceNote": indicator.get("sourceNote"),
+ "sourceOrganization": indicator.get("sourceOrganization")
+ }
+ enhanced_data.append(enhanced_indicator)
+
+ result["data"] = enhanced_data
+ result["metadata"]["count"] = len(enhanced_data)
+
+ return result
+
+ except Exception as e:
+ return {
+ "data": [],
+ "metadata": {},
+ "error": f"Error fetching all indicators: {str(e)}"
+ }
+
def get_indicators(country_code: str = "all", indicator: str = GDP_PER_CAPITA,
date_range: Optional[str] = None, per_page: int = 1000) -> Dict[str, Any]:
"""
@@ -280,14 +340,20 @@ def get_indicators(country_code: str = "all", indicator: str = GDP_PER_CAPITA,
if result["error"]:
return result
- # Enhance indicator data
+ # Enhance indicator data - handle None case
+ raw_data = result.get("data") or []
+ if raw_data is None:
+ raw_data = []
+
enhanced_data = []
- for item in result.get("data", []):
+ for item in raw_data:
+ if item is None:
+ continue
enhanced_item = {
- "indicator_id": item.get("indicator", {}).get("id"),
- "indicator_name": item.get("indicator", {}).get("value"),
- "country_id": item.get("country", {}).get("id"),
- "country_name": item.get("country", {}).get("value"),
+ "indicator_id": item.get("indicator", {}).get("id") if isinstance(item.get("indicator"), dict) else None,
+ "indicator_name": item.get("indicator", {}).get("value") if isinstance(item.get("indicator"), dict) else None,
+ "country_id": item.get("country", {}).get("id") if isinstance(item.get("country"), dict) else None,
+ "country_name": item.get("country", {}).get("value") if isinstance(item.get("country"), dict) else None,
"date": item.get("date"),
"value": item.get("value"),
"unit": item.get("unit"),
@@ -297,6 +363,7 @@ def get_indicators(country_code: str = "all", indicator: str = GDP_PER_CAPITA,
enhanced_data.append(enhanced_item)
result["data"] = enhanced_data
+ result["metadata"] = result.get("metadata") or {}
result["metadata"]["indicator"] = indicator
result["metadata"]["countries"] = country_code
result["metadata"]["observation_count"] = len(enhanced_data)
@@ -537,6 +604,7 @@ def main():
"available_commands": [
"countries [region_code]",
"sources",
+ "all_indicators",
"indicators <country_code> <indicator_code> [date_range]",
"gdp_per_capita <country_codes> [years]",
"commodity_prices <commodity_code> [years]",
@@ -556,6 +624,9 @@ def main():
elif command == "sources":
result = get_sources()
+ elif command == "all_indicators":
+ result = get_all_indicators()
+
elif command == "indicators":
if len(sys.argv) < 3:
print(json.dumps({"error": "Usage: indicators <country_code> <indicator_code> [date_range]"}))
diff --git a/fincept-terminal-desktop/src/components/command-bar/CommandBar.tsx b/fincept-terminal-desktop/src/components/command-bar/CommandBar.tsx
index 6024693eb..ebb0b2ddc 100644
--- a/fincept-terminal-desktop/src/components/command-bar/CommandBar.tsx
+++ b/fincept-terminal-desktop/src/components/command-bar/CommandBar.tsx
@@ -2,6 +2,7 @@
// Fincept-style command bar with autocomplete
import React, { useState, useRef, useEffect } from 'react';
+import { createPortal } from 'react-dom';
import { Terminal, ChevronRight } from 'lucide-react';
import { searchCommands, getCommand, Command } from './commandRegistry';
@@ -14,7 +15,9 @@ export const CommandBar: React.FC<CommandBarProps> = ({ onExecuteCommand }) => {
const [suggestions, setSuggestions] = useState<Command[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [showSuggestions, setShowSuggestions] = useState(false);
+ const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });
const inputRef = useRef<HTMLInputElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
const suggestionsRef = useRef<HTMLDivElement>(null);
// Update suggestions when input changes
@@ -95,8 +98,8 @@ export const CommandBar: React.FC<CommandBarProps> = ({ onExecuteCommand }) => {
if (
suggestionsRef.current &&
!suggestionsRef.current.contains(event.target as Node) &&
- inputRef.current &&
- !inputRef.current.contains(event.target as Node)
+ containerRef.current &&
+ !containerRef.current.contains(event.target as Node)
) {
setShowSuggestions(false);
}
@@ -106,16 +109,118 @@ export const CommandBar: React.FC<CommandBarProps> = ({ onExecuteCommand }) => {
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
+ // Update dropdown position when showing suggestions
+ useEffect(() => {
+ if (showSuggestions && containerRef.current) {
+ const rect = containerRef.current.getBoundingClientRect();
+ setDropdownPosition({
+ top: rect.bottom + 2,
+ left: rect.left,
+ width: Math.max(rect.width, 280) // Minimum width for better readability
+ });
+ }
+ }, [showSuggestions, input]);
+
+ // Render suggestions dropdown using portal to avoid overflow clipping
+ const renderSuggestions = () => {
+ if (!showSuggestions || suggestions.length === 0) return null;
+
+ const dropdown = (
+ <div
+ ref={suggestionsRef}
+ style={{
+ position: 'fixed',
+ top: dropdownPosition.top,
+ left: dropdownPosition.left,
+ width: dropdownPosition.width,
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ borderRadius: '2px',
+ maxHeight: '300px',
+ overflowY: 'auto',
+ zIndex: 99999,
+ boxShadow: '0 4px 12px rgba(0,0,0,0.5)'
+ }}
+ >
+ {suggestions.map((cmd, index) => (
+ <div
+ key={cmd.id}
+ onClick={() => {
+ setInput(cmd.aliases[0]);
+ executeCommand(cmd.aliases[0]);
+ }}
+ style={{
+ padding: '8px 12px',
+ cursor: 'pointer',
+ backgroundColor: index === selectedIndex ? '#2a2a2a' : 'transparent',
+ borderLeft: index === selectedIndex ? '3px solid #ea580c' : '3px solid transparent',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '12px',
+ transition: 'all 0.1s'
+ }}
+ onMouseEnter={() => setSelectedIndex(index)}
+ >
+ <div style={{ flex: 1 }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '2px'
+ }}>
+ <span style={{
+ color: '#ffffff',
+ fontSize: '11px',
+ fontFamily: 'Consolas, "Courier New", monospace',
+ fontWeight: 'bold'
+ }}>
+ {cmd.aliases[0].toUpperCase()}
+ </span>
+ <ChevronRight size={10} color="#666" />
+ <span style={{
+ color: '#a3a3a3',
+ fontSize: '11px'
+ }}>
+ {cmd.name}
+ </span>
+ {cmd.shortcut && (
+ <span style={{
+ marginLeft: 'auto',
+ color: '#666',
+ fontSize: '10px',
+ fontFamily: 'Consolas, "Courier New", monospace'
+ }}>
+ {cmd.shortcut}
+ </span>
+ )}
+ </div>
+ <div style={{
+ color: '#737373',
+ fontSize: '10px',
+ marginLeft: '0'
+ }}>
+ {cmd.description}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+
+ return createPortal(dropdown, document.body);
+ };
+
return (
- <div style={{ position: 'relative', width: '180px', minWidth: '120px', maxWidth: '200px', flex: '0 1 180px' }}>
+ <div ref={containerRef} style={{ position: 'relative', width: '180px', minWidth: '120px', maxWidth: '200px', flex: '0 1 180px' }}>
<div style={{
display: 'flex',
alignItems: 'center',
backgroundColor: '#1a1a1a',
- border: '1px solid #404040',
+ border: showSuggestions ? '1px solid #ea580c' : '1px solid #404040',
borderRadius: '2px',
padding: '0 6px',
- height: '20px'
+ height: '20px',
+ transition: 'border-color 0.2s'
}}>
<Terminal size={10} color="#ea580c" style={{ marginRight: '4px', flexShrink: 0 }} />
<input
@@ -144,90 +249,8 @@ export const CommandBar: React.FC<CommandBarProps> = ({ onExecuteCommand }) => {
/>
</div>
- {/* Autocomplete Suggestions */}
- {showSuggestions && suggestions.length > 0 && (
- <div
- ref={suggestionsRef}
- style={{
- position: 'absolute',
- top: '100%',
- left: 0,
- right: 0,
- marginTop: '2px',
- backgroundColor: '#1a1a1a',
- border: '1px solid #404040',
- borderRadius: '2px',
- maxHeight: '300px',
- overflowY: 'auto',
- zIndex: 9999,
- boxShadow: '0 4px 12px rgba(0,0,0,0.5)'
- }}
- >
- {suggestions.map((cmd, index) => (
- <div
- key={cmd.id}
- onClick={() => {
- setInput(cmd.aliases[0]);
- executeCommand(cmd.aliases[0]);
- }}
- style={{
- padding: '8px 12px',
- cursor: 'pointer',
- backgroundColor: index === selectedIndex ? '#2a2a2a' : 'transparent',
- borderLeft: index === selectedIndex ? '3px solid #ea580c' : '3px solid transparent',
- display: 'flex',
- alignItems: 'flex-start',
- gap: '12px',
- transition: 'all 0.1s'
- }}
- onMouseEnter={() => setSelectedIndex(index)}
- >
- <div style={{ flex: 1 }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- marginBottom: '2px'
- }}>
- <span style={{
- color: '#ffffff',
- fontSize: '11px',
- fontFamily: 'Consolas, "Courier New", monospace',
- fontWeight: 'bold'
- }}>
- {cmd.aliases[0].toUpperCase()}
- </span>
- <ChevronRight size={10} color="#666" />
- <span style={{
- color: '#a3a3a3',
- fontSize: '11px'
- }}>
- {cmd.name}
- </span>
- {cmd.shortcut && (
- <span style={{
- marginLeft: 'auto',
- color: '#666',
- fontSize: '10px',
- fontFamily: 'Consolas, "Courier New", monospace'
- }}>
- {cmd.shortcut}
- </span>
- )}
- </div>
- <div style={{
- color: '#737373',
- fontSize: '10px',
- marginLeft: '0'
- }}>
- {cmd.description}
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
-
+ {/* Autocomplete Suggestions - rendered via portal */}
+ {renderSuggestions()}
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
index dc5f2682c..6c7f00aa9 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
@@ -22,6 +22,7 @@ import {
CryptoChartArea,
CryptoBottomPanel,
CryptoStatusBar,
+ CryptoSettingsPanel,
} from './components';
// Import constants and types
@@ -75,8 +76,7 @@ type CryptoAction =
| { type: 'SET_SYMBOLS'; symbols: string[]; isLoading: boolean }
| { type: 'RESET_DATA' }
| { type: 'CLEAR_TICKER_TRADES' }
- | { type: 'UPDATE_POSITION_PRICES'; prices: Map<string, number> }
- | { type: 'UPDATE_FROM_TRADE'; trade: { symbol: string; side: 'buy' | 'sell'; price: number; quantity: number; timestamp: number } };
+ | { type: 'UPDATE_POSITION_PRICES'; prices: Map<string, number> };
const initialState: CryptoState = {
status: 'idle',
@@ -164,66 +164,6 @@ function cryptoReducer(state: CryptoState, action: CryptoAction): CryptoState {
};
}),
};
- case 'UPDATE_FROM_TRADE':
- // Handle position updates from trade execution
- const { trade } = action;
- const existingPos = state.positions.find(p => p.symbol === trade.symbol);
-
- let updatedPositions = [...state.positions];
-
- if (!existingPos) {
- // New position opened
- updatedPositions.push({
- symbol: trade.symbol,
- side: trade.side === 'buy' ? 'long' : 'short',
- quantity: trade.quantity,
- entryPrice: trade.price,
- currentPrice: trade.price,
- positionValue: trade.price * trade.quantity,
- unrealizedPnl: 0,
- pnlPercent: 0,
- });
- } else {
- // Update existing position or close it
- updatedPositions = updatedPositions.map(pos => {
- if (pos.symbol !== trade.symbol) return pos;
-
- const isSameSide = (pos.side === 'long' && trade.side === 'buy') || (pos.side === 'short' && trade.side === 'sell');
-
- if (isSameSide) {
- // Adding to position - recalculate average entry
- const totalQty = pos.quantity + trade.quantity;
- const newEntry = ((pos.entryPrice * pos.quantity) + (trade.price * trade.quantity)) / totalQty;
-
- return {
- ...pos,
- quantity: totalQty,
- entryPrice: newEntry,
- positionValue: trade.price * totalQty,
- };
- } else {
- // Reducing position
- const newQty = pos.quantity - trade.quantity;
-
- if (newQty <= 0) {
- // Position closed - will be filtered out
- return null;
- }
-
- return {
- ...pos,
- quantity: newQty,
- positionValue: trade.price * newQty,
- };
- }
- }).filter(Boolean) as Position[];
- }
-
- return {
- ...state,
- positions: updatedPositions,
- trades: [trade, ...state.trades].slice(0, 50), // Keep last 50 trades
- };
default:
return state;
}
@@ -683,6 +623,11 @@ export function CryptoTradingTab() {
}
}, [tradingMode, paperAdapter, activeBroker]);
+ // Normalize symbol for comparison (removes slashes, dashes, converts to uppercase)
+ const normalizeSymbol = (symbol: string): string => {
+ return symbol.replace(/[/\-_]/g, '').toUpperCase();
+ };
+
// Real-time WebSocket listeners for positions
useEffect(() => {
let mounted = true;
@@ -694,32 +639,24 @@ export function CryptoTradingTab() {
if (!mounted) return;
const { symbol, price } = event.payload;
+ const normalizedEventSymbol = normalizeSymbol(symbol);
- // Check if we have a position for this symbol
- const hasPosition = state.positions.some(p => p.symbol === symbol);
- if (!hasPosition) return;
+ // Find position that matches this symbol (with normalization)
+ const matchingPosition = state.positions.find(p => normalizeSymbol(p.symbol) === normalizedEventSymbol);
+ if (!matchingPosition) return;
- // Update position prices
+ // Update position prices using the position's original symbol format
const priceMap = new Map<string, number>();
- priceMap.set(symbol, price);
+ priceMap.set(matchingPosition.symbol, price);
dispatch({ type: 'UPDATE_POSITION_PRICES', prices: priceMap });
});
unlisteners.push(tickerUnlisten);
- // 2. Trade executions (ws_trade) - for paper trading fills
- const tradeUnlisten = await listen<{ provider: string; symbol: string; price: number; quantity: number; side: 'buy' | 'sell'; timestamp: number }>('ws_trade', (event) => {
- if (!mounted) return;
-
- const { symbol, price, quantity, side, timestamp } = event.payload;
-
- // Update positions based on trade execution
- dispatch({
- type: 'UPDATE_FROM_TRADE',
- trade: { symbol, price, quantity, side, timestamp }
- });
- });
- unlisteners.push(tradeUnlisten);
+ // Note: ws_trade events are market trades (all trades on the exchange)
+ // NOT the user's paper trading fills. User trades come from loadPaperTradingData.
+ // We don't need to listen to ws_trade here as it would incorrectly add
+ // market trades to the user's trade history.
};
setupWebSocketListeners();
@@ -811,6 +748,20 @@ export function CryptoTradingTab() {
setSearchQuery(sanitizeInput(query));
}, []);
+ // Handle reset portfolio
+ const handleResetPortfolio = useCallback(async () => {
+ if (!paperAdapter || !('portfolioId' in paperAdapter)) return;
+
+ try {
+ const { resetPortfolio } = await import('@/paper-trading');
+ await resetPortfolio((paperAdapter as any).portfolioId);
+ // Reload paper trading data after reset
+ loadPaperTradingData();
+ } catch (error) {
+ console.error('[CryptoTrading] Failed to reset portfolio:', error);
+ }
+ }, [paperAdapter, loadPaperTradingData]);
+
const currentPrice = state.tickerData?.last || state.tickerData?.price || state.orderBook.asks[0]?.price || 0;
// Calculate price change and percentage
@@ -948,6 +899,7 @@ export function CryptoTradingTab() {
selectedSymbol={selectedSymbol}
currentPrice={currentPrice}
balance={state.balance}
+ positions={state.positions}
tradingMode={tradingMode}
activeBroker={activeBroker}
isLoading={isLoading}
@@ -978,6 +930,20 @@ export function CryptoTradingTab() {
isConnected={activeAdapter?.isConnected() || false}
/>
</ErrorBoundary>
+
+ {/* Settings Panel */}
+ <CryptoSettingsPanel
+ isOpen={showSettings}
+ onClose={() => setShowSettings(false)}
+ slippage={slippage}
+ makerFee={makerFee}
+ takerFee={takerFee}
+ onSlippageChange={setSlippage}
+ onMakerFeeChange={setMakerFee}
+ onTakerFeeChange={setTakerFee}
+ onResetPortfolio={handleResetPortfolio}
+ tradingMode={tradingMode}
+ />
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
index b7d61d6bc..7eec3339b 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
@@ -3,10 +3,19 @@ import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react'
import { RefreshCw, TrendingUp, TrendingDown, AlertTriangle, Check, Loader2, ChevronDown, ChevronUp } from 'lucide-react';
import { FINCEPT } from '../constants';
+interface Position {
+ symbol: string;
+ side: 'long' | 'short';
+ quantity: number;
+ entryPrice: number;
+ currentPrice: number;
+}
+
interface CryptoOrderEntryProps {
selectedSymbol: string;
currentPrice: number;
balance: number;
+ positions?: Position[];
tradingMode: 'paper' | 'live';
activeBroker: string | null;
isLoading: boolean;
@@ -25,6 +34,7 @@ export function CryptoOrderEntry({
selectedSymbol,
currentPrice,
balance,
+ positions = [],
tradingMode,
activeBroker,
isLoading,
@@ -89,6 +99,13 @@ export function CryptoOrderEntry({
const effectivePriceForMax = priceNum > 0 ? priceNum : currentPrice;
const maxBuyQuantity = balance > 0 && effectivePriceForMax > 0 ? balance / effectivePriceForMax : 0;
+ // For sell orders, find current position quantity for this symbol
+ const currentPosition = positions.find(p => p.symbol === selectedSymbol);
+ const positionQuantity = currentPosition?.quantity || 0;
+ const positionSide = currentPosition?.side || 'long';
+ // Max sell quantity is the position size (can only sell what you hold)
+ const maxSellQuantity = positionQuantity;
+
// Format helpers
const formatNum = (num: number, decimals = 2) => {
if (num >= 1000000) return `${(num / 1000000).toFixed(2)}M`;
@@ -117,20 +134,27 @@ export function CryptoOrderEntry({
// Handle percentage buttons
const handlePercentage = useCallback((percent: number) => {
const effectivePrice = priceNum > 0 ? priceNum : currentPrice;
- if (effectivePrice <= 0) return;
if (side === 'buy') {
// Buy: how much base asset can we afford with balance
+ if (effectivePrice <= 0 || balance <= 0) return;
const maxQty = balance / effectivePrice;
const qty = maxQty * percent;
setQuantity(qty > 0 ? qty.toFixed(6) : '');
} else {
- // Sell: percentage of balance (balance here is USD, not holdings)
- // For sell side the percentage is of available holdings, not USD balance
- const qty = balance * percent / effectivePrice;
- setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ // Sell/Short: percentage of current position holdings OR percentage of balance for new shorts
+ if (positionQuantity > 0 && positionSide === 'long') {
+ // If we have a long position, sell percentage of that position
+ const qty = positionQuantity * percent;
+ setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ } else if (effectivePrice > 0 && balance > 0) {
+ // No position or short position - calculate short size based on available margin
+ const maxQty = balance / effectivePrice;
+ const qty = maxQty * percent;
+ setQuantity(qty > 0 ? qty.toFixed(6) : '');
+ }
}
- }, [balance, currentPrice, priceNum, side]);
+ }, [balance, currentPrice, priceNum, side, positionQuantity, positionSide]);
// Handle order submission
const handleSubmit = useCallback(async () => {
@@ -470,7 +494,15 @@ export function CryptoOrderEntry({
<div style={{ marginBottom: '12px' }}>
<div className="oe-label">
<span>Amount</span>
- <span>Max: {formatNum(maxBuyQuantity, 6)} {baseAsset}</span>
+ <span>
+ {side === 'buy' ? (
+ <>Max: {formatNum(maxBuyQuantity, 6)} {baseAsset}</>
+ ) : positionQuantity > 0 && positionSide === 'long' ? (
+ <>Position: {formatNum(positionQuantity, 6)} {baseAsset}</>
+ ) : (
+ <>Max Short: {formatNum(maxBuyQuantity, 6)} {baseAsset}</>
+ )}
+ </span>
</div>
<div style={{ position: 'relative' }}>
<input
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx
new file mode 100644
index 000000000..11375370a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoSettingsPanel.tsx
@@ -0,0 +1,408 @@
+// CryptoSettingsPanel.tsx - Terminal-style settings modal for crypto trading
+import React from 'react';
+import { X, Sliders, DollarSign, Percent, RotateCcw, Trash2 } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface CryptoSettingsPanelProps {
+ isOpen: boolean;
+ onClose: () => void;
+ // Trading settings
+ slippage: number;
+ makerFee: number;
+ takerFee: number;
+ onSlippageChange: (value: number) => void;
+ onMakerFeeChange: (value: number) => void;
+ onTakerFeeChange: (value: number) => void;
+ // Portfolio actions
+ onResetPortfolio?: () => void;
+ tradingMode: 'paper' | 'live';
+}
+
+export function CryptoSettingsPanel({
+ isOpen,
+ onClose,
+ slippage,
+ makerFee,
+ takerFee,
+ onSlippageChange,
+ onMakerFeeChange,
+ onTakerFeeChange,
+ onResetPortfolio,
+ tradingMode,
+}: CryptoSettingsPanelProps) {
+ if (!isOpen) return null;
+
+ const handleSlippageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = parseFloat(e.target.value);
+ if (!isNaN(value) && value >= 0 && value <= 10) {
+ onSlippageChange(value);
+ }
+ };
+
+ const handleMakerFeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = parseFloat(e.target.value);
+ if (!isNaN(value) && value >= 0 && value <= 1) {
+ onMakerFeeChange(value);
+ }
+ };
+
+ const handleTakerFeeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = parseFloat(e.target.value);
+ if (!isNaN(value) && value >= 0 && value <= 1) {
+ onTakerFeeChange(value);
+ }
+ };
+
+ const handleResetPortfolio = () => {
+ if (onResetPortfolio && window.confirm('Are you sure you want to reset your paper trading portfolio? This will clear all positions, orders, and trade history.')) {
+ onResetPortfolio();
+ onClose();
+ }
+ };
+
+ return (
+ <div
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 10000,
+ }}
+ onClick={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+ <div
+ style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `2px solid ${FINCEPT.ORANGE}`,
+ width: '400px',
+ maxWidth: '90vw',
+ maxHeight: '80vh',
+ overflow: 'auto',
+ boxShadow: `0 0 30px ${FINCEPT.ORANGE}30`,
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '12px 16px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <Sliders size={16} color={FINCEPT.ORANGE} />
+ <span
+ style={{
+ color: FINCEPT.WHITE,
+ fontSize: '12px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ }}
+ >
+ TRADING SETTINGS
+ </span>
+ </div>
+ <button
+ onClick={onClose}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.color = FINCEPT.WHITE)}
+ onMouseLeave={(e) => (e.currentTarget.style.color = FINCEPT.GRAY)}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ {/* Content */}
+ <div style={{ padding: '16px' }}>
+ {/* Paper Trading Settings */}
+ {tradingMode === 'paper' && (
+ <>
+ <div
+ style={{
+ marginBottom: '20px',
+ padding: '12px',
+ backgroundColor: `${FINCEPT.ORANGE}10`,
+ border: `1px solid ${FINCEPT.ORANGE}30`,
+ }}
+ >
+ <div
+ style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ }}
+ >
+ PAPER TRADING MODE
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: 1.5 }}>
+ Configure simulation settings. These only apply to paper trading and do not affect live orders.
+ </div>
+ </div>
+
+ {/* Slippage Setting */}
+ <div style={{ marginBottom: '16px' }}>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '10px',
+ fontWeight: 600,
+ color: FINCEPT.GRAY,
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ }}
+ >
+ <Percent size={12} color={FINCEPT.CYAN} />
+ SLIPPAGE SIMULATION (%)
+ </label>
+ <input
+ type="number"
+ value={slippage}
+ onChange={handleSlippageChange}
+ min="0"
+ max="10"
+ step="0.01"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '12px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ />
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Simulates price slippage on market orders (0-10%)
+ </div>
+ </div>
+
+ {/* Maker Fee */}
+ <div style={{ marginBottom: '16px' }}>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '10px',
+ fontWeight: 600,
+ color: FINCEPT.GRAY,
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ }}
+ >
+ <DollarSign size={12} color={FINCEPT.GREEN} />
+ MAKER FEE (%)
+ </label>
+ <input
+ type="number"
+ value={(makerFee * 100).toFixed(4)}
+ onChange={(e) => {
+ const value = parseFloat(e.target.value) / 100;
+ if (!isNaN(value) && value >= 0 && value <= 1) {
+ onMakerFeeChange(value);
+ }
+ }}
+ min="0"
+ max="100"
+ step="0.001"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '12px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ />
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Fee for limit orders that add liquidity
+ </div>
+ </div>
+
+ {/* Taker Fee */}
+ <div style={{ marginBottom: '20px' }}>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ fontSize: '10px',
+ fontWeight: 600,
+ color: FINCEPT.GRAY,
+ marginBottom: '8px',
+ letterSpacing: '0.5px',
+ }}
+ >
+ <DollarSign size={12} color={FINCEPT.RED} />
+ TAKER FEE (%)
+ </label>
+ <input
+ type="number"
+ value={(takerFee * 100).toFixed(4)}
+ onChange={(e) => {
+ const value = parseFloat(e.target.value) / 100;
+ if (!isNaN(value) && value >= 0 && value <= 1) {
+ onTakerFeeChange(value);
+ }
+ }}
+ min="0"
+ max="100"
+ step="0.001"
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '12px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ }}
+ />
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Fee for market orders that take liquidity
+ </div>
+ </div>
+
+ {/* Divider */}
+ <div
+ style={{
+ height: '1px',
+ backgroundColor: FINCEPT.BORDER,
+ margin: '20px 0',
+ }}
+ />
+
+ {/* Reset Portfolio */}
+ <div>
+ <div
+ style={{
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.RED,
+ marginBottom: '12px',
+ letterSpacing: '0.5px',
+ }}
+ >
+ DANGER ZONE
+ </div>
+ <button
+ onClick={handleResetPortfolio}
+ style={{
+ width: '100%',
+ padding: '12px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.RED}`,
+ color: FINCEPT.RED,
+ fontSize: '10px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = FINCEPT.RED;
+ e.currentTarget.style.color = FINCEPT.WHITE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = FINCEPT.RED;
+ }}
+ >
+ <RotateCcw size={12} />
+ RESET PAPER PORTFOLIO
+ </button>
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: '8px', textAlign: 'center' }}>
+ Clears all positions, orders, and resets balance to initial amount
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Live Trading Mode Info */}
+ {tradingMode === 'live' && (
+ <div
+ style={{
+ padding: '20px',
+ backgroundColor: `${FINCEPT.RED}10`,
+ border: `1px solid ${FINCEPT.RED}30`,
+ textAlign: 'center',
+ }}
+ >
+ <div
+ style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: FINCEPT.RED,
+ marginBottom: '8px',
+ }}
+ >
+ LIVE TRADING MODE
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: 1.5 }}>
+ Settings are managed by your exchange. Fees and slippage are determined by market conditions.
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div
+ style={{
+ padding: '12px 16px',
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ display: 'flex',
+ justifyContent: 'flex-end',
+ }}
+ >
+ <button
+ onClick={onClose}
+ style={{
+ padding: '8px 20px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ fontSize: '10px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#FFA030')}
+ onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = FINCEPT.ORANGE)}
+ >
+ CLOSE
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default CryptoSettingsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts
index eff56ac17..6b5c3ac7e 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts
@@ -7,3 +7,4 @@ export { CryptoOrderEntry } from './CryptoOrderEntry';
export { CryptoChartArea } from './CryptoChartArea';
export { CryptoBottomPanel } from './CryptoBottomPanel';
export { CryptoStatusBar } from './CryptoStatusBar';
+export { CryptoSettingsPanel } from './CryptoSettingsPanel';
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx
index 30a77a04a..59e751611 100644
--- a/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx
@@ -1,676 +1,497 @@
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import React, { useState, useCallback } from 'react';
-import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
-import { RefreshCw, Download, Globe, TrendingUp, BarChart3, PieChart } from 'lucide-react';
-import { invoke } from '@tauri-apps/api/core';
-import bisDataService from '@/services/data-sources/bisDataService';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-
-interface Indicator {
- code: string;
- name: string;
- description: string;
-}
-
-interface Country {
- code: string;
- name: string;
-}
-
-interface Observation {
- date: string;
- value: number;
-}
-
-interface IndicatorData {
- indicator: string;
- country: string;
- transform: string;
- observations: Observation[];
- observation_count?: number;
- metadata: any;
-}
-
-interface ProfileData {
- country: string;
- indicators: Record<string, { date: string; value: number }>;
-}
+// EconomicsTab - Main component for economic data visualization
+// Refactored to use modular components, hooks, and constants
+
+import React, { useRef, useState } from 'react';
+import { revealItemInDir } from '@tauri-apps/plugin-opener';
+import {
+ RefreshCw,
+ Download,
+ Globe,
+ AlertCircle,
+ Database,
+ Image,
+ CheckCircle,
+ FolderOpen,
+ Key,
+} from 'lucide-react';
+
+// Local imports
+import { FINCEPT, DATA_SOURCES, getIndicatorsForSource } from './constants';
+import type { DataSource } from './types';
+import { useEconomicsData, useExport } from './hooks';
+import {
+ EconomicsChart,
+ StatsBar,
+ DataTable,
+ ApiKeyPanel,
+ CountrySelector,
+ IndicatorSelector,
+ DateRangePicker,
+} from './components';
+
+// Utility function for formatting values
+const formatValue = (val: number): string => {
+ if (Math.abs(val) >= 1e12) return `${(val / 1e12).toFixed(2)}T`;
+ if (Math.abs(val) >= 1e9) return `${(val / 1e9).toFixed(2)}B`;
+ if (Math.abs(val) >= 1e6) return `${(val / 1e6).toFixed(2)}M`;
+ if (Math.abs(val) >= 1e3) return `${(val / 1e3).toFixed(2)}K`;
+ if (Math.abs(val) < 0.01 && val !== 0) return val.toExponential(2);
+ return val.toFixed(2);
+};
export default function EconomicsTab() {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const { t } = useTranslation('economics');
- const [dataSource, setDataSource] = useState<'econdb' | 'bis'>('econdb');
- const [view, setView] = useState<'indicator' | 'profile' | 'countries'>('indicator');
- const [loading, setLoading] = useState(false);
- const [status, setStatus] = useState('Ready');
-
- // Indicator view state
- const [selectedIndicator, setSelectedIndicator] = useState('GDP');
- const [selectedCountry, setSelectedCountry] = useState('US');
- const [selectedTransform, setSelectedTransform] = useState('level');
- const [indicatorData, setIndicatorData] = useState<IndicatorData | null>(null);
-
- // BIS-specific state
- const [bisDataType, setBisDataType] = useState<
- 'policy_rates' | 'effective_exchange' | 'property_prices' | 'total_credit' |
- 'consumer_prices' | 'credit_gap' | 'debt_service' | 'cb_assets'
- >('policy_rates');
- const [bisStartDate, setBisStartDate] = useState(() => {
- const date = new Date();
- date.setFullYear(date.getFullYear() - 1); // 1 year ago
- return date.toISOString().split('T')[0];
- });
- const [bisEndDate, setBisEndDate] = useState(() => new Date().toISOString().split('T')[0]);
-
- // Workspace tab state
- const getWorkspaceState = useCallback(() => ({
- dataSource, view, selectedIndicator, selectedCountry, selectedTransform, bisDataType,
- }), [dataSource, view, selectedIndicator, selectedCountry, selectedTransform, bisDataType]);
-
- const setWorkspaceState = useCallback((state: Record<string, unknown>) => {
- if (state.dataSource === "econdb" || state.dataSource === "bis") setDataSource(state.dataSource);
- if (state.view === "indicator" || state.view === "profile" || state.view === "countries") setView(state.view);
- if (typeof state.selectedIndicator === "string") setSelectedIndicator(state.selectedIndicator);
- if (typeof state.selectedCountry === "string") setSelectedCountry(state.selectedCountry);
- if (typeof state.selectedTransform === "string") setSelectedTransform(state.selectedTransform);
- if (typeof state.bisDataType === "string") setBisDataType(state.bisDataType as any);
- }, []);
-
- useWorkspaceTabState("economics", getWorkspaceState, setWorkspaceState);
-
- // BIS available countries (only major economies with data)
- const bisCountries = [
- { code: 'US', name: 'United States' },
- { code: 'CN', name: 'China' },
- { code: 'JP', name: 'Japan' },
- { code: 'GB', name: 'United Kingdom' },
- { code: 'IN', name: 'India' },
- { code: 'BR', name: 'Brazil' },
- { code: 'CA', name: 'Canada' },
- { code: 'KR', name: 'South Korea' },
- { code: 'RU', name: 'Russia' },
- { code: 'AU', name: 'Australia' },
- { code: 'MX', name: 'Mexico' },
- { code: 'ID', name: 'Indonesia' },
- { code: 'SA', name: 'Saudi Arabia' },
- { code: 'TR', name: 'Turkey' },
- { code: 'CH', name: 'Switzerland' },
- { code: 'ZA', name: 'South Africa' },
- { code: 'AR', name: 'Argentina' },
- { code: 'SE', name: 'Sweden' },
- { code: 'NO', name: 'Norway' },
- { code: 'PL', name: 'Poland' },
- { code: 'TH', name: 'Thailand' },
- { code: 'MY', name: 'Malaysia' },
- { code: 'SG', name: 'Singapore' },
- { code: 'HK', name: 'Hong Kong' },
- { code: 'NZ', name: 'New Zealand' },
- ];
-
- // Profile view state
- const [profileCountry, setProfileCountry] = useState('US');
- const [profileData, setProfileData] = useState<ProfileData | null>(null);
-
- // Available options
- const indicators: Indicator[] = [
- { code: 'GDP', name: 'GDP (Nominal)', description: 'Gross Domestic Product' },
- { code: 'RGDP', name: 'GDP (Real)', description: 'Real GDP' },
- { code: 'CPI', name: 'CPI', description: 'Consumer Price Index' },
- { code: 'PPI', name: 'PPI', description: 'Producer Price Index' },
- { code: 'CORE', name: 'Core CPI', description: 'Core Inflation' },
- { code: 'URATE', name: 'Unemployment', description: 'Unemployment Rate' },
- { code: 'EMP', name: 'Employment', description: 'Employment Level' },
- { code: 'IP', name: 'Industrial Production', description: 'Industrial Production Index' },
- { code: 'RETA', name: 'Retail Sales', description: 'Retail Sales' },
- { code: 'CONF', name: 'Consumer Confidence', description: 'Consumer Confidence Index' },
- { code: 'POLIR', name: 'Policy Rate', description: 'Policy Interest Rate' },
- { code: 'Y10YD', name: '10Y Yield', description: '10-Year Government Bond Yield' },
- { code: 'M3YD', name: '3M Yield', description: '3-Month Treasury Yield' },
- { code: 'GDEBT', name: 'Government Debt', description: 'Government Debt' },
- { code: 'CA', name: 'Current Account', description: 'Current Account Balance' },
- { code: 'TB', name: 'Trade Balance', description: 'Trade Balance' },
- { code: 'POP', name: 'Population', description: 'Total Population' },
- ];
-
- const countries: Country[] = [
- { code: 'US', name: 'United States' },
- { code: 'CN', name: 'China' },
- { code: 'JP', name: 'Japan' },
- { code: 'DE', name: 'Germany' },
- { code: 'UK', name: 'United Kingdom' },
- { code: 'FR', name: 'France' },
- { code: 'IN', name: 'India' },
- { code: 'IT', name: 'Italy' },
- { code: 'BR', name: 'Brazil' },
- { code: 'CA', name: 'Canada' },
- { code: 'KR', name: 'South Korea' },
- { code: 'RU', name: 'Russia' },
- { code: 'AU', name: 'Australia' },
- { code: 'ES', name: 'Spain' },
- { code: 'MX', name: 'Mexico' },
- { code: 'ID', name: 'Indonesia' },
- { code: 'NL', name: 'Netherlands' },
- { code: 'SA', name: 'Saudi Arabia' },
- { code: 'TR', name: 'Turkey' },
- { code: 'CH', name: 'Switzerland' },
- ];
-
- const transforms = [
- { code: 'level', name: 'Level', description: 'No transformation' },
- { code: 'toya', name: 'YoY %', description: 'Year-over-year change' },
- { code: 'tpop', name: 'QoQ %', description: 'Quarter-over-quarter change' },
- { code: 'tusd', name: 'USD', description: 'Convert to USD' },
- { code: 'tpgp', name: '% of GDP', description: 'As percent of GDP' },
- ];
-
- const fetchIndicator = async () => {
- setLoading(true);
- setStatus(`Fetching data for ${selectedCountry}...`);
-
- try {
- if (dataSource === 'bis') {
- // Fetch from BIS based on selected data type with date range
- let result;
-
- // Map data type to BIS dataset and frequency
- const bisDatasetMap: Record<string, { flow: string; freq: string }> = {
- policy_rates: { flow: 'WS_CBPOL', freq: 'D' },
- effective_exchange: { flow: 'WS_EER', freq: 'M' },
- property_prices: { flow: 'WS_SPP', freq: 'Q' },
- total_credit: { flow: 'WS_TC', freq: 'Q' },
- consumer_prices: { flow: 'WS_LONG_CPI', freq: 'M' },
- credit_gap: { flow: 'WS_CREDIT_GAP', freq: 'Q' },
- debt_service: { flow: 'WS_DSR', freq: 'Q' },
- cb_assets: { flow: 'WS_CBTA', freq: 'M' },
- };
-
- const dataset = bisDatasetMap[bisDataType];
-
- if (bisDataType === 'policy_rates') {
- result = await bisDataService.getCentralBankPolicyRates([selectedCountry], bisStartDate, bisEndDate);
- } else if (bisDataType === 'effective_exchange') {
- result = await bisDataService.getEffectiveExchangeRates([selectedCountry], bisStartDate, bisEndDate);
- } else {
- // Use generic get_data for other datasets
- result = await bisDataService.getData(
- dataset.flow,
- `${dataset.freq}.${selectedCountry}`,
- bisStartDate,
- bisEndDate
- );
- }
-
- if (result.success && result.data) {
- // Transform BIS SDMX-JSON data to match indicatorData format
- let observations: Observation[] = [];
-
- try {
- // BIS returns SDMX-JSON format: data.data.dataSets[0].series["0:0"].observations
- const dataSets = result.data.data?.dataSets || [];
- if (dataSets.length > 0) {
- const dataSet = dataSets[0];
- const series = dataSet.series;
- const seriesKey = Object.keys(series || {})[0];
-
- if (seriesKey && series[seriesKey]) {
- const obsData = series[seriesKey].observations;
-
- // Try to get TIME_PERIOD dimension values from structure
- const timeDimension = result.data.structure?.dimensions?.observation?.find(
- (d: any) => d.id === 'TIME_PERIOD'
- );
- const timeValues = timeDimension?.values || [];
-
- // Convert SDMX observations to our format
- observations = Object.entries(obsData || {}).map(([index, value]: [string, any]) => {
- const timeIndex = parseInt(index);
- let dateValue: string;
-
- // Use TIME_PERIOD values if available, otherwise generate from reportingBegin
- if (timeValues.length > timeIndex) {
- dateValue = timeValues[timeIndex].id || timeValues[timeIndex].name;
- } else {
- // Fallback: generate date from reportingBegin
- const reportingBegin = dataSet.reportingBegin || '2020-01-01';
- const startDate = new Date(reportingBegin.split('T')[0]);
- const obsDate = new Date(startDate);
- obsDate.setDate(obsDate.getDate() + timeIndex);
- dateValue = obsDate.toISOString().split('T')[0];
- }
-
- const numValue = Array.isArray(value) ? parseFloat(value[0]) : parseFloat(value);
-
- return {
- date: dateValue,
- value: isNaN(numValue) ? 0 : numValue
- };
- });
- }
- }
- } catch (parseError) {
- console.error('Error parsing BIS data:', parseError);
- setStatus(`Error parsing BIS data: ${parseError}`);
- return;
- }
-
- if (observations.length === 0) {
- setStatus('No observations found in BIS data');
- return;
- }
-
- setIndicatorData({
- indicator: bisDataType,
- country: selectedCountry,
- transform: 'level',
- observations: observations,
- observation_count: observations.length,
- metadata: result.data
- });
- setStatus(`Loaded ${observations.length} observations from BIS`);
- } else {
- setStatus(`Error: ${result.error || 'Failed to fetch BIS data'}`);
- }
- } else {
- // Fetch from EconDB
- const result = await invoke('execute_python_script', {
- scriptName: 'econdb_data.py',
- args: ['indicator', selectedIndicator, selectedCountry, '', '', selectedTransform]
- }) as string;
-
- const data = JSON.parse(result);
-
- if (data.error) {
- setStatus(`Error: ${data.error}`);
- } else {
- setIndicatorData(data);
- setStatus(`Loaded ${data.observation_count} observations from EconDB`);
- }
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const [searchCountry, setSearchCountry] = useState('');
+ const [searchIndicator, setSearchIndicator] = useState('');
+
+ // Use custom hooks
+ const {
+ dataSource,
+ setDataSource,
+ selectedCountry,
+ setSelectedCountry,
+ selectedIndicator,
+ setSelectedIndicator,
+ data,
+ loading,
+ error,
+ fetchData,
+ stats,
+ wtoApiKey,
+ setWtoApiKey,
+ eiaApiKey,
+ setEiaApiKey,
+ showApiKeyInput,
+ setShowApiKeyInput,
+ apiKeySaving,
+ saveApiKey,
+ // Date range
+ dateRangePreset,
+ setDateRangePreset,
+ startDate,
+ endDate,
+ setStartDate,
+ setEndDate,
+ } = useEconomicsData();
+
+ const currentSourceConfig = DATA_SOURCES.find(s => s.id === dataSource)!;
+ const indicators = getIndicatorsForSource(dataSource);
+
+ const {
+ saveNotification,
+ setSaveNotification,
+ exportCSV,
+ exportImage,
+ } = useExport(data, currentSourceConfig, chartContainerRef);
+
+ // Get API key portal URL based on source
+ const getApiKeyPortalUrl = (source: DataSource): string => {
+ switch (source) {
+ case 'wto': return 'https://apiportal.wto.org/';
+ case 'eia': return 'https://www.eia.gov/opendata/register.php';
+ default: return '';
}
};
- const fetchProfile = async () => {
- setLoading(true);
- setStatus(`Fetching profile for ${profileCountry}...`);
-
- try {
- const result = await invoke('execute_python_script', {
- scriptName: 'econdb_data.py',
- args: ['profile', profileCountry, 'true']
- }) as string;
-
- const data = JSON.parse(result);
-
- if (data.error) {
- setStatus(`Error: ${data.error}`);
- } else {
- setProfileData(data);
- setStatus(`Profile loaded for ${profileCountry}`);
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
+ // Get current API key value
+ const getCurrentApiKey = (): string => {
+ switch (dataSource) {
+ case 'wto': return wtoApiKey;
+ case 'eia': return eiaApiKey;
+ default: return '';
}
};
- const exportData = () => {
- if (!indicatorData) return;
-
- const csv = [
- 'Date,Value',
- ...indicatorData.observations.map(obs => `${obs.date},${obs.value}`)
- ].join('\n');
-
- const blob = new Blob([csv], { type: 'text/csv' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `econdb_${selectedIndicator}_${selectedCountry}_${Date.now()}.csv`;
- a.click();
- URL.revokeObjectURL(url);
- setStatus('Data exported');
+ // Set current API key
+ const setCurrentApiKey = (value: string) => {
+ switch (dataSource) {
+ case 'wto': setWtoApiKey(value); break;
+ case 'eia': setEiaApiKey(value); break;
+ }
};
- const renderChart = (data: Observation[]) => {
- if (data.length === 0) return null;
-
- const w = 800;
- const h = 300;
- const ml = 70;
- const mr = 20;
- const mt = 20;
- const mb = 50;
- const pw = w - ml - mr;
- const ph = h - mt - mb;
-
- const values = data.map(d => d.value);
- const yMin = Math.min(...values) * 0.95;
- const yMax = Math.max(...values) * 1.05;
- const yRange = yMax - yMin;
-
- return (
- <svg width={w} height={h} style={{ backgroundColor: 'colors.panel', width: '100%', height: 'auto' }}>
- {/* Axes */}
- <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke="#404040" strokeWidth="1" />
- <line x1={ml} y1={h - mb} x2={w - mr} y2={h - mb} stroke="#404040" strokeWidth="1" />
-
- {/* Y-axis grid and labels */}
- {[0, 1, 2, 3, 4].map(i => {
- const val = yMin + (yRange * i) / 4;
- const y = h - mb - (ph * i) / 4;
- return (
- <g key={i}>
- <line x1={ml} y1={y} x2={w - mr} y2={y} stroke="#1a1a1a" strokeDasharray="2,2" />
- <text x={ml - 10} y={y + 4} textAnchor="end" fill="#737373" fontSize="10" fontFamily="monospace">
- {val.toFixed(2)}
- </text>
- </g>
- );
- })}
-
- {/* Line and points */}
- {data.map((obs, idx) => {
- const x = ml + (pw * idx) / (data.length - 1 || 1);
- const y = h - mb - (ph * ((obs.value - yMin) / yRange));
-
- return (
- <g key={idx}>
- <circle cx={x} cy={y} r="3" fill="#ea580c" />
- {idx < data.length - 1 && (
- <line
- x1={x}
- y1={y}
- x2={ml + (pw * (idx + 1)) / (data.length - 1 || 1)}
- y2={h - mb - (ph * ((data[idx + 1].value - yMin) / yRange))}
- stroke="#ea580c"
- strokeWidth="2"
- />
- )}
- </g>
- );
- })}
-
- {/* X-axis labels */}
- {data.map((obs, idx) => {
- if (idx % Math.max(1, Math.floor(data.length / 8)) !== 0 && idx !== data.length - 1) return null;
- const x = ml + (pw * idx) / (data.length - 1 || 1);
- return (
- <text key={idx} x={x} y={h - mb + 20} textAnchor="middle" fill="#737373" fontSize="9" fontFamily="monospace">
- {obs.date.substring(0, 10)}
- </text>
- );
- })}
- </svg>
- );
+ // Save current API key
+ const handleSaveApiKey = () => {
+ const keyName = currentSourceConfig.apiKeyName;
+ if (keyName) {
+ saveApiKey(keyName, getCurrentApiKey());
+ }
};
return (
- <div style={{ width: '100%', height: '100%', backgroundColor: 'colors.background', color: '#d4d4d4', fontFamily: 'Consolas, monospace', fontSize: '11px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <div
+ style={{
+ width: '100%',
+ height: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", monospace',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}
+ >
{/* Header */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid #404040', display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0 }}>
- <span style={{ color: '#ea580c', fontWeight: 'bold' }}>{t('title')} - {dataSource.toUpperCase()}</span>
- <span style={{ color: '#10b981', fontSize: '10px' }}>● {status}</span>
- <div style={{ flex: 1 }}></div>
+ <div
+ style={{
+ padding: '10px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <Globe size={18} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.WHITE }}>ECONOMIC DATA</span>
+
+ {/* Data source dropdown selector */}
+ <select
+ value={dataSource}
+ onChange={(e) => setDataSource(e.target.value as DataSource)}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: currentSourceConfig.color,
+ border: `1px solid ${currentSourceConfig.color}`,
+ borderRadius: '2px',
+ fontSize: '11px',
+ fontWeight: 600,
+ cursor: 'pointer',
+ outline: 'none',
+ minWidth: '220px',
+ }}
+ >
+ {DATA_SOURCES.map((source) => (
+ <option key={source.id} value={source.id} style={{ backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE }}>
+ {source.fullName} {source.requiresApiKey ? '(API Key)' : ''}
+ </option>
+ ))}
+ </select>
+
+ {/* API Key indicator for sources that require it */}
+ {currentSourceConfig.requiresApiKey && (
+ <button
+ onClick={() => setShowApiKeyInput(!showApiKeyInput)}
+ title={getCurrentApiKey() ? 'API Key configured - Click to edit' : `Configure ${currentSourceConfig.name} API Key`}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: getCurrentApiKey() ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
+ color: getCurrentApiKey() ? FINCEPT.GREEN : FINCEPT.RED,
+ border: `1px solid ${getCurrentApiKey() ? FINCEPT.GREEN : FINCEPT.RED}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <Key size={12} />
+ {getCurrentApiKey() ? 'API KEY SET' : 'SET API KEY'}
+ </button>
+ )}
- {/* Data Source Toggle */}
- <div style={{ display: 'flex', gap: '4px', marginRight: '12px' }}>
+ {/* Date Range Picker */}
+ <DateRangePicker
+ dateRangePreset={dateRangePreset}
+ setDateRangePreset={setDateRangePreset}
+ startDate={startDate}
+ endDate={endDate}
+ setStartDate={setStartDate}
+ setEndDate={setEndDate}
+ sourceColor={currentSourceConfig.color}
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px' }}>
<button
- onClick={() => setDataSource('econdb')}
+ onClick={fetchData}
+ disabled={loading}
style={{
- padding: '4px 8px',
- backgroundColor: dataSource === 'econdb' ? '#3b82f6' : '#2d2d2d',
- color: colors.text,
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
border: 'none',
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: 700,
cursor: 'pointer',
- fontSize: '9px',
- borderRadius: '2px'
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
}}
>
- EconDB
+ <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />
+ FETCH DATA
</button>
<button
- onClick={() => setDataSource('bis')}
+ onClick={exportCSV}
+ disabled={!data || data.data.length === 0}
style={{
- padding: '4px 8px',
- backgroundColor: dataSource === 'bis' ? '#3b82f6' : '#2d2d2d',
- color: colors.text,
- border: 'none',
+ padding: '6px 12px',
+ backgroundColor: 'transparent',
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: data && data.data.length > 0 ? 1 : 0.5,
+ }}
+ >
+ <Download size={12} />
+ CSV
+ </button>
+ <button
+ onClick={exportImage}
+ disabled={!data || data.data.length === 0}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: 'transparent',
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: 700,
cursor: 'pointer',
- fontSize: '9px',
- borderRadius: '2px'
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: data && data.data.length > 0 ? 1 : 0.5,
}}
>
- BIS
+ <Image size={12} />
+ IMAGE
</button>
</div>
-
- <button onClick={() => setView('indicator')} style={{ padding: '4px 10px', backgroundColor: view === 'indicator' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
- <BarChart3 size={10} style={{ display: 'inline', marginRight: '4px' }} />{t('header.indicators')}
- </button>
- <button onClick={() => setView('profile')} style={{ padding: '4px 10px', backgroundColor: view === 'profile' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
- <PieChart size={10} style={{ display: 'inline', marginRight: '4px' }} />{t('header.overview')}
- </button>
- <button onClick={() => setView('countries')} style={{ padding: '4px 10px', backgroundColor: view === 'countries' ? '#ea580c' : '#2d2d2d', color: 'colors.text', border: 'none', cursor: 'pointer', fontSize: '9px' }}>
- <Globe size={10} style={{ display: 'inline', marginRight: '4px' }} />{t('header.countries')}
- </button>
</div>
- {/* Main Content */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Panel - Controls */}
- <div style={{ width: '300px', borderRight: '1px solid #404040', display: 'flex', flexDirection: 'column', backgroundColor: 'colors.panel', overflowY: 'auto' }}>
- {view === 'indicator' && (
- <div style={{ padding: '12px' }}>
- {dataSource === 'bis' ? (
- <>
- {/* BIS-specific controls */}
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>BIS DATA TYPE</div>
- <select value={bisDataType} onChange={(e) => setBisDataType(e.target.value as any)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- <optgroup label="Interest Rates & FX">
- <option value="policy_rates">Central Bank Policy Rates (Daily)</option>
- <option value="effective_exchange">Effective Exchange Rates (Monthly)</option>
- </optgroup>
- <optgroup label="Property & Credit">
- <option value="property_prices">Property Prices (Quarterly)</option>
- <option value="total_credit">Total Credit (Quarterly)</option>
- <option value="credit_gap">Credit-to-GDP Gaps (Quarterly)</option>
- <option value="debt_service">Debt Service Ratios (Quarterly)</option>
- </optgroup>
- <optgroup label="Other Indicators">
- <option value="consumer_prices">Consumer Prices (Monthly)</option>
- <option value="cb_assets">Central Bank Assets (Monthly)</option>
- </optgroup>
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY (G20 + Major Economies)</div>
- <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- {bisCountries.map(c => (
- <option key={c.code} value={c.code}>{c.name}</option>
- ))}
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>START DATE</div>
- <input
- type="date"
- value={bisStartDate}
- onChange={(e) => setBisStartDate(e.target.value)}
- style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}
- />
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>END DATE</div>
- <input
- type="date"
- value={bisEndDate}
- onChange={(e) => setBisEndDate(e.target.value)}
- style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}
- />
-
- <div style={{ padding: '8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', fontSize: '9px', marginBottom: '12px' }}>
- <div style={{ color: '#3b82f6', marginBottom: '4px' }}>ℹ️ BIS Data Info</div>
- <div style={{ color: '#737373', lineHeight: '1.4' }}>
- Limit date range to avoid slow loading. Recommended: 1-2 years max.
- </div>
- </div>
- </>
- ) : (
- <>
- {/* EconDB controls */}
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>INDICATOR</div>
- <select value={selectedIndicator} onChange={(e) => setSelectedIndicator(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- {indicators.map(ind => (
- <option key={ind.code} value={ind.code}>{ind.name}</option>
- ))}
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>COUNTRY</div>
- <select value={selectedCountry} onChange={(e) => setSelectedCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '12px', fontSize: '10px' }}>
- {countries.map(c => (
- <option key={c.code} value={c.code}>{c.name}</option>
- ))}
- </select>
-
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>TRANSFORM</div>
- <select value={selectedTransform} onChange={(e) => setSelectedTransform(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>
- {transforms.map(t => (
- <option key={t.code} value={t.code}>{t.name}</option>
- ))}
- </select>
- </>
- )}
-
- <button onClick={fetchIndicator} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: 'colors.text', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px', marginBottom: '8px' }}>
- {loading ? 'Loading...' : 'FETCH DATA'}
- </button>
-
- <button onClick={exportData} disabled={!indicatorData} style={{ width: '100%', padding: '8px', backgroundColor: '#2d2d2d', color: '#d4d4d4', border: '1px solid #404040', cursor: !indicatorData ? 'not-allowed' : 'pointer', fontSize: '10px' }}>
- <Download size={10} style={{ display: 'inline', marginRight: '4px' }} />EXPORT CSV
- </button>
-
- {indicatorData && (
- <div style={{ marginTop: '16px', padding: '8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', fontSize: '9px' }}>
- <div style={{ color: '#fbbf24', marginBottom: '4px' }}>METADATA</div>
- <div style={{ color: '#737373' }}>Country: {indicatorData.country}</div>
- <div style={{ color: '#737373' }}>Indicator: {indicatorData.indicator}</div>
- <div style={{ color: '#737373' }}>Transform: {indicatorData.transform}</div>
- <div style={{ color: '#737373' }}>Points: {indicatorData.observation_count}</div>
- </div>
- )}
- </div>
- )}
-
- {view === 'profile' && (
- <div style={{ padding: '12px' }}>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>SELECT COUNTRY</div>
- <select value={profileCountry} onChange={(e) => setProfileCountry(e.target.value)} style={{ width: '100%', padding: '6px', backgroundColor: '#1a1a1a', color: '#d4d4d4', border: '1px solid #404040', marginBottom: '16px', fontSize: '10px' }}>
- {countries.map(c => (
- <option key={c.code} value={c.code}>{c.name}</option>
- ))}
- </select>
-
- <button onClick={fetchProfile} disabled={loading} style={{ width: '100%', padding: '8px', backgroundColor: '#ea580c', color: 'colors.text', border: 'none', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '10px' }}>
- {loading ? 'Loading...' : 'LOAD PROFILE'}
- </button>
- </div>
- )}
-
- {view === 'countries' && (
- <div style={{ padding: '12px' }}>
- <div style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px' }}>AVAILABLE COUNTRIES ({countries.length})</div>
- {countries.map(c => (
- <div key={c.code} style={{ padding: '6px 8px', backgroundColor: '#1a1a1a', border: '1px solid #404040', marginBottom: '4px', fontSize: '10px' }}>
- <span style={{ color: '#fbbf24' }}>{c.code}</span> - {c.name}
- </div>
- ))}
+ {/* Save Success Notification */}
+ {saveNotification?.show && (
+ <div
+ style={{
+ padding: '12px 16px',
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ borderBottom: `1px solid ${FINCEPT.GREEN}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '12px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <CheckCircle size={18} color={FINCEPT.GREEN} />
+ <div>
+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>
+ {saveNotification.type === 'image' ? 'Image' : 'CSV'} saved successfully!
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginTop: '2px' }}>
+ {saveNotification.path}
+ </div>
</div>
- )}
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <button
+ onClick={async () => {
+ try {
+ await revealItemInDir(saveNotification.path);
+ } catch (err) {
+ console.error('Failed to open path:', err);
+ }
+ }}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.GREEN,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ >
+ <FolderOpen size={12} />
+ OPEN FILE
+ </button>
+ <button
+ onClick={() => setSaveNotification(null)}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: 'transparent',
+ color: FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ }}
+ >
+ DISMISS
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* API Key Configuration Panel */}
+ {showApiKeyInput && currentSourceConfig.requiresApiKey && (
+ <ApiKeyPanel
+ apiKey={getCurrentApiKey()}
+ setApiKey={setCurrentApiKey}
+ onSave={handleSaveApiKey}
+ onClose={() => setShowApiKeyInput(false)}
+ saving={apiKeySaving}
+ sourceName={currentSourceConfig.name}
+ sourceColor={currentSourceConfig.color}
+ portalUrl={getApiKeyPortalUrl(dataSource)}
+ />
+ )}
+
+ {/* Main content */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel - Selectors */}
+ <div
+ style={{
+ width: '280px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ }}
+ >
+ {/* Country selector */}
+ <CountrySelector
+ selectedCountry={selectedCountry}
+ setSelectedCountry={setSelectedCountry}
+ searchCountry={searchCountry}
+ setSearchCountry={setSearchCountry}
+ />
+
+ {/* Indicator selector */}
+ <IndicatorSelector
+ indicators={indicators}
+ selectedIndicator={selectedIndicator}
+ setSelectedIndicator={setSelectedIndicator}
+ searchIndicator={searchIndicator}
+ setSearchIndicator={setSearchIndicator}
+ sourceName={currentSourceConfig.name}
+ sourceColor={currentSourceConfig.color}
+ />
</div>
- {/* Right Panel - Data Display */}
+ {/* Right Panel - Chart and Data */}
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- <div style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>
- {view === 'indicator' && indicatorData && (
+ {/* Stats bar */}
+ {stats && (
+ <StatsBar
+ stats={stats}
+ sourceColor={currentSourceConfig.color}
+ formatValue={formatValue}
+ />
+ )}
+
+ {/* Chart area */}
+ <div style={{ flex: 1, padding: '16px', overflowY: 'auto' }}>
+ {loading ? (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
+ <RefreshCw size={32} className="animate-spin" style={{ color: currentSourceConfig.color, marginBottom: '16px' }} />
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>Loading data from {currentSourceConfig.fullName}...</div>
+ </div>
+ ) : error ? (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
+ <AlertCircle size={32} style={{ color: FINCEPT.RED, marginBottom: '16px' }} />
+ <div style={{ fontSize: '12px', color: FINCEPT.RED, marginBottom: '8px' }}>Error loading data</div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '400px' }}>{error}</div>
+ <button
+ onClick={fetchData}
+ style={{
+ marginTop: '16px',
+ padding: '8px 16px',
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ }}
+ >
+ TRY AGAIN
+ </button>
+ </div>
+ ) : data && data.data.length > 0 ? (
<>
+ {/* Title */}
<div style={{ marginBottom: '16px' }}>
- <div style={{ color: '#ea580c', fontSize: '12px', marginBottom: '8px' }}>
- {indicatorData.metadata.description || indicatorData.indicator}
- </div>
- <div style={{ color: '#737373', fontSize: '10px' }}>
- {indicatorData.country} • {indicatorData.observation_count} observations
+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.WHITE }}>{data.metadata?.indicator_name || data.indicator}</div>
+ <div style={{ fontSize: '11px', color: FINCEPT.GRAY }}>
+ {data.metadata?.country_name || data.country} • Source: <span style={{ color: currentSourceConfig.color }}>{currentSourceConfig.fullName}</span>
</div>
</div>
- {renderChart(indicatorData.observations)}
-
- <div style={{ marginTop: '24px' }}>
- <div style={{ color: '#ea580c', fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
- <div style={{ maxHeight: '400px', overflowY: 'auto', border: '1px solid #404040', backgroundColor: 'colors.panel' }}>
- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
- <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a' }}>
- <tr>
- <th style={{ padding: '8px', textAlign: 'left', color: '#ea580c', borderBottom: '2px solid #404040' }}>Date</th>
- <th style={{ padding: '8px', textAlign: 'right', color: '#ea580c', borderBottom: '2px solid #404040' }}>Value</th>
- </tr>
- </thead>
- <tbody>
- {indicatorData.observations.slice().reverse().map((obs, idx) => (
- <tr key={idx} style={{ borderBottom: '1px solid #1a1a1a' }}>
- <td style={{ padding: '6px 8px', color: '#d4d4d4' }}>{obs.date}</td>
- <td style={{ padding: '6px 8px', textAlign: 'right', color: '#a3a3a3' }}>{obs.value.toFixed(4)}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
+ {/* Chart */}
+ <div ref={chartContainerRef} style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', padding: '16px', marginBottom: '16px' }}>
+ <EconomicsChart
+ data={data.data}
+ sourceColor={currentSourceConfig.color}
+ formatValue={formatValue}
+ />
</div>
- </>
- )}
- {view === 'profile' && profileData && (
- <div>
- <div style={{ color: '#ea580c', fontSize: '12px', marginBottom: '16px' }}>
- ECONOMIC PROFILE - {profileData.country}
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>
- {Object.entries(profileData.indicators).map(([name, data]) => (
- <div key={name} style={{ padding: '12px', backgroundColor: 'colors.panel', border: '1px solid #404040' }}>
- <div style={{ color: '#fbbf24', fontSize: '10px', marginBottom: '8px' }}>{name}</div>
- <div style={{ color: 'colors.text', fontSize: '20px', fontWeight: 'bold', marginBottom: '4px' }}>
- {typeof data.value === 'number' ? data.value.toFixed(4) : data.value}
- </div>
- <div style={{ color: '#737373', fontSize: '9px' }}>{data.date}</div>
- </div>
- ))}
+ {/* Data table */}
+ <DataTable
+ data={data.data}
+ sourceColor={currentSourceConfig.color}
+ formatValue={formatValue}
+ />
+ </>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
+ <Database size={48} style={{ color: FINCEPT.MUTED, marginBottom: '16px', opacity: 0.5 }} />
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE, marginBottom: '8px' }}>Select data and click FETCH DATA</div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, textAlign: 'center', maxWidth: '300px' }}>
+ Choose a country and indicator from the left panel, then click the FETCH DATA button to load economic data from {currentSourceConfig.fullName}.
</div>
</div>
)}
-
- {!indicatorData && !profileData && view !== 'countries' && (
- <div style={{ textAlign: 'center', color: '#737373', paddingTop: '80px' }}>
- <TrendingUp size={48} style={{ margin: '0 auto 16px', opacity: 0.3 }} />
- <div>Select parameters and fetch data to begin</div>
- </div>
- )}
</div>
</div>
</div>
- <TabFooter
- tabName="ECONOMIC INDICATORS"
- leftInfo={[
- { label: `Source: ${dataSource.toUpperCase()}`, color: colors.textMuted },
- { label: `View: ${view.toUpperCase()}`, color: colors.textMuted },
- ...(indicatorData ? [{ label: `Data points: ${indicatorData.observations.length}`, color: colors.textMuted }] : [])
- ]}
- statusInfo={status}
- backgroundColor={colors.panel}
- borderColor={colors.textMuted}
- />
+ {/* Status bar */}
+ <div
+ style={{
+ padding: '6px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ fontSize: '9px',
+ }}
+ >
+ <div style={{ display: 'flex', gap: '16px', color: FINCEPT.WHITE, flexWrap: 'wrap' }}>
+ <span title={currentSourceConfig.fullName}><span style={{ color: FINCEPT.GRAY }}>SOURCE:</span> <span style={{ color: currentSourceConfig.color }}>{currentSourceConfig.name}</span></span>
+ <span><span style={{ color: FINCEPT.GRAY }}>COUNTRY:</span> {selectedCountry}</span>
+ <span><span style={{ color: FINCEPT.GRAY }}>INDICATOR:</span> {selectedIndicator}</span>
+ {data && <span><span style={{ color: FINCEPT.GRAY }}>POINTS:</span> {data.data.length}</span>}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: loading ? FINCEPT.YELLOW : error ? FINCEPT.RED : FINCEPT.GREEN }} />
+ <span style={{ color: loading ? FINCEPT.YELLOW : error ? FINCEPT.RED : FINCEPT.GREEN }}>
+ {loading ? 'Loading...' : error ? 'Error' : 'Ready'}
+ </span>
+ </div>
+ </div>
</div>
);
}
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/ApiKeyPanel.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/ApiKeyPanel.tsx
new file mode 100644
index 000000000..a1937c40d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/ApiKeyPanel.tsx
@@ -0,0 +1,109 @@
+// ApiKeyPanel Component - Configure API keys for data sources
+
+import React from 'react';
+import { Key, RefreshCw, Settings } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface ApiKeyPanelProps {
+ apiKey: string;
+ setApiKey: (key: string) => void;
+ onSave: () => void;
+ onClose: () => void;
+ saving: boolean;
+ sourceName: string;
+ sourceColor: string;
+ portalUrl: string;
+}
+
+export function ApiKeyPanel({
+ apiKey,
+ setApiKey,
+ onSave,
+ onClose,
+ saving,
+ sourceName,
+ sourceColor,
+ portalUrl,
+}: ApiKeyPanelProps) {
+ return (
+ <div
+ style={{
+ padding: '12px 16px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ }}
+ >
+ <Key size={16} color={sourceColor} />
+ <div style={{ flex: 1 }}>
+ <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '4px' }}>
+ {sourceName} API KEY
+ </div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>
+ Get your API key from <span style={{ color: sourceColor }}>{portalUrl}</span>
+ </div>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <input
+ type="password"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder={`Enter your ${sourceName} API Key...`}
+ style={{
+ flex: 1,
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none',
+ }}
+ onFocus={(e) => e.currentTarget.style.borderColor = sourceColor}
+ onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}
+ />
+ <button
+ onClick={onSave}
+ disabled={saving || !apiKey.trim()}
+ style={{
+ padding: '8px 16px',
+ backgroundColor: sourceColor,
+ color: FINCEPT.WHITE,
+ border: 'none',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: saving || !apiKey.trim() ? 'not-allowed' : 'pointer',
+ opacity: saving || !apiKey.trim() ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ >
+ {saving ? <RefreshCw size={12} className="animate-spin" /> : <Settings size={12} />}
+ SAVE KEY
+ </button>
+ <button
+ onClick={onClose}
+ style={{
+ padding: '8px 12px',
+ backgroundColor: 'transparent',
+ color: FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ }}
+ >
+ CLOSE
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default ApiKeyPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/CountrySelector.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/CountrySelector.tsx
new file mode 100644
index 000000000..4ab65e45c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/CountrySelector.tsx
@@ -0,0 +1,91 @@
+// CountrySelector Component - Select country for data fetching
+
+import React from 'react';
+import { Search } from 'lucide-react';
+import { FINCEPT, COUNTRIES } from '../constants';
+
+interface CountrySelectorProps {
+ selectedCountry: string;
+ setSelectedCountry: (code: string) => void;
+ searchCountry: string;
+ setSearchCountry: (search: string) => void;
+}
+
+export function CountrySelector({
+ selectedCountry,
+ setSelectedCountry,
+ searchCountry,
+ setSearchCountry,
+}: CountrySelectorProps) {
+ const filteredCountries = COUNTRIES.filter(
+ (c) =>
+ c.name.toLowerCase().includes(searchCountry.toLowerCase()) ||
+ c.code.toLowerCase().includes(searchCountry.toLowerCase())
+ );
+
+ return (
+ <div style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <div
+ style={{
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ }}
+ >
+ <span>COUNTRY</span>
+ <span style={{ color: FINCEPT.MUTED }}>{COUNTRIES.length}</span>
+ </div>
+ <div style={{ padding: '8px' }}>
+ <div style={{ position: 'relative', marginBottom: '8px' }}>
+ <Search size={12} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.MUTED }} />
+ <input
+ type="text"
+ placeholder="Search countries..."
+ value={searchCountry}
+ onChange={(e) => setSearchCountry(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px 8px 30px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: 'inherit',
+ outline: 'none',
+ }}
+ />
+ </div>
+ <div style={{ maxHeight: '180px', overflowY: 'auto' }}>
+ {filteredCountries.map((country) => (
+ <div
+ key={country.code}
+ onClick={() => setSelectedCountry(country.code)}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: selectedCountry === country.code ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: selectedCountry === country.code ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ cursor: 'pointer',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ }}
+ >
+ <span style={{ fontSize: '10px', color: selectedCountry === country.code ? FINCEPT.WHITE : FINCEPT.GRAY }}>
+ {country.name}
+ </span>
+ <span style={{ fontSize: '9px', color: FINCEPT.YELLOW, fontWeight: 700 }}>{country.code}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default CountrySelector;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsx
new file mode 100644
index 000000000..5491a6189
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/DataTable.tsx
@@ -0,0 +1,55 @@
+// DataTable Component - Display economic data in table format
+
+import React from 'react';
+import { ChevronUp, ChevronDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { DataPoint } from '../types';
+
+interface DataTableProps {
+ data: DataPoint[];
+ sourceColor: string;
+ formatValue: (val: number) => string;
+}
+
+export function DataTable({ data, sourceColor, formatValue }: DataTableProps) {
+ return (
+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', overflow: 'hidden' }}>
+ <div style={{ padding: '10px 12px', backgroundColor: FINCEPT.HEADER_BG, fontSize: '9px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>
+ DATA TABLE
+ </div>
+ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
+ <table style={{ width: '100%', borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>DATE</th>
+ <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>VALUE</th>
+ <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: '9px', fontWeight: 700, color: FINCEPT.ORANGE, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>CHANGE</th>
+ </tr>
+ </thead>
+ <tbody>
+ {[...data].reverse().map((d, i, arr) => {
+ const prev = arr[i + 1];
+ const change = prev ? ((d.value - prev.value) / Math.abs(prev.value)) * 100 : 0;
+ return (
+ <tr key={d.date} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <td style={{ padding: '8px 12px', fontSize: '11px', color: FINCEPT.WHITE }}>{d.date}</td>
+ <td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '11px', color: sourceColor, fontWeight: 600 }}>{formatValue(d.value)}</td>
+ <td style={{ padding: '8px 12px', textAlign: 'right', fontSize: '10px', color: change >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {prev && (
+ <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>
+ {change >= 0 ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ {Math.abs(change).toFixed(2)}%
+ </span>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
+
+export default DataTable;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsx
new file mode 100644
index 000000000..63554c669
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/DateRangePicker.tsx
@@ -0,0 +1,116 @@
+// DateRangePicker Component - Date range selection for economic data
+
+import React from 'react';
+import { Calendar } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { DateRangePreset } from '../hooks/useEconomicsData';
+
+interface DateRangePickerProps {
+ dateRangePreset: DateRangePreset;
+ setDateRangePreset: (preset: DateRangePreset) => void;
+ startDate: string;
+ endDate: string;
+ setStartDate: (date: string) => void;
+ setEndDate: (date: string) => void;
+ sourceColor: string;
+}
+
+const PRESETS: { value: DateRangePreset; label: string }[] = [
+ { value: '1M', label: '1M' },
+ { value: '3M', label: '3M' },
+ { value: '6M', label: '6M' },
+ { value: '1Y', label: '1Y' },
+ { value: '2Y', label: '2Y' },
+ { value: '5Y', label: '5Y' },
+ { value: '10Y', label: '10Y' },
+ { value: 'ALL', label: 'ALL' },
+];
+
+export function DateRangePicker({
+ dateRangePreset,
+ setDateRangePreset,
+ startDate,
+ endDate,
+ setStartDate,
+ setEndDate,
+ sourceColor,
+}: DateRangePickerProps) {
+ return (
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRadius: '2px',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ }}
+ >
+ <Calendar size={14} color={FINCEPT.GRAY} />
+
+ {/* Preset buttons */}
+ <div style={{ display: 'flex', gap: '2px' }}>
+ {PRESETS.map((preset) => (
+ <button
+ key={preset.value}
+ onClick={() => setDateRangePreset(preset.value)}
+ style={{
+ padding: '3px 6px',
+ backgroundColor: dateRangePreset === preset.value ? sourceColor : 'transparent',
+ color: dateRangePreset === preset.value ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${dateRangePreset === preset.value ? sourceColor : FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ }}
+ >
+ {preset.label}
+ </button>
+ ))}
+ </div>
+
+ {/* Separator */}
+ <div style={{ width: '1px', height: '16px', backgroundColor: FINCEPT.BORDER }} />
+
+ {/* Custom date inputs */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <input
+ type="date"
+ value={startDate}
+ onChange={(e) => setStartDate(e.target.value)}
+ style={{
+ padding: '3px 6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontFamily: 'inherit',
+ cursor: 'pointer',
+ }}
+ />
+ <span style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>to</span>
+ <input
+ type="date"
+ value={endDate}
+ onChange={(e) => setEndDate(e.target.value)}
+ style={{
+ padding: '3px 6px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontFamily: 'inherit',
+ cursor: 'pointer',
+ }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export default DateRangePicker;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsx
new file mode 100644
index 000000000..85e45c61d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/EconomicsChart.tsx
@@ -0,0 +1,219 @@
+// EconomicsChart Component - SVG Chart for Economic Data
+
+import React from 'react';
+import { FINCEPT, CHART_WIDTH, CHART_HEIGHT } from '../constants';
+import type { DataPoint } from '../types';
+
+interface EconomicsChartProps {
+ data: DataPoint[];
+ sourceColor: string;
+ formatValue: (val: number) => string;
+}
+
+// Smart date label formatter - creates unique, readable labels
+const formatSmartLabel = (date: string, index: number, allDates: string[], totalLabels: number): string => {
+ const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+ // Parse date components safely
+ const year = date.substring(0, 4) || '';
+ const month = date.length >= 7 ? date.substring(5, 7) : '';
+ const day = date.length >= 10 ? date.substring(8, 10) : '';
+
+ const monthIdx = month ? parseInt(month, 10) - 1 : -1;
+ const monthName = monthIdx >= 0 && monthIdx < 12 ? monthNames[monthIdx] : '';
+ const shortYear = year.substring(2, 4);
+
+ // Determine what level of detail we need based on data span
+ const firstDate = allDates[0] || '';
+ const lastDate = allDates[allDates.length - 1] || '';
+ const firstYear = firstDate.substring(0, 4);
+ const lastYear = lastDate.substring(0, 4);
+ const sameYear = firstYear === lastYear;
+
+ // Count unique values at each level
+ const uniqueYears = new Set(allDates.map(d => d.substring(0, 4))).size;
+ const uniqueMonths = new Set(allDates.map(d => d.substring(0, 7))).size;
+
+ // If only one year of data, don't repeat the year
+ if (sameYear && day && monthName) {
+ // Daily data within same year: "15 Jan"
+ return `${parseInt(day)} ${monthName}`;
+ }
+
+ if (uniqueYears <= 2 && monthName && day) {
+ // Daily data spanning ~2 years: "15 Jan'25"
+ return `${parseInt(day)} ${monthName}'${shortYear}`;
+ }
+
+ if (uniqueMonths > uniqueYears * 2 && monthName) {
+ // Monthly or more frequent data: "Jan'25"
+ return `${monthName}'${shortYear}`;
+ }
+
+ // Annual or sparse data: just show year
+ return year;
+};
+
+// Filter data to only show points where value changed (for constant data like Fed rates)
+const filterSignificantPoints = (data: DataPoint[]): DataPoint[] => {
+ if (data.length <= 2) return data;
+
+ const result: DataPoint[] = [];
+
+ // Always include first point
+ result.push(data[0]);
+
+ for (let i = 1; i < data.length - 1; i++) {
+ const prev = data[i - 1].value;
+ const curr = data[i].value;
+ const next = data[i + 1].value;
+
+ // Include point if value changed from previous OR will change to next
+ // This keeps the "step" pattern for rate changes
+ if (curr !== prev || curr !== next) {
+ result.push(data[i]);
+ }
+ }
+
+ // Always include last point
+ result.push(data[data.length - 1]);
+
+ return result;
+};
+
+// Check if data has many repeated values (like Fed rates)
+const hasSignificantRepetition = (data: DataPoint[]): boolean => {
+ if (data.length < 10) return false;
+
+ let sameCount = 0;
+ for (let i = 1; i < data.length; i++) {
+ if (data[i].value === data[i - 1].value) {
+ sameCount++;
+ }
+ }
+
+ // If more than 50% of consecutive points are the same, filter them
+ return sameCount / data.length > 0.5;
+};
+
+// Generate evenly distributed label indices with no duplicates
+const generateLabelIndices = (
+ data: DataPoint[],
+ maxLabels: number
+): number[] => {
+ if (data.length === 0) return [];
+ if (data.length <= maxLabels) {
+ return data.map((_, i) => i);
+ }
+
+ const indices: number[] = [];
+ const step = (data.length - 1) / (maxLabels - 1);
+
+ for (let i = 0; i < maxLabels; i++) {
+ const idx = Math.round(i * step);
+ if (indices.length === 0 || indices[indices.length - 1] !== idx) {
+ indices.push(idx);
+ }
+ }
+
+ // Ensure last point is included
+ if (indices[indices.length - 1] !== data.length - 1) {
+ indices.push(data.length - 1);
+ }
+
+ return indices;
+};
+
+export function EconomicsChart({ data: rawData, sourceColor, formatValue }: EconomicsChartProps) {
+ if (!rawData || rawData.length === 0) return null;
+
+ // Filter out redundant points if data has many repeated values (like Fed rates)
+ const data = hasSignificantRepetition(rawData) ? filterSignificantPoints(rawData) : rawData;
+
+ const width = CHART_WIDTH;
+ const height = CHART_HEIGHT;
+ const padding = { top: 30, right: 40, bottom: 50, left: 80 };
+ const chartWidth = width - padding.left - padding.right;
+ const chartHeight = height - padding.top - padding.bottom;
+
+ const values = data.map((d) => d.value);
+ const minVal = Math.min(...values);
+ const maxVal = Math.max(...values);
+ const range = maxVal - minVal || 1;
+
+ const points = data.map((d, i) => {
+ const x = padding.left + (i / (data.length - 1 || 1)) * chartWidth;
+ const y = padding.top + chartHeight - ((d.value - minVal) / range) * chartHeight;
+ return { x, y, data: d };
+ });
+
+ const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' ');
+ const areaD = `${pathD} L ${points[points.length - 1].x} ${padding.top + chartHeight} L ${padding.left} ${padding.top + chartHeight} Z`;
+
+ // Get all dates for label formatting
+ const allDates = data.map(d => d.date);
+
+ // Calculate how many labels can fit (estimate ~70px per label for horizontal)
+ const maxLabels = Math.max(2, Math.min(15, Math.floor(chartWidth / 70)));
+
+ // Generate evenly distributed label indices
+ const labelIndices = generateLabelIndices(data, maxLabels);
+
+ return (
+ <svg width={width} height={height} style={{ display: 'block', margin: '0 auto', maxWidth: '100%' }}>
+ <rect width={width} height={height} fill={FINCEPT.PANEL_BG} />
+
+ {/* Horizontal Grid lines */}
+ {[0, 1, 2, 3, 4, 5].map((i) => {
+ const y = padding.top + (chartHeight * i) / 5;
+ const val = maxVal - (range * i) / 5;
+ return (
+ <g key={i}>
+ <line x1={padding.left} y1={y} x2={width - padding.right} y2={y} stroke={FINCEPT.BORDER} strokeDasharray="4,4" />
+ <text x={padding.left - 12} y={y + 4} textAnchor="end" fill={FINCEPT.WHITE} fontSize="11" fontFamily="monospace">
+ {formatValue(val)}
+ </text>
+ </g>
+ );
+ })}
+
+ {/* Vertical grid lines */}
+ {labelIndices.map((idx) => {
+ const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;
+ return (
+ <line key={`vgrid-${idx}`} x1={x} y1={padding.top} x2={x} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeDasharray="2,4" strokeOpacity="0.5" />
+ );
+ })}
+
+ {/* Area fill */}
+ <path d={areaD} fill={`${sourceColor}25`} />
+
+ {/* Line */}
+ <path d={pathD} fill="none" stroke={sourceColor} strokeWidth="2.5" />
+
+
+ {/* X-axis labels - horizontal only */}
+ {labelIndices.map((idx) => {
+ const d = data[idx];
+ const x = padding.left + (idx / (data.length - 1 || 1)) * chartWidth;
+ const label = formatSmartLabel(d.date, idx, allDates, labelIndices.length);
+ return (
+ <text key={`xlabel-${idx}`} x={x} y={height - 15} textAnchor="middle" fill={FINCEPT.WHITE} fontSize="10" fontFamily="monospace">
+ {label}
+ </text>
+ );
+ })}
+
+ {/* Data points */}
+ {points.map((p, i) => (
+ <circle key={i} cx={p.x} cy={p.y} r={data.length > 30 ? 2 : 3} fill={sourceColor} />
+ ))}
+
+ {/* Axis lines */}
+ <line x1={padding.left} y1={padding.top + chartHeight} x2={width - padding.right} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeWidth="1" />
+ <line x1={padding.left} y1={padding.top} x2={padding.left} y2={padding.top + chartHeight} stroke={FINCEPT.BORDER} strokeWidth="1" />
+ </svg>
+ );
+}
+
+export default EconomicsChart;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/IndicatorSelector.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/IndicatorSelector.tsx
new file mode 100644
index 000000000..4d41ef97c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/IndicatorSelector.tsx
@@ -0,0 +1,98 @@
+// IndicatorSelector Component - Select indicator for data fetching
+
+import React from 'react';
+import { Search } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { Indicator } from '../types';
+
+interface IndicatorSelectorProps {
+ indicators: Indicator[];
+ selectedIndicator: string;
+ setSelectedIndicator: (id: string) => void;
+ searchIndicator: string;
+ setSearchIndicator: (search: string) => void;
+ sourceName: string;
+ sourceColor: string;
+}
+
+export function IndicatorSelector({
+ indicators,
+ selectedIndicator,
+ setSelectedIndicator,
+ searchIndicator,
+ setSearchIndicator,
+ sourceName,
+ sourceColor,
+}: IndicatorSelectorProps) {
+ const filteredIndicators = indicators.filter(
+ (i) =>
+ i.name.toLowerCase().includes(searchIndicator.toLowerCase()) ||
+ i.id.toLowerCase().includes(searchIndicator.toLowerCase()) ||
+ i.category.toLowerCase().includes(searchIndicator.toLowerCase())
+ );
+
+ return (
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ <div
+ style={{
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ color: FINCEPT.WHITE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ }}
+ >
+ <span>INDICATORS ({sourceName})</span>
+ <span style={{ color: FINCEPT.MUTED }}>{indicators.length}</span>
+ </div>
+ <div style={{ padding: '8px', flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ <div style={{ position: 'relative', marginBottom: '8px' }}>
+ <Search size={12} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.MUTED }} />
+ <input
+ type="text"
+ placeholder="Search indicators..."
+ value={searchIndicator}
+ onChange={(e) => setSearchIndicator(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px 10px 8px 30px',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontFamily: 'inherit',
+ outline: 'none',
+ }}
+ />
+ </div>
+ <div style={{ flex: 1, overflowY: 'auto' }}>
+ {filteredIndicators.map((indicator) => (
+ <div
+ key={indicator.id}
+ onClick={() => setSelectedIndicator(indicator.id)}
+ style={{
+ padding: '6px 10px',
+ backgroundColor: selectedIndicator === indicator.id ? `${sourceColor}15` : 'transparent',
+ borderLeft: selectedIndicator === indicator.id ? `2px solid ${sourceColor}` : '2px solid transparent',
+ cursor: 'pointer',
+ }}
+ >
+ <div style={{ fontSize: '10px', color: selectedIndicator === indicator.id ? FINCEPT.WHITE : FINCEPT.GRAY, marginBottom: '2px' }}>
+ {indicator.name}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>
+ {indicator.category} • {indicator.id}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default IndicatorSelector;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsx b/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsx
new file mode 100644
index 000000000..8d37676e5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/StatsBar.tsx
@@ -0,0 +1,57 @@
+// StatsBar Component - Display statistics for economic data
+
+import React from 'react';
+import { TrendingUp, TrendingDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { ChartStats } from '../types';
+
+interface StatsBarProps {
+ stats: ChartStats;
+ sourceColor: string;
+ formatValue: (val: number) => string;
+}
+
+export function StatsBar({ stats, sourceColor, formatValue }: StatsBarProps) {
+ return (
+ <div
+ style={{
+ padding: '12px 16px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ gap: '24px',
+ flexWrap: 'wrap',
+ }}
+ >
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>LATEST VALUE</div>
+ <div style={{ fontSize: '18px', fontWeight: 700, color: sourceColor }}>{formatValue(stats.latest)}</div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>CHANGE</div>
+ <div style={{ fontSize: '14px', fontWeight: 700, color: stats.change >= 0 ? FINCEPT.GREEN : FINCEPT.RED, display: 'flex', alignItems: 'center', gap: '4px' }}>
+ {stats.change >= 0 ? <TrendingUp size={14} /> : <TrendingDown size={14} />}
+ {stats.change >= 0 ? '+' : ''}{stats.change.toFixed(2)}%
+ </div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>MIN</div>
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.min)}</div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>MAX</div>
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.max)}</div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>AVERAGE</div>
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{formatValue(stats.avg)}</div>
+ </div>
+ <div>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>DATA POINTS</div>
+ <div style={{ fontSize: '12px', color: FINCEPT.WHITE }}>{stats.count}</div>
+ </div>
+ </div>
+ );
+}
+
+export default StatsBar;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts b/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts
new file mode 100644
index 000000000..503b93c2b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/components/index.ts
@@ -0,0 +1,9 @@
+// Economics Tab Components
+
+export { EconomicsChart } from './EconomicsChart';
+export { StatsBar } from './StatsBar';
+export { DataTable } from './DataTable';
+export { ApiKeyPanel } from './ApiKeyPanel';
+export { CountrySelector } from './CountrySelector';
+export { IndicatorSelector } from './IndicatorSelector';
+export { DateRangePicker } from './DateRangePicker';
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/constants.ts b/fincept-terminal-desktop/src/components/tabs/economics/constants.ts
new file mode 100644
index 000000000..39fd3253c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/constants.ts
@@ -0,0 +1,373 @@
+// Economics Tab Constants
+
+import type { DataSourceConfig, Indicator, Country, DataSource } from './types';
+
+// Fincept Design System Colors
+export const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ PURPLE: '#9D4EDD',
+};
+
+// Chart dimensions
+export const CHART_WIDTH = 1200;
+export const CHART_HEIGHT = 400;
+
+// Data source configurations
+export const DATA_SOURCES: DataSourceConfig[] = [
+ { id: 'worldbank', name: 'World Bank', fullName: 'World Bank', description: 'Global development indicators', color: FINCEPT.CYAN, scriptName: 'worldbank_data.py' },
+ { id: 'bis', name: 'BIS', fullName: 'Bank for International Settlements', description: 'Central bank statistics, exchange rates, credit', color: FINCEPT.PURPLE, scriptName: 'bis_data.py' },
+ { id: 'imf', name: 'IMF', fullName: 'International Monetary Fund', description: 'World Economic Outlook, fiscal & monetary data', color: FINCEPT.BLUE, scriptName: 'imf_data.py' },
+ { id: 'fred', name: 'FRED', fullName: 'Federal Reserve Economic Data', description: 'U.S. economic data from the Federal Reserve', color: FINCEPT.GREEN, scriptName: 'fred_data.py' },
+ { id: 'oecd', name: 'OECD', fullName: 'Organisation for Economic Co-operation', description: 'Economic indicators for developed countries', color: FINCEPT.YELLOW, scriptName: 'oecd_data.py' },
+ { id: 'wto', name: 'WTO', fullName: 'World Trade Organization', description: 'Trade statistics, tariffs & trade policy', color: '#E91E63', scriptName: 'wto_data.py', requiresApiKey: true, apiKeyName: 'WTO_API_KEY' },
+ { id: 'cftc', name: 'CFTC', fullName: 'Commodity Futures Trading Commission', description: 'Commitment of Traders (COT) Reports', color: '#FF5722', scriptName: 'cftc_data.py' },
+ { id: 'eia', name: 'EIA', fullName: 'Energy Information Administration', description: 'U.S. energy production & prices', color: '#4CAF50', scriptName: 'eia_data.py', requiresApiKey: true, apiKeyName: 'EIA_API_KEY' },
+ { id: 'adb', name: 'ADB', fullName: 'Asian Development Bank', description: 'Asia-Pacific economic indicators', color: '#0072BC', scriptName: 'adb_data.py' },
+ { id: 'fed', name: 'Fed', fullName: 'Federal Reserve', description: 'US monetary policy, rates & money supply', color: '#1A5F7A', scriptName: 'federal_reserve_data.py' },
+];
+
+// World Bank indicators
+export const WORLDBANK_INDICATORS: Indicator[] = [
+ { id: 'NY.GDP.MKTP.CD', name: 'GDP (current US$)', category: 'GDP' },
+ { id: 'NY.GDP.MKTP.KD.ZG', name: 'GDP growth (annual %)', category: 'GDP' },
+ { id: 'NY.GDP.PCAP.CD', name: 'GDP per capita (current US$)', category: 'GDP' },
+ { id: 'FP.CPI.TOTL.ZG', name: 'Inflation, consumer prices (annual %)', category: 'Prices' },
+ { id: 'SL.UEM.TOTL.ZS', name: 'Unemployment, total (% of labor force)', category: 'Labor' },
+ { id: 'NE.EXP.GNFS.ZS', name: 'Exports of goods and services (% of GDP)', category: 'Trade' },
+ { id: 'NE.IMP.GNFS.ZS', name: 'Imports of goods and services (% of GDP)', category: 'Trade' },
+ { id: 'BN.CAB.XOKA.GD.ZS', name: 'Current account balance (% of GDP)', category: 'Trade' },
+ { id: 'GC.DOD.TOTL.GD.ZS', name: 'Central government debt (% of GDP)', category: 'Government' },
+ { id: 'SP.POP.TOTL', name: 'Population, total', category: 'Demographics' },
+ { id: 'SP.POP.GROW', name: 'Population growth (annual %)', category: 'Demographics' },
+ { id: 'FR.INR.RINR', name: 'Real interest rate (%)', category: 'Financial' },
+ { id: 'PA.NUS.FCRF', name: 'Official exchange rate (LCU per US$)', category: 'Financial' },
+ { id: 'FI.RES.TOTL.CD', name: 'Total reserves (includes gold, current US$)', category: 'Financial' },
+ { id: 'BX.KLT.DINV.WD.GD.ZS', name: 'Foreign direct investment, net inflows (% of GDP)', category: 'Investment' },
+];
+
+// BIS indicators
+export const BIS_INDICATORS: Indicator[] = [
+ { id: 'CBPOL_D', name: 'Central Bank Policy Rates (Daily)', category: 'Rates' },
+ { id: 'CBPOL_M', name: 'Central Bank Policy Rates (Monthly)', category: 'Rates' },
+ { id: 'EER_B', name: 'Effective Exchange Rates (Broad)', category: 'Exchange Rates' },
+ { id: 'EER_N', name: 'Effective Exchange Rates (Narrow)', category: 'Exchange Rates' },
+ { id: 'REER_B', name: 'Real Effective Exchange Rates (Broad)', category: 'Exchange Rates' },
+ { id: 'SPP', name: 'Residential Property Prices', category: 'Property' },
+ { id: 'CPP', name: 'Commercial Property Prices', category: 'Property' },
+ { id: 'CREDIT', name: 'Credit to Non-financial Sector', category: 'Credit' },
+ { id: 'DEBT', name: 'Debt Service Ratios', category: 'Credit' },
+ { id: 'LBS', name: 'Locational Banking Statistics', category: 'Banking' },
+ { id: 'CBS', name: 'Consolidated Banking Statistics', category: 'Banking' },
+ { id: 'DSR', name: 'Debt Service Ratios', category: 'Debt' },
+];
+
+// IMF indicators
+export const IMF_INDICATORS: Indicator[] = [
+ { id: 'NGDP_RPCH', name: 'Real GDP growth (Annual %)', category: 'GDP' },
+ { id: 'NGDPD', name: 'GDP, current prices (Billions USD)', category: 'GDP' },
+ { id: 'NGDPDPC', name: 'GDP per capita, current prices (USD)', category: 'GDP' },
+ { id: 'PCPIPCH', name: 'Inflation, average consumer prices (Annual %)', category: 'Prices' },
+ { id: 'PCPIEPCH', name: 'Inflation, end of period (Annual %)', category: 'Prices' },
+ { id: 'LUR', name: 'Unemployment rate (%)', category: 'Labor' },
+ { id: 'BCA_NGDPD', name: 'Current account balance (% of GDP)', category: 'Trade' },
+ { id: 'GGXWDG_NGDP', name: 'General government gross debt (% of GDP)', category: 'Government' },
+ { id: 'GGXCNL_NGDP', name: 'General government net lending (% of GDP)', category: 'Government' },
+ { id: 'GGR_NGDP', name: 'General government revenue (% of GDP)', category: 'Government' },
+];
+
+// FRED indicators (US-focused)
+export const FRED_INDICATORS: Indicator[] = [
+ { id: 'GDP', name: 'Gross Domestic Product', category: 'GDP' },
+ { id: 'GDPC1', name: 'Real Gross Domestic Product', category: 'GDP' },
+ { id: 'CPIAUCSL', name: 'Consumer Price Index for All Urban Consumers', category: 'Prices' },
+ { id: 'CPILFESL', name: 'Core CPI (Less Food and Energy)', category: 'Prices' },
+ { id: 'UNRATE', name: 'Unemployment Rate', category: 'Labor' },
+ { id: 'PAYEMS', name: 'All Employees, Total Nonfarm', category: 'Labor' },
+ { id: 'FEDFUNDS', name: 'Federal Funds Effective Rate', category: 'Rates' },
+ { id: 'DGS10', name: '10-Year Treasury Constant Maturity Rate', category: 'Rates' },
+ { id: 'DGS2', name: '2-Year Treasury Constant Maturity Rate', category: 'Rates' },
+ { id: 'DEXUSEU', name: 'US / Euro Foreign Exchange Rate', category: 'Exchange Rates' },
+ { id: 'DTWEXBGS', name: 'Trade Weighted US Dollar Index', category: 'Exchange Rates' },
+ { id: 'M2SL', name: 'M2 Money Stock', category: 'Money Supply' },
+ { id: 'WALCL', name: 'Federal Reserve Total Assets', category: 'Fed Balance Sheet' },
+ { id: 'HOUST', name: 'Housing Starts', category: 'Housing' },
+ { id: 'INDPRO', name: 'Industrial Production Index', category: 'Production' },
+];
+
+// OECD indicators
+export const OECD_INDICATORS: Indicator[] = [
+ { id: 'GDP', name: 'Gross Domestic Product', category: 'GDP' },
+ { id: 'RGDP', name: 'Real GDP', category: 'GDP' },
+ { id: 'CPI', name: 'Consumer Price Index', category: 'Prices' },
+ { id: 'UNR', name: 'Unemployment Rate', category: 'Labor' },
+ { id: 'LF', name: 'Labour Force', category: 'Labor' },
+ { id: 'IRSTCI', name: 'Short-term Interest Rates', category: 'Rates' },
+ { id: 'IRLTLT', name: 'Long-term Interest Rates', category: 'Rates' },
+ { id: 'EXCH', name: 'Exchange Rates', category: 'Exchange Rates' },
+ { id: 'TBAL', name: 'Trade Balance', category: 'Trade' },
+ { id: 'CLI', name: 'Composite Leading Indicators', category: 'Leading Indicators' },
+ { id: 'BCI', name: 'Business Confidence Index', category: 'Confidence' },
+ { id: 'CCI', name: 'Consumer Confidence Index', category: 'Confidence' },
+];
+
+// WTO indicators (Timeseries API)
+export const WTO_INDICATORS: Indicator[] = [
+ // MFN Applied Tariffs
+ { id: 'TP_A_0010', name: 'Simple Average MFN Tariff - All Products', category: 'Tariffs' },
+ { id: 'TP_A_0160', name: 'Simple Average MFN Tariff - Agricultural', category: 'Tariffs' },
+ { id: 'TP_A_0430', name: 'Simple Average MFN Tariff - Non-Agricultural', category: 'Tariffs' },
+ { id: 'TP_A_0030', name: 'Trade-Weighted MFN Tariff - All Products', category: 'Tariffs' },
+ { id: 'TP_A_0170', name: 'Trade-Weighted MFN Tariff - Agricultural', category: 'Tariffs' },
+ { id: 'TP_A_0440', name: 'Trade-Weighted MFN Tariff - Non-Agricultural', category: 'Tariffs' },
+ // Bound Tariffs
+ { id: 'TP_A_0020', name: 'Simple Average Bound Tariff - All Products', category: 'Bound Tariffs' },
+ { id: 'TP_A_0310', name: 'Simple Average Bound Tariff - Agricultural', category: 'Bound Tariffs' },
+ { id: 'TP_A_0560', name: 'Simple Average Bound Tariff - Non-Agricultural', category: 'Bound Tariffs' },
+ // Tariff Peaks and Bindings
+ { id: 'TP_A_0100', name: 'Share of Duty-Free Tariff Lines - All', category: 'Tariff Structure' },
+ { id: 'TP_A_0090', name: 'Binding Coverage - All Products', category: 'Tariff Structure' },
+ { id: 'TP_A_0130', name: 'Share of Domestic Peaks - All Products', category: 'Tariff Structure' },
+ { id: 'TP_A_0140', name: 'Share of International Peaks - All Products', category: 'Tariff Structure' },
+ // Maximum Tariffs
+ { id: 'TP_A_0070', name: 'Maximum MFN Applied Tariff - All Products', category: 'Tariff Peaks' },
+ { id: 'TP_A_0080', name: 'Maximum Bound Tariff - All Products', category: 'Tariff Peaks' },
+ // Non-Ad Valorem Tariffs
+ { id: 'TP_A_0110', name: 'Share of Non-Ad Valorem Tariffs - All', category: 'Tariff Types' },
+ { id: 'TP_A_0250', name: 'Share of Non-Ad Valorem Tariffs - Agricultural', category: 'Tariff Types' },
+ { id: 'TP_A_0520', name: 'Share of Non-Ad Valorem Tariffs - Non-Agricultural', category: 'Tariff Types' },
+];
+
+// CFTC COT Markets (Commitment of Traders)
+export const CFTC_MARKETS: Indicator[] = [
+ // Agricultural Commodities
+ { id: 'corn', name: 'Corn', category: 'Agricultural', code: '002602' },
+ { id: 'wheat', name: 'Wheat (SRW)', category: 'Agricultural', code: '001602' },
+ { id: 'soybeans', name: 'Soybeans', category: 'Agricultural', code: '005602' },
+ { id: 'cotton', name: 'Cotton', category: 'Agricultural', code: '033661' },
+ { id: 'cocoa', name: 'Cocoa', category: 'Agricultural', code: '073732' },
+ { id: 'coffee', name: 'Coffee', category: 'Agricultural', code: '083731' },
+ { id: 'sugar', name: 'Sugar', category: 'Agricultural', code: '080732' },
+ { id: 'live_cattle', name: 'Live Cattle', category: 'Agricultural', code: '057642' },
+ { id: 'lean_hogs', name: 'Lean Hogs', category: 'Agricultural', code: '054642' },
+ // Energy
+ { id: 'crude_oil', name: 'Crude Oil (WTI)', category: 'Energy', code: '067651' },
+ { id: 'natural_gas', name: 'Natural Gas (Henry Hub)', category: 'Energy', code: '02365B' },
+ { id: 'gasoline', name: 'RBOB Gasoline', category: 'Energy', code: '111659' },
+ { id: 'heating_oil', name: 'Heating Oil', category: 'Energy', code: '022651' },
+ // Precious Metals
+ { id: 'gold', name: 'Gold', category: 'Metals', code: '088691' },
+ { id: 'silver', name: 'Silver', category: 'Metals', code: '084691' },
+ { id: 'copper', name: 'Copper', category: 'Metals', code: '085692' },
+ { id: 'platinum', name: 'Platinum', category: 'Metals', code: '076651' },
+ { id: 'palladium', name: 'Palladium', category: 'Metals', code: '075651' },
+ // Currencies
+ { id: 'euro', name: 'Euro FX', category: 'Currencies', code: '099741' },
+ { id: 'jpy', name: 'Japanese Yen', category: 'Currencies', code: '097741' },
+ { id: 'british_pound', name: 'British Pound', category: 'Currencies', code: '096742' },
+ { id: 'swiss_franc', name: 'Swiss Franc', category: 'Currencies', code: '092741' },
+ { id: 'canadian_dollar', name: 'Canadian Dollar', category: 'Currencies', code: '090741' },
+ { id: 'australian_dollar', name: 'Australian Dollar', category: 'Currencies', code: '232741' },
+ { id: 'us_dollar_index', name: 'US Dollar Index', category: 'Currencies', code: '098662' },
+ // Stock Index Futures
+ { id: 's&p_500', name: 'E-mini S&P 500', category: 'Indices', code: '13874A' },
+ { id: 'nasdaq_100', name: 'Nasdaq 100 E-mini', category: 'Indices', code: '209742' },
+ { id: 'dow_jones', name: 'Dow Jones E-mini', category: 'Indices', code: '124603' },
+ { id: 'nikkei', name: 'Nikkei 225', category: 'Indices', code: '240741' },
+ { id: 'vix', name: 'VIX Futures', category: 'Indices', code: '1170E1' },
+ // Interest Rates
+ { id: 'treasury_bonds', name: 'US Treasury Bonds', category: 'Interest Rates', code: '020601' },
+ { id: 'treasury_notes_2y', name: '2-Year Treasury Notes', category: 'Interest Rates', code: '042601' },
+ { id: 'treasury_notes_5y', name: '5-Year Treasury Notes', category: 'Interest Rates', code: '044601' },
+ { id: 'treasury_notes_10y', name: '10-Year Treasury Notes', category: 'Interest Rates', code: '043602' },
+ { id: 'fed_funds', name: '30-Day Fed Funds', category: 'Interest Rates', code: '045601' },
+ // Cryptocurrencies
+ { id: 'bitcoin', name: 'Bitcoin', category: 'Crypto', code: '133741' },
+ { id: 'ether', name: 'Ether', category: 'Crypto', code: '146021' },
+];
+
+// ADB Indicators (Asian Development Bank - Key Indicators Database)
+// API: https://kidb.adb.org/api - Uses SDMX format with dataflows: EO_NA, PPL_POP
+// These are the actual verified indicator codes from the ADB API
+export const ADB_INDICATORS: Indicator[] = [
+ // === ECONOMY AND OUTPUT (Dataflow: EO_NA) ===
+ { id: 'NGDP_XDC', name: 'GDP at Current Prices', category: 'Economy & Output' },
+ { id: 'NGDPPC_XDC', name: 'GDP per Capita', category: 'Economy & Output' },
+ { id: 'NYG_XDC', name: 'GNI at Current Prices', category: 'Economy & Output' },
+ { id: 'NYGPC_XDC', name: 'GNI per Capita', category: 'Economy & Output' },
+ { id: 'NYG_USD', name: 'GNI (USD millions)', category: 'Economy & Output' },
+ // GDP Composition
+ { id: 'NGDPSO_AGR_XGDP_PS', name: 'Agriculture (% of GDP)', category: 'GDP Composition' },
+ { id: 'NGDPSO_IND_XGDP_PS', name: 'Industry (% of GDP)', category: 'GDP Composition' },
+ { id: 'NGDPSO_SER_XGDP_PS', name: 'Services (% of GDP)', category: 'GDP Composition' },
+ // Expenditure
+ { id: 'NC_HFC_XGDP_PS', name: 'Household Consumption (% of GDP)', category: 'Expenditure' },
+ { id: 'NCGG_XGDP_PS', name: 'Government Consumption (% of GDP)', category: 'Expenditure' },
+ { id: 'NI_XGDP_PS', name: 'Gross Capital Formation (% of GDP)', category: 'Expenditure' },
+ { id: 'NEGS_XGDP_PS', name: 'Exports of Goods & Services (% of GDP)', category: 'Trade' },
+ { id: 'NIGS_XGDP_PS', name: 'Imports of Goods & Services (% of GDP)', category: 'Trade' },
+ // Sector Value Added
+ { id: 'NGDPVA_ISIC4_A_XDC', name: 'Agriculture, Forestry, Fishing', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_C_XDC', name: 'Manufacturing', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_F_XDC', name: 'Construction', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_G_XDC', name: 'Wholesale & Retail Trade', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_K_XDC', name: 'Financial & Insurance', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_L_XDC', name: 'Real Estate', category: 'Sector Output' },
+ { id: 'NGDPVA_ISIC4_J_XDC', name: 'Information & Communication', category: 'Sector Output' },
+
+ // === POPULATION (Dataflow: PPL_POP) ===
+ { id: 'LP_PE_NUM_MOP', name: 'Total Population', category: 'Population' },
+ { id: 'LP_MOP_PTX_PS', name: 'Population Growth Rate (%)', category: 'Population' },
+ { id: 'LP_PE_PD_PS', name: 'Population Density (per sq km)', category: 'Population' },
+ { id: 'LP_UP_PTX_PS', name: 'Urban Population (%)', category: 'Population' },
+ { id: 'SP_POP_0014_TO_ZS', name: 'Population Age 0-14 (%)', category: 'Demographics' },
+ { id: 'SP_POP_1564_TO_ZS', name: 'Population Age 15-64 (%)', category: 'Demographics' },
+ { id: 'SP_POP_GTE_65_TO_ZS_RT_PS', name: 'Population Age 65+ (%)', category: 'Demographics' },
+ { id: 'SP_POP_DPND', name: 'Age Dependency Ratio', category: 'Demographics' },
+ { id: 'SM_POP_NETM_RT_PS', name: 'Net Migration Rate', category: 'Demographics' },
+];
+
+// Federal Reserve Indicators (NY Fed & Federal Reserve Board)
+// Note: Daily data sources use date range to limit data volume
+export const FED_INDICATORS: Indicator[] = [
+ // Key Interest Rates (Daily data - last 1 year by default)
+ { id: 'federal_funds_rate', name: 'Federal Funds Rate (EFFR)', category: 'Interest Rates' },
+ { id: 'sofr_rate', name: 'SOFR (Secured Overnight Financing Rate)', category: 'Interest Rates' },
+ // Treasury Rates (Daily data - last 1 year by default)
+ { id: 'treasury_rates', name: 'Treasury Rates (All Maturities)', category: 'Treasury' },
+ { id: 'yield_curve', name: 'Yield Curve (Latest)', category: 'Treasury' },
+ // Money Supply (Monthly data)
+ { id: 'money_measures', name: 'Money Supply (M1, M2)', category: 'Money Supply' },
+ { id: 'money_measures_adjusted', name: 'Money Supply (Seasonally Adjusted)', category: 'Money Supply' },
+ // Central Bank Operations
+ { id: 'central_bank_holdings', name: 'Fed Holdings (SOMA)', category: 'Central Bank' },
+ // Composite Data (Recent 7 days)
+ { id: 'market_overview', name: 'Market Overview (Recent)', category: 'Overview' },
+];
+
+// EIA Indicators (U.S. Energy Information Administration)
+export const EIA_INDICATORS: Indicator[] = [
+ // Petroleum Status Report Categories
+ { id: 'balance_sheet', name: 'Petroleum Balance Sheet', category: 'Petroleum' },
+ { id: 'inputs_and_production', name: 'Refinery Inputs & Production', category: 'Petroleum' },
+ { id: 'crude_petroleum_stocks', name: 'Crude Oil Stocks', category: 'Petroleum' },
+ { id: 'gasoline_fuel_stocks', name: 'Gasoline Stocks', category: 'Petroleum' },
+ { id: 'distillate_fuel_oil_stocks', name: 'Distillate Fuel Oil Stocks', category: 'Petroleum' },
+ { id: 'imports', name: 'Petroleum Imports', category: 'Petroleum' },
+ { id: 'imports_by_country', name: 'Petroleum Imports by Country', category: 'Petroleum' },
+ { id: 'spot_prices_crude_gas_heating', name: 'Spot Prices (Crude, Gas, Heating)', category: 'Prices' },
+ { id: 'spot_prices_diesel_jet_fuel_propane', name: 'Spot Prices (Diesel, Jet, Propane)', category: 'Prices' },
+ { id: 'retail_prices', name: 'Retail Fuel Prices', category: 'Prices' },
+ // STEO Tables (Short Term Energy Outlook) - requires API key
+ { id: 'steo_01', name: 'US Energy Markets Summary', category: 'STEO' },
+ { id: 'steo_02', name: 'Nominal Energy Prices', category: 'STEO' },
+ { id: 'steo_04a', name: 'US Petroleum Supply & Consumption', category: 'STEO' },
+ { id: 'steo_05a', name: 'US Natural Gas Supply & Consumption', category: 'STEO' },
+ { id: 'steo_07a', name: 'US Electricity Overview', category: 'STEO' },
+ { id: 'steo_09a', name: 'US Macro Indicators & CO2 Emissions', category: 'STEO' },
+];
+
+// Countries list (with codes for each data source)
+export const COUNTRIES: Country[] = [
+ { code: 'USA', name: 'United States', bis: 'US', imf: 'USA', fred: 'US', oecd: 'USA', wto: '840' },
+ { code: 'CHN', name: 'China', bis: 'CN', imf: 'CHN', oecd: 'CHN', wto: '156', adb: 'CHN' },
+ { code: 'JPN', name: 'Japan', bis: 'JP', imf: 'JPN', oecd: 'JPN', wto: '392', adb: 'JPN' },
+ { code: 'DEU', name: 'Germany', bis: 'DE', imf: 'DEU', oecd: 'DEU', wto: '276' },
+ { code: 'GBR', name: 'United Kingdom', bis: 'GB', imf: 'GBR', oecd: 'GBR', wto: '826' },
+ { code: 'FRA', name: 'France', bis: 'FR', imf: 'FRA', oecd: 'FRA', wto: '251' },
+ { code: 'IND', name: 'India', bis: 'IN', imf: 'IND', oecd: 'IND', wto: '699', adb: 'IND' },
+ { code: 'ITA', name: 'Italy', bis: 'IT', imf: 'ITA', oecd: 'ITA', wto: '381' },
+ { code: 'BRA', name: 'Brazil', bis: 'BR', imf: 'BRA', oecd: 'BRA', wto: '076' },
+ { code: 'CAN', name: 'Canada', bis: 'CA', imf: 'CAN', oecd: 'CAN', wto: '124' },
+ { code: 'RUS', name: 'Russian Federation', bis: 'RU', imf: 'RUS', oecd: 'RUS', wto: '643' },
+ { code: 'KOR', name: 'Korea, Rep.', bis: 'KR', imf: 'KOR', oecd: 'KOR', wto: '410', adb: 'KOR' },
+ { code: 'AUS', name: 'Australia', bis: 'AU', imf: 'AUS', oecd: 'AUS', wto: '036', adb: 'AUS' },
+ { code: 'ESP', name: 'Spain', bis: 'ES', imf: 'ESP', oecd: 'ESP', wto: '724' },
+ { code: 'MEX', name: 'Mexico', bis: 'MX', imf: 'MEX', oecd: 'MEX', wto: '484' },
+ { code: 'IDN', name: 'Indonesia', bis: 'ID', imf: 'IDN', oecd: 'IDN', wto: '360', adb: 'IDN' },
+ { code: 'NLD', name: 'Netherlands', bis: 'NL', imf: 'NLD', oecd: 'NLD', wto: '528' },
+ { code: 'SAU', name: 'Saudi Arabia', bis: 'SA', imf: 'SAU', wto: '682' },
+ { code: 'TUR', name: 'Turkey', bis: 'TR', imf: 'TUR', oecd: 'TUR', wto: '792' },
+ { code: 'CHE', name: 'Switzerland', bis: 'CH', imf: 'CHE', oecd: 'CHE', wto: '757' },
+ { code: 'POL', name: 'Poland', bis: 'PL', imf: 'POL', oecd: 'POL', wto: '616' },
+ { code: 'SWE', name: 'Sweden', bis: 'SE', imf: 'SWE', oecd: 'SWE', wto: '752' },
+ { code: 'BEL', name: 'Belgium', bis: 'BE', imf: 'BEL', oecd: 'BEL', wto: '056' },
+ { code: 'ARG', name: 'Argentina', bis: 'AR', imf: 'ARG', oecd: 'ARG', wto: '032' },
+ { code: 'NOR', name: 'Norway', bis: 'NO', imf: 'NOR', oecd: 'NOR', wto: '579' },
+ { code: 'AUT', name: 'Austria', bis: 'AT', imf: 'AUT', oecd: 'AUT', wto: '040' },
+ { code: 'ARE', name: 'United Arab Emirates', bis: 'AE', imf: 'ARE', wto: '784' },
+ { code: 'NGA', name: 'Nigeria', bis: 'NG', imf: 'NGA', wto: '566' },
+ { code: 'ISR', name: 'Israel', bis: 'IL', imf: 'ISR', oecd: 'ISR', wto: '376' },
+ { code: 'ZAF', name: 'South Africa', bis: 'ZA', imf: 'ZAF', oecd: 'ZAF', wto: '710' },
+ { code: 'SGP', name: 'Singapore', bis: 'SG', imf: 'SGP', wto: '702', adb: 'SGP' },
+ { code: 'HKG', name: 'Hong Kong', bis: 'HK', imf: 'HKG', wto: '344', adb: 'HKG' },
+ { code: 'DNK', name: 'Denmark', bis: 'DK', imf: 'DNK', oecd: 'DNK', wto: '208' },
+ { code: 'MYS', name: 'Malaysia', bis: 'MY', imf: 'MYS', wto: '458', adb: 'MYS' },
+ { code: 'PHL', name: 'Philippines', bis: 'PH', imf: 'PHL', wto: '608', adb: 'PHI' },
+ { code: 'CHL', name: 'Chile', bis: 'CL', imf: 'CHL', oecd: 'CHL', wto: '152' },
+ { code: 'FIN', name: 'Finland', bis: 'FI', imf: 'FIN', oecd: 'FIN', wto: '246' },
+ { code: 'COL', name: 'Colombia', bis: 'CO', imf: 'COL', oecd: 'COL', wto: '170' },
+ { code: 'CZE', name: 'Czech Republic', bis: 'CZ', imf: 'CZE', oecd: 'CZE', wto: '203' },
+ { code: 'PRT', name: 'Portugal', bis: 'PT', imf: 'PRT', oecd: 'PRT', wto: '620' },
+ { code: 'NZL', name: 'New Zealand', bis: 'NZ', imf: 'NZL', oecd: 'NZL', wto: '554', adb: 'NZL' },
+ { code: 'GRC', name: 'Greece', bis: 'GR', imf: 'GRC', oecd: 'GRC', wto: '300' },
+ { code: 'HUN', name: 'Hungary', bis: 'HU', imf: 'HUN', oecd: 'HUN', wto: '348' },
+ { code: 'IRL', name: 'Ireland', bis: 'IE', imf: 'IRL', oecd: 'IRL', wto: '372' },
+ { code: 'THA', name: 'Thailand', bis: 'TH', imf: 'THA', wto: '764', adb: 'THA' },
+ { code: 'VNM', name: 'Vietnam', bis: 'VN', imf: 'VNM', wto: '704', adb: 'VNM' },
+ { code: 'TWN', name: 'Taiwan', bis: 'TW', adb: 'TWN' },
+ { code: 'PAK', name: 'Pakistan', bis: 'PK', imf: 'PAK', wto: '586', adb: 'PAK' },
+ { code: 'BGD', name: 'Bangladesh', bis: 'BD', imf: 'BGD', wto: '050', adb: 'BGD' },
+ { code: 'MMR', name: 'Myanmar', imf: 'MMR', adb: 'MYA' },
+ { code: 'KHM', name: 'Cambodia', imf: 'KHM', adb: 'CAM' },
+ { code: 'LAO', name: 'Lao PDR', imf: 'LAO', adb: 'LAO' },
+ { code: 'MNG', name: 'Mongolia', imf: 'MNG', adb: 'MON' },
+ { code: 'NPL', name: 'Nepal', imf: 'NPL', adb: 'NEP' },
+ { code: 'LKA', name: 'Sri Lanka', imf: 'LKA', adb: 'SRI' },
+];
+
+// Get indicators for selected data source
+export const getIndicatorsForSource = (source: DataSource): Indicator[] => {
+ switch (source) {
+ case 'worldbank': return WORLDBANK_INDICATORS;
+ case 'bis': return BIS_INDICATORS;
+ case 'imf': return IMF_INDICATORS;
+ case 'fred': return FRED_INDICATORS;
+ case 'oecd': return OECD_INDICATORS;
+ case 'wto': return WTO_INDICATORS;
+ case 'cftc': return CFTC_MARKETS;
+ case 'eia': return EIA_INDICATORS;
+ case 'adb': return ADB_INDICATORS;
+ case 'fed': return FED_INDICATORS;
+ default: return WORLDBANK_INDICATORS;
+ }
+};
+
+// Get default indicator for source
+export const getDefaultIndicator = (source: DataSource): string => {
+ switch (source) {
+ case 'worldbank': return 'NY.GDP.MKTP.CD';
+ case 'bis': return 'CBPOL_M';
+ case 'imf': return 'NGDP_RPCH';
+ case 'fred': return 'GDP';
+ case 'oecd': return 'GDP';
+ case 'wto': return 'TP_A_0010';
+ case 'cftc': return 'gold';
+ case 'eia': return 'crude_petroleum_stocks';
+ case 'adb': return 'NGDP_XDC';
+ case 'fed': return 'federal_funds_rate';
+ default: return 'NY.GDP.MKTP.CD';
+ }
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/index.ts
new file mode 100644
index 000000000..a898817bd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/index.ts
@@ -0,0 +1,4 @@
+// Economics Tab Hooks
+
+export { useEconomicsData } from './useEconomicsData';
+export { useExport } from './useExport';
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts
new file mode 100644
index 000000000..fa3b55252
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useEconomicsData.ts
@@ -0,0 +1,630 @@
+// useEconomicsData Hook - Fetch and manage economic data
+
+import { useState, useCallback, useEffect } from 'react';
+import { invoke } from '@tauri-apps/api/core';
+import { sqliteService } from '@/services/core/sqliteService';
+import {
+ COUNTRIES,
+ CFTC_MARKETS,
+ EIA_INDICATORS,
+ ADB_INDICATORS,
+ FED_INDICATORS,
+ getIndicatorsForSource,
+ getDefaultIndicator,
+ DATA_SOURCES,
+} from '../constants';
+import type { DataSource, IndicatorData, DataPoint, ChartStats } from '../types';
+
+// Date range presets for quick selection
+export type DateRangePreset = '1M' | '3M' | '6M' | '1Y' | '2Y' | '5Y' | '10Y' | 'ALL';
+
+interface UseEconomicsDataReturn {
+ dataSource: DataSource;
+ setDataSource: (source: DataSource) => void;
+ selectedCountry: string;
+ setSelectedCountry: (code: string) => void;
+ selectedIndicator: string;
+ setSelectedIndicator: (id: string) => void;
+ data: IndicatorData | null;
+ loading: boolean;
+ error: string | null;
+ fetchData: () => Promise<void>;
+ stats: ChartStats | null;
+ // Date range for pagination
+ dateRangePreset: DateRangePreset;
+ setDateRangePreset: (preset: DateRangePreset) => void;
+ startDate: string;
+ endDate: string;
+ setStartDate: (date: string) => void;
+ setEndDate: (date: string) => void;
+ // API Keys
+ wtoApiKey: string;
+ setWtoApiKey: (key: string) => void;
+ eiaApiKey: string;
+ setEiaApiKey: (key: string) => void;
+ showApiKeyInput: boolean;
+ setShowApiKeyInput: (show: boolean) => void;
+ apiKeySaving: boolean;
+ saveApiKey: (keyName: string, keyValue: string) => Promise<void>;
+}
+
+// Helper to calculate date from preset
+const getDateFromPreset = (preset: DateRangePreset): { start: string; end: string } => {
+ const now = new Date();
+ const end = now.toISOString().split('T')[0];
+ let start: Date;
+
+ switch (preset) {
+ case '1M':
+ start = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
+ break;
+ case '3M':
+ start = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
+ break;
+ case '6M':
+ start = new Date(now.getFullYear(), now.getMonth() - 6, now.getDate());
+ break;
+ case '1Y':
+ start = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
+ break;
+ case '2Y':
+ start = new Date(now.getFullYear() - 2, now.getMonth(), now.getDate());
+ break;
+ case '5Y':
+ start = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate());
+ break;
+ case '10Y':
+ start = new Date(now.getFullYear() - 10, now.getMonth(), now.getDate());
+ break;
+ case 'ALL':
+ default:
+ start = new Date(1960, 0, 1); // Start from 1960 for historical data
+ break;
+ }
+
+ return { start: start.toISOString().split('T')[0], end };
+};
+
+export function useEconomicsData(): UseEconomicsDataReturn {
+ const [dataSource, setDataSourceState] = useState<DataSource>('worldbank');
+ const [selectedCountry, setSelectedCountry] = useState('USA');
+ const [selectedIndicator, setSelectedIndicator] = useState('NY.GDP.MKTP.CD');
+ const [data, setData] = useState<IndicatorData | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Date range state for pagination
+ const [dateRangePreset, setDateRangePresetState] = useState<DateRangePreset>('5Y');
+ const initialDates = getDateFromPreset('5Y');
+ const [startDate, setStartDate] = useState(initialDates.start);
+ const [endDate, setEndDate] = useState(initialDates.end);
+
+ // Update dates when preset changes
+ const setDateRangePreset = useCallback((preset: DateRangePreset) => {
+ setDateRangePresetState(preset);
+ const dates = getDateFromPreset(preset);
+ setStartDate(dates.start);
+ setEndDate(dates.end);
+ }, []);
+
+ // API Keys
+ const [wtoApiKey, setWtoApiKey] = useState<string>('');
+ const [eiaApiKey, setEiaApiKey] = useState<string>('');
+ const [showApiKeyInput, setShowApiKeyInput] = useState(false);
+ const [apiKeySaving, setApiKeySaving] = useState(false);
+
+ // Load API keys on mount
+ useEffect(() => {
+ const loadApiKeys = async () => {
+ try {
+ const wtoKey = await sqliteService.getApiKey('WTO_API_KEY');
+ if (wtoKey) setWtoApiKey(wtoKey);
+
+ const eiaKey = await sqliteService.getApiKey('EIA_API_KEY');
+ if (eiaKey) setEiaApiKey(eiaKey);
+ } catch (err) {
+ console.error('Failed to load API keys:', err);
+ }
+ };
+ loadApiKeys();
+ }, []);
+
+ // Reset indicator and country when data source changes
+ const setDataSource = useCallback((source: DataSource) => {
+ setDataSourceState(source);
+ setSelectedIndicator(getDefaultIndicator(source));
+ // Set appropriate default country for source
+ if (source === 'adb') {
+ // ADB is Asia-Pacific only - default to India
+ setSelectedCountry('IND');
+ } else if (source === 'fred' || source === 'fed') {
+ // FRED and Federal Reserve are US-only
+ setSelectedCountry('USA');
+ }
+ setData(null);
+ setError(null);
+ }, []);
+
+ // Save API key
+ const saveApiKey = useCallback(async (keyName: string, keyValue: string) => {
+ if (!keyValue.trim()) return;
+ setApiKeySaving(true);
+ try {
+ await sqliteService.setApiKey(keyName, keyValue);
+ setShowApiKeyInput(false);
+ } catch (err) {
+ setError('Failed to save API key');
+ } finally {
+ setApiKeySaving(false);
+ }
+ }, []);
+
+ // Fetch data
+ const fetchData = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+
+ try {
+ const country = COUNTRIES.find(c => c.code === selectedCountry);
+ const indicators = getIndicatorsForSource(dataSource);
+ const currentSourceConfig = DATA_SOURCES.find(s => s.id === dataSource)!;
+ let result: string;
+ let countryCode = selectedCountry;
+
+ // Get appropriate country code for data source
+ if (dataSource === 'bis' && country?.bis) {
+ countryCode = country.bis;
+ } else if (dataSource === 'imf' && country?.imf) {
+ countryCode = country.imf;
+ } else if (dataSource === 'fred') {
+ countryCode = 'US'; // FRED is US-only
+ } else if (dataSource === 'oecd' && country?.oecd) {
+ countryCode = country.oecd;
+ } else if (dataSource === 'wto' && country?.wto) {
+ countryCode = country.wto;
+ } else if (dataSource === 'adb' && country?.adb) {
+ countryCode = country.adb;
+ }
+
+ // Check if API key is required
+ if (dataSource === 'wto' && !wtoApiKey) {
+ setError('WTO API Key required. Click the key icon to configure.');
+ setShowApiKeyInput(true);
+ setLoading(false);
+ return;
+ }
+
+ if (dataSource === 'eia' && selectedIndicator.startsWith('steo_') && !eiaApiKey) {
+ setError('EIA API Key required for STEO data. Click the key icon to configure.');
+ setShowApiKeyInput(true);
+ setLoading(false);
+ return;
+ }
+
+ // Fetch data based on source
+ switch (dataSource) {
+ case 'worldbank':
+ result = await invoke('execute_python_script', {
+ scriptName: 'worldbank_data.py',
+ args: ['indicators', countryCode, selectedIndicator],
+ env: {},
+ }) as string;
+ break;
+
+ case 'bis':
+ result = await invoke('execute_python_script', {
+ scriptName: 'bis_data.py',
+ args: ['fetch', selectedIndicator, countryCode],
+ env: {},
+ }) as string;
+ break;
+
+ case 'imf':
+ result = await invoke('execute_python_script', {
+ scriptName: 'imf_data.py',
+ args: ['weo', countryCode, selectedIndicator],
+ env: {},
+ }) as string;
+ break;
+
+ case 'fred':
+ result = await invoke('execute_python_script', {
+ scriptName: 'fred_data.py',
+ args: ['series', selectedIndicator],
+ env: {},
+ }) as string;
+ break;
+
+ case 'oecd':
+ result = await invoke('execute_python_script', {
+ scriptName: 'oecd_data.py',
+ args: ['fetch', selectedIndicator, countryCode],
+ env: {},
+ }) as string;
+ break;
+
+ case 'wto':
+ result = await invoke('execute_python_script', {
+ scriptName: 'wto_data.py',
+ args: ['timeseries_data', '--i', selectedIndicator, '--reporters', countryCode, wtoApiKey],
+ env: {},
+ }) as string;
+ break;
+
+ case 'cftc':
+ result = await invoke('execute_python_script', {
+ scriptName: 'cftc_data.py',
+ args: ['cot_historical_trend', selectedIndicator, 'legacy', '104'],
+ env: {},
+ }) as string;
+ break;
+
+ case 'eia':
+ if (selectedIndicator.startsWith('steo_')) {
+ // STEO data requires API key
+ const tableNum = selectedIndicator.replace('steo_', '');
+ result = await invoke('execute_python_script', {
+ scriptName: 'eia_data.py',
+ args: ['get_steo', tableNum, '', 'month'],
+ env: { EIA_API_KEY: eiaApiKey },
+ }) as string;
+ } else {
+ // Petroleum status report data (no API key needed)
+ result = await invoke('execute_python_script', {
+ scriptName: 'eia_data.py',
+ args: ['get_petroleum', selectedIndicator],
+ env: {},
+ }) as string;
+ }
+ break;
+
+ case 'adb':
+ // Check if country has ADB code
+ if (!country?.adb) {
+ throw new Error(`${country?.name || selectedCountry} is not available in ADB database. ADB covers Asia-Pacific region only.`);
+ }
+ // Extract years from date range for ADB API (it only accepts years)
+ const adbStartYear = startDate.substring(0, 4);
+ const adbEndYear = endDate.substring(0, 4);
+
+ // Map indicators to ADB dataflows and commands
+ // ADB uses two main dataflows:
+ // - PPL_POP: Population data (indicators starting with LP_, SP_, SM_)
+ // - EO_NA: Economy & Output (indicators starting with NGDP, NYG, NC_, NI_, NEGS_, NIGS_, NGDPVA_)
+
+ // Population dataflow (PPL_POP)
+ if (selectedIndicator.startsWith('LP_') || selectedIndicator.startsWith('SP_') || selectedIndicator.startsWith('SM_')) {
+ result = await invoke('execute_python_script', {
+ scriptName: 'adb_data.py',
+ args: ['get_population', countryCode, selectedIndicator, adbStartYear, adbEndYear],
+ env: {},
+ }) as string;
+ }
+ // Economy & Output dataflow (EO_NA) - this covers GDP, GNI, expenditure, and sector output
+ else {
+ result = await invoke('execute_python_script', {
+ scriptName: 'adb_data.py',
+ args: ['get_gdp', countryCode, selectedIndicator, adbStartYear, adbEndYear],
+ env: {},
+ }) as string;
+ }
+ break;
+
+ case 'fed':
+ // Federal Reserve data - US only, no country selection needed
+ // Use user-selected date range for pagination
+ // Map indicator IDs to Python script commands with user date range
+ if (selectedIndicator === 'federal_funds_rate') {
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['federal_funds_rate', startDate, endDate],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'sofr_rate') {
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['sofr_rate', startDate, endDate],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'treasury_rates') {
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['treasury_rates', startDate, endDate],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'yield_curve') {
+ // Get latest yield curve (single date)
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['yield_curve', endDate],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'money_measures') {
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['money_measures', startDate, endDate, 'false'],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'money_measures_adjusted') {
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['money_measures', startDate, endDate, 'true'],
+ env: {},
+ }) as string;
+ } else if (selectedIndicator === 'market_overview') {
+ // Composite - already limited internally
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: ['market_overview'],
+ env: {},
+ }) as string;
+ } else {
+ // Default - direct mapping with user date range
+ result = await invoke('execute_python_script', {
+ scriptName: 'federal_reserve_data.py',
+ args: [selectedIndicator, startDate, endDate],
+ env: {},
+ }) as string;
+ }
+ break;
+
+ default:
+ throw new Error('Unknown data source');
+ }
+
+ const parsed = JSON.parse(result);
+
+ // Check for error in response
+ if (parsed.error || parsed.success === false) {
+ // Handle error that could be a string or an object
+ let errorMessage: string;
+ if (typeof parsed.error === 'string') {
+ errorMessage = parsed.error;
+ } else if (typeof parsed.error === 'object' && parsed.error !== null) {
+ errorMessage = parsed.error.error || parsed.error.message || JSON.stringify(parsed.error);
+ } else if (parsed.message) {
+ errorMessage = parsed.message;
+ } else {
+ errorMessage = 'An error occurred while fetching data';
+ }
+ setError(errorMessage);
+ setData(null);
+ } else {
+ // Handle different response formats
+ let rawData: any[] = [];
+ let indicatorName = '';
+ let countryName = '';
+
+ if (dataSource === 'wto') {
+ const wtoData = parsed.data?.Dataset || parsed.Dataset || [];
+ if (Array.isArray(wtoData) && wtoData.length > 0) {
+ rawData = wtoData.map((d: any) => ({
+ date: String(d.Year || d.year || ''),
+ value: d.Value ?? d.value,
+ }));
+ indicatorName = wtoData[0]?.Indicator || wtoData[0]?.IndicatorCode || '';
+ countryName = wtoData[0]?.ReportingEconomy || wtoData[0]?.Reporter || '';
+ }
+ } else if (dataSource === 'cftc') {
+ const cftcData = parsed.data || [];
+ if (Array.isArray(cftcData) && cftcData.length > 0) {
+ rawData = cftcData.map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.non_commercial_net ?? d.commercial_net ?? d.open_interest ?? 0,
+ }));
+ const marketInfo = CFTC_MARKETS.find(m => m.id === selectedIndicator);
+ indicatorName = marketInfo ? `${marketInfo.name} - Net Speculator Position` : selectedIndicator;
+ countryName = 'Global';
+ }
+ } else if (dataSource === 'eia') {
+ const eiaData = parsed.data || [];
+ if (Array.isArray(eiaData) && eiaData.length > 0) {
+ rawData = eiaData.map((d: any) => ({
+ date: String(d.date || d.period || ''),
+ value: d.value,
+ }));
+ const eiaIndicator = EIA_INDICATORS.find(i => i.id === selectedIndicator);
+ indicatorName = eiaIndicator?.name || parsed.category || selectedIndicator;
+ countryName = 'United States';
+ }
+ } else if (dataSource === 'adb') {
+ // ADB returns SDMX-JSON format parsed into simpler structure
+ const adbData = parsed.data || [];
+ if (Array.isArray(adbData) && adbData.length > 0) {
+ rawData = adbData.map((d: any) => ({
+ date: String(d.time_period || d.date || ''),
+ value: d.value,
+ }));
+ const adbIndicator = ADB_INDICATORS.find(i => i.id === selectedIndicator);
+ indicatorName = adbIndicator?.name || parsed.metadata?.description || selectedIndicator;
+ countryName = parsed.metadata?.economy_name || country?.name || '';
+ } else {
+ // Sometimes ADB returns nested structure
+ const metadata = parsed.metadata || {};
+ indicatorName = metadata.description || selectedIndicator;
+ countryName = metadata.economy_name || country?.name || '';
+ }
+ } else if (dataSource === 'fed') {
+ // Federal Reserve data - various formats depending on endpoint
+ const fedData = parsed.data || [];
+ const fedIndicator = FED_INDICATORS.find(i => i.id === selectedIndicator);
+ indicatorName = fedIndicator?.name || selectedIndicator;
+ countryName = 'United States';
+
+ if (Array.isArray(fedData) && fedData.length > 0) {
+ // Handle different Fed data structures
+ if (selectedIndicator === 'federal_funds_rate' || selectedIndicator === 'sofr_rate') {
+ // Interest rate data - has 'rate' field
+ rawData = fedData.map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.rate !== null && d.rate !== undefined ? d.rate * 100 : null, // Convert to percentage
+ }));
+ } else if (selectedIndicator === 'treasury_rates') {
+ // Treasury rates - use 10-year as default display value
+ rawData = fedData.map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.year_10 !== null && d.year_10 !== undefined ? d.year_10 * 100 : null,
+ }));
+ indicatorName = '10-Year Treasury Rate';
+ } else if (selectedIndicator === 'yield_curve') {
+ // Yield curve data - filter for specific maturity or use rate field
+ rawData = fedData
+ .filter((d: any) => d.maturity === 'year_10')
+ .map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.rate !== null && d.rate !== undefined ? d.rate * 100 : null,
+ }));
+ } else if (selectedIndicator === 'money_measures' || selectedIndicator === 'money_measures_adjusted') {
+ // Money supply data - use M2 as default display
+ rawData = fedData.map((d: any) => ({
+ date: String(d.month || d.date || ''),
+ value: d.M2 || d.m2 || null,
+ }));
+ indicatorName = selectedIndicator === 'money_measures_adjusted'
+ ? 'M2 Money Supply (Seasonally Adjusted)'
+ : 'M2 Money Supply';
+ } else if (selectedIndicator === 'market_overview') {
+ // Market overview - extract federal funds rate from nested structure
+ const ffr = parsed.endpoints?.federal_funds_rate?.data || [];
+ if (Array.isArray(ffr) && ffr.length > 0) {
+ rawData = ffr.map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.rate !== null && d.rate !== undefined ? d.rate * 100 : null,
+ }));
+ indicatorName = 'Federal Funds Rate (from Market Overview)';
+ }
+ } else {
+ // Generic fallback
+ rawData = fedData.map((d: any) => ({
+ date: String(d.date || d.month || ''),
+ value: d.value ?? d.rate ?? d.M2 ?? null,
+ }));
+ }
+ } else if (parsed.endpoints) {
+ // Composite endpoint like market_overview or comprehensive_monetary_data
+ const ffr = parsed.endpoints?.federal_funds_rate?.data || [];
+ if (Array.isArray(ffr) && ffr.length > 0) {
+ rawData = ffr.map((d: any) => ({
+ date: String(d.date || ''),
+ value: d.rate !== null && d.rate !== undefined ? d.rate * 100 : null,
+ }));
+ indicatorName = 'Federal Funds Rate';
+ }
+ }
+ } else if (parsed.data && Array.isArray(parsed.data)) {
+ rawData = parsed.data.map((d: any) => ({
+ date: d.date || d.period || d.year || '',
+ value: d.value,
+ }));
+ indicatorName = parsed.data[0]?.indicator_name || parsed.indicator_name || '';
+ countryName = parsed.data[0]?.country_name || parsed.country_name || '';
+ }
+
+ // Filter and transform data
+ let dataPoints: DataPoint[] = rawData
+ .filter((d: any) => d.value !== null && d.value !== undefined)
+ .map((d: any) => ({
+ date: String(d.date),
+ value: typeof d.value === 'number' ? d.value : parseFloat(d.value),
+ }))
+ .filter((d: DataPoint) => !isNaN(d.value) && d.date)
+ .sort((a: DataPoint, b: DataPoint) => a.date.localeCompare(b.date));
+
+ // Apply date range filter for all providers (client-side filtering)
+ // This ensures consistent pagination across all data sources
+ if (startDate && endDate) {
+ dataPoints = dataPoints.filter((d: DataPoint) => {
+ // Handle various date formats: YYYY, YYYY-MM, YYYY-MM-DD
+ const dateStr = d.date;
+ // Normalize to comparable format
+ const normalizedDate = dateStr.length === 4
+ ? `${dateStr}-01-01` // Year only -> Jan 1
+ : dateStr.length === 7
+ ? `${dateStr}-01` // Year-Month -> 1st of month
+ : dateStr; // Full date
+ return normalizedDate >= startDate && normalizedDate <= endDate;
+ });
+ }
+
+ if (dataPoints.length === 0) {
+ setError('No data available for this selection');
+ setData(null);
+ } else {
+ const indicatorInfo = indicators.find((i) => i.id === selectedIndicator);
+
+ setData({
+ indicator: selectedIndicator,
+ country: selectedCountry,
+ data: dataPoints,
+ metadata: {
+ indicator_name: indicatorName || indicatorInfo?.name,
+ country_name: countryName || country?.name,
+ source: currentSourceConfig.name,
+ },
+ });
+ }
+ }
+ } catch (err) {
+ console.error('Fetch error:', err);
+ // Ensure error is always a string
+ let errorMessage: string;
+ if (err instanceof Error) {
+ errorMessage = err.message;
+ } else if (typeof err === 'string') {
+ errorMessage = err;
+ } else if (typeof err === 'object' && err !== null) {
+ errorMessage = (err as any).message || (err as any).error || JSON.stringify(err);
+ } else {
+ errorMessage = 'An unknown error occurred';
+ }
+ setError(`Failed to fetch data: ${errorMessage}`);
+ setData(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [dataSource, selectedCountry, selectedIndicator, wtoApiKey, eiaApiKey, startDate, endDate]);
+
+ // Calculate stats
+ const stats: ChartStats | null = data && data.data.length > 0 ? (() => {
+ const values = data.data.map((d) => d.value);
+ const latest = values[values.length - 1];
+ const previous = values.length > 1 ? values[values.length - 2] : latest;
+ const change = previous !== 0 ? ((latest - previous) / Math.abs(previous)) * 100 : 0;
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const avg = values.reduce((a, b) => a + b, 0) / values.length;
+ return { latest, change, min, max, avg, count: values.length };
+ })() : null;
+
+ return {
+ dataSource,
+ setDataSource,
+ selectedCountry,
+ setSelectedCountry,
+ selectedIndicator,
+ setSelectedIndicator,
+ data,
+ loading,
+ error,
+ fetchData,
+ stats,
+ // Date range
+ dateRangePreset,
+ setDateRangePreset,
+ startDate,
+ endDate,
+ setStartDate,
+ setEndDate,
+ // API Keys
+ wtoApiKey,
+ setWtoApiKey,
+ eiaApiKey,
+ setEiaApiKey,
+ showApiKeyInput,
+ setShowApiKeyInput,
+ apiKeySaving,
+ saveApiKey,
+ };
+}
+
+export default useEconomicsData;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts
new file mode 100644
index 000000000..48de32245
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/hooks/useExport.ts
@@ -0,0 +1,192 @@
+// useExport Hook - Export chart and data functionality
+
+import { useState, useCallback, RefObject } from 'react';
+import { save } from '@tauri-apps/plugin-dialog';
+import { writeFile } from '@tauri-apps/plugin-fs';
+import { FINCEPT, CHART_WIDTH, CHART_HEIGHT } from '../constants';
+import type { IndicatorData, SaveNotification, DataSourceConfig } from '../types';
+
+interface UseExportReturn {
+ saveNotification: SaveNotification | null;
+ setSaveNotification: (notification: SaveNotification | null) => void;
+ exportCSV: () => void;
+ exportImage: () => Promise<void>;
+}
+
+export function useExport(
+ data: IndicatorData | null,
+ currentSourceConfig: DataSourceConfig,
+ chartContainerRef: RefObject<HTMLDivElement | null>
+): UseExportReturn {
+ const [saveNotification, setSaveNotification] = useState<SaveNotification | null>(null);
+
+ const exportCSV = useCallback(() => {
+ if (!data || data.data.length === 0) return;
+
+ const csv = [
+ `# ${data.metadata?.indicator_name || data.indicator}`,
+ `# Country: ${data.metadata?.country_name || data.country}`,
+ `# Source: ${data.metadata?.source || currentSourceConfig.name}`,
+ '',
+ 'Date,Value',
+ ...data.data.map((d) => `${d.date},${d.value}`),
+ ].join('\n');
+
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `fincept_terminal_${currentSourceConfig.id}_${data.indicator}_${data.country}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }, [data, currentSourceConfig]);
+
+ const exportImage = useCallback(async () => {
+ if (!data || data.data.length === 0 || !chartContainerRef.current) return;
+
+ try {
+ const defaultFileName = `fincept_terminal_${currentSourceConfig.id}_${data.indicator}_${data.country}_4K.png`;
+ const filePath = await save({
+ defaultPath: defaultFileName,
+ filters: [
+ { name: 'PNG Image', extensions: ['png'] },
+ { name: 'All Files', extensions: ['*'] },
+ ],
+ title: 'Save Chart Image (Ultra HD) - Fincept Terminal',
+ });
+
+ if (!filePath) return;
+
+ const svgElement = chartContainerRef.current.querySelector('svg');
+ if (!svgElement) return;
+
+ const clonedSvg = svgElement.cloneNode(true) as SVGElement;
+ const width = CHART_WIDTH;
+ const height = CHART_HEIGHT;
+ const headerHeight = 80;
+ const footerHeight = 40;
+ const totalHeight = height + headerHeight + footerHeight;
+
+ // Create wrapper SVG
+ const wrapperSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ wrapperSvg.setAttribute('width', String(width));
+ wrapperSvg.setAttribute('height', String(totalHeight));
+ wrapperSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+
+ // Background
+ const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ bg.setAttribute('width', String(width));
+ bg.setAttribute('height', String(totalHeight));
+ bg.setAttribute('fill', FINCEPT.DARK_BG);
+ wrapperSvg.appendChild(bg);
+
+ // Title
+ const title = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ title.setAttribute('x', '24');
+ title.setAttribute('y', '35');
+ title.setAttribute('fill', FINCEPT.WHITE);
+ title.setAttribute('font-family', 'IBM Plex Mono, monospace');
+ title.setAttribute('font-size', '22');
+ title.setAttribute('font-weight', '700');
+ title.textContent = data.metadata?.indicator_name || data.indicator;
+ wrapperSvg.appendChild(title);
+
+ // Subtitle
+ const subtitle = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ subtitle.setAttribute('x', '24');
+ subtitle.setAttribute('y', '60');
+ subtitle.setAttribute('fill', FINCEPT.GRAY);
+ subtitle.setAttribute('font-family', 'IBM Plex Mono, monospace');
+ subtitle.setAttribute('font-size', '14');
+ subtitle.textContent = `${data.metadata?.country_name || data.country} • Source: ${data.metadata?.source || currentSourceConfig.name}`;
+ wrapperSvg.appendChild(subtitle);
+
+ // Chart
+ const chartGroup = document.createElementNS('http://www.w3.org/2000/svg', 'g');
+ chartGroup.setAttribute('transform', `translate(0, ${headerHeight})`);
+ chartGroup.innerHTML = clonedSvg.innerHTML;
+ wrapperSvg.appendChild(chartGroup);
+
+ // Footer
+ const footer = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ footer.setAttribute('x', String(width - 24));
+ footer.setAttribute('y', String(totalHeight - 12));
+ footer.setAttribute('fill', FINCEPT.MUTED);
+ footer.setAttribute('font-family', 'IBM Plex Mono, monospace');
+ footer.setAttribute('font-size', '12');
+ footer.setAttribute('text-anchor', 'end');
+ footer.textContent = `Fincept Terminal • ${new Date().toISOString().split('T')[0]}`;
+ wrapperSvg.appendChild(footer);
+
+ // Watermark - top right corner inside chart area, white color, more visible
+ const watermark = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ watermark.setAttribute('x', String(width - 50));
+ watermark.setAttribute('y', String(headerHeight + 50));
+ watermark.setAttribute('fill', `${FINCEPT.WHITE}50`);
+ watermark.setAttribute('font-family', 'IBM Plex Mono, monospace');
+ watermark.setAttribute('font-size', '22');
+ watermark.setAttribute('font-weight', '700');
+ watermark.setAttribute('text-anchor', 'end');
+ watermark.textContent = 'FINCEPT TERMINAL';
+ wrapperSvg.appendChild(watermark);
+
+ // Convert to canvas
+ const svgData = new XMLSerializer().serializeToString(wrapperSvg);
+ const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
+ const svgUrl = URL.createObjectURL(svgBlob);
+
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
+ const img = new window.Image();
+
+ img.onload = async () => {
+ const scale = 4; // Ultra HD
+ canvas.width = width * scale;
+ canvas.height = totalHeight * scale;
+
+ if (ctx) {
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = 'high';
+ ctx.scale(scale, scale);
+ ctx.fillStyle = FINCEPT.DARK_BG;
+ ctx.fillRect(0, 0, width, totalHeight);
+ ctx.drawImage(img, 0, 0);
+
+ canvas.toBlob(async (blob) => {
+ if (blob) {
+ try {
+ const arrayBuffer = await blob.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
+ await writeFile(filePath, uint8Array);
+ setSaveNotification({ show: true, path: filePath, type: 'image' });
+ setTimeout(() => setSaveNotification(null), 5000);
+ } catch (writeErr) {
+ console.error('Failed to write image file:', writeErr);
+ }
+ }
+ }, 'image/png');
+ }
+
+ URL.revokeObjectURL(svgUrl);
+ };
+
+ img.onerror = () => {
+ console.error('Failed to load SVG for image export');
+ URL.revokeObjectURL(svgUrl);
+ };
+
+ img.src = svgUrl;
+ } catch (err) {
+ console.error('Failed to export image:', err);
+ }
+ }, [data, currentSourceConfig, chartContainerRef]);
+
+ return {
+ saveNotification,
+ setSaveNotification,
+ exportCSV,
+ exportImage,
+ };
+}
+
+export default useExport;
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/types.ts b/fincept-terminal-desktop/src/components/tabs/economics/types.ts
new file mode 100644
index 000000000..d143e1231
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/types.ts
@@ -0,0 +1,63 @@
+// Economics Tab Types
+
+export interface DataPoint {
+ date: string;
+ value: number;
+}
+
+export interface IndicatorData {
+ indicator: string;
+ country: string;
+ data: DataPoint[];
+ metadata?: {
+ indicator_name?: string;
+ country_name?: string;
+ source?: string;
+ };
+}
+
+export type DataSource = 'worldbank' | 'bis' | 'imf' | 'fred' | 'oecd' | 'wto' | 'cftc' | 'eia' | 'adb' | 'fed';
+
+export interface DataSourceConfig {
+ id: DataSource;
+ name: string; // Short name for buttons (e.g., "BIS", "IMF")
+ fullName: string; // Full name for display (e.g., "Bank for International Settlements")
+ description: string; // Brief description
+ color: string;
+ scriptName: string;
+ requiresApiKey?: boolean;
+ apiKeyName?: string;
+}
+
+export interface Indicator {
+ id: string;
+ name: string;
+ category: string;
+ code?: string; // For CFTC markets
+}
+
+export interface Country {
+ code: string;
+ name: string;
+ bis?: string;
+ imf?: string;
+ fred?: string;
+ oecd?: string;
+ wto?: string;
+ adb?: string; // ADB uses 3-letter codes like PHI, SGP, JPN
+}
+
+export interface SaveNotification {
+ show: boolean;
+ path: string;
+ type: 'image' | 'csv';
+}
+
+export interface ChartStats {
+ latest: number;
+ change: number;
+ min: number;
+ max: number;
+ avg: number;
+ count: number;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchWithPeers.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchWithPeers.tsx
index 5b22c4a9b..9e0d3b6ae 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchWithPeers.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchWithPeers.tsx
@@ -6,7 +6,8 @@ import { PeerComparisonPanel } from './components/PeerComparisonPanel';
import { SectorHeatmap, SectorPerformance } from './components/SectorHeatmap';
import { PercentileRankChart, PercentileTable } from './components/PercentileRankChart';
import { StockScreenerPanel } from './components/StockScreenerPanel';
-import { usePeerComparison } from '../../../hooks/usePeerComparison';
+import { usePeerComparison } from '@/hooks/usePeerComparison';
+import type { PeerCompany, PercentileRanking } from '@/types/peer';
interface EquityResearchWithPeersProps {
symbol: string;
@@ -45,8 +46,8 @@ export const EquityResearchWithPeers: React.FC<EquityResearchWithPeersProps> = (
];
// Extract percentile rankings from comparison data
- const percentileRankings = comparisonData?.percentileRanks
- ? Object.values(comparisonData.percentileRanks)
+ const percentileRankings: PercentileRanking[] = comparisonData?.percentileRanks
+ ? (Object.values(comparisonData.percentileRanks) as PercentileRanking[])
: [];
return (
@@ -157,7 +158,7 @@ export const EquityResearchWithPeers: React.FC<EquityResearchWithPeersProps> = (
<span className="text-white font-semibold">
{selectedPeers.length > 0
? `${(
- (selectedPeers.reduce((sum, p) => sum + p.similarityScore, 0) /
+ (selectedPeers.reduce((sum: number, p: PeerCompany) => sum + p.similarityScore, 0) /
selectedPeers.length) *
100
).toFixed(1)}%`
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx
index 8f6396fbf..debdab08c 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/PeerComparisonPanel.tsx
@@ -3,9 +3,9 @@
import React, { useState } from 'react';
import { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, Legend, ResponsiveContainer, Tooltip, ComposedChart, Bar, XAxis, YAxis, CartesianGrid } from 'recharts';
-import type { PeerCompany, CompanyMetrics, ViewMode } from '../../../../types/peer';
+import type { PeerCompany, CompanyMetrics, ViewMode, PercentileRanking } from '@/types/peer';
import { formatMetricValue, getMetricValue, getAllMetricNames } from '../../../../types/peer';
-import { usePeerComparison } from '../../../../hooks/usePeerComparison';
+import { usePeerComparison } from '@/hooks/usePeerComparison';
import { PercentileRankMini } from './PercentileRankChart';
import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';
@@ -74,18 +74,18 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
if (!comparisonData) return;
// Prepare CSV data
- const headers = ['Metric', comparisonData.target.symbol, ...comparisonData.peers.map(p => p.symbol)];
+ const headers = ['Metric', comparisonData.target.symbol, ...comparisonData.peers.map((p: CompanyMetrics) => p.symbol)];
const rows: string[][] = [];
// Add all metrics
const allMetrics = getAllMetricNames(comparisonData.target);
allMetrics.forEach(metric => {
const targetVal = getMetricValue(comparisonData.target, metric);
- const peerVals = comparisonData.peers.map(p => getMetricValue(p, metric));
+ const peerVals = comparisonData.peers.map((p: CompanyMetrics) => getMetricValue(p, metric));
const row = [
metric,
targetVal !== undefined ? targetVal.toString() : 'N/A',
- ...peerVals.map(v => v !== undefined ? v.toString() : 'N/A')
+ ...peerVals.map((v: number | undefined) => v !== undefined ? v.toString() : 'N/A')
];
rows.push(row);
});
@@ -117,13 +117,13 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
// Collect all values for this metric
const targetValue = getMetricValue(comparisonData.target, metric) || 0;
- const peerValues = comparisonData.peers.map((peer, index) => ({
+ const peerValues = comparisonData.peers.map((peer: CompanyMetrics, index: number) => ({
index,
value: getMetricValue(peer, metric) || 0,
}));
// Find min and max for normalization
- const allValues = [targetValue, ...peerValues.map(p => p.value)];
+ const allValues = [targetValue, ...peerValues.map((p: { index: number; value: number }) => p.value)];
const minVal = Math.min(...allValues);
const maxVal = Math.max(...allValues);
const range = maxVal - minVal;
@@ -135,13 +135,13 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
};
data.target = normalize(targetValue);
- peerValues.forEach(({ index, value }) => {
+ peerValues.forEach(({ index, value }: { index: number; value: number }) => {
data[`peer${index + 1}`] = normalize(value);
});
// Store original values for tooltip
data.targetOriginal = targetValue;
- peerValues.forEach(({ index, value }) => {
+ peerValues.forEach(({ index, value }: { index: number; value: number }) => {
data[`peer${index + 1}Original`] = value;
});
@@ -284,7 +284,7 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))',
gap: SPACING.MEDIUM,
}}>
- {selectedPeers.map((peer) => (
+ {selectedPeers.map((peer: PeerCompany) => (
<div
key={peer.symbol}
style={{
@@ -405,8 +405,8 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
</h4>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: SPACING.SMALL }}>
{availablePeers
- .filter((peer) => !selectedPeers.find((p) => p.symbol === peer.symbol))
- .map((peer) => (
+ .filter((peer: PeerCompany) => !selectedPeers.find((p: PeerCompany) => p.symbol === peer.symbol))
+ .map((peer: PeerCompany) => (
<button
key={peer.symbol}
onClick={() => addPeer(peer)}
@@ -488,9 +488,9 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
const pbValue = comparisonData.target.valuation.pbRatio;
const psValue = comparisonData.target.valuation.psRatio;
- const pePeers = comparisonData.peers.map(p => p.valuation.peRatio).filter(v => v !== undefined) as number[];
- const pbPeers = comparisonData.peers.map(p => p.valuation.pbRatio).filter(v => v !== undefined) as number[];
- const psPeers = comparisonData.peers.map(p => p.valuation.psRatio).filter(v => v !== undefined) as number[];
+ const pePeers = comparisonData.peers.map((p: CompanyMetrics) => p.valuation.peRatio).filter((v: number | undefined): v is number => v !== undefined);
+ const pbPeers = comparisonData.peers.map((p: CompanyMetrics) => p.valuation.pbRatio).filter((v: number | undefined): v is number => v !== undefined);
+ const psPeers = comparisonData.peers.map((p: CompanyMetrics) => p.valuation.psRatio).filter((v: number | undefined): v is number => v !== undefined);
const calcPercentile = (val: number | undefined, peers: number[]) => {
if (val === undefined || peers.length === 0) return 50;
@@ -760,7 +760,7 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
value: targetValue || 0,
fill: FINCEPT.ORANGE,
},
- ...comparisonData.peers.map((peer, index) => ({
+ ...comparisonData.peers.map((peer: CompanyMetrics, index: number) => ({
name: peer.symbol,
value: getMetricValue(peer, metric) || 0,
fill: [FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.YELLOW, FINCEPT.PURPLE, FINCEPT.BLUE][index % 5],
@@ -861,7 +861,7 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
fillOpacity={0.3}
strokeWidth={2}
/>
- {comparisonData.peers.map((peer, index) => (
+ {comparisonData.peers.map((peer: CompanyMetrics, index: number) => (
<Radar
key={peer.symbol}
name={peer.symbol}
@@ -944,7 +944,7 @@ export const PeerComparisonPanel: React.FC<PeerComparisonPanelProps> = ({ initia
<div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.LARGE }}>
{selectedMetrics.map((metric) => {
const targetValue = getMetricValue(comparisonData.target, metric);
- const peerValues = comparisonData.peers.map((p) => getMetricValue(p, metric)).filter(v => v !== undefined) as number[];
+ const peerValues = comparisonData.peers.map((p: CompanyMetrics) => getMetricValue(p, metric)).filter((v: number | undefined): v is number => v !== undefined);
if (targetValue === undefined || peerValues.length === 0) return null;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
index 516ef9a06..7e6c68ef6 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/AdvancedFeaturesPanel.tsx
@@ -1,9 +1,9 @@
// File: src/components/tabs/trading/AdvancedFeaturesPanel.tsx
// Advanced trading features panel with leverage, margin mode, and broker-specific controls
-import React, { useState } from 'react';
+import React, { useState, useEffect, useCallback } from 'react';
import { useBrokerContext } from '../../../contexts/BrokerContext';
-import { Sliders, ArrowUpDown, Settings, Zap } from 'lucide-react';
+import { Sliders, ArrowUpDown, Settings, Zap, Loader } from 'lucide-react';
const COLORS = {
ORANGE: '#ea580c',
@@ -27,14 +27,49 @@ export function AdvancedFeaturesPanel() {
const [leverage, setLeverage] = useState(1);
const [marginMode, setMarginMode] = useState<'cross' | 'isolated'>('cross');
const [isLoading, setIsLoading] = useState(false);
+ const [isFetching, setIsFetching] = useState(false);
- const { ORANGE, WHITE, GREEN, RED, GRAY, PANEL_BG, DARK_BG } = COLORS;
+ const { ORANGE, WHITE, GREEN, GRAY, PANEL_BG, DARK_BG } = COLORS;
const canSetLeverage = supports?.canSetLeverage() || false;
const canTransfer = supports?.canTransfer() || false;
const hasVaults = supports?.hasVaults() || false;
const hasSubaccounts = supports?.hasSubaccounts() || false;
- const maxLeverage = activeBrokerMetadata?.advancedFeatures.maxLeverage || 1;
+ const maxLeverage = activeBrokerMetadata?.advancedFeatures?.maxLeverage || 100;
+
+ const fetchCurrentSettings = useCallback(async () => {
+ if (!activeAdapter || !canSetLeverage) return;
+
+ setIsFetching(true);
+ try {
+ if ('fetchLeverage' in activeAdapter && typeof (activeAdapter as any).fetchLeverage === 'function') {
+ const leverageData = await (activeAdapter as any).fetchLeverage();
+ if (leverageData?.leverage) {
+ setLeverage(leverageData.leverage);
+ } else if (leverageData?.longLeverage) {
+ setLeverage(leverageData.longLeverage);
+ }
+ if (leverageData?.marginMode) {
+ setMarginMode(leverageData.marginMode);
+ }
+ }
+
+ if ('fetchMarginMode' in activeAdapter && typeof (activeAdapter as any).fetchMarginMode === 'function') {
+ const modeData = await (activeAdapter as any).fetchMarginMode();
+ if (modeData?.marginMode) {
+ setMarginMode(modeData.marginMode);
+ }
+ }
+ } catch (err) {
+ console.warn('[AdvancedFeaturesPanel] Failed to fetch current settings:', err);
+ } finally {
+ setIsFetching(false);
+ }
+ }, [activeAdapter, canSetLeverage]);
+
+ useEffect(() => {
+ fetchCurrentSettings();
+ }, [fetchCurrentSettings, activeBroker]);
// Handle leverage change
const handleLeverageChange = async (newLeverage: number) => {
@@ -101,34 +136,40 @@ export function AdvancedFeaturesPanel() {
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Sliders size={12} style={{ color: GRAY }} />
<span style={{ fontSize: '10px', color: GRAY }}>Leverage:</span>
- <input
- type="range"
- min="1"
- max={maxLeverage}
- value={leverage}
- onChange={(e) => handleLeverageChange(Number(e.target.value))}
- disabled={isLoading}
- style={{
- width: '100px',
- height: '4px',
- accentColor: ORANGE,
- cursor: isLoading ? 'not-allowed' : 'pointer',
- }}
- />
- <span style={{
- fontSize: '11px',
- fontWeight: 'bold',
- color: leverage > 1 ? ORANGE : WHITE,
- minWidth: '35px',
- textAlign: 'right',
- }}>
- {leverage}x
- </span>
+ {isFetching ? (
+ <Loader size={12} style={{ color: ORANGE, animation: 'spin 1s linear infinite' }} />
+ ) : (
+ <>
+ <input
+ type="range"
+ min="1"
+ max={maxLeverage}
+ value={leverage}
+ onChange={(e) => handleLeverageChange(Number(e.target.value))}
+ disabled={isLoading}
+ style={{
+ width: '100px',
+ height: '4px',
+ accentColor: ORANGE,
+ cursor: isLoading ? 'not-allowed' : 'pointer',
+ }}
+ />
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 'bold',
+ color: leverage > 1 ? ORANGE : WHITE,
+ minWidth: '35px',
+ textAlign: 'right',
+ }}>
+ {leverage}x
+ </span>
+ </>
+ )}
</div>
)}
{/* Margin Mode */}
- {canSetLeverage && (
+ {canSetLeverage && !isFetching && (
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<ArrowUpDown size={12} style={{ color: GRAY }} />
<span style={{ fontSize: '10px', color: GRAY }}>Margin:</span>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx
index 50d432641..495744afc 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/cross-exchange/PortfolioAggregator.tsx
@@ -4,7 +4,7 @@
*/
import React from 'react';
-import { Wallet, TrendingUp, RefreshCw, Loader, PieChart } from 'lucide-react';
+import { Wallet, RefreshCw, Loader, PieChart } from 'lucide-react';
import { useCrossExchangePortfolio } from '../hooks/useCrossExchange';
// Fincept Professional Color Palette
@@ -152,13 +152,9 @@ export function PortfolioAggregator() {
<div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
${formatCurrency(totalPortfolioValue)}
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px', color: FINCEPT.GREEN, fontSize: '11px' }}>
- <TrendingUp style={{ width: 14, height: 14 }} />
- <span>+2.45%</span>
- </div>
</div>
<div style={{ fontSize: '10px', color: FINCEPT.MUTED, marginTop: '6px' }}>
- ACROSS {aggregatedBalances.length} ASSETS
+ {aggregatedBalances.length > 0 ? `ACROSS ${aggregatedBalances.length} ASSETS` : 'NO ASSETS'}
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx
index d983d4961..397f8a163 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridConfigPanel.tsx
@@ -1,32 +1,30 @@
/**
* Grid Configuration Panel
- *
- * UI for configuring and creating new grid trading bots.
- * Works with both crypto and stock brokers.
+ * Fincept Terminal Style - Inline styles
*/
import React, { useState, useMemo, useCallback } from 'react';
import {
Grid, TrendingUp, TrendingDown, Minus, DollarSign,
- ArrowUpRight, ArrowDownRight, AlertCircle, Info, Calculator,
- ChevronDown, Check,
+ ArrowUpRight, ArrowDownRight, AlertCircle, Info, Calculator, CheckCircle,
} from 'lucide-react';
import type { GridConfig, GridType, GridDirection, GridCalculation } from '../../../../services/gridTrading/types';
import { calculateGridDetails, validateGridConfig } from '../../../../services/gridTrading';
-// Fincept-style colors
-const COLORS = {
+const FINCEPT = {
ORANGE: '#FF8800',
WHITE: '#FFFFFF',
RED: '#FF3B3B',
GREEN: '#00D66F',
GRAY: '#787878',
- DARK_BG: '#0F0F0F',
- PANEL_BG: '#1A1A1A',
- BORDER: '#2A2A2A',
- MUTED: '#4A4A4A',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
CYAN: '#00E5FF',
YELLOW: '#FFD700',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
};
interface GridConfigPanelProps {
@@ -50,7 +48,6 @@ export function GridConfigPanel({
onCreateGrid,
onCancel,
}: GridConfigPanelProps) {
- // Form state
const [upperPrice, setUpperPrice] = useState(currentPrice * 1.1);
const [lowerPrice, setLowerPrice] = useState(currentPrice * 0.9);
const [gridLevels, setGridLevels] = useState(10);
@@ -59,12 +56,34 @@ export function GridConfigPanel({
const [direction, setDirection] = useState<GridDirection>('neutral');
const [stopLoss, setStopLoss] = useState<number | undefined>(undefined);
const [takeProfit, setTakeProfit] = useState<number | undefined>(undefined);
- const [productType, setProductType] = useState('CASH'); // For stocks
-
- // Validation
+ const [productType, setProductType] = useState('CASH');
const [errors, setErrors] = useState<string[]>([]);
- // Calculate grid details
+ const inputStyle: React.CSSProperties = {
+ width: '100%',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.DARK_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ fontFamily: '"IBM Plex Mono", monospace',
+ outline: 'none',
+ };
+
+ const selectStyle: React.CSSProperties = {
+ ...inputStyle,
+ cursor: 'pointer',
+ };
+
+ const labelStyle: React.CSSProperties = {
+ display: 'block',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ };
+
const gridCalculation = useMemo<GridCalculation | null>(() => {
try {
const config: Partial<GridConfig> = {
@@ -88,12 +107,11 @@ export function GridConfigPanel({
setErrors([]);
return calculateGridDetails(config as GridConfig);
- } catch (error) {
+ } catch {
return null;
}
}, [symbol, exchange, upperPrice, lowerPrice, gridLevels, gridType, totalInvestment, direction, brokerType, brokerId]);
- // Handle form submission
const handleCreate = useCallback(() => {
const config: GridConfig = {
id: `grid_${Date.now()}`,
@@ -122,7 +140,6 @@ export function GridConfigPanel({
onCreateGrid(config);
}, [symbol, exchange, upperPrice, lowerPrice, gridLevels, gridType, totalInvestment, direction, stopLoss, takeProfit, brokerType, brokerId, productType, gridCalculation, onCreateGrid]);
- // Quick presets
const applyPreset = (preset: 'conservative' | 'moderate' | 'aggressive') => {
switch (preset) {
case 'conservative':
@@ -144,235 +161,259 @@ export function GridConfigPanel({
};
return (
- <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
- {/* Header */}
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-2">
- <Grid className="w-5 h-5 text-[#FF8800]" />
- <span className="text-white font-semibold">Grid Trading Configuration</span>
+ <div style={{ padding: '12px', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {/* Symbol & Price Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ marginBottom: '12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Grid size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>{symbol}</span>
</div>
- <div className="text-sm text-[#787878]">
- {symbol} @ {currentPrice.toFixed(2)}
+ <div style={{ fontSize: '12px', color: FINCEPT.CYAN, fontWeight: 600 }}>
+ ${currentPrice.toFixed(2)}
</div>
</div>
{/* Quick Presets */}
- <div className="mb-4">
- <div className="text-xs text-[#787878] mb-2">Quick Presets</div>
- <div className="flex gap-2">
- <button
- onClick={() => applyPreset('conservative')}
- className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#00D66F] border border-[#00D66F]/30 rounded transition-colors"
- >
- Conservative (5%)
- </button>
- <button
- onClick={() => applyPreset('moderate')}
- className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF8800] border border-[#FF8800]/30 rounded transition-colors"
- >
- Moderate (10%)
- </button>
- <button
- onClick={() => applyPreset('aggressive')}
- className="px-3 py-1.5 text-xs bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#FF3B3B]/30 rounded transition-colors"
- >
- Aggressive (20%)
- </button>
+ <div style={{ marginBottom: '12px' }}>
+ <div style={labelStyle}>QUICK PRESETS</div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ {[
+ { key: 'conservative', label: 'CONSERVATIVE (5%)', color: FINCEPT.GREEN },
+ { key: 'moderate', label: 'MODERATE (10%)', color: FINCEPT.ORANGE },
+ { key: 'aggressive', label: 'AGGRESSIVE (20%)', color: FINCEPT.RED },
+ ].map(preset => (
+ <button
+ key={preset.key}
+ onClick={() => applyPreset(preset.key as any)}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${preset.color}40`,
+ color: preset.color,
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={e => {
+ e.currentTarget.style.backgroundColor = `${preset.color}15`;
+ e.currentTarget.style.borderColor = preset.color;
+ }}
+ onMouseLeave={e => {
+ e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
+ e.currentTarget.style.borderColor = `${preset.color}40`;
+ }}
+ >
+ {preset.label}
+ </button>
+ ))}
</div>
</div>
{/* Price Range */}
- <div className="grid grid-cols-2 gap-4 mb-4">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px' }}>
<div>
- <label className="block text-xs text-[#787878] mb-1">Upper Price</label>
- <div className="relative">
+ <label style={labelStyle}>UPPER PRICE</label>
+ <div style={{ position: 'relative' }}>
<input
type="text"
inputMode="decimal"
value={upperPrice}
onChange={e => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setUpperPrice(parseFloat(v) || 0); }}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={inputStyle}
/>
- <ArrowUpRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#00D66F]" />
+ <ArrowUpRight size={12} color={FINCEPT.GREEN} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)' }} />
</div>
- <div className="text-xs text-[#787878] mt-1">
+ <div style={{ fontSize: '9px', color: FINCEPT.GREEN, marginTop: 2 }}>
+{(((upperPrice - currentPrice) / currentPrice) * 100).toFixed(1)}%
</div>
</div>
<div>
- <label className="block text-xs text-[#787878] mb-1">Lower Price</label>
- <div className="relative">
+ <label style={labelStyle}>LOWER PRICE</label>
+ <div style={{ position: 'relative' }}>
<input
type="text"
inputMode="decimal"
value={lowerPrice}
onChange={e => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setLowerPrice(parseFloat(v) || 0); }}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={inputStyle}
/>
- <ArrowDownRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#FF3B3B]" />
+ <ArrowDownRight size={12} color={FINCEPT.RED} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)' }} />
</div>
- <div className="text-xs text-[#787878] mt-1">
+ <div style={{ fontSize: '9px', color: FINCEPT.RED, marginTop: 2 }}>
{(((lowerPrice - currentPrice) / currentPrice) * 100).toFixed(1)}%
</div>
</div>
</div>
{/* Grid Settings */}
- <div className="grid grid-cols-2 gap-4 mb-4">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px' }}>
<div>
- <label className="block text-xs text-[#787878] mb-1">Grid Levels</label>
+ <label style={labelStyle}>GRID LEVELS</label>
<input
type="text"
inputMode="numeric"
value={gridLevels}
onChange={e => { const v = e.target.value; if (v === '' || /^\d+$/.test(v)) setGridLevels(Math.min(parseInt(v) || 2, 200)); }}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={inputStyle}
/>
</div>
<div>
- <label className="block text-xs text-[#787878] mb-1">Grid Type</label>
+ <label style={labelStyle}>GRID TYPE</label>
<select
value={gridType}
onChange={e => setGridType(e.target.value as GridType)}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={selectStyle}
>
- <option value="arithmetic">Arithmetic (Equal Price)</option>
- <option value="geometric">Geometric (Equal %)</option>
+ <option value="arithmetic">ARITHMETIC</option>
+ <option value="geometric">GEOMETRIC</option>
</select>
</div>
</div>
{/* Investment */}
- <div className="mb-4">
- <label className="block text-xs text-[#787878] mb-1">Total Investment</label>
- <div className="relative">
+ <div style={{ marginBottom: '12px' }}>
+ <label style={labelStyle}>TOTAL INVESTMENT</label>
+ <div style={{ position: 'relative' }}>
<input
type="text"
inputMode="decimal"
value={totalInvestment}
onChange={e => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setTotalInvestment(parseFloat(v) || 0); }}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={inputStyle}
/>
- <DollarSign className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[#787878]" />
+ <DollarSign size={12} color={FINCEPT.GRAY} style={{ position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)' }} />
</div>
- <div className="text-xs text-[#787878] mt-1">
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: 2 }}>
Available: ${availableBalance.toFixed(2)}
</div>
</div>
{/* Direction */}
- <div className="mb-4">
- <label className="block text-xs text-[#787878] mb-1">Trading Direction</label>
- <div className="grid grid-cols-3 gap-2">
- <button
- onClick={() => setDirection('long')}
- className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
- direction === 'long'
- ? 'bg-[#00D66F]/20 border border-[#00D66F] text-[#00D66F]'
- : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
- }`}
- >
- <TrendingUp className="w-4 h-4" />
- Long
- </button>
- <button
- onClick={() => setDirection('neutral')}
- className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
- direction === 'neutral'
- ? 'bg-[#FF8800]/20 border border-[#FF8800] text-[#FF8800]'
- : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
- }`}
- >
- <Minus className="w-4 h-4" />
- Neutral
- </button>
- <button
- onClick={() => setDirection('short')}
- className={`flex items-center justify-center gap-1 px-3 py-2 rounded text-sm transition-colors ${
- direction === 'short'
- ? 'bg-[#FF3B3B]/20 border border-[#FF3B3B] text-[#FF3B3B]'
- : 'bg-[#1A1A1A] border border-[#2A2A2A] text-[#787878] hover:text-white'
- }`}
- >
- <TrendingDown className="w-4 h-4" />
- Short
- </button>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={labelStyle}>TRADING DIRECTION</label>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '6px' }}>
+ {[
+ { key: 'long', label: 'LONG', icon: TrendingUp, color: FINCEPT.GREEN },
+ { key: 'neutral', label: 'NEUTRAL', icon: Minus, color: FINCEPT.ORANGE },
+ { key: 'short', label: 'SHORT', icon: TrendingDown, color: FINCEPT.RED },
+ ].map(dir => {
+ const Icon = dir.icon;
+ const isActive = direction === dir.key;
+ return (
+ <button
+ key={dir.key}
+ onClick={() => setDirection(dir.key as GridDirection)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 700,
+ backgroundColor: isActive ? `${dir.color}20` : FINCEPT.HEADER_BG,
+ border: `1px solid ${isActive ? dir.color : FINCEPT.BORDER}`,
+ color: isActive ? dir.color : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.15s',
+ }}
+ >
+ <Icon size={12} />
+ {dir.label}
+ </button>
+ );
+ })}
</div>
</div>
{/* Stop Loss / Take Profit */}
- <div className="grid grid-cols-2 gap-4 mb-4">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px' }}>
<div>
- <label className="block text-xs text-[#787878] mb-1">Stop Loss (Optional)</label>
+ <label style={labelStyle}>STOP LOSS (OPTIONAL)</label>
<input
type="text"
inputMode="decimal"
value={stopLoss || ''}
onChange={e => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setStopLoss(v ? parseFloat(v) : undefined); }}
placeholder={`< ${lowerPrice.toFixed(2)}`}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF3B3B] focus:outline-none placeholder-[#4A4A4A]"
+ style={{ ...inputStyle, borderColor: stopLoss ? FINCEPT.RED : FINCEPT.BORDER }}
/>
</div>
<div>
- <label className="block text-xs text-[#787878] mb-1">Take Profit (Optional)</label>
+ <label style={labelStyle}>TAKE PROFIT (OPTIONAL)</label>
<input
type="text"
inputMode="decimal"
value={takeProfit || ''}
onChange={e => { const v = e.target.value; if (v === '' || /^\d*\.?\d*$/.test(v)) setTakeProfit(v ? parseFloat(v) : undefined); }}
placeholder={`> ${upperPrice.toFixed(2)}`}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#00D66F] focus:outline-none placeholder-[#4A4A4A]"
+ style={{ ...inputStyle, borderColor: takeProfit ? FINCEPT.GREEN : FINCEPT.BORDER }}
/>
</div>
</div>
- {/* Stock-specific: Product Type */}
+ {/* Stock Product Type */}
{brokerType === 'stock' && (
- <div className="mb-4">
- <label className="block text-xs text-[#787878] mb-1">Product Type</label>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={labelStyle}>PRODUCT TYPE</label>
<select
value={productType}
onChange={e => setProductType(e.target.value)}
- className="w-full bg-[#1A1A1A] border border-[#2A2A2A] rounded px-3 py-2 text-white text-sm focus:border-[#FF8800] focus:outline-none"
+ style={selectStyle}
>
- <option value="CASH">Cash (Delivery)</option>
- <option value="INTRADAY">Intraday (MIS)</option>
- <option value="MARGIN">Margin</option>
+ <option value="CASH">CASH (DELIVERY)</option>
+ <option value="INTRADAY">INTRADAY (MIS)</option>
+ <option value="MARGIN">MARGIN</option>
</select>
</div>
)}
- {/* Grid Calculation Summary */}
+ {/* Grid Summary */}
{gridCalculation && (
- <div className="bg-[#1A1A1A] rounded p-3 mb-4">
- <div className="flex items-center gap-2 mb-2">
- <Calculator className="w-4 h-4 text-[#00E5FF]" />
- <span className="text-sm text-white">Grid Summary</span>
+ <div style={{
+ padding: '10px 12px',
+ backgroundColor: `${FINCEPT.CYAN}10`,
+ border: `1px solid ${FINCEPT.CYAN}30`,
+ marginBottom: '12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: 8 }}>
+ <Calculator size={12} color={FINCEPT.CYAN} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE }}>GRID SUMMARY</span>
</div>
- <div className="grid grid-cols-2 gap-2 text-xs">
- <div className="flex justify-between">
- <span className="text-[#787878]">Grid Spacing:</span>
- <span className="text-white">
- {gridType === 'arithmetic'
- ? `$${gridCalculation.gridSpacing.toFixed(2)}`
- : `${gridCalculation.gridSpacing.toFixed(2)}%`}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', fontSize: '10px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Grid Spacing:</span>
+ <span style={{ color: FINCEPT.WHITE }}>
+ {gridType === 'arithmetic' ? `$${gridCalculation.gridSpacing.toFixed(2)}` : `${gridCalculation.gridSpacing.toFixed(2)}%`}
</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Qty/Level:</span>
- <span className="text-white">{gridCalculation.quantityPerLevel.toFixed(4)}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Qty/Level:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{gridCalculation.quantityPerLevel.toFixed(4)}</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Total Qty:</span>
- <span className="text-white">{gridCalculation.totalQuantity.toFixed(4)}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Total Qty:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{gridCalculation.totalQuantity.toFixed(4)}</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Break-even:</span>
- <span className="text-white">${gridCalculation.breakEvenPrice.toFixed(2)}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Break-even:</span>
+ <span style={{ color: FINCEPT.WHITE }}>${gridCalculation.breakEvenPrice.toFixed(2)}</span>
</div>
- <div className="flex justify-between col-span-2">
- <span className="text-[#787878]">Potential Profit/Cycle:</span>
- <span className="text-[#00D66F]">${gridCalculation.potentialProfit.toFixed(2)}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', gridColumn: 'span 2' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Potential Profit/Cycle:</span>
+ <span style={{ color: FINCEPT.GREEN, fontWeight: 600 }}>${gridCalculation.potentialProfit.toFixed(2)}</span>
</div>
</div>
</div>
@@ -380,12 +421,17 @@ export function GridConfigPanel({
{/* Errors */}
{errors.length > 0 && (
- <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3 mb-4">
- <div className="flex items-center gap-2 text-[#FF3B3B] text-sm mb-1">
- <AlertCircle className="w-4 h-4" />
- Validation Errors
+ <div style={{
+ padding: '10px 12px',
+ backgroundColor: `${FINCEPT.RED}15`,
+ border: `1px solid ${FINCEPT.RED}30`,
+ marginBottom: '12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: 4 }}>
+ <AlertCircle size={12} color={FINCEPT.RED} />
+ <span style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.RED }}>VALIDATION ERRORS</span>
</div>
- <ul className="text-xs text-[#FF3B3B] list-disc list-inside">
+ <ul style={{ margin: 0, paddingLeft: 16, fontSize: '9px', color: FINCEPT.RED }}>
{errors.map((error, i) => (
<li key={i}>{error}</li>
))}
@@ -394,29 +440,67 @@ export function GridConfigPanel({
)}
{/* Actions */}
- <div className="flex gap-2">
+ <div style={{ display: 'flex', gap: '8px' }}>
{onCancel && (
<button
onClick={onCancel}
- className="flex-1 py-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#787878] hover:text-white rounded transition-colors text-sm"
+ style={{
+ flex: 1,
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 700,
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={e => e.currentTarget.style.color = FINCEPT.WHITE}
+ onMouseLeave={e => e.currentTarget.style.color = FINCEPT.GRAY}
>
- Cancel
+ CANCEL
</button>
)}
<button
onClick={handleCreate}
disabled={errors.length > 0 || !gridCalculation}
- className="flex-1 py-2 bg-[#FF8800] hover:bg-[#FF9900] disabled:bg-[#4A4A4A] disabled:cursor-not-allowed text-black font-semibold rounded transition-colors text-sm flex items-center justify-center gap-2"
+ style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ padding: '10px',
+ fontSize: '11px',
+ fontWeight: 700,
+ backgroundColor: errors.length > 0 || !gridCalculation ? FINCEPT.MUTED : FINCEPT.ORANGE,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ cursor: errors.length > 0 || !gridCalculation ? 'not-allowed' : 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.15s',
+ }}
>
- <Grid className="w-4 h-4" />
- Create Grid
+ <CheckCircle size={12} />
+ CREATE GRID
</button>
</div>
{/* Info */}
- <div className="mt-4 flex items-start gap-2 text-xs text-[#787878]">
- <Info className="w-4 h-4 flex-shrink-0 mt-0.5" />
- <p>
+ <div style={{
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '6px',
+ marginTop: '12px',
+ padding: '10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ fontSize: '9px',
+ color: FINCEPT.MUTED,
+ lineHeight: 1.4,
+ }}>
+ <Info size={12} style={{ flexShrink: 0, marginTop: 1 }} />
+ <p style={{ margin: 0 }}>
Grid trading places buy orders below and sell orders above the current price.
When orders fill, opposite orders are placed to capture profits from price oscillations.
</p>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx
index cb5de2896..89f624f88 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridStatusPanel.tsx
@@ -1,16 +1,31 @@
/**
* Grid Status Panel
- *
- * Shows grid status, statistics, and controls for managing running grids.
+ * Fincept Terminal Style - Inline styles
*/
import React from 'react';
import {
Grid, Play, Pause, Square, Trash2, TrendingUp, TrendingDown,
- DollarSign, Activity, BarChart3, Clock, AlertCircle, RefreshCw,
+ DollarSign, Activity, BarChart3, Clock, AlertCircle,
} from 'lucide-react';
import type { GridState } from '../../../../services/gridTrading/types';
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+};
+
interface GridStatusPanelProps {
grid: GridState;
onStart: () => void;
@@ -28,24 +43,20 @@ export function GridStatusPanel({
}: GridStatusPanelProps) {
const { config, status, currentPrice, levels } = grid;
- // Calculate statistics
const openOrders = levels.filter(l => l.status === 'open').length;
const filledOrders = levels.filter(l => l.status === 'filled').length;
const pendingOrders = levels.filter(l => l.status === 'pending').length;
const buyOrders = levels.filter(l => l.side === 'buy' && l.status === 'open').length;
const sellOrders = levels.filter(l => l.side === 'sell' && l.status === 'open').length;
-
- // Price position in grid
const pricePosition = ((currentPrice - config.lowerPrice) / (config.upperPrice - config.lowerPrice)) * 100;
- // Status colors
const getStatusColor = () => {
switch (status) {
- case 'running': return '#00D66F';
- case 'paused': return '#FFD700';
- case 'stopped': return '#787878';
- case 'error': return '#FF3B3B';
- default: return '#787878';
+ case 'running': return FINCEPT.GREEN;
+ case 'paused': return FINCEPT.YELLOW;
+ case 'stopped': return FINCEPT.GRAY;
+ case 'error': return FINCEPT.RED;
+ default: return FINCEPT.GRAY;
}
};
@@ -62,228 +73,293 @@ export function GridStatusPanel({
};
const runningTime = grid.startedAt ? Date.now() - grid.startedAt : 0;
+ const statusColor = getStatusColor();
+
+ const btnStyle: React.CSSProperties = {
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ padding: '8px 12px',
+ fontSize: '10px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ border: 'none',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ };
+
+ const statBoxStyle: React.CSSProperties = {
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ };
return (
- <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
+ <div style={{ fontFamily: '"IBM Plex Mono", monospace' }}>
{/* Header */}
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-2">
- <Grid className="w-5 h-5 text-[#FF8800]" />
- <span className="text-white font-semibold">{config.symbol}</span>
- <div
- className="px-2 py-0.5 rounded text-xs font-medium"
- style={{
- backgroundColor: `${getStatusColor()}20`,
- color: getStatusColor(),
- }}
- >
- {status.toUpperCase()}
- </div>
- </div>
- <div className="text-xs text-[#787878]">
- {config.brokerId}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ marginBottom: '10px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Grid size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>{config.symbol}</span>
+ <span style={{
+ padding: '2px 8px',
+ backgroundColor: `${statusColor}20`,
+ color: statusColor,
+ fontSize: '9px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ }}>
+ {status}
+ </span>
</div>
+ <span style={{ fontSize: '9px', color: FINCEPT.MUTED }}>{config.brokerId}</span>
</div>
{/* Controls */}
- <div className="flex gap-2 mb-4">
+ <div style={{ display: 'flex', gap: '6px', marginBottom: '10px' }}>
{(status === 'draft' || status === 'paused') && (
- <button
- onClick={onStart}
- className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#00D66F] hover:bg-[#00E57F] text-black font-semibold rounded transition-colors"
- >
- <Play className="w-4 h-4" />
- {status === 'draft' ? 'Start' : 'Resume'}
+ <button onClick={onStart} style={{ ...btnStyle, backgroundColor: FINCEPT.GREEN, color: FINCEPT.DARK_BG }}>
+ <Play size={12} />
+ {status === 'draft' ? 'START' : 'RESUME'}
</button>
)}
{status === 'running' && (
- <button
- onClick={onPause}
- className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#FFD700] hover:bg-[#FFE030] text-black font-semibold rounded transition-colors"
- >
- <Pause className="w-4 h-4" />
- Pause
+ <button onClick={onPause} style={{ ...btnStyle, backgroundColor: FINCEPT.YELLOW, color: FINCEPT.DARK_BG }}>
+ <Pause size={12} />
+ PAUSE
</button>
)}
{(status === 'running' || status === 'paused') && (
- <button
- onClick={onStop}
- className="flex-1 flex items-center justify-center gap-1 py-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#FF3B3B]/30 rounded transition-colors"
- >
- <Square className="w-4 h-4" />
- Stop
+ <button onClick={onStop} style={{
+ ...btnStyle,
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.RED,
+ border: `1px solid ${FINCEPT.RED}40`,
+ }}>
+ <Square size={12} />
+ STOP
</button>
)}
- <button
- onClick={onDelete}
- className="p-2 bg-[#1A1A1A] hover:bg-[#2A2A2A] text-[#FF3B3B] border border-[#2A2A2A] hover:border-[#FF3B3B]/30 rounded transition-colors"
- >
- <Trash2 className="w-4 h-4" />
+ <button onClick={onDelete} style={{
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.RED,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ }}>
+ <Trash2 size={12} />
</button>
</div>
{/* Price Info */}
- <div className="bg-[#1A1A1A] rounded p-3 mb-4">
- <div className="flex items-center justify-between mb-2">
- <span className="text-xs text-[#787878]">Current Price</span>
- <span className="text-lg text-white font-mono">${currentPrice.toFixed(2)}</span>
+ <div style={{ ...statBoxStyle, marginBottom: '10px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textTransform: 'uppercase' }}>Current Price</span>
+ <span style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.WHITE, fontFamily: 'monospace' }}>
+ ${currentPrice.toFixed(2)}
+ </span>
</div>
{/* Price position bar */}
- <div className="relative h-2 bg-[#2A2A2A] rounded-full overflow-hidden">
- <div
- className="absolute top-0 left-0 h-full bg-gradient-to-r from-[#FF3B3B] via-[#FFD700] to-[#00D66F]"
- style={{ width: '100%' }}
- />
- <div
- className="absolute top-0 h-full w-1 bg-white shadow-lg"
- style={{ left: `${Math.max(0, Math.min(100, pricePosition))}%`, transform: 'translateX(-50%)' }}
- />
+ <div style={{
+ position: 'relative',
+ height: 6,
+ backgroundColor: FINCEPT.BORDER,
+ borderRadius: 3,
+ overflow: 'hidden',
+ }}>
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ height: '100%',
+ width: '100%',
+ background: `linear-gradient(90deg, ${FINCEPT.RED}, ${FINCEPT.YELLOW}, ${FINCEPT.GREEN})`,
+ }} />
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ height: '100%',
+ width: 3,
+ backgroundColor: FINCEPT.WHITE,
+ left: `${Math.max(0, Math.min(100, pricePosition))}%`,
+ transform: 'translateX(-50%)',
+ boxShadow: '0 0 4px rgba(255,255,255,0.5)',
+ }} />
</div>
- <div className="flex justify-between mt-1 text-xs text-[#787878]">
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, fontSize: '9px', color: FINCEPT.MUTED }}>
<span>${config.lowerPrice.toFixed(2)}</span>
<span>${config.upperPrice.toFixed(2)}</span>
</div>
</div>
{/* Statistics Grid */}
- <div className="grid grid-cols-2 gap-3 mb-4">
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>
{/* P&L */}
- <div className="bg-[#1A1A1A] rounded p-3">
- <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
- <DollarSign className="w-3 h-3" />
- Total P&L
+ <div style={statBoxStyle}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: 4 }}>
+ <DollarSign size={10} />
+ TOTAL P&L
</div>
- <div className={`text-lg font-mono ${grid.totalPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}`}>
+ <div style={{
+ fontSize: '16px',
+ fontWeight: 700,
+ fontFamily: 'monospace',
+ color: grid.totalPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED,
+ }}>
{grid.totalPnl >= 0 ? '+' : ''}{grid.totalPnl.toFixed(2)}
</div>
- <div className="text-xs text-[#787878]">
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>
Realized: {grid.realizedPnl >= 0 ? '+' : ''}{grid.realizedPnl.toFixed(2)}
</div>
</div>
{/* Grid Profit */}
- <div className="bg-[#1A1A1A] rounded p-3">
- <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
- <BarChart3 className="w-3 h-3" />
- Grid Profit
+ <div style={statBoxStyle}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: 4 }}>
+ <BarChart3 size={10} />
+ GRID PROFIT
</div>
- <div className="text-lg font-mono text-[#00D66F]">
+ <div style={{ fontSize: '16px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.GREEN }}>
+{grid.gridProfit.toFixed(2)}
</div>
- <div className="text-xs text-[#787878]">
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>
{grid.totalBuys + grid.totalSells} trades
</div>
</div>
{/* Position */}
- <div className="bg-[#1A1A1A] rounded p-3">
- <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
- <Activity className="w-3 h-3" />
- Position
+ <div style={statBoxStyle}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: 4 }}>
+ <Activity size={10} />
+ POSITION
</div>
- <div className={`text-lg font-mono ${
- grid.currentPosition > 0 ? 'text-[#00D66F]' :
- grid.currentPosition < 0 ? 'text-[#FF3B3B]' : 'text-white'
- }`}>
+ <div style={{
+ fontSize: '16px',
+ fontWeight: 700,
+ fontFamily: 'monospace',
+ color: grid.currentPosition > 0 ? FINCEPT.GREEN : grid.currentPosition < 0 ? FINCEPT.RED : FINCEPT.WHITE,
+ }}>
{grid.currentPosition > 0 ? '+' : ''}{grid.currentPosition.toFixed(4)}
</div>
- <div className="text-xs text-[#787878]">
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>
Avg: ${grid.averageEntryPrice.toFixed(2)}
</div>
</div>
{/* Running Time */}
- <div className="bg-[#1A1A1A] rounded p-3">
- <div className="flex items-center gap-1 text-xs text-[#787878] mb-1">
- <Clock className="w-3 h-3" />
- Running Time
+ <div style={statBoxStyle}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: 4 }}>
+ <Clock size={10} />
+ RUNNING TIME
</div>
- <div className="text-lg font-mono text-white">
+ <div style={{ fontSize: '16px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.WHITE }}>
{formatDuration(runningTime)}
</div>
- <div className="text-xs text-[#787878]">
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED }}>
Started: {grid.startedAt ? new Date(grid.startedAt).toLocaleDateString() : 'N/A'}
</div>
</div>
</div>
{/* Order Status */}
- <div className="bg-[#1A1A1A] rounded p-3 mb-4">
- <div className="text-xs text-[#787878] mb-2">Order Status</div>
- <div className="grid grid-cols-4 gap-2 text-center">
+ <div style={{ ...statBoxStyle, marginBottom: '10px' }}>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, textTransform: 'uppercase', marginBottom: 8 }}>Order Status</div>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 4, textAlign: 'center' }}>
<div>
- <div className="text-lg font-mono text-[#00E5FF]">{openOrders}</div>
- <div className="text-xs text-[#787878]">Open</div>
+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.CYAN }}>{openOrders}</div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>OPEN</div>
</div>
<div>
- <div className="text-lg font-mono text-[#00D66F]">{filledOrders}</div>
- <div className="text-xs text-[#787878]">Filled</div>
+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.GREEN }}>{filledOrders}</div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>FILLED</div>
</div>
<div>
- <div className="text-lg font-mono text-[#787878]">{pendingOrders}</div>
- <div className="text-xs text-[#787878]">Pending</div>
+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.GRAY }}>{pendingOrders}</div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>PENDING</div>
</div>
<div>
- <div className="text-lg font-mono text-white">{config.gridLevels}</div>
- <div className="text-xs text-[#787878]">Total</div>
+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: 'monospace', color: FINCEPT.WHITE }}>{config.gridLevels}</div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED }}>TOTAL</div>
</div>
</div>
- <div className="flex justify-center gap-4 mt-2 text-xs">
- <div className="flex items-center gap-1">
- <TrendingUp className="w-3 h-3 text-[#00D66F]" />
- <span className="text-[#787878]">{buyOrders} buys open</span>
+ <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginTop: 8, fontSize: '9px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
+ <TrendingUp size={10} color={FINCEPT.GREEN} />
+ <span style={{ color: FINCEPT.MUTED }}>{buyOrders} buys open</span>
</div>
- <div className="flex items-center gap-1">
- <TrendingDown className="w-3 h-3 text-[#FF3B3B]" />
- <span className="text-[#787878]">{sellOrders} sells open</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
+ <TrendingDown size={10} color={FINCEPT.RED} />
+ <span style={{ color: FINCEPT.MUTED }}>{sellOrders} sells open</span>
</div>
</div>
</div>
{/* Error Display */}
{grid.lastError && (
- <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3">
- <div className="flex items-center gap-2 text-[#FF3B3B] text-sm">
- <AlertCircle className="w-4 h-4" />
- Last Error
+ <div style={{
+ padding: '10px 12px',
+ backgroundColor: `${FINCEPT.RED}15`,
+ border: `1px solid ${FINCEPT.RED}30`,
+ marginBottom: '10px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: '10px', color: FINCEPT.RED, marginBottom: 4 }}>
+ <AlertCircle size={12} />
+ LAST ERROR
</div>
- <div className="text-xs text-[#FF3B3B] mt-1">{grid.lastError}</div>
- <div className="text-xs text-[#787878] mt-1">
+ <div style={{ fontSize: '9px', color: FINCEPT.RED }}>{grid.lastError}</div>
+ <div style={{ fontSize: '9px', color: FINCEPT.MUTED, marginTop: 4 }}>
Total errors: {grid.errorCount}
</div>
</div>
)}
{/* Grid Config Summary */}
- <div className="mt-4 pt-4 border-t border-[#2A2A2A]">
- <div className="text-xs text-[#787878] mb-2">Grid Configuration</div>
- <div className="grid grid-cols-2 gap-1 text-xs">
- <div className="flex justify-between">
- <span className="text-[#787878]">Type:</span>
- <span className="text-white capitalize">{config.gridType}</span>
+ <div style={{
+ padding: '10px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ }}>
+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, textTransform: 'uppercase', marginBottom: 8 }}>Grid Configuration</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 12px', fontSize: '10px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Type:</span>
+ <span style={{ color: FINCEPT.WHITE, textTransform: 'capitalize' }}>{config.gridType}</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Direction:</span>
- <span className="text-white capitalize">{config.direction}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Direction:</span>
+ <span style={{ color: FINCEPT.WHITE, textTransform: 'capitalize' }}>{config.direction}</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Investment:</span>
- <span className="text-white">${config.totalInvestment}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Investment:</span>
+ <span style={{ color: FINCEPT.WHITE }}>${config.totalInvestment}</span>
</div>
- <div className="flex justify-between">
- <span className="text-[#787878]">Qty/Grid:</span>
- <span className="text-white">{config.quantityPerGrid}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Qty/Grid:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{config.quantityPerGrid}</span>
</div>
{config.stopLoss && (
- <div className="flex justify-between">
- <span className="text-[#787878]">Stop Loss:</span>
- <span className="text-[#FF3B3B]">${config.stopLoss}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Stop Loss:</span>
+ <span style={{ color: FINCEPT.RED }}>${config.stopLoss}</span>
</div>
)}
{config.takeProfit && (
- <div className="flex justify-between">
- <span className="text-[#787878]">Take Profit:</span>
- <span className="text-[#00D66F]">${config.takeProfit}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: FINCEPT.MUTED }}>Take Profit:</span>
+ <span style={{ color: FINCEPT.GREEN }}>${config.takeProfit}</span>
</div>
)}
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx
index 525e10d0f..235f1e6c4 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/grid-trading/GridTradingPanel.tsx
@@ -1,12 +1,10 @@
/**
* Grid Trading Panel
- *
- * Main component for grid trading that integrates all grid trading sub-components.
- * Can be embedded in TradingTab or used standalone.
+ * Fincept Terminal Style - Inline styles matching the trading UI design
*/
import React, { useState, useEffect, useCallback } from 'react';
-import { Grid, Plus, List, BarChart3, Settings, X, ChevronDown, AlertCircle } from 'lucide-react';
+import { Grid, Plus, ChevronLeft, AlertCircle, X, Loader, RefreshCw } from 'lucide-react';
import { GridConfigPanel } from './GridConfigPanel';
import { GridStatusPanel } from './GridStatusPanel';
import { GridVisualization } from './GridVisualization';
@@ -23,24 +21,31 @@ import type {
import type { IExchangeAdapter } from '../../../../brokers/crypto/types';
import type { IStockBrokerAdapter } from '../../../../brokers/stocks/types';
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A',
+};
+
interface GridTradingPanelProps {
- // Current symbol/price context
symbol: string;
exchange?: string;
currentPrice: number;
-
- // Broker info
brokerType: 'crypto' | 'stock';
brokerId: string;
-
- // Broker adapters - pass one of these
cryptoAdapter?: IExchangeAdapter;
stockAdapter?: IStockBrokerAdapter;
-
- // Layout
variant?: 'compact' | 'full';
-
- // Callbacks
onGridCreated?: (grid: GridState) => void;
onGridStarted?: (gridId: string) => void;
onGridStopped?: (gridId: string) => void;
@@ -70,7 +75,6 @@ export function GridTradingPanel({
const service = getGridTradingService();
- // Register adapter on mount
useEffect(() => {
let adapter: IGridBrokerAdapter | null = null;
@@ -82,8 +86,6 @@ export function GridTradingPanel({
if (adapter) {
service.registerAdapter(adapter);
-
- // Fetch available balance
adapter.getAvailableBalance().then(balance => {
setAvailableBalance(balance);
}).catch(console.error);
@@ -99,7 +101,6 @@ export function GridTradingPanel({
};
}, [brokerType, cryptoAdapter, stockAdapter, service]);
- // Load grids for this broker
useEffect(() => {
const loadGrids = () => {
const allGrids = service.getGridsForBroker(brokerId);
@@ -107,8 +108,6 @@ export function GridTradingPanel({
};
loadGrids();
-
- // Subscribe to updates
const unsubscribe = service.onGridUpdate((grid) => {
if (grid.config.brokerId === brokerId) {
loadGrids();
@@ -118,10 +117,8 @@ export function GridTradingPanel({
return unsubscribe;
}, [brokerId, service]);
- // Get selected grid
const selectedGrid = selectedGridId ? grids.find(g => g.config.id === selectedGridId) : null;
- // Handlers
const handleCreateGrid = useCallback(async (config: GridConfig) => {
setIsLoading(true);
setError(null);
@@ -186,115 +183,212 @@ export function GridTradingPanel({
}
}, [service, brokerId, selectedGridId]);
- // Render list view
+ const btnStyle: React.CSSProperties = {
+ padding: '6px 12px',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: 'transparent',
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ transition: 'all 0.15s',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ };
+
const renderList = () => (
- <div className="space-y-3">
- {/* Header */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Grid className="w-5 h-5 text-[#FF8800]" />
- <span className="text-white font-semibold">Grid Bots</span>
- <span className="text-xs text-[#787878]">({grids.length})</span>
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px 12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Grid size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>
+ GRID BOTS
+ </span>
+ <span style={{ fontSize: '10px', color: FINCEPT.MUTED }}>({grids.length})</span>
</div>
- <button
- onClick={() => setView('create')}
- className="flex items-center gap-1 px-3 py-1.5 bg-[#FF8800] hover:bg-[#FF9900] text-black text-sm font-semibold rounded transition-colors"
- >
- <Plus className="w-4 h-4" />
- New Grid
- </button>
- </div>
-
- {/* Grid list */}
- {grids.length === 0 ? (
- <div className="bg-[#1A1A1A] rounded-lg p-8 text-center">
- <Grid className="w-12 h-12 text-[#4A4A4A] mx-auto mb-3" />
- <div className="text-white mb-1">No Grid Bots</div>
- <div className="text-sm text-[#787878] mb-4">
- Create your first grid trading bot to automate trading
- </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
<button
onClick={() => setView('create')}
- className="px-4 py-2 bg-[#FF8800] hover:bg-[#FF9900] text-black font-semibold rounded transition-colors"
+ style={{
+ ...btnStyle,
+ backgroundColor: FINCEPT.GREEN,
+ color: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.GREEN,
+ }}
+ >
+ <Plus size={12} />
+ NEW GRID
+ </button>
+ <button
+ onClick={() => setGrids(service.getGridsForBroker(brokerId))}
+ style={{ ...btnStyle, padding: '6px 8px' }}
+ title="Refresh"
>
- Create Grid Bot
+ <RefreshCw size={12} />
</button>
</div>
- ) : (
- <div className="space-y-2">
- {grids.map(grid => (
- <div
- key={grid.config.id}
- onClick={() => {
- setSelectedGridId(grid.config.id);
- setView('details');
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {grids.length === 0 ? (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '40px 20px',
+ textAlign: 'center',
+ }}>
+ <Grid size={40} color={FINCEPT.BORDER} style={{ marginBottom: 12 }} />
+ <div style={{ fontSize: '12px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: 4 }}>
+ NO GRID BOTS
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: 16 }}>
+ Create your first grid trading bot to automate trading
+ </div>
+ <button
+ onClick={() => setView('create')}
+ style={{
+ ...btnStyle,
+ backgroundColor: FINCEPT.ORANGE,
+ color: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.ORANGE,
+ padding: '8px 16px',
}}
- className="bg-[#1A1A1A] hover:bg-[#2A2A2A] border border-[#2A2A2A] rounded-lg p-3 cursor-pointer transition-colors"
>
- <div className="flex items-center justify-between mb-2">
- <div className="flex items-center gap-2">
- <span className="text-white font-medium">{grid.config.symbol}</span>
- <div
- className="px-2 py-0.5 rounded text-xs font-medium"
- style={{
- backgroundColor: grid.status === 'running' ? '#00D66F20' : '#78787820',
- color: grid.status === 'running' ? '#00D66F' : '#787878',
- }}
- >
- {grid.status.toUpperCase()}
+ <Grid size={12} />
+ CREATE GRID BOT
+ </button>
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {grids.map(grid => {
+ const statusColor = grid.status === 'running' ? FINCEPT.GREEN :
+ grid.status === 'paused' ? FINCEPT.YELLOW :
+ grid.status === 'error' ? FINCEPT.RED : FINCEPT.GRAY;
+ return (
+ <div
+ key={grid.config.id}
+ onClick={() => {
+ setSelectedGridId(grid.config.id);
+ setView('details');
+ }}
+ style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={e => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }}
+ onMouseLeave={e => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>
+ {grid.config.symbol}
+ </span>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: `${statusColor}20`,
+ color: statusColor,
+ fontSize: '9px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ }}>
+ {grid.status}
+ </span>
+ </div>
+ <ChevronLeft size={14} color={FINCEPT.GRAY} style={{ transform: 'rotate(180deg)' }} />
</div>
- </div>
- <ChevronDown className="w-4 h-4 text-[#787878] -rotate-90" />
- </div>
- <div className="grid grid-cols-3 gap-2 text-xs">
- <div>
- <div className="text-[#787878]">P&L</div>
- <div className={grid.totalPnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}>
- {grid.totalPnl >= 0 ? '+' : ''}{grid.totalPnl.toFixed(2)}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px', fontSize: '10px' }}>
+ <div>
+ <div style={{ color: FINCEPT.GRAY, marginBottom: 2 }}>P&L</div>
+ <div style={{ color: grid.totalPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED, fontWeight: 600 }}>
+ {grid.totalPnl >= 0 ? '+' : ''}{grid.totalPnl.toFixed(2)}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: FINCEPT.GRAY, marginBottom: 2 }}>TRADES</div>
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>
+ {grid.totalBuys + grid.totalSells}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: FINCEPT.GRAY, marginBottom: 2 }}>LEVELS</div>
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>
+ {grid.config.gridLevels}
+ </div>
+ </div>
</div>
</div>
- <div>
- <div className="text-[#787878]">Trades</div>
- <div className="text-white">{grid.totalBuys + grid.totalSells}</div>
- </div>
- <div>
- <div className="text-[#787878]">Levels</div>
- <div className="text-white">{grid.config.gridLevels}</div>
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
+ );
+ })}
+ </div>
+ )}
+ </div>
</div>
);
- // Render create view
const renderCreate = () => (
- <div>
- <div className="flex items-center gap-2 mb-4">
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '8px 12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}>
<button
onClick={() => setView('list')}
- className="p-1 hover:bg-[#2A2A2A] rounded transition-colors"
+ style={{
+ background: 'none',
+ border: 'none',
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ }}
>
- <X className="w-5 h-5 text-[#787878]" />
+ <ChevronLeft size={16} />
</button>
- <span className="text-white font-semibold">Create Grid Bot</span>
+ <Grid size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>
+ CREATE GRID BOT
+ </span>
+ </div>
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ <GridConfigPanel
+ symbol={symbol}
+ exchange={exchange}
+ currentPrice={currentPrice}
+ brokerType={brokerType}
+ brokerId={brokerId}
+ availableBalance={availableBalance}
+ onCreateGrid={handleCreateGrid}
+ onCancel={() => setView('list')}
+ />
</div>
- <GridConfigPanel
- symbol={symbol}
- exchange={exchange}
- currentPrice={currentPrice}
- brokerType={brokerType}
- brokerId={brokerId}
- availableBalance={availableBalance}
- onCreateGrid={handleCreateGrid}
- onCancel={() => setView('list')}
- />
</div>
);
- // Render details view
const renderDetails = () => {
if (!selectedGrid) {
setView('list');
@@ -302,30 +396,57 @@ export function GridTradingPanel({
}
return (
- <div>
- <div className="flex items-center gap-2 mb-4">
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '8px 12px',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ }}>
<button
onClick={() => {
setSelectedGridId(null);
setView('list');
}}
- className="p-1 hover:bg-[#2A2A2A] rounded transition-colors"
+ style={{
+ background: 'none',
+ border: 'none',
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ }}
>
- <X className="w-5 h-5 text-[#787878]" />
+ <ChevronLeft size={16} />
</button>
- <span className="text-white font-semibold">Grid Details</span>
+ <Grid size={14} color={FINCEPT.ORANGE} />
+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>
+ {selectedGrid.config.symbol} GRID
+ </span>
</div>
-
- <div className={variant === 'full' ? 'grid grid-cols-2 gap-4' : 'space-y-4'}>
- <GridStatusPanel
- grid={selectedGrid}
- onStart={() => handleStartGrid(selectedGrid.config.id)}
- onPause={() => handlePauseGrid(selectedGrid.config.id)}
- onStop={() => handleStopGrid(selectedGrid.config.id)}
- onDelete={() => handleDeleteGrid(selectedGrid.config.id)}
- />
- {variant === 'full' && (
- <GridVisualization grid={selectedGrid} height={400} />
+ <div style={{ flex: 1, overflow: 'auto', padding: variant === 'full' ? '12px' : '0' }}>
+ {variant === 'full' ? (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <GridStatusPanel
+ grid={selectedGrid}
+ onStart={() => handleStartGrid(selectedGrid.config.id)}
+ onPause={() => handlePauseGrid(selectedGrid.config.id)}
+ onStop={() => handleStopGrid(selectedGrid.config.id)}
+ onDelete={() => handleDeleteGrid(selectedGrid.config.id)}
+ />
+ <GridVisualization grid={selectedGrid} height={400} />
+ </div>
+ ) : (
+ <GridStatusPanel
+ grid={selectedGrid}
+ onStart={() => handleStartGrid(selectedGrid.config.id)}
+ onPause={() => handlePauseGrid(selectedGrid.config.id)}
+ onStop={() => handleStopGrid(selectedGrid.config.id)}
+ onDelete={() => handleDeleteGrid(selectedGrid.config.id)}
+ />
)}
</div>
</div>
@@ -333,31 +454,49 @@ export function GridTradingPanel({
};
return (
- <div className="bg-[#0F0F0F] border border-[#2A2A2A] rounded-lg p-4">
- {/* Error display */}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ backgroundColor: FINCEPT.PANEL_BG,
+ fontFamily: '"IBM Plex Mono", monospace',
+ position: 'relative',
+ overflow: 'hidden',
+ }}>
{error && (
- <div className="bg-[#FF3B3B]/10 border border-[#FF3B3B]/30 rounded p-3 mb-4 flex items-start gap-2">
- <AlertCircle className="w-4 h-4 text-[#FF3B3B] flex-shrink-0 mt-0.5" />
- <div className="flex-1">
- <div className="text-sm text-[#FF3B3B]">{error}</div>
- </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '8px 12px',
+ backgroundColor: `${FINCEPT.RED}15`,
+ borderBottom: `1px solid ${FINCEPT.RED}30`,
+ }}>
+ <AlertCircle size={14} color={FINCEPT.RED} />
+ <span style={{ flex: 1, fontSize: '10px', color: FINCEPT.RED }}>{error}</span>
<button
onClick={() => setError(null)}
- className="text-[#FF3B3B] hover:text-white"
+ style={{ background: 'none', border: 'none', color: FINCEPT.RED, cursor: 'pointer', padding: '2px' }}
>
- <X className="w-4 h-4" />
+ <X size={12} />
</button>
</div>
)}
- {/* Loading overlay */}
{isLoading && (
- <div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
- <div className="animate-spin w-8 h-8 border-2 border-[#FF8800] border-t-transparent rounded-full" />
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ backgroundColor: 'rgba(0,0,0,0.6)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 10,
+ }}>
+ <Loader size={24} color={FINCEPT.ORANGE} style={{ animation: 'spin 1s linear infinite' }} />
</div>
)}
- {/* Content */}
{view === 'list' && renderList()}
{view === 'create' && renderCreate()}
{view === 'details' && renderDetails()}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts
index 532944373..aef346c26 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts
@@ -12,14 +12,17 @@ import type { UnifiedBalance, UnifiedAccount, TradingStatistics } from '../types
// ============================================================================
export function useBalance(autoRefresh: boolean = true, refreshInterval: number = 5000) {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [balances, setBalances] = useState<UnifiedBalance[]>([]);
const [totalEquity, setTotalEquity] = useState<number>(0);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchBalance = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
setBalances([]);
setTotalEquity(0);
return;
@@ -29,7 +32,7 @@ export function useBalance(autoRefresh: boolean = true, refreshInterval: number
setError(null);
try {
- const rawBalance = await activeAdapter.fetchBalance();
+ const rawBalance = await adapter.fetchBalance();
// Normalize balances
const normalizedBalances: UnifiedBalance[] = Object.entries(rawBalance || {})
@@ -58,7 +61,7 @@ export function useBalance(autoRefresh: boolean = true, refreshInterval: number
} finally {
setIsLoading(false);
}
- }, [activeAdapter]);
+ }, [activeAdapter, tradingMode, paperAdapter]);
useEffect(() => {
fetchBalance();
@@ -90,13 +93,16 @@ export interface FeeStructure {
}
export function useFees() {
- const { activeAdapter, activeBroker } = useBrokerContext();
+ const { activeAdapter, activeBroker, tradingMode, paperAdapter } = useBrokerContext();
const [fees, setFees] = useState<FeeStructure | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchFees = useCallback(async () => {
- if (!activeAdapter) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter ? paperAdapter : activeAdapter;
+
+ if (!adapter) {
setFees(null);
return;
}
@@ -106,7 +112,7 @@ export function useFees() {
try {
// Try to fetch trading fees from adapter
- const tradingFees = (activeAdapter as any).getTradingFees?.() || null;
+ const tradingFees = (adapter as any).getTradingFees?.() || null;
if (tradingFees) {
setFees({
@@ -133,7 +139,7 @@ export function useFees() {
} finally {
setIsLoading(false);
}
- }, [activeAdapter, activeBroker]);
+ }, [activeAdapter, tradingMode, paperAdapter, activeBroker]);
useEffect(() => {
fetchFees();
@@ -161,13 +167,16 @@ export interface MarginInfo {
}
export function useMarginInfo(autoRefresh: boolean = true) {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [marginInfo, setMarginInfo] = useState<MarginInfo | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchMarginInfo = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
setMarginInfo(null);
return;
}
@@ -177,7 +186,7 @@ export function useMarginInfo(autoRefresh: boolean = true) {
try {
// Check if adapter supports margin info
- const balance = await activeAdapter.fetchBalance();
+ const balance = await adapter.fetchBalance();
// Extract margin info if available
const info = (balance as any).info;
@@ -209,7 +218,7 @@ export function useMarginInfo(autoRefresh: boolean = true) {
} finally {
setIsLoading(false);
}
- }, [activeAdapter]);
+ }, [activeAdapter, tradingMode, paperAdapter]);
useEffect(() => {
fetchMarginInfo();
@@ -240,7 +249,7 @@ export interface LeverageInfo {
}
export function useLeverage(symbol?: string) {
- const { activeAdapter, activeBroker } = useBrokerContext();
+ const { activeAdapter, activeBroker, tradingMode, paperAdapter } = useBrokerContext();
const [leverageInfo, setLeverageInfo] = useState<LeverageInfo | null>(null);
const [leverageTiers, setLeverageTiers] = useState<any[] | null>(null);
const [isLoading, setIsLoading] = useState(false);
@@ -248,13 +257,16 @@ export function useLeverage(symbol?: string) {
const [isSupported, setIsSupported] = useState(true);
const fetchLeverage = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected() || !symbol) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected() || !symbol) {
setLeverageInfo(null);
return;
}
// Check if adapter supports fetchLeverage
- if (typeof (activeAdapter as any).fetchLeverage !== 'function') {
+ if (typeof (adapter as any).fetchLeverage !== 'function') {
setIsSupported(false);
setLeverageInfo(null);
return;
@@ -264,7 +276,7 @@ export function useLeverage(symbol?: string) {
setError(null);
try {
- const rawLeverage = await (activeAdapter as any).fetchLeverage(symbol);
+ const rawLeverage = await (adapter as any).fetchLeverage(symbol);
setLeverageInfo({
symbol,
@@ -285,27 +297,30 @@ export function useLeverage(symbol?: string) {
} finally {
setIsLoading(false);
}
- }, [activeAdapter, symbol]);
+ }, [activeAdapter, tradingMode, paperAdapter, symbol]);
const fetchTiers = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected() || !symbol) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected() || !symbol) {
setLeverageTiers(null);
return;
}
- if (typeof (activeAdapter as any).fetchLeverageTiers !== 'function') {
+ if (typeof (adapter as any).fetchLeverageTiers !== 'function') {
setLeverageTiers(null);
return;
}
try {
- const tiers = await (activeAdapter as any).fetchLeverageTiers([symbol]);
+ const tiers = await (adapter as any).fetchLeverageTiers([symbol]);
setLeverageTiers(tiers?.[symbol] || null);
} catch (err) {
console.error('[useLeverage] Failed to fetch leverage tiers:', err);
setLeverageTiers(null);
}
- }, [activeAdapter, symbol]);
+ }, [activeAdapter, tradingMode, paperAdapter, symbol]);
useEffect(() => {
fetchLeverage();
@@ -347,22 +362,37 @@ export function useTradingStats() {
const rustStats = await paperTradingApi.getStats(paperPortfolio.id);
// Get fresh portfolio data for balance info
const portfolio = await paperTradingApi.getPortfolio(paperPortfolio.id);
+ // Get positions for unrealized P&L
+ const positions = await paperTradingApi.getPositions(paperPortfolio.id);
+ // Get trades for fee calculation
+ const trades = await paperTradingApi.getTrades(paperPortfolio.id, 1000);
const totalPnL = rustStats.total_pnl;
const currentBalance = portfolio.balance;
const initialBalance = portfolio.initial_balance;
- const returnPercent = initialBalance > 0 ? ((currentBalance - initialBalance) / initialBalance) * 100 : 0;
+
+ // Calculate unrealized P&L from open positions
+ const unrealizedPnL = positions.reduce((sum, pos) => sum + (pos.unrealized_pnl || 0), 0);
+
+ // Calculate total fees from trades
+ const totalFees = trades.reduce((sum, trade) => sum + (trade.fee || 0), 0);
+
+ // Calculate equity = balance + unrealized P&L
+ const totalEquity = currentBalance + unrealizedPnL;
+
+ // Calculate return percent based on equity vs initial
+ const returnPercent = initialBalance > 0 ? ((totalEquity - initialBalance) / initialBalance) * 100 : 0;
setStats({
// Account
initialBalance,
currentBalance,
- totalEquity: currentBalance,
+ totalEquity,
// P&L
- totalPnL,
- realizedPnL: totalPnL, // For paper trading, total = realized
- unrealizedPnL: 0, // Would need to sum position unrealized P&L
+ totalPnL: totalPnL + unrealizedPnL,
+ realizedPnL: totalPnL,
+ unrealizedPnL,
returnPercent,
// Trading
@@ -376,7 +406,7 @@ export function useTradingStats() {
largestLoss: rustStats.largest_loss,
// Fees
- totalFees: 0, // Could accumulate from trades
+ totalFees,
});
} else {
// For live trading, calculate stats from closed orders
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts
index 2e07d2a2a..d4f6f44ea 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useCrossExchange.ts
@@ -1,9 +1,11 @@
/**
* useCrossExchange - Cross-exchange portfolio aggregation and arbitrage detection
+ * Uses real data from connected brokers and paper trading
*/
import { useState, useEffect, useCallback } from 'react';
import { useBrokerContext } from '../../../../contexts/BrokerContext';
+import { getMarketDataService } from '../../../../services/trading/UnifiedMarketDataService';
// Types
export interface CrossExchangeBalance {
@@ -51,9 +53,10 @@ export interface CrossExchangePosition {
/**
* Hook for cross-exchange portfolio aggregation
+ * Fetches real balances from paper trading and connected exchanges
*/
export function useCrossExchangePortfolio() {
- const { availableBrokers } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperTradingApi, paperPortfolio, activeBroker } = useBrokerContext();
const [balances, setBalances] = useState<CrossExchangeBalance[]>([]);
const [aggregatedBalances, setAggregatedBalances] = useState<AggregatedBalance[]>([]);
const [totalPortfolioValue, setTotalPortfolioValue] = useState<number>(0);
@@ -67,20 +70,81 @@ export function useCrossExchangePortfolio() {
try {
const allBalances: CrossExchangeBalance[] = [];
- // Mock data for demonstration (in production, fetch from all connected exchanges)
- const mockBalances: CrossExchangeBalance[] = [
- // Kraken
- { exchange: 'kraken', currency: 'BTC', total: 0.5, free: 0.3, used: 0.2, usdValue: 21625 },
- { exchange: 'kraken', currency: 'ETH', total: 10, free: 8, used: 2, usdValue: 23456 },
- { exchange: 'kraken', currency: 'USDC', total: 5000, free: 4500, used: 500, usdValue: 5000 },
+ // Fetch from paper trading if in paper mode
+ if (tradingMode === 'paper' && paperPortfolio && paperTradingApi) {
+ try {
+ const portfolio = await paperTradingApi.getPortfolio(paperPortfolio.id);
+ const positions = await paperTradingApi.getPositions(paperPortfolio.id);
+
+ // Calculate total unrealized P&L
+ let totalUnrealizedPnl = 0;
+ for (const pos of positions) {
+ totalUnrealizedPnl += pos.unrealized_pnl || 0;
+ }
+
+ // For derivatives/margin trading:
+ // - Balance = Available cash (what you can use for new trades)
+ // - Equity = Balance + Unrealized P&L (total account value)
+ const equity = portfolio.balance + totalUnrealizedPnl;
+
+ // Show equity as the total portfolio value
+ allBalances.push({
+ exchange: 'paper',
+ currency: 'USD',
+ total: equity,
+ free: portfolio.balance,
+ used: totalUnrealizedPnl,
+ usdValue: equity,
+ });
+ } catch (err) {
+ console.warn('[useCrossExchangePortfolio] Paper trading fetch error:', err);
+ }
+ }
- // HyperLiquid
- { exchange: 'hyperliquid', currency: 'BTC', total: 0.3, free: 0.3, used: 0, usdValue: 12975 },
- { exchange: 'hyperliquid', currency: 'ETH', total: 5, free: 3, used: 2, usdValue: 11728 },
- { exchange: 'hyperliquid', currency: 'USDC', total: 10000, free: 8000, used: 2000, usdValue: 10000 },
- ];
+ // Fetch from real adapter if connected
+ if (activeAdapter && activeAdapter.isConnected() && tradingMode === 'live') {
+ try {
+ const balance = await activeAdapter.fetchBalance();
+
+ if (balance) {
+ // Process free balances
+ const freeBalances = balance.free || {};
+ const usedBalances = balance.used || {};
+ const totalBalances = balance.total || {};
+
+ for (const [currency, amount] of Object.entries(totalBalances)) {
+ const total = typeof amount === 'number' ? amount : 0;
+ if (total <= 0) continue;
+
+ const free = (freeBalances as any)[currency] || 0;
+ const used = (usedBalances as any)[currency] || 0;
+
+ // Get USD value - for stablecoins use 1:1, for others try to get price
+ let usdValue = total;
+ if (!['USD', 'USDT', 'USDC', 'DAI', 'BUSD'].includes(currency)) {
+ const marketData = getMarketDataService();
+ const priceData = marketData.getCurrentPrice(`${currency}/USD`, activeBroker || undefined) ||
+ marketData.getCurrentPrice(`${currency}/USDT`, activeBroker || undefined);
+ if (priceData) {
+ usdValue = total * priceData.last;
+ }
+ }
+
+ allBalances.push({
+ exchange: activeBroker || 'unknown',
+ currency,
+ total,
+ free,
+ used,
+ usdValue,
+ });
+ }
+ }
+ } catch (err) {
+ console.warn('[useCrossExchangePortfolio] Live adapter fetch error:', err);
+ }
+ }
- allBalances.push(...mockBalances);
setBalances(allBalances);
// Aggregate by currency
@@ -113,17 +177,20 @@ export function useCrossExchangePortfolio() {
const totalValue = aggregatedArray.reduce((sum, bal) => sum + bal.totalUsdValue, 0);
setTotalPortfolioValue(totalValue);
+ if (allBalances.length === 0) {
+ setError('No balances found. Connect an exchange or start paper trading.');
+ }
+
} catch (err: any) {
setError(err?.message || 'Failed to fetch cross-exchange balances');
- console.error('Cross-exchange balance error:', err);
+ console.error('[useCrossExchangePortfolio] Error:', err);
} finally {
setIsLoading(false);
}
- }, [availableBrokers]);
+ }, [activeAdapter, tradingMode, paperTradingApi, paperPortfolio, activeBroker]);
useEffect(() => {
fetchCrossExchangeBalances();
- // Auto-refresh every 30 seconds
const interval = setInterval(fetchCrossExchangeBalances, 30000);
return () => clearInterval(interval);
}, [fetchCrossExchangeBalances]);
@@ -140,56 +207,77 @@ export function useCrossExchangePortfolio() {
/**
* Hook for arbitrage opportunity detection
+ * Compares prices across multiple providers using UnifiedMarketDataService
*/
-export function useArbitrageDetection(symbols: string[] = ['BTC/USDC', 'ETH/USDC']) {
+export function useArbitrageDetection(symbols: string[] = ['BTC/USD', 'ETH/USD', 'SOL/USD']) {
const { availableBrokers } = useBrokerContext();
const [opportunities, setOpportunities] = useState<ArbitrageOpportunity[]>([]);
const [isScanning, setIsScanning] = useState(false);
const [lastScanTime, setLastScanTime] = useState<number | null>(null);
const scanArbitrageOpportunities = useCallback(async () => {
+ if (availableBrokers.length < 2) {
+ setOpportunities([]);
+ return;
+ }
+
setIsScanning(true);
try {
const foundOpportunities: ArbitrageOpportunity[] = [];
+ const marketData = getMarketDataService();
+
+ for (const symbol of symbols) {
+ const prices: { exchange: string; price: number }[] = [];
+
+ // Get prices from all available providers
+ const allPrices = marketData.getAllPrices(symbol);
+
+ for (const [provider, priceData] of allPrices) {
+ if (priceData.last > 0) {
+ prices.push({
+ exchange: provider,
+ price: priceData.last,
+ });
+ }
+ }
+
+ // Need at least 2 prices to find arbitrage
+ if (prices.length < 2) continue;
+
+ // Sort by price to find min and max
+ prices.sort((a, b) => a.price - b.price);
+
+ const lowest = prices[0];
+ const highest = prices[prices.length - 1];
+
+ const spread = highest.price - lowest.price;
+ const spreadPercent = (spread / lowest.price) * 100;
+
+ // Only report opportunities with spread > 0.2%
+ if (spreadPercent > 0.2) {
+ foundOpportunities.push({
+ symbol,
+ buyExchange: lowest.exchange,
+ sellExchange: highest.exchange,
+ buyPrice: lowest.price,
+ sellPrice: highest.price,
+ spread,
+ spreadPercent,
+ potentialProfit: spread, // Per unit profit
+ timestamp: Date.now(),
+ });
+ }
+ }
+
+ // Sort by spread percent descending
+ foundOpportunities.sort((a, b) => b.spreadPercent - a.spreadPercent);
- // Mock arbitrage opportunities (in production, fetch real prices from all exchanges)
- const mockOpportunities: ArbitrageOpportunity[] = [
- {
- symbol: 'BTC/USDC',
- buyExchange: 'hyperliquid',
- sellExchange: 'kraken',
- buyPrice: 43150.50,
- sellPrice: 43285.75,
- spread: 135.25,
- spreadPercent: 0.31,
- potentialProfit: 135.25,
- timestamp: Date.now(),
- },
- {
- symbol: 'ETH/USDC',
- buyExchange: 'kraken',
- sellExchange: 'hyperliquid',
- buyPrice: 2340.25,
- sellPrice: 2358.50,
- spread: 18.25,
- spreadPercent: 0.78,
- potentialProfit: 18.25,
- timestamp: Date.now(),
- },
- ];
-
- // Filter opportunities with spread > 0.2%
- const viableOpportunities = mockOpportunities.filter(
- (opp) => opp.spreadPercent > 0.2
- );
-
- foundOpportunities.push(...viableOpportunities);
setOpportunities(foundOpportunities);
setLastScanTime(Date.now());
} catch (err) {
- console.error('Arbitrage scan error:', err);
+ console.error('[useArbitrageDetection] Scan error:', err);
} finally {
setIsScanning(false);
}
@@ -197,7 +285,6 @@ export function useArbitrageDetection(symbols: string[] = ['BTC/USDC', 'ETH/USDC
useEffect(() => {
scanArbitrageOpportunities();
- // Auto-scan every 10 seconds
const interval = setInterval(scanArbitrageOpportunities, 10000);
return () => clearInterval(interval);
}, [scanArbitrageOpportunities]);
@@ -212,9 +299,10 @@ export function useArbitrageDetection(symbols: string[] = ['BTC/USDC', 'ETH/USDC
/**
* Hook for cross-exchange positions aggregation
+ * Fetches real positions from paper trading and connected exchanges
*/
export function useCrossExchangePositions() {
- const { availableBrokers } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperTradingApi, paperPortfolio, activeBroker } = useBrokerContext();
const [positions, setPositions] = useState<CrossExchangePosition[]>([]);
const [totalUnrealizedPnl, setTotalUnrealizedPnl] = useState<number>(0);
const [isLoading, setIsLoading] = useState(true);
@@ -223,55 +311,72 @@ export function useCrossExchangePositions() {
setIsLoading(true);
try {
- // Mock positions (in production, fetch from all connected exchanges)
- const mockPositions: CrossExchangePosition[] = [
- {
- symbol: 'BTC/USDC',
- exchange: 'kraken',
- side: 'long',
- quantity: 0.2,
- entryPrice: 42500,
- currentPrice: 43250,
- unrealizedPnl: 150,
- pnlPercent: 1.76,
- },
- {
- symbol: 'ETH/USDC',
- exchange: 'hyperliquid',
- side: 'long',
- quantity: 2,
- entryPrice: 2300,
- currentPrice: 2345,
- unrealizedPnl: 90,
- pnlPercent: 1.96,
- },
- {
- symbol: 'SOL/USDC',
- exchange: 'kraken',
- side: 'short',
- quantity: 10,
- entryPrice: 105,
- currentPrice: 98,
- unrealizedPnl: 70,
- pnlPercent: 6.67,
- },
- ];
-
- setPositions(mockPositions);
-
- const totalPnl = mockPositions.reduce((sum, pos) => sum + pos.unrealizedPnl, 0);
+ const allPositions: CrossExchangePosition[] = [];
+
+ // Fetch from paper trading
+ if (tradingMode === 'paper' && paperPortfolio && paperTradingApi) {
+ try {
+ const paperPositions = await paperTradingApi.getPositions(paperPortfolio.id);
+
+ for (const pos of paperPositions) {
+ const pnlPercent = pos.entry_price > 0
+ ? ((pos.current_price - pos.entry_price) / pos.entry_price) * 100
+ : 0;
+
+ allPositions.push({
+ symbol: pos.symbol,
+ exchange: 'paper',
+ side: pos.side,
+ quantity: pos.quantity,
+ entryPrice: pos.entry_price,
+ currentPrice: pos.current_price,
+ unrealizedPnl: pos.unrealized_pnl,
+ pnlPercent: pos.side === 'short' ? -pnlPercent : pnlPercent,
+ });
+ }
+ } catch (err) {
+ console.warn('[useCrossExchangePositions] Paper trading fetch error:', err);
+ }
+ }
+
+ // Fetch from real adapter
+ if (activeAdapter && activeAdapter.isConnected() && tradingMode === 'live') {
+ try {
+ if (typeof (activeAdapter as any).fetchPositions === 'function') {
+ const livePositions = await (activeAdapter as any).fetchPositions();
+
+ for (const pos of livePositions || []) {
+ allPositions.push({
+ symbol: pos.symbol,
+ exchange: activeBroker || 'unknown',
+ side: pos.side,
+ quantity: pos.contracts || pos.quantity || 0,
+ entryPrice: pos.entryPrice || pos.entry_price || 0,
+ currentPrice: pos.markPrice || pos.current_price || 0,
+ unrealizedPnl: pos.unrealizedPnl || pos.unrealized_pnl || 0,
+ pnlPercent: pos.percentage || 0,
+ });
+ }
+ }
+ } catch (err) {
+ console.warn('[useCrossExchangePositions] Live adapter fetch error:', err);
+ }
+ }
+
+ setPositions(allPositions);
+
+ const totalPnl = allPositions.reduce((sum, pos) => sum + pos.unrealizedPnl, 0);
setTotalUnrealizedPnl(totalPnl);
} catch (err) {
- console.error('Cross-exchange positions error:', err);
+ console.error('[useCrossExchangePositions] Error:', err);
} finally {
setIsLoading(false);
}
- }, [availableBrokers]);
+ }, [activeAdapter, tradingMode, paperTradingApi, paperPortfolio, activeBroker]);
useEffect(() => {
fetchCrossExchangePositions();
- // Auto-refresh every 5 seconds
const interval = setInterval(fetchCrossExchangePositions, 5000);
return () => clearInterval(interval);
}, [fetchCrossExchangePositions]);
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts
index 7ef950a01..08735d0c1 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts
@@ -8,14 +8,16 @@ import { useBrokerContext } from '../../../../contexts/BrokerContext';
import type { UnifiedOrder } from '../types';
export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [openOrders, setOpenOrders] = useState<UnifiedOrder[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchOrders = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
- setOpenOrders([]);
+ // In paper trading mode, we can use the paperAdapter even if activeAdapter check fails
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
return;
}
@@ -23,7 +25,7 @@ export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshI
setError(null);
try {
- const rawOrders = await activeAdapter.fetchOpenOrders(symbol);
+ const rawOrders = await adapter.fetchOpenOrders(symbol);
// Normalize to unified format
const normalized: UnifiedOrder[] = (rawOrders || []).map((order: any) => ({
@@ -62,7 +64,7 @@ export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshI
} finally {
setIsLoading(false);
}
- }, [activeAdapter, symbol]);
+ }, [activeAdapter, paperAdapter, tradingMode, symbol]);
// Auto-refresh
useEffect(() => {
@@ -86,13 +88,16 @@ export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshI
* Hook to cancel order(s)
*/
export function useCancelOrder() {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [isCanceling, setIsCanceling] = useState(false);
const [error, setError] = useState<Error | null>(null);
const cancelOrder = useCallback(
async (orderId: string, symbol: string) => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
throw new Error('Exchange not connected');
}
@@ -100,7 +105,7 @@ export function useCancelOrder() {
setError(null);
try {
- await activeAdapter.cancelOrder(orderId, symbol);
+ await adapter.cancelOrder(orderId, symbol);
return true;
} catch (err) {
const error = err as Error;
@@ -110,17 +115,20 @@ export function useCancelOrder() {
setIsCanceling(false);
}
},
- [activeAdapter]
+ [activeAdapter, tradingMode, paperAdapter]
);
const cancelAllOrders = useCallback(
async (symbol?: string) => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
throw new Error('Exchange not connected');
}
// Check if exchange supports cancel all
- if (typeof activeAdapter.cancelAllOrders !== 'function') {
+ if (typeof adapter.cancelAllOrders !== 'function') {
throw new Error('This exchange does not support cancel all orders');
}
@@ -128,7 +136,7 @@ export function useCancelOrder() {
setError(null);
try {
- await activeAdapter.cancelAllOrders(symbol);
+ await adapter.cancelAllOrders(symbol);
return true;
} catch (err) {
const error = err as Error;
@@ -139,7 +147,7 @@ export function useCancelOrder() {
setIsCanceling(false);
}
},
- [activeAdapter]
+ [activeAdapter, tradingMode, paperAdapter]
);
return { cancelOrder, cancelAllOrders, isCanceling, error };
@@ -147,22 +155,21 @@ export function useCancelOrder() {
/**
* Hook to fetch closed orders
+ * Supports both live exchanges (fetchClosedOrders) and paper trading (getOrders with filled/cancelled status)
*/
-export function useClosedOrders(symbol?: string, limit: number = 50) {
- const { activeAdapter } = useBrokerContext();
+export function useClosedOrders(symbol?: string, limit: number = 50, autoRefresh: boolean = true, refreshInterval: number = 5000) {
+ const { activeAdapter, tradingMode, paperTradingApi, paperAdapter } = useBrokerContext();
const [closedOrders, setClosedOrders] = useState<UnifiedOrder[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchClosedOrders = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
- setClosedOrders([]);
- return;
- }
+ // For paper trading, we can fetch even if activeAdapter isn't fully connected
+ // because we use the paperTradingApi directly
+ const canFetchPaper = tradingMode === 'paper' && paperAdapter && paperTradingApi && paperAdapter.portfolioId;
+ const canFetchLive = activeAdapter && activeAdapter.isConnected();
- // Check if exchange supports fetching closed orders
- if (typeof (activeAdapter as any).fetchClosedOrders !== 'function') {
- setClosedOrders([]);
+ if (!canFetchPaper && !canFetchLive) {
return;
}
@@ -170,30 +177,78 @@ export function useClosedOrders(symbol?: string, limit: number = 50) {
setError(null);
try {
- const rawOrders = await (activeAdapter as any).fetchClosedOrders(symbol, undefined, limit);
+ let normalized: UnifiedOrder[] = [];
- const normalized: UnifiedOrder[] = (rawOrders || []).map((order: any) => ({
- id: order.id,
- symbol: order.symbol,
- type: order.type,
- side: order.side,
- quantity: order.amount || 0,
- price: order.price,
- stopPrice: order.stopPrice,
- status: order.status,
- filled: order.filled || 0,
- remaining: 0,
- timestamp: order.timestamp || Date.now(),
- createdAt: order.datetime || new Date().toISOString(),
- average: order.average,
- cost: order.cost,
- fee: order.fee
- ? {
- cost: order.fee.cost || 0,
- currency: order.fee.currency || 'USD',
- }
- : undefined,
- }));
+ // Check if we're in paper trading mode
+ if (tradingMode === 'paper' && paperAdapter && paperTradingApi && paperAdapter.portfolioId) {
+ // For paper trading, get orders with filled/cancelled status from Rust backend
+ const portfolioId = paperAdapter.portfolioId;
+
+ // Get filled orders
+ const filledOrders = await paperTradingApi.getOrders(portfolioId, 'filled');
+ // Get cancelled orders
+ const cancelledOrders = await paperTradingApi.getOrders(portfolioId, 'cancelled');
+
+ // Combine and sort by timestamp (newest first)
+ const allClosedOrders = [...filledOrders, ...cancelledOrders]
+ .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
+ .slice(0, limit);
+
+ normalized = allClosedOrders.map((order: any) => ({
+ id: order.id,
+ symbol: order.symbol,
+ type: order.order_type || order.type,
+ side: order.side,
+ quantity: order.quantity || order.amount || 0,
+ price: order.price,
+ stopPrice: order.stop_price || order.stopPrice,
+ status: order.status,
+ filled: order.filled_qty || order.filled || 0,
+ remaining: 0,
+ timestamp: new Date(order.created_at).getTime(),
+ createdAt: order.created_at || new Date().toISOString(),
+ average: order.avg_price || order.average,
+ cost: order.price && (order.filled_qty || order.filled)
+ ? order.price * (order.filled_qty || order.filled)
+ : undefined,
+ fee: undefined, // Paper trading tracks fees separately in trades
+ }));
+ } else if (canFetchLive && typeof (activeAdapter as any).fetchClosedOrders === 'function') {
+ // Live trading - use exchange's fetchClosedOrders if available
+ const rawOrders = await (activeAdapter as any).fetchClosedOrders(symbol, undefined, limit);
+
+ normalized = (rawOrders || []).map((order: any) => ({
+ id: order.id,
+ symbol: order.symbol,
+ type: order.type,
+ side: order.side,
+ quantity: order.amount || 0,
+ price: order.price,
+ stopPrice: order.stopPrice,
+ status: order.status,
+ filled: order.filled || 0,
+ remaining: 0,
+ timestamp: order.timestamp || Date.now(),
+ createdAt: order.datetime || new Date().toISOString(),
+ average: order.average,
+ cost: order.cost,
+ fee: order.fee
+ ? {
+ cost: order.fee.cost || 0,
+ currency: order.fee.currency || 'USD',
+ }
+ : undefined,
+ }));
+ } else {
+ // Exchange doesn't support closed orders - return empty
+ setClosedOrders([]);
+ return;
+ }
+
+ // Filter by symbol if specified
+ if (symbol) {
+ normalized = normalized.filter(o => o.symbol === symbol);
+ }
setClosedOrders(normalized);
} catch (err) {
@@ -203,11 +258,17 @@ export function useClosedOrders(symbol?: string, limit: number = 50) {
} finally {
setIsLoading(false);
}
- }, [activeAdapter, symbol, limit]);
+ }, [activeAdapter, tradingMode, paperAdapter, paperTradingApi, symbol, limit]);
+ // Initial fetch and auto-refresh
useEffect(() => {
fetchClosedOrders();
- }, [fetchClosedOrders]);
+
+ if (!autoRefresh) return;
+
+ const interval = setInterval(fetchClosedOrders, refreshInterval);
+ return () => clearInterval(interval);
+ }, [fetchClosedOrders, autoRefresh, refreshInterval]);
return {
closedOrders,
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
index 0f9c7e3dd..af6c98e45 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
@@ -10,7 +10,7 @@ import { getMarketDataService } from '../../../../services/trading/UnifiedMarket
import type { UnifiedPosition } from '../types';
export function usePositions(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {
- const { activeAdapter, activeBroker } = useBrokerContext();
+ const { activeAdapter, activeBroker, tradingMode, paperAdapter } = useBrokerContext();
const [positions, setPositions] = useState<UnifiedPosition[]>([]);
// Start with loading false - only set true when actually fetching
const [isLoading, setIsLoading] = useState(false);
@@ -25,8 +25,11 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refre
const fetchPositionsRef = useRef<(() => Promise<void>) | undefined>(undefined);
const fetchPositions = useCallback(async () => {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
// Quick early exit if no adapter - don't set loading state
- if (!activeAdapter) {
+ if (!adapter) {
setPositions([]);
setIsLoading(false);
return;
@@ -40,7 +43,7 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refre
try {
// Fetch positions from adapter (removed timeout - let it complete naturally)
- const rawPositions = await activeAdapter.fetchPositions(symbol ? [symbol] : undefined);
+ const rawPositions = await adapter.fetchPositions(symbol ? [symbol] : undefined);
// Get market data service for live prices
const marketDataService = getMarketDataService();
@@ -100,7 +103,7 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refre
} finally {
setIsLoading(false);
}
- }, [activeAdapter, symbol, activeBroker]);
+ }, [activeAdapter, paperAdapter, tradingMode, symbol, activeBroker]);
fetchPositionsRef.current = fetchPositions;
@@ -187,13 +190,16 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refre
* Hook to close a position
*/
export function useClosePosition() {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [isClosing, setIsClosing] = useState(false);
const [error, setError] = useState<Error | null>(null);
const closePosition = useCallback(
async (position: UnifiedPosition) => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
throw new Error('Exchange not connected');
}
@@ -206,12 +212,12 @@ export function useClosePosition() {
// Create opposite order to close position
const closeSide = position.side === 'long' ? 'sell' : 'buy';
- await activeAdapter.createOrder(
+ await adapter.createOrder(
position.symbol,
'market',
closeSide,
position.quantity,
- undefined,
+ position.currentPrice, // Use position's current price as fallback for paper trading
{ reduceOnly: true }
);
@@ -224,7 +230,7 @@ export function useClosePosition() {
setIsClosing(false);
}
},
- [activeAdapter]
+ [activeAdapter, tradingMode, paperAdapter]
);
return { closePosition, isClosing, error };
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts
index 6dfc35ee2..0a892f81e 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts
@@ -25,20 +25,22 @@ export interface UnifiedTrade {
}
export function useTrades(symbol?: string, limit: number = 50, autoRefresh: boolean = false) {
- const { activeAdapter, activeBroker } = useBrokerContext();
+ const { activeAdapter, activeBroker, tradingMode, paperAdapter } = useBrokerContext();
const [trades, setTrades] = useState<UnifiedTrade[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [isSupported, setIsSupported] = useState(true);
const fetchTrades = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
- setTrades([]);
+ // In paper trading mode, we can use the paperAdapter even if activeAdapter check fails
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected()) {
return;
}
// Check if exchange supports fetchMyTrades
- if (typeof (activeAdapter as any).fetchMyTrades !== 'function') {
+ if (typeof (adapter as any).fetchMyTrades !== 'function') {
setIsSupported(false);
setTrades([]);
return;
@@ -48,7 +50,7 @@ export function useTrades(symbol?: string, limit: number = 50, autoRefresh: bool
setError(null);
try {
- const rawTrades = await (activeAdapter as any).fetchMyTrades(symbol, undefined, limit);
+ const rawTrades = await (adapter as any).fetchMyTrades(symbol, undefined, limit);
const normalized: UnifiedTrade[] = (rawTrades || []).map((trade: any) => ({
id: trade.id,
@@ -84,7 +86,7 @@ export function useTrades(symbol?: string, limit: number = 50, autoRefresh: bool
} finally {
setIsLoading(false);
}
- }, [activeAdapter, symbol, limit]);
+ }, [activeAdapter, paperAdapter, tradingMode, symbol, limit]);
// Fetch on mount and when dependencies change
useEffect(() => {
@@ -110,18 +112,21 @@ export function useTrades(symbol?: string, limit: number = 50, autoRefresh: bool
* Hook to fetch trades for a specific order
*/
export function useOrderTrades(orderId: string, symbol: string) {
- const { activeAdapter } = useBrokerContext();
+ const { activeAdapter, tradingMode, paperAdapter } = useBrokerContext();
const [trades, setTrades] = useState<UnifiedTrade[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchOrderTrades = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected() || !orderId || !symbol) {
+ // In paper trading mode, use paperAdapter
+ const adapter = tradingMode === 'paper' && paperAdapter?.isConnected() ? paperAdapter : activeAdapter;
+
+ if (!adapter || !adapter.isConnected() || !orderId || !symbol) {
setTrades([]);
return;
}
- if (typeof (activeAdapter as any).fetchOrderTrades !== 'function') {
+ if (typeof (adapter as any).fetchOrderTrades !== 'function') {
setTrades([]);
return;
}
@@ -130,7 +135,7 @@ export function useOrderTrades(orderId: string, symbol: string) {
setError(null);
try {
- const rawTrades = await (activeAdapter as any).fetchOrderTrades(orderId, symbol);
+ const rawTrades = await (adapter as any).fetchOrderTrades(orderId, symbol);
const normalized: UnifiedTrade[] = (rawTrades || []).map((trade: any) => ({
id: trade.id,
@@ -158,7 +163,7 @@ export function useOrderTrades(orderId: string, symbol: string) {
} finally {
setIsLoading(false);
}
- }, [activeAdapter, orderId, symbol]);
+ }, [activeAdapter, tradingMode, paperAdapter, orderId, symbol]);
useEffect(() => {
fetchOrderTrades();
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/monitoring/MonitoringPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/monitoring/MonitoringPanel.tsx
index 3d082e5d6..01545df4f 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/monitoring/MonitoringPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/monitoring/MonitoringPanel.tsx
@@ -40,6 +40,7 @@ interface MonitoringPanelProps {
provider: string;
symbol: string;
assetType: 'equity' | 'crypto';
+ filterByAssetType?: boolean; // If true, only show conditions matching the asset type
}
// ---------- Color palette (matches FINCEPT constants) ----------
@@ -85,9 +86,21 @@ const FIELD_ICON: Record<string, React.ReactNode> = {
// ---------- Component ----------
-export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanelProps) {
- const [conditions, setConditions] = useState<MonitorCondition[]>([]);
- const [alerts, setAlerts] = useState<MonitorAlert[]>([]);
+// Helper to determine if a symbol is crypto (contains "/" like BTC/USD) or equity (plain ticker like AAPL)
+const isCryptoSymbol = (sym: string): boolean => sym.includes('/');
+
+export function MonitoringPanel({ provider, symbol, assetType, filterByAssetType = true }: MonitoringPanelProps) {
+ const [allConditions, setAllConditions] = useState<MonitorCondition[]>([]);
+ const [allAlerts, setAllAlerts] = useState<MonitorAlert[]>([]);
+
+ // Filter conditions and alerts based on asset type
+ const conditions = filterByAssetType
+ ? allConditions.filter(c => assetType === 'crypto' ? isCryptoSymbol(c.symbol) : !isCryptoSymbol(c.symbol))
+ : allConditions;
+
+ const alerts = filterByAssetType
+ ? allAlerts.filter(a => assetType === 'crypto' ? isCryptoSymbol(a.symbol) : !isCryptoSymbol(a.symbol))
+ : allAlerts;
const [view, setView] = useState<'conditions' | 'alerts'>('conditions');
const [showAdd, setShowAdd] = useState(false);
const [loading, setLoading] = useState(false);
@@ -123,8 +136,8 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
await invoke('monitor_load_conditions');
const conds = await invoke<MonitorCondition[]>('monitor_get_conditions');
const alertList = await invoke<MonitorAlert[]>('monitor_get_alerts', { limit: 50 });
- setConditions(conds || []);
- setAlerts(alertList || []);
+ setAllConditions(conds || []);
+ setAllAlerts(alertList || []);
} catch (err) {
console.warn('[MonitoringPanel] load failed:', err);
} finally {
@@ -141,10 +154,15 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
useEffect(() => {
const unlisten = listen<MonitorAlert>('monitor_alert', (event) => {
const alert = event.payload;
- setAlerts(prev => [alert, ...prev].slice(0, 100));
- // Remove the triggered condition from the conditions list (it's already deleted in DB by Rust)
- setConditions(prev => prev.filter(c => c.id !== alert.condition_id));
+ // Only process alerts matching this panel's asset type
+ const alertIsCrypto = isCryptoSymbol(alert.symbol);
+ if (filterByAssetType && ((assetType === 'crypto') !== alertIsCrypto)) {
+ return; // Skip alerts that don't match this panel's type
+ }
+
+ setAllAlerts(prev => [alert, ...prev].slice(0, 100));
+ setAllConditions(prev => prev.filter(c => c.id !== alert.condition_id));
const triggerTime = new Date(alert.triggered_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
toast.warning(`ALERT: ${alert.symbol} — ${alert.field.toUpperCase()} = ${alert.triggered_value.toFixed(2)} at ${triggerTime}`);
@@ -169,14 +187,12 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
if (!form.symbol || !form.provider) return;
try {
await invoke('monitor_add_condition', { condition: form });
- // Optimistically add to local state so it appears immediately
- setConditions(prev => [...prev, { ...form, id: Date.now() }]);
- toast.success('Condition added');
+ setAllConditions(prev => [...prev, { ...form, id: Date.now() }]);
+ toast.success(`${assetType === 'crypto' ? 'Crypto' : 'Equity'} alert added`);
setShowAdd(false);
setForm(prev => ({ ...prev, value: 0, value2: undefined, operator: '>', field: 'price' }));
setValueStr('');
setValue2Str('');
- // Also reload from backend to get the real ID
loadData().catch(() => {});
} catch (err) {
toast.error('Failed to add condition');
@@ -187,10 +203,10 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
const deleteCondition = async (id: number) => {
try {
await invoke('monitor_delete_condition', { id });
- setConditions(prev => prev.filter(c => c.id !== id));
- toast.info('Condition deleted');
+ setAllConditions(prev => prev.filter(c => c.id !== id));
+ toast.info('Alert deleted');
} catch (err) {
- toast.error('Failed to delete condition');
+ toast.error('Failed to delete');
console.error(err);
}
};
@@ -244,7 +260,10 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
backgroundColor: C.HEADER_BG,
flexShrink: 0,
}}>
- <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <span style={{ fontSize: '10px', fontWeight: 700, color: C.WHITE, letterSpacing: '0.5px' }}>
+ {assetType === 'crypto' ? 'CRYPTO' : 'EQUITY'} ALERTS
+ </span>
<button
onClick={() => setView('conditions')}
style={{
@@ -255,7 +274,7 @@ export function MonitoringPanel({ provider, symbol, assetType }: MonitoringPanel
}}
>
<Target size={9} style={{ marginRight: 4, verticalAlign: 'middle' }} />
- CONDITIONS ({conditions.length})
+ ACTIVE ({conditions.length})
</button>
<button
onClick={() => setView('alerts')}
diff --git a/fincept-terminal-desktop/src/hooks/usePeerComparison.ts b/fincept-terminal-desktop/src/hooks/usePeerComparison.ts
new file mode 100644
index 000000000..d449ad343
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/usePeerComparison.ts
@@ -0,0 +1,243 @@
+// usePeerComparison Hook - Peer Comparison State Management
+// Manages peer comparison data fetching and state
+
+import { useState, useCallback, useEffect } from 'react';
+import type {
+ PeerCompany,
+ PeerComparisonResult,
+ CompanyMetrics,
+ PercentileRanking,
+} from '../types/peer';
+
+interface UsePeerComparisonReturn {
+ targetSymbol: string;
+ selectedPeers: PeerCompany[];
+ availablePeers: PeerCompany[];
+ comparisonData: PeerComparisonResult | null;
+ loading: boolean;
+ error: string | null;
+ setTargetSymbol: (symbol: string) => void;
+ addPeer: (peer: PeerCompany) => void;
+ removePeer: (symbol: string) => void;
+ fetchPeers: () => Promise<void>;
+ runComparison: () => Promise<void>;
+}
+
+// Mock data generator for development
+function generateMockCompanyMetrics(symbol: string): CompanyMetrics {
+ const randomValue = (min: number, max: number) =>
+ Math.random() * (max - min) + min;
+
+ return {
+ symbol,
+ name: `${symbol} Inc.`,
+ valuation: {
+ peRatio: randomValue(10, 50),
+ pbRatio: randomValue(1, 10),
+ psRatio: randomValue(1, 15),
+ evToEbitda: randomValue(5, 25),
+ pegRatio: randomValue(0.5, 3),
+ },
+ profitability: {
+ roe: randomValue(0.05, 0.35),
+ roa: randomValue(0.02, 0.2),
+ roic: randomValue(0.05, 0.25),
+ grossMargin: randomValue(0.2, 0.8),
+ operatingMargin: randomValue(0.05, 0.4),
+ netMargin: randomValue(0.02, 0.3),
+ },
+ growth: {
+ revenueGrowth: randomValue(-0.1, 0.5),
+ earningsGrowth: randomValue(-0.2, 0.6),
+ fcfGrowth: randomValue(-0.15, 0.4),
+ },
+ leverage: {
+ debtToEquity: randomValue(0, 2),
+ debtToAssets: randomValue(0.1, 0.6),
+ interestCoverage: randomValue(2, 20),
+ },
+ };
+}
+
+function generateMockPeerCompany(symbol: string, index: number): PeerCompany {
+ return {
+ symbol,
+ name: `${symbol} Corporation`,
+ sector: 'Information Technology',
+ industry: 'Software',
+ marketCap: Math.random() * 500_000_000_000,
+ marketCapCategory: 'Large Cap',
+ similarityScore: 0.7 + Math.random() * 0.3,
+ matchDetails: {
+ sectorMatch: true,
+ industryMatch: index < 3,
+ marketCapSimilarity: 0.6 + Math.random() * 0.4,
+ geographicMatch: true,
+ },
+ };
+}
+
+export function usePeerComparison(initialSymbol?: string): UsePeerComparisonReturn {
+ const [targetSymbol, setTargetSymbol] = useState<string>(initialSymbol || '');
+ const [selectedPeers, setSelectedPeers] = useState<PeerCompany[]>([]);
+ const [availablePeers, setAvailablePeers] = useState<PeerCompany[]>([]);
+ const [comparisonData, setComparisonData] = useState<PeerComparisonResult | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Add a peer to selected peers
+ const addPeer = useCallback((peer: PeerCompany) => {
+ setSelectedPeers((prev) => {
+ if (prev.find((p) => p.symbol === peer.symbol)) {
+ return prev;
+ }
+ return [...prev, peer];
+ });
+ }, []);
+
+ // Remove a peer from selected peers
+ const removePeer = useCallback((symbol: string) => {
+ setSelectedPeers((prev) => prev.filter((p) => p.symbol !== symbol));
+ }, []);
+
+ // Fetch available peers for the target symbol
+ const fetchPeers = useCallback(async () => {
+ if (!targetSymbol) {
+ setError('Please enter a target symbol');
+ return;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ // TODO: Replace with actual API call
+ // For now, generate mock peers
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ const mockPeers: PeerCompany[] = [
+ 'MSFT', 'GOOGL', 'META', 'AMZN', 'NVDA', 'CRM', 'ORCL', 'ADBE'
+ ]
+ .filter((s) => s !== targetSymbol.toUpperCase())
+ .slice(0, 8)
+ .map((symbol, index) => generateMockPeerCompany(symbol, index));
+
+ setAvailablePeers(mockPeers);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch peers');
+ } finally {
+ setLoading(false);
+ }
+ }, [targetSymbol]);
+
+ // Run comparison between target and selected peers
+ const runComparison = useCallback(async () => {
+ if (!targetSymbol) {
+ setError('Please enter a target symbol');
+ return;
+ }
+
+ if (selectedPeers.length === 0) {
+ setError('Please select at least one peer');
+ return;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ // TODO: Replace with actual API call
+ await new Promise((resolve) => setTimeout(resolve, 800));
+
+ const targetMetrics = generateMockCompanyMetrics(targetSymbol);
+ const peerMetrics = selectedPeers.map((peer) =>
+ generateMockCompanyMetrics(peer.symbol)
+ );
+
+ // Calculate percentile rankings
+ const percentileRanks: Record<string, PercentileRanking> = {};
+
+ const calculatePercentile = (targetValue: number, peerValues: number[]): number => {
+ const allValues = [targetValue, ...peerValues];
+ const sorted = [...allValues].sort((a, b) => a - b);
+ const rank = sorted.indexOf(targetValue);
+ return (rank / (allValues.length - 1)) * 100;
+ };
+
+ if (targetMetrics.valuation.peRatio) {
+ const peerValues = peerMetrics
+ .map((p) => p.valuation.peRatio)
+ .filter((v): v is number => v !== undefined);
+ if (peerValues.length > 0) {
+ const percentile = calculatePercentile(targetMetrics.valuation.peRatio, peerValues);
+ const mean = peerValues.reduce((a, b) => a + b, 0) / peerValues.length;
+ const variance = peerValues.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / peerValues.length;
+ const stdDev = Math.sqrt(variance);
+ percentileRanks['P/E Ratio'] = {
+ metricName: 'P/E Ratio',
+ value: targetMetrics.valuation.peRatio,
+ percentile,
+ zScore: stdDev > 0 ? (targetMetrics.valuation.peRatio - mean) / stdDev : 0,
+ peerMedian: [...peerValues].sort((a, b) => a - b)[Math.floor(peerValues.length / 2)],
+ peerMean: mean,
+ peerStdDev: stdDev,
+ };
+ }
+ }
+
+ // Calculate summary scores
+ const valuationScore = Math.random() * 2;
+ const profitabilityScore = Math.random() * 2;
+ const growthScore = Math.random() * 2;
+
+ const result: PeerComparisonResult = {
+ target: targetMetrics,
+ peers: peerMetrics,
+ benchmarks: {
+ sector: 'Information Technology',
+ medianPe: peerMetrics.reduce((sum, p) => sum + (p.valuation.peRatio || 0), 0) / peerMetrics.length,
+ medianPb: peerMetrics.reduce((sum, p) => sum + (p.valuation.pbRatio || 0), 0) / peerMetrics.length,
+ medianRoe: peerMetrics.reduce((sum, p) => sum + (p.profitability.roe || 0), 0) / peerMetrics.length * 100,
+ medianRevenueGrowth: peerMetrics.reduce((sum, p) => sum + (p.growth.revenueGrowth || 0), 0) / peerMetrics.length * 100,
+ medianDebtToEquity: peerMetrics.reduce((sum, p) => sum + (p.leverage.debtToEquity || 0), 0) / peerMetrics.length,
+ },
+ percentileRanks,
+ summary: {
+ valuationScore,
+ profitabilityScore,
+ growthScore,
+ overallRating: valuationScore + profitabilityScore + growthScore,
+ },
+ };
+
+ setComparisonData(result);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to run comparison');
+ } finally {
+ setLoading(false);
+ }
+ }, [targetSymbol, selectedPeers]);
+
+ // Auto-fetch peers when target symbol changes
+ useEffect(() => {
+ if (targetSymbol && targetSymbol.length >= 1) {
+ fetchPeers();
+ }
+ }, [targetSymbol, fetchPeers]);
+
+ return {
+ targetSymbol,
+ selectedPeers,
+ availablePeers,
+ comparisonData,
+ loading,
+ error,
+ setTargetSymbol,
+ addPeer,
+ removePeer,
+ fetchPeers,
+ runComparison,
+ };
+}
+
+export default usePeerComparison;
diff --git a/fincept-terminal-desktop/src/paper-trading/index.ts b/fincept-terminal-desktop/src/paper-trading/index.ts
index b8bc22d81..525f5b013 100644
--- a/fincept-terminal-desktop/src/paper-trading/index.ts
+++ b/fincept-terminal-desktop/src/paper-trading/index.ts
@@ -92,6 +92,8 @@ export const placeOrder = (portfolioId: string, symbol: string, side: 'buy' | 's
invoke<Order>('pt_place_order', { portfolioId, symbol, side, orderType, quantity, price, stopPrice, reduceOnly });
export const cancelOrder = (orderId: string) => invoke<void>('pt_cancel_order', { orderId });
+// Internal alias for use in PaperTradingAdapter to avoid name collision
+const cancelOrderInBackend = cancelOrder;
export const getOrders = (portfolioId: string, status?: string) => invoke<Order[]>('pt_get_orders', { portfolioId, status });
export const fillOrder = (orderId: string, fillPrice: number, fillQty?: number) => invoke<Trade>('pt_fill_order', { orderId, fillPrice, fillQty });
@@ -230,6 +232,12 @@ export class PaperTradingAdapter {
private subscribeToSymbol(symbol: string): void {
if (this.priceUnsubscribers.has(symbol)) return; // Already subscribed
+ // First, subscribe via WebSocket to actually receive price updates
+ // This ensures we get real-time data for ALL position symbols, not just the chart symbol
+ this.marketDataService.subscribeViaWebSocket(this.config.provider, symbol).catch((err) => {
+ console.warn(`[PaperTradingAdapter] Failed to subscribe to ${symbol} via WebSocket:`, err);
+ });
+
const unsubscribe = this.marketDataService.subscribeToPrice(symbol, async (price: PriceData) => {
// 1. Update position P&L in Rust backend
try {
@@ -262,6 +270,10 @@ export class PaperTradingAdapter {
unsubscribe();
this.priceUnsubscribers.delete(symbol);
this.trackedSymbols.delete(symbol);
+
+ // Also unsubscribe from WebSocket
+ this.marketDataService.unsubscribeViaWebSocket(this.config.provider, symbol).catch(() => {});
+
console.log(`[PaperTradingAdapter] Unsubscribed from ${symbol} - no longer needed`);
}
}
@@ -303,14 +315,17 @@ export class PaperTradingAdapter {
}
}
- // Balance = available cash (after margin reserved for positions)
- // Equity = Balance + Margin Used + Unrealized P&L = Total account value
- const equity = portfolio.balance + totalMarginUsed + totalUnrealizedPnl;
+ // Derivatives-style balance calculation:
+ // - Wallet Balance: Cash in account (doesn't change when opening positions)
+ // - Available Balance: Wallet Balance - Margin Used (what can be used for new positions)
+ // - Equity: Wallet Balance + Unrealized P&L (actual account value)
+ const availableBalance = portfolio.balance - totalMarginUsed;
+ const equity = portfolio.balance + totalUnrealizedPnl;
return {
- free: { USD: portfolio.balance }, // Available margin (cash)
- used: { USD: totalMarginUsed }, // Margin locked in positions
- total: { USD: equity }, // Total equity (balance + margin + unrealized P&L)
+ free: { USD: Math.max(0, availableBalance) }, // Available margin (cash minus locked margin)
+ used: { USD: totalMarginUsed }, // Margin locked in positions
+ total: { USD: equity }, // Total equity (wallet + unrealized P&L)
};
}
@@ -319,7 +334,24 @@ export class PaperTradingAdapter {
}
async fetchOpenOrders(): Promise<any[]> {
- return getOrders(this.portfolioId, 'pending');
+ const orders = await getOrders(this.portfolioId, 'pending');
+ // Normalize to CCXT-style format expected by UI components
+ return orders.map(order => ({
+ id: order.id,
+ symbol: order.symbol,
+ type: order.order_type,
+ side: order.side,
+ amount: order.quantity,
+ price: order.price,
+ stopPrice: order.stop_price,
+ filled: order.filled_qty,
+ remaining: order.quantity - order.filled_qty,
+ average: order.avg_price,
+ status: order.status,
+ datetime: order.created_at,
+ timestamp: new Date(order.created_at).getTime(),
+ reduceOnly: order.reduce_only,
+ }));
}
async fetchMyTrades(_symbol?: string, _since?: number, limit?: number): Promise<any[]> {
@@ -416,13 +448,21 @@ export class PaperTradingAdapter {
}
async cancelOrder(orderId: string, _symbol?: string): Promise<any> {
- // Remove from matcher
- this.orderMatcher.removeOrder(orderId);
+ console.log(`[PaperTradingAdapter] Canceling order: ${orderId}`);
- // Cancel in Rust backend
- await cancelOrder(orderId);
+ try {
+ // Remove from matcher first
+ this.orderMatcher.removeOrder(orderId);
- return { id: orderId, status: 'cancelled' };
+ // Cancel in Rust backend
+ await cancelOrderInBackend(orderId);
+
+ console.log(`[PaperTradingAdapter] Order ${orderId} canceled successfully`);
+ return { id: orderId, status: 'cancelled' };
+ } catch (error) {
+ console.error(`[PaperTradingAdapter] Failed to cancel order ${orderId}:`, error);
+ throw error;
+ }
}
async fetchOrder(orderId: string, _symbol?: string): Promise<any> {
diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.ts
index 4e8030ab3..344838770 100644
--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts
@@ -35,6 +35,8 @@ export interface ApiKeys {
FINANCIAL_MODELING_PREP_API_KEY?: string;
OPENROUTER_API_KEY?: string;
DATABENTO_API_KEY?: string;
+ WTO_API_KEY?: string;
+ EIA_API_KEY?: string;
[key: string]: string | undefined;
}
@@ -47,6 +49,8 @@ export const PREDEFINED_API_KEYS = [
{ key: 'FINANCIAL_MODELING_PREP_API_KEY', label: 'Financial Modeling Prep', description: 'Financial statements & ratios' },
{ key: 'DATABENTO_API_KEY', label: 'Databento API Key', description: 'Institutional-grade market data (Options, Equities, Futures)' },
{ key: 'OPENROUTER_API_KEY', label: 'OpenRouter API Key', description: 'Access 400+ AI models from all providers (Model Library)' },
+ { key: 'WTO_API_KEY', label: 'WTO API Key', description: 'World Trade Organization - Trade statistics, restrictions & notifications' },
+ { key: 'EIA_API_KEY', label: 'EIA API Key', description: 'U.S. Energy Information Administration - Petroleum, natural gas & energy data' },
] as const;
// LLM Provider configurations
diff --git a/fincept-terminal-desktop/src/services/trading/UnifiedMarketDataService.ts b/fincept-terminal-desktop/src/services/trading/UnifiedMarketDataService.ts
index 56df6b8b0..d0ffa51ae 100644
--- a/fincept-terminal-desktop/src/services/trading/UnifiedMarketDataService.ts
+++ b/fincept-terminal-desktop/src/services/trading/UnifiedMarketDataService.ts
@@ -20,6 +20,15 @@ export interface PriceData {
changePercent?: number;
}
+/**
+ * Normalize a symbol for consistent lookup
+ * Removes slashes, dashes, underscores and converts to uppercase
+ * E.g., "BTC/USD", "BTC-USD", "BTCUSD" all become "BTCUSD"
+ */
+function normalizeSymbol(symbol: string): string {
+ return symbol.replace(/[/\-_]/g, '').toUpperCase();
+}
+
// Event types emitted by the service
export interface MarketDataEvents {
priceUpdate: (data: PriceData & { symbol: string }) => void;
@@ -45,15 +54,19 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
// Cache: Map<"provider:symbol", PriceData>
private priceCache: Map<string, PriceData> = new Map();
- // Symbol -> providers that support it
+ // Symbol (normalized) -> providers that support it
private symbolProviders: Map<string, Set<string>> = new Map();
- // Symbol -> preferred provider
+ // Symbol (normalized) -> preferred provider
private symbolPreferredProvider: Map<string, string> = new Map();
- // Symbol -> array of callbacks
+ // Symbol (normalized) -> array of callbacks
+ // We use normalized symbols as keys for consistent lookup
private subscriptions: Map<string, Set<PriceCallback>> = new Map();
+ // Map original symbol -> normalized symbol for reverse lookup
+ private symbolNormalizationMap: Map<string, string> = new Map();
+
// Active WebSocket subscriptions
private activeWsSubscriptions: Map<string, boolean> = new Map();
@@ -118,21 +131,30 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
changePercent: ticker.change_percent,
};
- // Update cache
+ // Normalize symbol for consistent lookup
+ const normalizedSymbol = normalizeSymbol(ticker.symbol);
+
+ // Update cache with both original and normalized keys for flexibility
const cacheKey = `${ticker.provider}:${ticker.symbol}`;
+ const normalizedCacheKey = `${ticker.provider}:${normalizedSymbol}`;
this.priceCache.set(cacheKey, price);
+ this.priceCache.set(normalizedCacheKey, price);
- // Track which providers support this symbol
- if (!this.symbolProviders.has(ticker.symbol)) {
- this.symbolProviders.set(ticker.symbol, new Set());
+ // Track which providers support this symbol (using normalized key)
+ if (!this.symbolProviders.has(normalizedSymbol)) {
+ this.symbolProviders.set(normalizedSymbol, new Set());
}
- this.symbolProviders.get(ticker.symbol)!.add(ticker.provider);
+ this.symbolProviders.get(normalizedSymbol)!.add(ticker.provider);
+
+ // Also track original symbol
+ this.symbolNormalizationMap.set(ticker.symbol, normalizedSymbol);
- // Emit to EventEmitter listeners
+ // Emit to EventEmitter listeners (with original symbol for backward compatibility)
this.emit('priceUpdate', { ...price, symbol: ticker.symbol });
- // Notify direct subscribers for this symbol
- const callbacks = this.subscriptions.get(ticker.symbol);
+ // Notify direct subscribers for this symbol (using NORMALIZED key)
+ // This ensures "BTC/USD", "BTC-USD", and "BTCUSD" all match
+ const callbacks = this.subscriptions.get(normalizedSymbol);
if (callbacks) {
for (const callback of callbacks) {
try {
@@ -151,18 +173,23 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
* @returns Price data or undefined if not available
*/
getCurrentPrice(symbol: string, preferredProvider?: string): PriceData | undefined {
- // Try preferred provider first
- const provider = preferredProvider || this.symbolPreferredProvider.get(symbol);
+ const normalizedSymbol = normalizeSymbol(symbol);
+
+ // Try preferred provider first (using normalized symbol)
+ const provider = preferredProvider || this.symbolPreferredProvider.get(normalizedSymbol);
if (provider) {
- const price = this.priceCache.get(`${provider}:${symbol}`);
+ // Try normalized key first, then original
+ const price = this.priceCache.get(`${provider}:${normalizedSymbol}`) ||
+ this.priceCache.get(`${provider}:${symbol}`);
if (price) return price;
}
- // Try any available provider
- const providers = this.symbolProviders.get(symbol);
+ // Try any available provider (using normalized lookup)
+ const providers = this.symbolProviders.get(normalizedSymbol);
if (providers) {
for (const p of providers) {
- const price = this.priceCache.get(`${p}:${symbol}`);
+ const price = this.priceCache.get(`${p}:${normalizedSymbol}`) ||
+ this.priceCache.get(`${p}:${symbol}`);
if (price) return price;
}
}
@@ -175,11 +202,13 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
*/
getAllPrices(symbol: string): Map<string, PriceData> {
const result = new Map<string, PriceData>();
- const providers = this.symbolProviders.get(symbol);
+ const normalizedSymbol = normalizeSymbol(symbol);
+ const providers = this.symbolProviders.get(normalizedSymbol);
if (providers) {
for (const provider of providers) {
- const price = this.priceCache.get(`${provider}:${symbol}`);
+ const price = this.priceCache.get(`${provider}:${normalizedSymbol}`) ||
+ this.priceCache.get(`${provider}:${symbol}`);
if (price) {
result.set(provider, price);
}
@@ -193,26 +222,30 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
* Set preferred provider for a symbol
*/
setPreferredProvider(symbol: string, provider: string): void {
- this.symbolPreferredProvider.set(symbol, provider);
+ const normalizedSymbol = normalizeSymbol(symbol);
+ this.symbolPreferredProvider.set(normalizedSymbol, provider);
}
/**
* Subscribe to price updates for a symbol
* Returns an unsubscribe function
+ * Note: Uses normalized symbol internally for consistent matching
*/
subscribeToPrice(symbol: string, callback: PriceCallback): () => void {
- if (!this.subscriptions.has(symbol)) {
- this.subscriptions.set(symbol, new Set());
+ const normalizedSymbol = normalizeSymbol(symbol);
+
+ if (!this.subscriptions.has(normalizedSymbol)) {
+ this.subscriptions.set(normalizedSymbol, new Set());
}
- this.subscriptions.get(symbol)!.add(callback);
+ this.subscriptions.get(normalizedSymbol)!.add(callback);
- // Return unsubscribe function
+ // Return unsubscribe function (uses normalized symbol)
return () => {
- const callbacks = this.subscriptions.get(symbol);
+ const callbacks = this.subscriptions.get(normalizedSymbol);
if (callbacks) {
callbacks.delete(callback);
if (callbacks.size === 0) {
- this.subscriptions.delete(symbol);
+ this.subscriptions.delete(normalizedSymbol);
}
}
};
@@ -245,13 +278,18 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
* This actually connects to the provider's WebSocket
*/
async subscribeViaWebSocket(provider: string, symbol: string): Promise<void> {
- const key = `${provider}:${symbol}`;
- if (this.activeWsSubscriptions.has(key)) return;
+ // Use original symbol for WebSocket subscription (provider expects specific format)
+ // But track using normalized key to prevent duplicate subscriptions
+ const normalizedKey = `${provider}:${normalizeSymbol(symbol)}`;
+ if (this.activeWsSubscriptions.has(normalizedKey)) {
+ console.log(`[UnifiedMarketDataService] Already subscribed to ${provider}:${symbol} (normalized: ${normalizedKey})`);
+ return;
+ }
try {
await websocketBridge.subscribe(provider, symbol, 'ticker');
- this.activeWsSubscriptions.set(key, true);
- console.log(`[UnifiedMarketDataService] Subscribed to ${provider}:${symbol}`);
+ this.activeWsSubscriptions.set(normalizedKey, true);
+ console.log(`[UnifiedMarketDataService] Subscribed to ${provider}:${symbol} (normalized: ${normalizedKey})`);
} catch (error) {
console.error(`[UnifiedMarketDataService] Failed to subscribe to ${provider}:${symbol}:`, error);
throw error;
@@ -262,12 +300,12 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
* Unsubscribe from WebSocket feed for a symbol
*/
async unsubscribeViaWebSocket(provider: string, symbol: string): Promise<void> {
- const key = `${provider}:${symbol}`;
- if (!this.activeWsSubscriptions.has(key)) return;
+ const normalizedKey = `${provider}:${normalizeSymbol(symbol)}`;
+ if (!this.activeWsSubscriptions.has(normalizedKey)) return;
try {
await websocketBridge.unsubscribe(provider, symbol, 'ticker');
- this.activeWsSubscriptions.delete(key);
+ this.activeWsSubscriptions.delete(normalizedKey);
console.log(`[UnifiedMarketDataService] Unsubscribed from ${provider}:${symbol}`);
} catch (error) {
console.error(`[UnifiedMarketDataService] Failed to unsubscribe from ${provider}:${symbol}:`, error);
@@ -286,7 +324,7 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
}
/**
- * Get all symbols with price data
+ * Get all symbols with price data (returns normalized symbols)
*/
getAvailableSymbols(): string[] {
return Array.from(this.symbolProviders.keys());
@@ -296,7 +334,8 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
* Get all providers for a symbol
*/
getProvidersForSymbol(symbol: string): string[] {
- const providers = this.symbolProviders.get(symbol);
+ const normalizedSymbol = normalizeSymbol(symbol);
+ const providers = this.symbolProviders.get(normalizedSymbol);
return providers ? Array.from(providers) : [];
}
@@ -312,10 +351,20 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
*/
async destroy(): Promise<void> {
// Unsubscribe from all WebSocket feeds
+ // Note: Keys are in normalized format (provider:NORMALIZEDSYMBOL)
for (const key of this.activeWsSubscriptions.keys()) {
- const [provider, symbol] = key.split(':');
- await this.unsubscribeViaWebSocket(provider, symbol);
+ const colonIndex = key.indexOf(':');
+ if (colonIndex > 0) {
+ const provider = key.substring(0, colonIndex);
+ const normalizedSymbol = key.substring(colonIndex + 1);
+ try {
+ await websocketBridge.unsubscribe(provider, normalizedSymbol, 'ticker');
+ } catch {
+ // Ignore cleanup errors
+ }
+ }
}
+ this.activeWsSubscriptions.clear();
// Remove WebSocket listeners
for (const unlisten of this.wsUnlisteners) {
@@ -328,6 +377,7 @@ export class UnifiedMarketDataService extends EventEmitter<MarketDataEvents> {
this.subscriptions.clear();
this.symbolProviders.clear();
this.symbolPreferredProvider.clear();
+ this.symbolNormalizationMap.clear();
this.initialized = false;
this.removeAllListeners();
diff --git a/scripts/generate_latest_json.py b/scripts/generate_latest_json.py
deleted file mode 100644
index a8f36b4bd..000000000
--- a/scripts/generate_latest_json.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/env python3
-"""Generate unified latest.json for Tauri auto-updater from platform-specific build artifacts."""
-
-import json
-import os
-import glob
-import sys
-from datetime import datetime, timezone
-
-
-def main():
- version = os.environ.get('VERSION', '0.0.0')
- tag_name = os.environ.get('TAG_NAME', 'v0.0.0')
- repo_url = os.environ.get('REPO_URL', '')
-
- merged = {
- "version": version,
- "notes": f"FinceptTerminal {tag_name} - See release notes at {repo_url}/releases/tag/{tag_name}",
- "pub_date": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
- "platforms": {}
- }
-
- # Try to merge from platform-specific latest.json files first
- platform_files = glob.glob("all-artifacts/**/latest-*.json", recursive=True)
- print(f"Found {len(platform_files)} platform-specific latest.json files")
-
- for pf in platform_files:
- print(f"Processing: {pf}")
- try:
- with open(pf, 'r') as f:
- data = json.load(f)
- if 'platforms' in data:
- for platform_key, platform_data in data['platforms'].items():
- if 'url' in platform_data:
- filename = os.path.basename(platform_data['url'])
- platform_data['url'] = f"{repo_url}/releases/download/{tag_name}/{filename}"
- merged['platforms'].update(data['platforms'])
- print(f" Added platforms: {list(data['platforms'].keys())}")
- except Exception as e:
- print(f" Error processing {pf}: {e}")
-
- # If no platforms found from JSON files, generate from artifacts
- if not merged['platforms']:
- print("No platforms found from JSON files, generating from artifacts...")
-
- # Windows NSIS (x86_64)
- nsis_zips = glob.glob("release-files/*-x86_64-windows.nsis.zip")
- nsis_sigs = glob.glob("release-files/*-x86_64-windows.nsis.zip.sig")
- if nsis_zips and nsis_sigs:
- nsis_filename = os.path.basename(nsis_zips[0])
- with open(nsis_sigs[0], 'r') as f:
- signature = f.read().strip()
- merged['platforms']['windows-x86_64'] = {
- "signature": signature,
- "url": f"{repo_url}/releases/download/{tag_name}/{nsis_filename}"
- }
- print(f"Added windows-x86_64 from artifacts: {nsis_filename}")
-
- # macOS ARM64 (aarch64)
- macos_arm_tars = glob.glob("release-files/*-arm64-darwin.app.tar.gz")
- macos_arm_sigs = glob.glob("release-files/*-arm64-darwin.app.tar.gz.sig")
- if macos_arm_tars and macos_arm_sigs:
- tar_filename = os.path.basename(macos_arm_tars[0])
- with open(macos_arm_sigs[0], 'r') as f:
- signature = f.read().strip()
- merged['platforms']['darwin-aarch64'] = {
- "signature": signature,
- "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"
- }
- print(f"Added darwin-aarch64 from artifacts: {tar_filename}")
-
- # macOS x64 (x86_64)
- macos_x64_tars = glob.glob("release-files/*-x64-darwin.app.tar.gz")
- macos_x64_sigs = glob.glob("release-files/*-x64-darwin.app.tar.gz.sig")
- if macos_x64_tars and macos_x64_sigs:
- tar_filename = os.path.basename(macos_x64_tars[0])
- with open(macos_x64_sigs[0], 'r') as f:
- signature = f.read().strip()
- merged['platforms']['darwin-x86_64'] = {
- "signature": signature,
- "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"
- }
- print(f"Added darwin-x86_64 from artifacts: {tar_filename}")
-
- # Linux x86_64
- linux_tars = glob.glob("release-files/*-x86_64-linux.AppImage.tar.gz")
- linux_sigs = glob.glob("release-files/*-x86_64-linux.AppImage.tar.gz.sig")
- if linux_tars and linux_sigs:
- tar_filename = os.path.basename(linux_tars[0])
- with open(linux_sigs[0], 'r') as f:
- signature = f.read().strip()
- merged['platforms']['linux-x86_64'] = {
- "signature": signature,
- "url": f"{repo_url}/releases/download/{tag_name}/{tar_filename}"
- }
- print(f"Added linux-x86_64 from artifacts: {tar_filename}")
-
- # Write the merged JSON
- with open('release-files/latest.json', 'w') as f:
- json.dump(merged, f, indent=2)
-
- print(f"\n=== Generated latest.json ===")
- print(json.dumps(merged, indent=2))
-
- if not merged['platforms']:
- print("ERROR: No platforms found for latest.json!")
- return 1
-
- print(f"\nSuccessfully generated latest.json with {len(merged['platforms'])} platform(s)")
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/scripts/update_readme_downloads.py b/scripts/update_readme_downloads.py
deleted file mode 100644
index 63693ab01..000000000
--- a/scripts/update_readme_downloads.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/usr/bin/env python3
-"""Update README.md download section with latest release links."""
-
-import os
-import re
-import sys
-
-
-def main():
- version = os.environ.get('VERSION', '0.0.0')
- tag = os.environ.get('TAG_NAME', 'v0.0.0')
- repo = os.environ.get('REPO_URL', '')
-
- section = f"""<!-- DOWNLOAD_SECTION_START -->
-## Download Latest Release
-
-**Version:** `{tag}`
-
-| Platform | Architecture | Download |
-|----------|-------------|----------|
-| **macOS** | Apple Silicon | [Download]({repo}/releases/download/{tag}/FinceptTerminal-v{version}-macOS-arm64.dmg) |
-| **macOS** | Intel | [Download]({repo}/releases/download/{tag}/FinceptTerminal-v{version}-macOS-x64.dmg) |
-| **Linux** | x64 (AppImage) | [Download]({repo}/releases/download/{tag}/FinceptTerminal-v{version}-Linux-x64.AppImage) |
-| **Linux** | x64 (Debian) | [Download]({repo}/releases/download/{tag}/FinceptTerminal-v{version}-Linux-x64.deb) |
-| **Windows** | x64 | [Download]({repo}/releases/download/{tag}/FinceptTerminal-v{version}-Windows-x64.msi) |
-
-[View All Releases]({repo}/releases)
-<!-- DOWNLOAD_SECTION_END -->"""
-
- readme_path = 'README.md'
- if not os.path.exists(readme_path):
- print("README.md not found")
- return 1
-
- with open(readme_path, 'r') as f:
- content = f.read()
-
- updated = re.sub(
- r'<!-- DOWNLOAD_SECTION_START -->.*?<!-- DOWNLOAD_SECTION_END -->',
- section, content, flags=re.DOTALL
- )
-
- with open(readme_path, 'w') as f:
- f.write(updated)
-
- print(f"README.md updated with {tag} download links")
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())