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.

v3.3.0 update

tilakpatel2287bf85e7580f
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py
index 1d744e4c6..98f022b89 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/corporateFinance/config.py
@@ -1,12 +1,34 @@
"""Configuration for Corporate Finance Module"""
+import os
from pathlib import Path
BASE_DIR = Path(__file__).parent
SCRIPTS_DIR = BASE_DIR.parent.parent
RESOURCES_DIR = SCRIPTS_DIR.parent
-DATABASE_DIR = RESOURCES_DIR / "databases"
+
+# Database path: Use FINCEPT_DATA_DIR env var if set, otherwise fall back to user data dir
+def get_database_dir() -> Path:
+ """Get the database directory from environment or default user data location."""
+ # Check for environment variable passed from Rust
+ if data_dir := os.environ.get("FINCEPT_DATA_DIR"):
+ return Path(data_dir)
+
+ # Default to platform-specific user data directory
+ if os.name == "nt": # Windows
+ base = Path(os.environ.get("LOCALAPPDATA", "C:/Users/Default/AppData/Local"))
+ elif os.uname().sysname == "Darwin": # macOS
+ base = Path.home() / "Library" / "Application Support"
+ else: # Linux
+ base = Path.home() / ".local" / "share"
+
+ return base / "fincept-dev"
+
+DATABASE_DIR = get_database_dir()
MA_DATABASE = DATABASE_DIR / "ma_deals.db"
+# Ensure database directory exists
+DATABASE_DIR.mkdir(parents=True, exist_ok=True)
+
DEFAULT_DISCOUNT_RATE = 0.10
DEFAULT_TERMINAL_GROWTH = 0.025
DEFAULT_TAX_RATE = 0.21
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
index bb893c48a..a56e1cab5 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py
@@ -362,19 +362,40 @@ class ModelsRegistry:
if final_api_key:
model_kwargs["api_key"] = final_api_key
- # Add base_url - check api_keys for custom endpoint, then config default
- base_url_key = f"{provider.upper()}_BASE_URL"
- custom_base_url = (api_keys or {}).get(base_url_key)
- if custom_base_url:
- model_kwargs["base_url"] = custom_base_url
- elif config.get("base_url"):
- model_kwargs["base_url"] = kwargs.pop("base_url", config["base_url"])
-
- # Add optional parameters (Agno uses these names)
+ # Providers whose SDK constructors do NOT accept base_url
+ NO_BASE_URL_PROVIDERS = {
+ "google", "vertexai", "anthropic", "aws", "ibm",
+ "cohere", "meta", "cerebras", "sambanova", "nebius",
+ "internlm", "dashscope", "siliconflow",
+ }
+
+ # Always pop base_url from kwargs so it never leaks via catch-all
+ kwarg_base_url = kwargs.pop("base_url", None)
+
+ if provider_lower not in NO_BASE_URL_PROVIDERS:
+ # Add base_url - check api_keys for custom endpoint, then config default
+ base_url_key = f"{provider.upper()}_BASE_URL"
+ custom_base_url = (api_keys or {}).get(base_url_key)
+ if custom_base_url:
+ model_kwargs["base_url"] = custom_base_url
+ elif kwarg_base_url:
+ model_kwargs["base_url"] = kwarg_base_url
+ elif config.get("base_url"):
+ model_kwargs["base_url"] = config["base_url"]
+
+ # Add optional parameters with provider-specific name mapping
+ # Google Gemini uses max_output_tokens instead of max_tokens
+ USES_MAX_OUTPUT_TOKENS = {"google", "vertexai"}
+
if "temperature" in kwargs:
model_kwargs["temperature"] = kwargs.pop("temperature")
if "max_tokens" in kwargs:
- model_kwargs["max_tokens"] = kwargs.pop("max_tokens")
+ max_tok = kwargs.pop("max_tokens")
+ if max_tok is not None:
+ if provider_lower in USES_MAX_OUTPUT_TOKENS:
+ model_kwargs["max_output_tokens"] = max_tok
+ else:
+ model_kwargs["max_tokens"] = max_tok
if "max_completion_tokens" in kwargs:
model_kwargs["max_completion_tokens"] = kwargs.pop("max_completion_tokens")
@@ -383,6 +404,11 @@ class ModelsRegistry:
if v is not None:
model_kwargs[k] = v
+ # DEBUG: log exactly what we're passing to the constructor
+ import sys
+ print(f"[DEBUG models_registry] provider={provider_lower}, class={class_name}, model_kwargs keys={list(model_kwargs.keys())}", file=sys.stderr, flush=True)
+ print(f"[DEBUG models_registry] model_kwargs={model_kwargs}", file=sys.stderr, flush=True)
+
model_instance = model_class(**model_kwargs)
logger.debug(f"Created model: {provider}/{final_model_id}")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py
index d542ddd57..e31bc3372 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/condition_evaluator.py
@@ -13,6 +13,12 @@ Input conditions JSON format:
{"indicator":"MACD","params":{"fast":12,"slow":26,"signal":9},"field":"histogram","operator":">","value":0}
]
+ Indicator-vs-indicator comparison:
+ [
+ {"indicator":"CLOSE","params":{},"field":"value","operator":"crosses_above",
+ "compareMode":"indicator","compareIndicator":"EMA","compareParams":{"period":20},"compareField":"value"}
+ ]
+
Output:
{"success": true, "result": true/false, "details": [...]}
"""
@@ -26,7 +32,7 @@ import math
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from indicators import get_latest_value, get_last_n_values
+from indicators import get_latest_value, get_last_n_values, get_value_at_offset
def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int = 200) -> pd.DataFrame:
@@ -49,22 +55,72 @@ def load_candles_from_db(db_path: str, symbol: str, timeframe: str, limit: int =
return df
+def _get_target_value(condition: dict, df: pd.DataFrame):
+ """
+ Get the comparison target value(s). Supports both numeric and indicator comparison modes.
+
+ Returns:
+ For non-crossing operators: (current_target_value, None)
+ For crossing operators: (current_target_value, previous_target_value)
+ Also returns target_info dict for debug output.
+ """
+ compare_mode = condition.get('compareMode', 'value')
+ operator = condition.get('operator', '>')
+ compare_offset = condition.get('compareOffset', 0)
+
+ if compare_mode == 'indicator':
+ compare_indicator = condition.get('compareIndicator', '')
+ compare_params = condition.get('compareParams', {})
+ compare_field = condition.get('compareField', 'value')
+
+ if not compare_indicator:
+ raise ValueError('compareIndicator is required when compareMode is "indicator"')
+
+ target_info = {
+ 'target_indicator': compare_indicator,
+ 'target_field': compare_field,
+ }
+
+ if operator in ('crosses_above', 'crosses_below'):
+ # Need last 2 values for both sides
+ target_values = get_last_n_values(compare_indicator, df, compare_params, compare_field, n=2)
+ if len(target_values) < 2:
+ raise ValueError(f'Insufficient data for {compare_indicator}')
+ target_info['target_computed_value'] = target_values[-1]
+ return target_values[-1], target_values[-2], target_info
+ else:
+ if compare_offset > 0:
+ val = get_value_at_offset(compare_indicator, df, compare_params, compare_field, compare_offset)
+ else:
+ val = get_latest_value(compare_indicator, df, compare_params, compare_field)
+ target_info['target_computed_value'] = val
+ return val, None, target_info
+ else:
+ target_value = condition.get('value', 0)
+ return target_value, None, {}
+
+
def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
"""
Evaluate a single condition against candle data.
-
- Returns: {"met": bool, "indicator": str, "field": str, "computed_value": float, "operator": str, "target": float}
+ Supports indicator-vs-indicator comparison, offsets, and advanced operators.
"""
indicator = condition.get('indicator', '')
params = condition.get('params', {})
field = condition.get('field', 'value')
operator = condition.get('operator', '>')
- target_value = condition.get('value', 0)
+ target_value_raw = condition.get('value', 0)
target_value2 = condition.get('value2', None)
+ offset = condition.get('offset', 0)
+ compare_mode = condition.get('compareMode', 'value')
+ lookback = condition.get('lookback', 5)
try:
+ # Get target value(s) — may be numeric or from another indicator
+ target_current, target_prev, target_info = _get_target_value(condition, df)
+
+ # ── Crossing operators ────────────────────────────────────────
if operator in ('crosses_above', 'crosses_below'):
- # Need last 2 values for crossing detection
values = get_last_n_values(indicator, df, params, field, n=2)
if len(values) < 2 or any(math.isnan(v) for v in values):
return {
@@ -73,15 +129,25 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
'field': field,
'computed_value': values[-1] if values else None,
'operator': operator,
- 'target': target_value,
- 'error': 'Insufficient data for crossing detection'
+ 'target': target_current if isinstance(target_current, (int, float)) else 0,
+ 'error': 'Insufficient data for crossing detection',
+ **target_info,
}
prev_val, curr_val = values
- if operator == 'crosses_above':
- met = prev_val <= target_value and curr_val > target_value
+
+ if compare_mode == 'indicator' and target_prev is not None:
+ # Crossing relative to another indicator
+ if operator == 'crosses_above':
+ met = prev_val <= target_prev and curr_val > target_current
+ else:
+ met = prev_val >= target_prev and curr_val < target_current
else:
- met = prev_val >= target_value and curr_val < target_value
+ # Crossing relative to a fixed value
+ if operator == 'crosses_above':
+ met = prev_val <= target_current and curr_val > target_current
+ else:
+ met = prev_val >= target_current and curr_val < target_current
return {
'met': met,
@@ -90,10 +156,76 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
'computed_value': curr_val,
'prev_value': prev_val,
'operator': operator,
- 'target': target_value,
+ 'target': target_current if isinstance(target_current, (int, float)) else 0,
+ **target_info,
}
+
+ # ── Crossed within N bars ─────────────────────────────────────
+ elif operator in ('crossed_above_within', 'crossed_below_within'):
+ n = int(lookback) + 1
+ values = get_last_n_values(indicator, df, params, field, n=n)
+ if len(values) < 2:
+ return {
+ 'met': False, 'indicator': indicator, 'field': field,
+ 'computed_value': values[-1] if values else None,
+ 'operator': operator, 'target': target_current,
+ 'error': 'Insufficient data',
+ }
+
+ # Check if any consecutive pair shows a crossing within the window
+ met = False
+ for i in range(len(values) - 1):
+ if operator == 'crossed_above_within':
+ if values[i] <= target_current and values[i + 1] > target_current:
+ met = True
+ break
+ else:
+ if values[i] >= target_current and values[i + 1] < target_current:
+ met = True
+ break
+
+ return {
+ 'met': met,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': values[-1],
+ 'operator': operator,
+ 'target': target_current if isinstance(target_current, (int, float)) else 0,
+ **target_info,
+ }
+
+ # ── Rising / Falling ──────────────────────────────────────────
+ elif operator in ('rising', 'falling'):
+ n = int(lookback)
+ values = get_last_n_values(indicator, df, params, field, n=n)
+ if len(values) < 2 or any(math.isnan(v) for v in values):
+ return {
+ 'met': False, 'indicator': indicator, 'field': field,
+ 'computed_value': values[-1] if values else None,
+ 'operator': operator, 'target': 0,
+ 'error': 'Insufficient data',
+ }
+
+ if operator == 'rising':
+ met = all(values[i] < values[i + 1] for i in range(len(values) - 1))
+ else:
+ met = all(values[i] > values[i + 1] for i in range(len(values) - 1))
+
+ return {
+ 'met': met,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': values[-1],
+ 'operator': operator,
+ 'target': 0,
+ }
+
+ # ── Standard comparison operators ─────────────────────────────
else:
- current_value = get_latest_value(indicator, df, params, field)
+ if offset > 0:
+ current_value = get_value_at_offset(indicator, df, params, field, offset)
+ else:
+ current_value = get_latest_value(indicator, df, params, field)
if math.isnan(current_value):
return {
@@ -102,23 +234,36 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
'field': field,
'computed_value': None,
'operator': operator,
- 'target': target_value,
- 'error': 'Indicator returned NaN'
+ 'target': target_current if isinstance(target_current, (int, float)) else 0,
+ 'error': 'Indicator returned NaN',
+ **target_info,
+ }
+
+ if math.isnan(target_current) if isinstance(target_current, float) else False:
+ return {
+ 'met': False,
+ 'indicator': indicator,
+ 'field': field,
+ 'computed_value': current_value,
+ 'operator': operator,
+ 'target': 0,
+ 'error': 'Target indicator returned NaN',
+ **target_info,
}
if operator == '>':
- met = current_value > target_value
+ met = current_value > target_current
elif operator == '<':
- met = current_value < target_value
+ met = current_value < target_current
elif operator == '>=':
- met = current_value >= target_value
+ met = current_value >= target_current
elif operator == '<=':
- met = current_value <= target_value
+ met = current_value <= target_current
elif operator == '==':
- met = abs(current_value - target_value) < 0.0001
+ met = abs(current_value - target_current) < 0.0001
elif operator == 'between':
if target_value2 is not None:
- met = target_value <= current_value <= target_value2
+ met = target_value_raw <= current_value <= target_value2
else:
met = False
else:
@@ -130,7 +275,8 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
'field': field,
'computed_value': current_value,
'operator': operator,
- 'target': target_value,
+ 'target': target_current if isinstance(target_current, (int, float)) else 0,
+ **target_info,
}
except Exception as e:
@@ -140,7 +286,7 @@ def evaluate_single_condition(condition: dict, df: pd.DataFrame) -> dict:
'field': field,
'computed_value': None,
'operator': operator,
- 'target': target_value,
+ 'target': target_value_raw,
'error': str(e)
}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py
index 97a109174..fb41e2eef 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/indicators.py
@@ -14,15 +14,23 @@ import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from technicals.momentum_indicators import (
- calculate_rsi, calculate_stochastic, calculate_williams_r, calculate_roc
+ calculate_rsi, calculate_stochastic, calculate_williams_r, calculate_roc,
+ calculate_stoch_rsi, calculate_tsi, calculate_ultimate_oscillator,
+ calculate_awesome_oscillator, calculate_kama, calculate_ppo, calculate_pvo
)
from technicals.trend_indicators import (
- calculate_sma, calculate_ema, calculate_macd, calculate_cci, calculate_adx
+ calculate_sma, calculate_ema, calculate_wma, calculate_macd, calculate_cci,
+ calculate_adx, calculate_ichimoku, calculate_psar, calculate_aroon,
+ calculate_stc, calculate_kst, calculate_vortex, calculate_dpo,
+ calculate_trix, calculate_mass_index
)
from technicals.volatility_indicators import (
calculate_atr, calculate_bollinger_bands, calculate_keltner_channel, calculate_donchian_channel
)
-from technicals.volume_indicators import calculate_obv
+from technicals.volume_indicators import (
+ calculate_obv, calculate_cmf, calculate_mfi, calculate_force_index,
+ calculate_adi, calculate_eom, calculate_vpt, calculate_nvi
+)
def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
@@ -39,11 +47,71 @@ def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
"""
name = name.upper()
- if name == 'RSI':
- period = params.get('period', 14)
- series = calculate_rsi(df, window=period, fillna=True)
- return {'value': series}
+ # ── Stock Attributes ──────────────────────────────────────────────
+ if name == 'CLOSE' or name == 'PRICE':
+ return {'value': df['close']}
+
+ elif name == 'OPEN':
+ return {'value': df['open']}
+
+ elif name == 'HIGH':
+ return {'value': df['high']}
+
+ elif name == 'LOW':
+ return {'value': df['low']}
+ elif name == 'VOLUME':
+ return {'value': df['volume']}
+
+ elif name == 'CHANGE_PCT':
+ pct = df['close'].pct_change() * 100
+ return {'value': pct.fillna(0)}
+
+ elif name == 'VWAP':
+ typical_price = (df['high'] + df['low'] + df['close']) / 3
+ cumulative_tp_vol = (typical_price * df['volume']).cumsum()
+ cumulative_vol = df['volume'].cumsum()
+ vwap = cumulative_tp_vol / cumulative_vol
+ return {'value': vwap}
+
+ elif name == 'HL2':
+ return {'value': (df['high'] + df['low']) / 2}
+
+ elif name == 'HLC3':
+ return {'value': (df['high'] + df['low'] + df['close']) / 3}
+
+ elif name == 'OHLC4':
+ return {'value': (df['open'] + df['high'] + df['low'] + df['close']) / 4}
+
+ # Heikin-Ashi candles
+ elif name == 'HA_CLOSE':
+ return {'value': (df['open'] + df['high'] + df['low'] + df['close']) / 4}
+
+ elif name == 'HA_OPEN':
+ ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
+ ha_open = pd.Series(index=df.index, dtype=float)
+ ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
+ for i in range(1, len(df)):
+ ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
+ return {'value': ha_open}
+
+ elif name == 'HA_HIGH':
+ ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
+ ha_open = pd.Series(index=df.index, dtype=float)
+ ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
+ for i in range(1, len(df)):
+ ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
+ return {'value': pd.concat([df['high'], ha_open, ha_close], axis=1).max(axis=1)}
+
+ elif name == 'HA_LOW':
+ ha_close = (df['open'] + df['high'] + df['low'] + df['close']) / 4
+ ha_open = pd.Series(index=df.index, dtype=float)
+ ha_open.iloc[0] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
+ for i in range(1, len(df)):
+ ha_open.iloc[i] = (ha_open.iloc[i - 1] + ha_close.iloc[i - 1]) / 2
+ return {'value': pd.concat([df['low'], ha_open, ha_close], axis=1).min(axis=1)}
+
+ # ── Moving Averages ───────────────────────────────────────────────
elif name == 'SMA':
period = params.get('period', 20)
series = calculate_sma(df, window=period, fillna=True)
@@ -54,59 +122,67 @@ def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
series = calculate_ema(df, window=period, fillna=True)
return {'value': series}
- elif name == 'MACD':
- fast = params.get('fast', 12)
- slow = params.get('slow', 26)
- signal = params.get('signal', 9)
- result = calculate_macd(df, window_fast=fast, window_slow=slow, window_sign=signal, fillna=True)
- return {
- 'line': result['macd'],
- 'signal_line': result['macd_signal'],
- 'histogram': result['macd_diff'],
- }
+ elif name == 'WMA':
+ period = params.get('period', 9)
+ series = calculate_wma(df, window=period, fillna=True)
+ return {'value': series}
- elif name == 'BOLLINGER' or name == 'BB':
+ elif name == 'KAMA':
+ period = params.get('period', 10)
+ pow1 = params.get('pow1', 2)
+ pow2 = params.get('pow2', 30)
+ series = calculate_kama(df, window=period, pow1=pow1, pow2=pow2, fillna=True)
+ return {'value': series}
+
+ elif name == 'TEMA':
period = params.get('period', 20)
- std_dev = params.get('std_dev', 2)
- result = calculate_bollinger_bands(df, window=period, window_dev=std_dev, fillna=True)
- # Calculate %B
- upper = result['bb_upper']
- lower = result['bb_lower']
- close = df['close']
- pct_b = (close - lower) / (upper - lower)
- return {
- 'upper': upper,
- 'middle': result['bb_middle'],
- 'lower': lower,
- 'pct_b': pct_b,
- }
+ ema1 = df['close'].ewm(span=period, adjust=False).mean()
+ ema2 = ema1.ewm(span=period, adjust=False).mean()
+ ema3 = ema2.ewm(span=period, adjust=False).mean()
+ return {'value': 3 * ema1 - 3 * ema2 + ema3}
- elif name == 'ATR':
- period = params.get('period', 14)
- series = calculate_atr(df, window=period, fillna=True)
- return {'value': series}
+ elif name == 'DEMA':
+ period = params.get('period', 20)
+ ema1 = df['close'].ewm(span=period, adjust=False).mean()
+ ema2 = ema1.ewm(span=period, adjust=False).mean()
+ return {'value': 2 * ema1 - ema2}
- elif name == 'ADX':
+ elif name == 'HMA':
period = params.get('period', 14)
- result = calculate_adx(df, window=period, fillna=True)
- return {
- 'value': result['adx'],
- 'plus_di': result['adx_pos'],
- 'minus_di': result['adx_neg'],
- }
+ half_period = max(int(period / 2), 1)
+ sqrt_period = max(int(period ** 0.5), 1)
+ wma_half = df['close'].rolling(half_period).apply(
+ lambda x: np.average(x, weights=range(1, half_period + 1)), raw=True
+ )
+ wma_full = df['close'].rolling(period).apply(
+ lambda x: np.average(x, weights=range(1, period + 1)), raw=True
+ )
+ diff = 2 * wma_half - wma_full
+ hma = diff.rolling(sqrt_period).apply(
+ lambda x: np.average(x, weights=range(1, sqrt_period + 1)), raw=True
+ )
+ return {'value': hma.bfill()}
+
+ elif name == 'RMA':
+ period = params.get('period', 14)
+ rma = df['close'].ewm(alpha=1.0 / period, adjust=False).mean()
+ return {'value': rma}
- elif name == 'CCI':
+ elif name == 'TMA':
period = params.get('period', 20)
- series = calculate_cci(df, window=period, fillna=True)
- return {'value': series}
+ sma1 = df['close'].rolling(window=period).mean()
+ tma = sma1.rolling(window=period).mean()
+ return {'value': tma.bfill()}
- elif name == 'OBV':
- series = calculate_obv(df, fillna=True)
- return {'value': series}
+ elif name == 'VWMA':
+ period = params.get('period', 20)
+ vwma = (df['close'] * df['volume']).rolling(period).sum() / df['volume'].rolling(period).sum()
+ return {'value': vwma}
- elif name == 'WILLIAMS_R' or name == 'WILLR':
+ # ── Momentum ──────────────────────────────────────────────────────
+ elif name == 'RSI':
period = params.get('period', 14)
- series = calculate_williams_r(df, lbp=period, fillna=True)
+ series = calculate_rsi(df, window=period, fillna=True)
return {'value': series}
elif name == 'STOCHASTIC' or name == 'STOCH':
@@ -118,29 +194,94 @@ def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
'd': result['stoch_d'],
}
+ elif name == 'STOCH_RSI':
+ period = params.get('period', 14)
+ smooth1 = params.get('smooth1', 3)
+ smooth2 = params.get('smooth2', 3)
+ result = calculate_stoch_rsi(df, window=period, smooth1=smooth1, smooth2=smooth2, fillna=True)
+ return {
+ 'stoch_rsi': result['stoch_rsi'],
+ 'k': result['stoch_rsi_k'],
+ 'd': result['stoch_rsi_d'],
+ }
+
+ elif name == 'WILLIAMS_R' or name == 'WILLR':
+ period = params.get('period', 14)
+ series = calculate_williams_r(df, lbp=period, fillna=True)
+ return {'value': series}
+
elif name == 'ROC' or name == 'MOMENTUM':
period = params.get('period', 12)
series = calculate_roc(df, window=period, fillna=True)
return {'value': series}
- elif name == 'KELTNER':
- period = params.get('period', 20)
- result = calculate_keltner_channel(df, window=period, fillna=True)
+ elif name == 'TSI':
+ window_slow = params.get('window_slow', 25)
+ window_fast = params.get('window_fast', 13)
+ series = calculate_tsi(df, window_slow=window_slow, window_fast=window_fast, fillna=True)
+ return {'value': series}
+
+ elif name == 'ULTIMATE_OSCILLATOR':
+ w1 = params.get('window1', 7)
+ w2 = params.get('window2', 14)
+ w3 = params.get('window3', 28)
+ series = calculate_ultimate_oscillator(df, window1=w1, window2=w2, window3=w3, fillna=True)
+ return {'value': series}
+
+ elif name == 'AWESOME_OSCILLATOR':
+ w1 = params.get('window1', 5)
+ w2 = params.get('window2', 34)
+ series = calculate_awesome_oscillator(df, window1=w1, window2=w2, fillna=True)
+ return {'value': series}
+
+ elif name == 'PPO':
+ fast = params.get('fast', 12)
+ slow = params.get('slow', 26)
+ signal = params.get('signal', 9)
+ result = calculate_ppo(df, window_slow=slow, window_fast=fast, window_sign=signal, fillna=True)
return {
- 'upper': result['kc_upper'],
- 'middle': result['kc_middle'],
- 'lower': result['kc_lower'],
+ 'ppo': result['ppo'],
+ 'ppo_signal': result['ppo_signal'],
+ 'ppo_hist': result['ppo_hist'],
}
- elif name == 'DONCHIAN':
- period = params.get('period', 20)
- result = calculate_donchian_channel(df, window=period, fillna=True)
+ elif name == 'PVO':
+ window_slow = params.get('window_slow', 26)
+ window_fast = params.get('window_fast', 12)
+ window_sign = params.get('window_sign', 9)
+ result = calculate_pvo(df, window_slow=window_slow, window_fast=window_fast, window_sign=window_sign, fillna=True)
return {
- 'upper': result['dc_upper'],
- 'middle': result['dc_middle'],
- 'lower': result['dc_lower'],
+ 'pvo': result['pvo'],
+ 'pvo_signal': result['pvo_signal'],
+ 'pvo_hist': result['pvo_hist'],
+ }
+
+ # ── Trend ─────────────────────────────────────────────────────────
+ elif name == 'MACD':
+ fast = params.get('fast', 12)
+ slow = params.get('slow', 26)
+ signal = params.get('signal', 9)
+ result = calculate_macd(df, window_fast=fast, window_slow=slow, window_sign=signal, fillna=True)
+ return {
+ 'line': result['macd'],
+ 'signal_line': result['macd_signal'],
+ 'histogram': result['macd_diff'],
+ }
+
+ elif name == 'ADX':
+ period = params.get('period', 14)
+ result = calculate_adx(df, window=period, fillna=True)
+ return {
+ 'value': result['adx'],
+ 'plus_di': result['adx_pos'],
+ 'minus_di': result['adx_neg'],
}
+ elif name == 'CCI':
+ period = params.get('period', 20)
+ series = calculate_cci(df, window=period, fillna=True)
+ return {'value': series}
+
elif name == 'SUPERTREND':
period = params.get('period', 10)
multiplier = params.get('multiplier', 3.0)
@@ -167,22 +308,207 @@ def compute_indicator(name: str, df: pd.DataFrame, params: dict) -> dict:
'direction': direction,
}
- elif name == 'VWAP':
- typical_price = (df['high'] + df['low'] + df['close']) / 3
- cumulative_tp_vol = (typical_price * df['volume']).cumsum()
- cumulative_vol = df['volume'].cumsum()
- vwap = cumulative_tp_vol / cumulative_vol
- return {'value': vwap}
+ elif name == 'ICHIMOKU':
+ w1 = params.get('window1', 9)
+ w2 = params.get('window2', 26)
+ w3 = params.get('window3', 52)
+ result = calculate_ichimoku(df, window1=w1, window2=w2, window3=w3, fillna=True)
+ return {
+ 'conversion': result['ichimoku_conversion'],
+ 'base': result['ichimoku_base'],
+ 'span_a': result['ichimoku_a'],
+ 'span_b': result['ichimoku_b'],
+ }
- elif name == 'PRICE':
- return {'value': df['close']}
+ elif name == 'PSAR':
+ step = params.get('step', 0.02)
+ max_step = params.get('max_step', 0.2)
+ result = calculate_psar(df, step=step, max_step=max_step, fillna=True)
+ return {
+ 'psar': result['psar'],
+ 'psar_up': result['psar_up'],
+ 'psar_down': result['psar_down'],
+ }
- elif name == 'VOLUME':
- return {'value': df['volume']}
+ elif name == 'AROON':
+ period = params.get('period', 25)
+ result = calculate_aroon(df, window=period, fillna=True)
+ return {
+ 'aroon_up': result['aroon_up'],
+ 'aroon_down': result['aroon_down'],
+ 'aroon_indicator': result['aroon_indicator'],
+ }
- elif name == 'CHANGE_PCT':
- pct = df['close'].pct_change() * 100
- return {'value': pct.fillna(0)}
+ elif name == 'STC':
+ window_slow = params.get('window_slow', 50)
+ window_fast = params.get('window_fast', 23)
+ cycle = params.get('cycle', 10)
+ series = calculate_stc(df, window_slow=window_slow, window_fast=window_fast, cycle=cycle, fillna=True)
+ return {'value': series}
+
+ elif name == 'KST':
+ nsig = params.get('nsig', 9)
+ result = calculate_kst(df, nsig=nsig, fillna=True)
+ return {
+ 'kst': result['kst'],
+ 'kst_signal': result['kst_signal'],
+ }
+
+ elif name == 'VORTEX':
+ period = params.get('period', 14)
+ result = calculate_vortex(df, window=period, fillna=True)
+ return {
+ 'vortex_pos': result['vortex_pos'],
+ 'vortex_neg': result['vortex_neg'],
+ }
+
+ elif name == 'DPO':
+ period = params.get('period', 20)
+ series = calculate_dpo(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'TRIX':
+ period = params.get('period', 15)
+ series = calculate_trix(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'MASS_INDEX':
+ window_fast = params.get('window_fast', 9)
+ window_slow = params.get('window_slow', 25)
+ series = calculate_mass_index(df, window_fast=window_fast, window_slow=window_slow, fillna=True)
+ return {'value': series}
+
+ # ── Volatility ────────────────────────────────────────────────────
+ elif name == 'BOLLINGER' or name == 'BB':
+ period = params.get('period', 20)
+ std_dev = params.get('std_dev', 2)
+ result = calculate_bollinger_bands(df, window=period, window_dev=std_dev, fillna=True)
+ # Calculate %B
+ upper = result['bb_upper']
+ lower = result['bb_lower']
+ close = df['close']
+ pct_b = (close - lower) / (upper - lower)
+ return {
+ 'upper': upper,
+ 'middle': result['bb_middle'],
+ 'lower': lower,
+ 'pct_b': pct_b,
+ }
+
+ elif name == 'ATR':
+ period = params.get('period', 14)
+ series = calculate_atr(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'KELTNER':
+ period = params.get('period', 20)
+ result = calculate_keltner_channel(df, window=period, fillna=True)
+ return {
+ 'upper': result['kc_upper'],
+ 'middle': result['kc_middle'],
+ 'lower': result['kc_lower'],
+ }
+
+ elif name == 'DONCHIAN':
+ period = params.get('period', 20)
+ result = calculate_donchian_channel(df, window=period, fillna=True)
+ return {
+ 'upper': result['dc_upper'],
+ 'middle': result['dc_middle'],
+ 'lower': result['dc_lower'],
+ }
+
+ # ── Volume ────────────────────────────────────────────────────────
+ elif name == 'OBV':
+ series = calculate_obv(df, fillna=True)
+ return {'value': series}
+
+ elif name == 'CMF':
+ period = params.get('period', 20)
+ series = calculate_cmf(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'MFI':
+ period = params.get('period', 14)
+ series = calculate_mfi(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'FORCE_INDEX' or name == 'FI':
+ period = params.get('period', 13)
+ series = calculate_force_index(df, window=period, fillna=True)
+ return {'value': series}
+
+ elif name == 'ADI':
+ series = calculate_adi(df, fillna=True)
+ return {'value': series}
+
+ elif name == 'EOM':
+ period = params.get('period', 14)
+ result = calculate_eom(df, window=period, fillna=True)
+ return {
+ 'value': result['eom'],
+ 'signal': result['eom_signal'],
+ }
+
+ elif name == 'VPT':
+ series = calculate_vpt(df, fillna=True)
+ return {'value': series}
+
+ elif name == 'NVI':
+ series = calculate_nvi(df, fillna=True)
+ return {'value': series}
+
+ # ── Pivot Points ──────────────────────────────────────────────────
+ elif name == 'PIVOT':
+ pivot_type = int(params.get('type', 0)) # 0=Standard, 1=Fibonacci, 2=Woodie, 3=Camarilla
+ # Use previous bar's HLC for pivot calculation
+ h = float(df['high'].iloc[-2]) if len(df) > 1 else float(df['high'].iloc[-1])
+ l = float(df['low'].iloc[-2]) if len(df) > 1 else float(df['low'].iloc[-1])
+ c = float(df['close'].iloc[-2]) if len(df) > 1 else float(df['close'].iloc[-1])
+
+ if pivot_type == 1: # Fibonacci
+ pp = (h + l + c) / 3
+ r1 = pp + 0.382 * (h - l)
+ s1 = pp - 0.382 * (h - l)
+ r2 = pp + 0.618 * (h - l)
+ s2 = pp - 0.618 * (h - l)
+ r3 = pp + 1.0 * (h - l)
+ s3 = pp - 1.0 * (h - l)
+ elif pivot_type == 2: # Woodie
+ pp = (h + l + 2 * c) / 4
+ r1 = 2 * pp - l
+ s1 = 2 * pp - h
+ r2 = pp + (h - l)
+ s2 = pp - (h - l)
+ r3 = h + 2 * (pp - l)
+ s3 = l - 2 * (h - pp)
+ elif pivot_type == 3: # Camarilla
+ pp = (h + l + c) / 3
+ r1 = c + 1.1 * (h - l) / 12
+ s1 = c - 1.1 * (h - l) / 12
+ r2 = c + 1.1 * (h - l) / 6
+ s2 = c - 1.1 * (h - l) / 6
+ r3 = c + 1.1 * (h - l) / 4
+ s3 = c - 1.1 * (h - l) / 4
+ else: # Standard
+ pp = (h + l + c) / 3
+ r1 = 2 * pp - l
+ s1 = 2 * pp - h
+ r2 = pp + (h - l)
+ s2 = pp - (h - l)
+ r3 = h + 2 * (pp - l)
+ s3 = l - 2 * (h - pp)
+
+ length = len(df)
+ return {
+ 'pp': pd.Series([pp] * length, index=df.index),
+ 'r1': pd.Series([r1] * length, index=df.index),
+ 'r2': pd.Series([r2] * length, index=df.index),
+ 'r3': pd.Series([r3] * length, index=df.index),
+ 's1': pd.Series([s1] * length, index=df.index),
+ 's2': pd.Series([s2] * length, index=df.index),
+ 's3': pd.Series([s3] * length, index=df.index),
+ }
else:
raise ValueError(f"Unknown indicator: {name}")
@@ -208,3 +534,16 @@ def get_last_n_values(name: str, df: pd.DataFrame, params: dict, field: str = 'v
series = result[field]
values = series.iloc[-n:].tolist()
return [float(v) if not pd.isna(v) else float('nan') for v in values]
+
+
+def get_value_at_offset(name: str, df: pd.DataFrame, params: dict, field: str = 'value', offset: int = 0) -> float:
+ """Get value of an indicator at N bars ago (offset=0 is latest, offset=1 is previous, etc.)."""
+ result = compute_indicator(name, df, params)
+ if field not in result:
+ raise ValueError(f"Indicator {name} has no field '{field}'. Available: {list(result.keys())}")
+ series = result[field]
+ idx = -(offset + 1)
+ if abs(idx) > len(series):
+ return float('nan')
+ val = series.iloc[idx]
+ return float(val) if not pd.isna(val) else float('nan')
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py
index 3c3056986..14a8d3104 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/algo_trading/scanner_engine.py
@@ -41,6 +41,26 @@ def main():
matches = []
errors = []
scanned = 0
+ debug_log = []
+
+ debug_log.append(f'[scanner.py] db={args.db}')
+ debug_log.append(f'[scanner.py] timeframe={args.timeframe}, symbols={len(symbols)}, conditions={len(conditions)}')
+
+ # Check DB connectivity and candle_cache state
+ try:
+ conn_check = sqlite3.connect(args.db)
+ cur = conn_check.cursor()
+ cur.execute('SELECT COUNT(*) FROM candle_cache WHERE timeframe = ?', (args.timeframe,))
+ total_rows = cur.fetchone()[0]
+ debug_log.append(f'[scanner.py] candle_cache total rows for tf={args.timeframe}: {total_rows}')
+
+ for sym in symbols:
+ cur.execute('SELECT COUNT(*) FROM candle_cache WHERE symbol = ? AND timeframe = ?', (sym, args.timeframe))
+ sym_count = cur.fetchone()[0]
+ debug_log.append(f'[scanner.py] {sym}: {sym_count} candles in cache')
+ conn_check.close()
+ except Exception as e:
+ debug_log.append(f'[scanner.py] DB check error: {e}')
for symbol in symbols:
scanned += 1
@@ -63,6 +83,9 @@ def main():
except Exception as e:
errors.append({'symbol': symbol, 'error': str(e)})
+ debug_log.append(f'[scanner.py] {symbol} exception: {e}')
+
+ debug_log.append(f'[scanner.py] summary: scanned={scanned}, matches={len(matches)}, errors={len(errors)}')
print(json.dumps({
'success': True,
@@ -71,6 +94,7 @@ def main():
'scanned': scanned,
'errors': errors,
'timeframe': args.timeframe,
+ 'scanner_debug': debug_log,
}))
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
index fb3dcca4a..b72841a2d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs
@@ -93,6 +93,14 @@ async fn execute_core_agent_with_timeout(
let payload_str = serde_json::to_string(&payload)
.map_err(|e| format!("Failed to serialize payload: {}", e))?;
+ // DEBUG: Log the action and model config being sent to Python
+ let action = payload.get("action").and_then(|v| v.as_str()).unwrap_or("unknown");
+ let model_info = payload.get("config")
+ .and_then(|c| c.get("model"))
+ .map(|m| m.to_string())
+ .unwrap_or_else(|| "no model config".to_string());
+ eprintln!("[AgentCmd] action={}, model_config={}, payload_len={}", action, model_info, payload_str.len());
+
let app_clone = app.clone();
let args: Vec<String> = vec![payload_str];
@@ -104,6 +112,23 @@ async fn execute_core_agent_with_timeout(
})
).await;
+ match &result {
+ Ok(Ok(Ok(ref output))) => {
+ // Log first 500 chars of successful output
+ let preview: String = output.chars().take(500).collect();
+ eprintln!("[AgentCmd] SUCCESS: {}", preview);
+ }
+ Ok(Ok(Err(ref e))) => {
+ eprintln!("[AgentCmd] PYTHON ERROR: {}", e);
+ }
+ Ok(Err(ref e)) => {
+ eprintln!("[AgentCmd] TASK ERROR: {}", e);
+ }
+ Err(_) => {
+ eprintln!("[AgentCmd] TIMEOUT after {}s", timeout_secs);
+ }
+ }
+
match result {
Ok(Ok(inner_result)) => inner_result,
Ok(Err(e)) => Err(format!("Task execution error: {}", e)),
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs
index 6c923bab1..d03c1f012 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/algo_trading.rs
@@ -589,25 +589,64 @@ pub async fn run_algo_scan(
let scanner_path = scripts_dir.join("scanner_engine.py");
let db_path = get_main_db_path_str()?;
let tf = timeframe.unwrap_or_else(|| "5m".to_string());
+ let broker = provider.as_deref().unwrap_or("fyers").to_string();
+
+ // Collect debug info throughout the scan process
+ let mut debug_log: Vec<String> = Vec::new();
+ debug_log.push(format!("[scan] broker={}, timeframe={}, db={}", broker, tf, db_path));
if !scanner_path.exists() {
+ debug_log.push(format!("[scan] ERROR: scanner_engine.py not found at {:?}", scanner_path));
return Ok(json!({
"success": false,
- "error": "scanner_engine.py not found"
+ "error": "scanner_engine.py not found",
+ "debug": debug_log
}).to_string());
}
+ debug_log.push(format!("[scan] scanner_path={:?}", scanner_path));
- // Pre-fetch historical data from broker into candle_cache for each symbol
- // This ensures the scanner has data even if WebSocket candle aggregation hasn't run
+ // Parse symbol list
let symbol_list: Vec<String> = serde_json::from_str(&symbols).unwrap_or_default();
+ debug_log.push(format!("[scan] symbols parsed: {} symbols", symbol_list.len()));
+
+ // Pre-fetch historical data from broker into candle_cache for each symbol
+ let mut prefetch_warning: Option<String> = None;
if !symbol_list.is_empty() {
- let broker = provider.as_deref().unwrap_or("fyers");
- if let Err(e) = prefetch_historical_candles(&db_path, &symbol_list, &tf, broker).await {
- eprintln!("[run_algo_scan] Warning: prefetch failed: {}", e);
- // Continue anyway — scanner will report insufficient data per symbol
+ debug_log.push(format!("[prefetch] starting for broker={}", broker));
+ match prefetch_historical_candles(&db_path, &symbol_list, &tf, &broker).await {
+ Ok(prefetch_debug) => {
+ debug_log.extend(prefetch_debug);
+ debug_log.push("[prefetch] completed successfully".to_string());
+ }
+ Err(e) => {
+ let err_msg = format!("Data prefetch failed: {}", e);
+ eprintln!("[run_algo_scan] {}", err_msg);
+ debug_log.push(format!("[prefetch] ERROR: {}", e));
+ prefetch_warning = Some(err_msg);
+ }
}
}
+ // Check candle_cache has data before running scanner
+ let candle_count = check_candle_cache_count(&db_path, &symbol_list, &tf);
+ debug_log.push(format!("[scan] candle_cache total rows for these symbols: {}", candle_count));
+
+ if candle_count == 0 {
+ // No data at all — return a clear error instead of running Python for nothing
+ let error_msg = if let Some(ref pw) = prefetch_warning {
+ format!("No candle data available. {}", pw)
+ } else {
+ format!("No candle data in cache for the given symbols and timeframe '{}'. Ensure broker is authenticated and symbols are valid.", tf)
+ };
+ return Ok(json!({
+ "success": false,
+ "error": error_msg,
+ "debug": debug_log
+ }).to_string());
+ }
+
+ // Run the Python scanner
+ debug_log.push("[scan] launching scanner_engine.py".to_string());
let output = Command::new("python")
.arg(&scanner_path)
.arg("--conditions")
@@ -621,63 +660,126 @@ pub async fn run_algo_scan(
.output()
.map_err(|e| format!("Failed to run scanner: {}", e))?;
+ let stderr_str = String::from_utf8_lossy(&output.stderr).to_string();
+ if !stderr_str.trim().is_empty() {
+ debug_log.push(format!("[scanner.py stderr] {}", stderr_str.trim()));
+ }
+
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
- // Try to parse as JSON, otherwise wrap
- if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stdout) {
+ debug_log.push(format!("[scan] scanner returned {} bytes", stdout.len()));
+
+ if let Ok(mut parsed) = serde_json::from_str::<serde_json::Value>(&stdout) {
+ // Merge scanner_debug from Python into our debug log
+ if let Some(scanner_debug) = parsed.get("scanner_debug").and_then(|v| v.as_array()) {
+ for entry in scanner_debug {
+ if let Some(s) = entry.as_str() {
+ debug_log.push(s.to_string());
+ }
+ }
+ }
+ // Inject debug log and prefetch warning into the response
+ if let Some(obj) = parsed.as_object_mut() {
+ obj.remove("scanner_debug"); // remove raw Python debug, we merged it
+ obj.insert("debug".to_string(), json!(debug_log));
+ if let Some(pw) = prefetch_warning {
+ obj.insert("prefetch_warning".to_string(), json!(pw));
+ }
+ }
Ok(parsed.to_string())
} else {
- Ok(json!({ "success": true, "raw": stdout.to_string() }).to_string())
+ debug_log.push(format!("[scan] WARNING: could not parse scanner output as JSON"));
+ Ok(json!({
+ "success": true,
+ "raw": stdout.to_string(),
+ "debug": debug_log
+ }).to_string())
}
} else {
- let stderr = String::from_utf8_lossy(&output.stderr);
+ debug_log.push(format!("[scan] scanner process exited with error"));
Ok(json!({
"success": false,
- "error": format!("Scanner failed: {}", stderr)
+ "error": format!("Scanner failed: {}", stderr_str.trim()),
+ "debug": debug_log
}).to_string())
}
}
+/// Quick helper to count candle_cache rows for the given symbols+timeframe
+fn check_candle_cache_count(db_path: &str, symbols: &[String], timeframe: &str) -> i64 {
+ let conn = match rusqlite::Connection::open(db_path) {
+ Ok(c) => c,
+ Err(_) => return 0,
+ };
+ let mut total: i64 = 0;
+ for symbol in symbols {
+ let count: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM candle_cache WHERE symbol = ?1 AND timeframe = ?2",
+ rusqlite::params![symbol, timeframe],
+ |row| row.get(0),
+ )
+ .unwrap_or(0);
+ total += count;
+ }
+ total
+}
+
/// Pre-fetch historical candles from broker API and insert into candle_cache table.
/// Maps timeframe strings to Fyers resolution values and fetches ~1 year of daily data
/// or appropriate ranges for other timeframes.
+/// Returns a Vec of debug log lines for the caller to include in the response.
async fn prefetch_historical_candles(
db_path: &str,
symbols: &[String],
timeframe: &str,
broker: &str,
-) -> Result<(), String> {
+) -> Result<Vec<String>, String> {
use crate::commands::brokers;
+ let mut debug_log: Vec<String> = Vec::new();
+
// Only support Fyers for now
if broker != "fyers" {
- return Ok(());
+ debug_log.push(format!("[prefetch] broker '{}' not supported for prefetch, only 'fyers' is supported", broker));
+ return Ok(debug_log);
}
// Get Fyers credentials
+ debug_log.push("[prefetch] fetching Fyers credentials...".to_string());
let creds = brokers::get_indian_broker_credentials("fyers".to_string())
.await
- .map_err(|e| format!("Failed to get credentials: {}", e))?;
+ .map_err(|e| format!("Failed to get Fyers credentials: {}", e))?;
if !creds.success || creds.data.is_none() {
- return Err("Fyers credentials not found. Authenticate first.".to_string());
+ return Err("Fyers credentials not found. Please authenticate with Fyers first (Settings > Brokers > Fyers).".to_string());
}
let cred_data = creds.data.unwrap();
let api_key = cred_data.get("apiKey")
.and_then(|v| v.as_str())
- .ok_or("Fyers API key not found")?
+ .ok_or("Fyers API key not found in stored credentials")?
.to_string();
let access_token = cred_data.get("accessToken")
.and_then(|v| v.as_str())
- .ok_or("Fyers access token not found")?
+ .ok_or("Fyers access token not found. Please re-authenticate with Fyers — tokens expire daily.")?
.to_string();
+ if api_key.is_empty() {
+ return Err("Fyers API key is empty. Please re-enter credentials in Settings > Brokers.".to_string());
+ }
+ if access_token.is_empty() {
+ return Err("Fyers access token is empty. Please re-authenticate — Fyers tokens expire daily.".to_string());
+ }
+
+ debug_log.push(format!("[prefetch] credentials OK (api_key len={}, token len={})", api_key.len(), access_token.len()));
+
// Map timeframe to Fyers resolution and lookback days
let (resolution, lookback_days) = match timeframe {
"1m" => ("1", 5),
"3m" => ("3", 10),
"5m" => ("5", 15),
+ "10m" => ("10", 20),
"15m" => ("15", 30),
"30m" => ("30", 60),
"1h" => ("60", 90),
@@ -690,12 +792,11 @@ async fn prefetch_historical_candles(
let from_date = (now - chrono::Duration::days(lookback_days)).format("%Y-%m-%d").to_string();
let to_date = now.format("%Y-%m-%d").to_string();
- eprintln!("[prefetch] Fetching {} candles for {} symbols, range {} to {}",
- resolution, symbols.len(), from_date, to_date);
+ debug_log.push(format!("[prefetch] resolution={}, lookback={}d, range={} to {}", resolution, lookback_days, from_date, to_date));
// Open DB connection for inserting candles
let conn = rusqlite::Connection::open(db_path)
- .map_err(|e| format!("Failed to open DB: {}", e))?;
+ .map_err(|e| format!("Failed to open DB at {}: {}", db_path, e))?;
// Ensure candle_cache table exists
conn.execute_batch(
@@ -714,6 +815,10 @@ async fn prefetch_historical_candles(
);"
).map_err(|e| format!("Failed to create candle_cache table: {}", e))?;
+ let mut total_fetched = 0;
+ let mut total_inserted = 0;
+ let mut fetch_errors: Vec<String> = Vec::new();
+
for symbol in symbols {
// Build Fyers symbol format: "NSE:SYMBOL-EQ" if not already formatted
let fyers_symbol = if symbol.contains(':') {
@@ -730,10 +835,12 @@ async fn prefetch_historical_candles(
).unwrap_or(0);
if existing_count >= 50 {
- eprintln!("[prefetch] {} already has {} candles, skipping", symbol, existing_count);
+ debug_log.push(format!("[prefetch] {} already cached ({} candles), skipping", symbol, existing_count));
continue;
}
+ debug_log.push(format!("[prefetch] {} -> fetching as '{}' (existing={})", symbol, fyers_symbol, existing_count));
+
// Fetch from Fyers API
match brokers::fyers_get_history(
api_key.clone(),
@@ -746,7 +853,8 @@ async fn prefetch_historical_candles(
Ok(response) => {
if response.success {
if let Some(candles) = response.data.and_then(|d| d.as_array().cloned()) {
- eprintln!("[prefetch] {} -> {} candles fetched", symbol, candles.len());
+ total_fetched += candles.len();
+ debug_log.push(format!("[prefetch] {} -> {} candles from API", symbol, candles.len()));
// Insert candles into candle_cache
// Fyers format: [timestamp, O, H, L, C, V]
@@ -771,19 +879,37 @@ async fn prefetch_historical_candles(
}
}
}
- eprintln!("[prefetch] {} -> {} candles inserted into cache", symbol, inserted);
+ total_inserted += inserted;
+ debug_log.push(format!("[prefetch] {} -> {} candles inserted", symbol, inserted));
+ } else {
+ let msg = format!("{}: API returned success but no candle data", symbol);
+ debug_log.push(format!("[prefetch] {} -> WARNING: {}", symbol, msg));
+ fetch_errors.push(msg);
}
} else {
- eprintln!("[prefetch] {} fetch failed: {:?}", symbol, response.error);
+ let api_err = response.error.unwrap_or_else(|| "Unknown API error".to_string());
+ let msg = format!("{}: Fyers API error — {}", symbol, api_err);
+ debug_log.push(format!("[prefetch] {} -> ERROR: {}", symbol, api_err));
+ fetch_errors.push(msg);
}
}
Err(e) => {
- eprintln!("[prefetch] {} fetch error: {}", symbol, e);
+ let msg = format!("{}: request failed — {}", symbol, e);
+ debug_log.push(format!("[prefetch] {} -> FETCH ERROR: {}", symbol, e));
+ fetch_errors.push(msg);
}
}
}
- Ok(())
+ debug_log.push(format!("[prefetch] summary: fetched={}, inserted={}, errors={}", total_fetched, total_inserted, fetch_errors.len()));
+
+ // If ALL symbols failed, return an error so the caller knows
+ if total_inserted == 0 && !fetch_errors.is_empty() {
+ let combined = fetch_errors.join("; ");
+ return Err(format!("All symbol fetches failed: {}", combined));
+ }
+
+ Ok(debug_log)
}
// ============================================================================
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/news.rs b/fincept-terminal-desktop/src-tauri/src/commands/news.rs
index 16b1af513..fcd77ee0a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/news.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/news.rs
@@ -264,8 +264,9 @@ fn parse_rss_feed(xml_text: &str, feed: &RSSFeed) -> Vec<NewsArticle> {
.unwrap()
.as_millis();
item_index += 1;
+ let feed_id = feed.id.as_deref().unwrap_or(&feed.source);
current_item = Some(NewsArticle {
- id: format!("{}-{}-{}", feed.source, timestamp, item_index),
+ id: format!("{}-{}-{}", feed_id, timestamp, item_index),
time: String::new(),
priority: "ROUTINE".to_string(),
category: feed.category.clone(),
diff --git a/fincept-terminal-desktop/src-tauri/src/python.rs b/fincept-terminal-desktop/src-tauri/src/python.rs
index 8e932aa8d..d2e4018fc 100644
--- a/fincept-terminal-desktop/src-tauri/src/python.rs
+++ b/fincept-terminal-desktop/src-tauri/src/python.rs
@@ -159,12 +159,22 @@ fn run_subprocess(
python: &PathBuf,
script: &PathBuf,
args: &[String],
+ data_dir: Option<&PathBuf>,
) -> Result<String, String> {
let mut cmd = Command::new(python);
- cmd.arg(script).args(args)
+ // -B flag: don't write .pyc files AND ignore existing __pycache__
+ cmd.arg("-B").arg(script).args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // Also set env var as belt-and-suspenders
+ cmd.env("PYTHONDONTWRITEBYTECODE", "1");
+
+ // Set FINCEPT_DATA_DIR environment variable for Python scripts
+ if let Some(dir) = data_dir {
+ cmd.env("FINCEPT_DATA_DIR", dir.to_string_lossy().to_string());
+ }
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -199,6 +209,7 @@ fn run_subprocess_with_stdin(
script: &PathBuf,
args: &[String],
stdin_data: &str,
+ data_dir: Option<&PathBuf>,
) -> Result<String, String> {
let mut cmd = Command::new(python);
cmd.arg(script).args(args).arg("--stdin")
@@ -206,6 +217,11 @@ fn run_subprocess_with_stdin(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // Set FINCEPT_DATA_DIR environment variable for Python scripts
+ if let Some(dir) = data_dir {
+ cmd.env("FINCEPT_DATA_DIR", dir.to_string_lossy().to_string());
+ }
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -277,7 +293,8 @@ pub async fn execute(
) -> Result<String, String> {
let script_path = resolve_script_path(app, script)?;
let python = resolve_python_path(app, script)?;
- run_subprocess(&python, &script_path, &args)
+ let data_dir = get_install_dir(app).ok();
+ run_subprocess(&python, &script_path, &args, data_dir.as_ref())
}
/// Execute Python script (sync wrapper)
@@ -288,7 +305,8 @@ pub fn execute_sync(
) -> Result<String, String> {
let script_path = resolve_script_path(app, script)?;
let python = resolve_python_path(app, script)?;
- run_subprocess(&python, &script_path, &args)
+ let data_dir = get_install_dir(app).ok();
+ run_subprocess(&python, &script_path, &args, data_dir.as_ref())
}
/// Execute with stdin data (for large payloads, sync only)
@@ -300,7 +318,8 @@ pub fn execute_with_stdin(
) -> Result<String, String> {
let python = resolve_python_path(app, script)?;
let script_path = resolve_script_path(app, script)?;
- run_subprocess_with_stdin(&python, &script_path, &args, stdin_data)
+ let data_dir = get_install_dir(app).ok();
+ run_subprocess_with_stdin(&python, &script_path, &args, stdin_data, data_dir.as_ref())
}
/// Get Bun executable path
@@ -363,6 +382,7 @@ pub async fn execute_streaming(
) -> Result<String, String> {
let script_path = resolve_script_path(&app, script)?;
let python = resolve_python_path(&app, script)?;
+ let data_dir = get_install_dir(&app).ok();
let mut cmd = Command::new(&python);
cmd.arg(&script_path)
@@ -371,6 +391,11 @@ pub async fn execute_streaming(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // Set FINCEPT_DATA_DIR environment variable for Python scripts
+ if let Some(ref dir) = data_dir {
+ cmd.env("FINCEPT_DATA_DIR", dir.to_string_lossy().to_string());
+ }
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -485,6 +510,7 @@ pub fn spawn_streaming(
) -> Result<Child, String> {
let script_path = resolve_script_path(app, script)?;
let python = resolve_python_path(app, script)?;
+ let data_dir = get_install_dir(app).ok();
let mut cmd = Command::new(&python);
cmd.arg(&script_path)
@@ -493,6 +519,11 @@ pub fn spawn_streaming(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // Set FINCEPT_DATA_DIR environment variable for Python scripts
+ if let Some(ref dir) = data_dir {
+ cmd.env("FINCEPT_DATA_DIR", dir.to_string_lossy().to_string());
+ }
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
diff --git a/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx b/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx
deleted file mode 100644
index 42b26963b..000000000
--- a/fincept-terminal-desktop/src/components/common/TimezoneSelector.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-/**
- * TimezoneSelector.tsx
- *
- * A compact timezone selector widget for terminal headers.
- * Displays current time with timezone code and allows switching
- * between major financial market timezones.
- */
-
-import React, { useState, useRef, useEffect } from 'react';
-import { Clock, ChevronDown, Globe } from 'lucide-react';
-import { useTimezone, useCurrentTime, TIMEZONE_OPTIONS } from '../../contexts/TimezoneContext';
-
-// Fincept-style colors
-const COLORS = {
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#141414',
- BORDER: '#333333',
- ORANGE: '#FFA500',
- CYAN: '#00D4FF',
- WHITE: '#FFFFFF',
- GRAY: '#888888',
- HOVER: '#1a1a1a',
-};
-
-interface TimezoneSelectorProps {
- /** Compact mode shows only time + short code */
- compact?: boolean;
- /** Custom styling */
- style?: React.CSSProperties;
-}
-
-export const TimezoneSelector: React.FC<TimezoneSelectorProps> = ({
- compact = false,
- style
-}) => {
- const [isOpen, setIsOpen] = useState(false);
- const dropdownRef = useRef<HTMLDivElement>(null);
- const { timezone, setTimezone, options } = useTimezone();
- const { formattedTime } = useCurrentTime();
-
- // Close dropdown when clicking outside
- useEffect(() => {
- const handleClickOutside = (event: MouseEvent) => {
- if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
- setIsOpen(false);
- }
- };
-
- if (isOpen) {
- document.addEventListener('mousedown', handleClickOutside);
- }
-
- return () => {
- document.removeEventListener('mousedown', handleClickOutside);
- };
- }, [isOpen]);
-
- // Handle timezone selection
- const handleSelect = (id: string) => {
- setTimezone(id);
- setIsOpen(false);
- };
-
- return (
- <div
- ref={dropdownRef}
- style={{
- position: 'relative',
- display: 'inline-block',
- ...style
- }}
- >
- {/* Trigger Button */}
- <button
- onClick={() => setIsOpen(!isOpen)}
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- padding: compact ? '2px 6px' : '4px 10px',
- backgroundColor: 'transparent',
- border: `1px solid ${isOpen ? COLORS.CYAN : COLORS.BORDER}`,
- borderRadius: '3px',
- color: COLORS.CYAN,
- cursor: 'pointer',
- fontSize: compact ? '10px' : '11px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- fontWeight: 500,
- transition: 'all 0.2s ease',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = COLORS.CYAN;
- e.currentTarget.style.backgroundColor = COLORS.HOVER;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = isOpen ? COLORS.CYAN : COLORS.BORDER;
- e.currentTarget.style.backgroundColor = 'transparent';
- }}
- title={`Current timezone: ${timezone.label}`}
- >
- <Clock size={compact ? 10 : 12} />
- <span style={{ fontVariantNumeric: 'tabular-nums' }}>
- {formattedTime}
- </span>
- <span style={{
- color: COLORS.ORANGE,
- fontWeight: 700,
- fontSize: compact ? '8px' : '9px',
- }}>
- {timezone.shortLabel}
- </span>
- <ChevronDown
- size={compact ? 8 : 10}
- style={{
- transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
- transition: 'transform 0.2s ease',
- }}
- />
- </button>
-
- {/* Dropdown Menu */}
- {isOpen && (
- <div
- style={{
- position: 'absolute',
- top: '100%',
- right: 0,
- marginTop: '4px',
- backgroundColor: COLORS.PANEL_BG,
- border: `1px solid ${COLORS.BORDER}`,
- borderRadius: '4px',
- minWidth: '200px',
- zIndex: 9999,
- boxShadow: `0 4px 16px rgba(0,0,0,0.5)`,
- overflow: 'hidden',
- }}
- >
- {/* Header */}
- <div
- style={{
- padding: '8px 12px',
- borderBottom: `1px solid ${COLORS.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- >
- <Globe size={12} color={COLORS.ORANGE} />
- <span style={{
- color: COLORS.ORANGE,
- fontSize: '10px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- }}>
- SELECT TIMEZONE
- </span>
- </div>
-
- {/* Options */}
- {options.map((option) => (
- <div
- key={option.id}
- onClick={() => handleSelect(option.id)}
- style={{
- padding: '10px 12px',
- cursor: 'pointer',
- fontSize: '11px',
- backgroundColor: timezone.id === option.id ? `${COLORS.ORANGE}15` : 'transparent',
- borderLeft: timezone.id === option.id
- ? `3px solid ${COLORS.ORANGE}`
- : '3px solid transparent',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- transition: 'all 0.15s ease',
- }}
- onMouseEnter={(e) => {
- if (timezone.id !== option.id) {
- e.currentTarget.style.backgroundColor = COLORS.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (timezone.id !== option.id) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- <div>
- <div style={{
- color: timezone.id === option.id ? COLORS.ORANGE : COLORS.WHITE,
- fontWeight: 600,
- marginBottom: '2px',
- }}>
- {option.label}
- </div>
- <div style={{
- color: COLORS.GRAY,
- fontSize: '9px',
- }}>
- {option.zone || 'System default'}
- </div>
- </div>
- <span style={{
- color: timezone.id === option.id ? COLORS.ORANGE : COLORS.CYAN,
- fontWeight: 700,
- fontSize: '10px',
- }}>
- {option.shortLabel}
- </span>
- </div>
- ))}
- </div>
- )}
- </div>
- );
-};
-
-export default TimezoneSelector;
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index cb82cd174..62a45b65c 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -4,7 +4,7 @@ import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye,
import { useAuth } from '@/contexts/AuthContext';
import { useNavigation } from '@/contexts/NavigationContext';
import { InterfaceModeProvider, useInterfaceMode } from '@/contexts/InterfaceModeContext';
-import { useCurrentTime, useDefaultTime } from '@/contexts/TimezoneContext';
+import { useCurrentTime } from '@/contexts/TimezoneContext';
import { ChatModeInterface } from '@/components/chat-mode';
import { APP_VERSION } from '@/constants/version';
import { useAutoUpdater } from '@/hooks/useAutoUpdater';
@@ -208,7 +208,7 @@ const DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any
// Header Time Display Component - uses DEFAULT timezone from settings for nav bar
const HeaderTimeDisplay = () => {
- const { formattedTime, timezone } = useDefaultTime();
+ const { formattedTime, timezone } = useCurrentTime();
// Get current date in YYYY-MM-DD format
const [currentDate, setCurrentDate] = React.useState(() => {
@@ -228,8 +228,8 @@ const HeaderTimeDisplay = () => {
}, []);
return (
- <span style={{ color: '#a3a3a3', fontSize: '9px' }}>
- {currentDate} {formattedTime}
+ <span style={{ color: '#a3a3a3', fontSize: '11px', fontWeight: 500 }}>
+ {currentDate} {formattedTime} <span style={{ color: '#ea580c', fontWeight: 600 }}>{timezone.shortLabel}</span>
</span>
);
};
@@ -682,7 +682,7 @@ function FinxeptTerminalContent() {
<div style={{ width: '1px', height: '14px', backgroundColor: '#525252', flexShrink: 0 }}></div>
<HeaderTimeDisplay />
<div style={{ width: '1px', height: '14px', backgroundColor: '#525252', flexShrink: 0 }}></div>
- <span style={{ color: '#10b981', fontSize: '10px', fontWeight: 'bold', whiteSpace: 'nowrap' }}>v{APP_VERSION}</span>
+ <span style={{ color: '#10b981', fontSize: '12px', fontWeight: 'bold', whiteSpace: 'nowrap' }}>v{APP_VERSION}</span>
<div style={{ width: '1px', height: '14px', backgroundColor: '#525252', flexShrink: 0 }}></div>
<span style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', letterSpacing: '0.5px', whiteSpace: 'nowrap' }}>FINCEPT PROFESSIONAL</span>
</div>
@@ -1062,7 +1062,7 @@ function FinxeptTerminalContent() {
<CryptoTradingTab />
</React.Suspense>
</TabsContent>
- <TabsContent value="equity-trading" className="h-full m-0 p-0" forceMount>
+ <TabsContent value="equity-trading" className="h-full m-0 p-0">
<React.Suspense fallback={<TabLoadingFallback />}>
<EquityTradingTab />
</React.Suspense>
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
index 223ead124..2af33d67d 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ConditionRow.tsx
@@ -1,12 +1,12 @@
import React from 'react';
-import { X } from 'lucide-react';
+import { X, ToggleLeft, ToggleRight, Clock } from 'lucide-react';
import type { ConditionItem } from '../types';
import { INDICATOR_DEFINITIONS, OPERATORS, getIndicatorDef } from '../constants/indicators';
const F = {
ORANGE: '#FF8800', WHITE: '#FFFFFF', GRAY: '#787878', DARK_BG: '#000000',
PANEL_BG: '#0F0F0F', BORDER: '#2A2A2A', HOVER: '#1F1F1F', MUTED: '#4A4A4A',
- CYAN: '#00E5FF', RED: '#FF3B3B',
+ CYAN: '#00E5FF', RED: '#FF3B3B', GREEN: '#00D66F', YELLOW: '#FFD600',
};
interface ConditionRowProps {
@@ -32,9 +32,109 @@ const inputStyle: React.CSSProperties = {
width: '60px',
};
+const tinyBtnStyle: React.CSSProperties = {
+ padding: '3px 6px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${F.BORDER}`,
+ borderRadius: '2px',
+ color: F.MUTED,
+ cursor: 'pointer',
+ fontSize: '8px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ letterSpacing: '0.5px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px',
+ transition: 'all 0.15s',
+};
+
+const categories = ['stock_attributes', 'moving_averages', 'momentum', 'trend', 'volatility', 'volume'] as const;
+
+const categoryLabels: Record<string, string> = {
+ stock_attributes: 'Stock',
+ moving_averages: 'Moving Avg',
+ momentum: 'Momentum',
+ trend: 'Trend',
+ volatility: 'Volatility',
+ volume: 'Volume',
+};
+
+// Render indicator selector dropdown
+function IndicatorSelect({ value, onChange, style }: {
+ value: string;
+ onChange: (name: string) => void;
+ style?: React.CSSProperties;
+}) {
+ return (
+ <select value={value} onChange={e => onChange(e.target.value)} style={{ ...selectStyle, width: '130px', ...style }}>
+ {categories.map(cat => {
+ const indicators = INDICATOR_DEFINITIONS.filter(d => d.category === cat);
+ if (indicators.length === 0) return null;
+ return (
+ <optgroup key={cat} label={categoryLabels[cat] || cat}>
+ {indicators.map(d => (
+ <option key={d.name} value={d.name}>{d.label}</option>
+ ))}
+ </optgroup>
+ );
+ })}
+ </select>
+ );
+}
+
+// Render params inputs for an indicator
+function ParamInputs({ indicatorDef, params, onChange }: {
+ indicatorDef: ReturnType<typeof getIndicatorDef>;
+ params: Record<string, number>;
+ onChange: (key: string, val: string) => void;
+}) {
+ if (!indicatorDef) return null;
+ return (
+ <>
+ {indicatorDef.params.map(p => (
+ <div key={p.key} style={{ display: 'flex', alignItems: 'center', gap: '3px' }}>
+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
+ {p.label.toUpperCase()}:
+ </span>
+ <input
+ type="number"
+ value={params[p.key] ?? p.default}
+ onChange={e => onChange(p.key, e.target.value)}
+ min={p.min}
+ max={p.max}
+ step={p.key === 'step' || p.key === 'max_step' ? 0.01 : 1}
+ style={inputStyle}
+ />
+ </div>
+ ))}
+ </>
+ );
+}
+
+// Render field selector
+function FieldSelect({ fields, value, onChange }: {
+ fields: string[];
+ value: string;
+ onChange: (field: string) => void;
+}) {
+ if (fields.length <= 1) return null;
+ return (
+ <select value={value} onChange={e => onChange(e.target.value)} style={{ ...selectStyle, width: '100px' }}>
+ {fields.map(f => <option key={f} value={f}>{f}</option>)}
+ </select>
+ );
+}
+
const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange, onRemove }) => {
const indicatorDef = getIndicatorDef(condition.indicator);
const fields = indicatorDef?.fields || ['value'];
+ const compareMode = condition.compareMode || 'value';
+ const showOffset = (condition.offset !== undefined && condition.offset > 0) ||
+ (condition.compareOffset !== undefined && condition.compareOffset > 0);
+
+ const compareDef = condition.compareIndicator ? getIndicatorDef(condition.compareIndicator) : undefined;
+ const compareFields = compareDef?.fields || ['value'];
const handleIndicatorChange = (name: string) => {
const def = getIndicatorDef(name);
@@ -56,7 +156,56 @@ const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange,
}
};
- const categories = ['momentum', 'trend', 'volatility', 'volume', 'price'] as const;
+ const handleCompareIndicatorChange = (name: string) => {
+ const def = getIndicatorDef(name);
+ if (!def) return;
+ const defaultParams: Record<string, number> = {};
+ def.params.forEach(p => { defaultParams[p.key] = p.default; });
+ onChange(index, {
+ ...condition,
+ compareIndicator: name,
+ compareField: def.defaultField,
+ compareParams: defaultParams,
+ });
+ };
+
+ const handleCompareParamChange = (key: string, val: string) => {
+ const num = parseFloat(val);
+ if (!isNaN(num)) {
+ onChange(index, {
+ ...condition,
+ compareParams: { ...(condition.compareParams || {}), [key]: num },
+ });
+ }
+ };
+
+ const toggleCompareMode = () => {
+ if (compareMode === 'value') {
+ // Switch to indicator mode — set default compare indicator
+ const defaultCompare = 'EMA';
+ const def = getIndicatorDef(defaultCompare)!;
+ const defaultParams: Record<string, number> = {};
+ def.params.forEach(p => { defaultParams[p.key] = p.default; });
+ onChange(index, {
+ ...condition,
+ compareMode: 'indicator',
+ compareIndicator: defaultCompare,
+ compareField: def.defaultField,
+ compareParams: defaultParams,
+ });
+ } else {
+ // Switch back to value mode
+ onChange(index, {
+ ...condition,
+ compareMode: 'value',
+ compareIndicator: undefined,
+ compareParams: undefined,
+ compareField: undefined,
+ });
+ }
+ };
+
+ const needsLookback = ['crossed_above_within', 'crossed_below_within', 'rising', 'falling'].includes(condition.operator);
return (
<div style={{
@@ -68,91 +217,175 @@ const ConditionRow: React.FC<ConditionRowProps> = ({ condition, index, onChange,
borderRadius: '2px',
transition: 'all 0.2s',
}}>
- {/* Indicator selector */}
- <select
- value={condition.indicator}
- onChange={e => handleIndicatorChange(e.target.value)}
- style={{ ...selectStyle, width: '120px' }}
- >
- {categories.map(cat => (
- <optgroup key={cat} label={cat.charAt(0).toUpperCase() + cat.slice(1)}>
- {INDICATOR_DEFINITIONS.filter(d => d.category === cat).map(d => (
- <option key={d.name} value={d.name}>{d.label}</option>
- ))}
- </optgroup>
- ))}
- </select>
+ {/* Left side: indicator + params + field */}
+ <IndicatorSelect value={condition.indicator} onChange={handleIndicatorChange} />
- {/* Params */}
- {indicatorDef?.params.map(p => (
- <div key={p.key} style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span style={{ fontSize: '9px', fontWeight: 700, color: F.GRAY, letterSpacing: '0.5px' }}>
- {p.label.toUpperCase()}:
- </span>
+ <ParamInputs
+ indicatorDef={indicatorDef}
+ params={condition.params}
+ onChange={handleParamChange}
+ />
+
+ <FieldSelect
+ fields={fields}
+ value={condition.field}
+ onChange={f => onChange(index, { ...condition, field: f })}
+ />
+
+ {/* Offset for left side */}
+ {condition.offset !== undefined && condition.offset > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
+ <Clock size={8} color={F.YELLOW} />
<input
type="number"
- value={condition.params[p.key] ?? p.default}
- onChange={e => handleParamChange(p.key, e.target.value)}
- min={p.min}
- max={p.max}
- style={inputStyle}
+ value={condition.offset}
+ onChange={e => {
+ const v = parseInt(e.target.value);
+ onChange(index, { ...condition, offset: isNaN(v) ? 0 : Math.max(0, v) });
+ }}
+ min={0}
+ max={100}
+ style={{ ...inputStyle, width: '40px', color: F.YELLOW, fontSize: '9px' }}
+ title="Bars ago"
/>
</div>
- ))}
-
- {/* Field selector */}
- {fields.length > 1 && (
- <select
- value={condition.field}
- onChange={e => onChange(index, { ...condition, field: e.target.value })}
- style={{ ...selectStyle, width: '90px' }}
- >
- {fields.map(f => (
- <option key={f} value={f}>{f}</option>
- ))}
- </select>
)}
{/* Operator */}
<select
value={condition.operator}
onChange={e => onChange(index, { ...condition, operator: e.target.value })}
- style={{ ...selectStyle, width: '110px' }}
+ style={{ ...selectStyle, width: '120px' }}
>
{OPERATORS.map(op => (
<option key={op.value} value={op.value}>{op.label}</option>
))}
</select>
- {/* Value */}
- <input
- type="number"
- value={condition.value}
- onChange={e => {
- const v = parseFloat(e.target.value);
- if (!isNaN(v)) onChange(index, { ...condition, value: v });
+ {/* Lookback for advanced operators */}
+ {needsLookback && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}>
+ <span style={{ fontSize: '8px', fontWeight: 700, color: F.GRAY }}>N:</span>
+ <input
+ type="number"
+ value={condition.lookback ?? 5}
+ onChange={e => {
+ const v = parseInt(e.target.value);
+ if (!isNaN(v)) onChange(index, { ...condition, lookback: Math.max(1, v) });
+ }}
+ min={1}
+ max={100}
+ style={{ ...inputStyle, width: '45px' }}
+ />
+ </div>
+ )}
+
+ {/* Compare mode toggle */}
+ <button
+ onClick={toggleCompareMode}
+ style={{
+ ...tinyBtnStyle,
+ color: compareMode === 'indicator' ? F.ORANGE : F.MUTED,
+ borderColor: compareMode === 'indicator' ? F.ORANGE : F.BORDER,
}}
- step="any"
- style={{ ...inputStyle, width: '72px', color: F.CYAN }}
- />
+ title={compareMode === 'value' ? 'Compare with number' : 'Compare with indicator'}
+ >
+ {compareMode === 'indicator' ? <ToggleRight size={10} /> : <ToggleLeft size={10} />}
+ {compareMode === 'indicator' ? 'IND' : '#'}
+ </button>
- {/* Value2 for between */}
- {condition.operator === 'between' && (
+ {/* Right side: value OR indicator comparison */}
+ {compareMode === 'value' ? (
<>
- <span style={{ fontSize: '9px', color: F.GRAY }}>AND</span>
<input
type="number"
- value={condition.value2 ?? 0}
+ value={condition.value}
onChange={e => {
const v = parseFloat(e.target.value);
- if (!isNaN(v)) onChange(index, { ...condition, value2: v });
+ if (!isNaN(v)) onChange(index, { ...condition, value: v });
}}
step="any"
style={{ ...inputStyle, width: '72px', color: F.CYAN }}
/>
+
+ {/* Value2 for between */}
+ {condition.operator === 'between' && (
+ <>
+ <span style={{ fontSize: '9px', color: F.GRAY }}>AND</span>
+ <input
+ type="number"
+ value={condition.value2 ?? 0}
+ onChange={e => {
+ const v = parseFloat(e.target.value);
+ if (!isNaN(v)) onChange(index, { ...condition, value2: v });
+ }}
+ step="any"
+ style={{ ...inputStyle, width: '72px', color: F.CYAN }}
+ />
+ </>
+ )}
+ </>
+ ) : (
+ <>
+ {/* Compare indicator selector */}
+ <IndicatorSelect
+ value={condition.compareIndicator || 'EMA'}
+ onChange={handleCompareIndicatorChange}
+ style={{ borderColor: F.ORANGE + '60' }}
+ />
+
+ <ParamInputs
+ indicatorDef={compareDef}
+ params={condition.compareParams || {}}
+ onChange={handleCompareParamChange}
+ />
+
+ <FieldSelect
+ fields={compareFields}
+ value={condition.compareField || 'value'}
+ onChange={f => onChange(index, { ...condition, compareField: f })}
+ />
+
+ {/* Offset for compare side */}
+ {condition.compareOffset !== undefined && condition.compareOffset > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
+ <Clock size={8} color={F.YELLOW} />
+ <input
+ type="number"
+ value={condition.compareOffset}
+ onChange={e => {
+ const v = parseInt(e.target.value);
+ onChange(index, { ...condition, compareOffset: isNaN(v) ? 0 : Math.max(0, v) });
+ }}
+ min={0}
+ max={100}
+ style={{ ...inputStyle, width: '40px', color: F.YELLOW, fontSize: '9px' }}
+ title="Bars ago"
+ />
+ </div>
+ )}
</>
)}
+ {/* Offset toggle */}
+ <button
+ onClick={() => {
+ if (showOffset) {
+ onChange(index, { ...condition, offset: 0, compareOffset: 0 });
+ } else {
+ onChange(index, { ...condition, offset: 1, compareOffset: 0 });
+ }
+ }}
+ style={{
+ ...tinyBtnStyle,
+ color: showOffset ? F.YELLOW : F.MUTED,
+ borderColor: showOffset ? F.YELLOW + '60' : F.BORDER,
+ }}
+ title="Toggle bar offset (n candles ago)"
+ >
+ <Clock size={9} />
+ </button>
+
{/* Remove */}
<button
onClick={() => onRemove(index)}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
index 827491418..250fb5c32 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/components/ScannerPanel.tsx
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
-import { Search, Loader } from 'lucide-react';
+import { Search, Loader, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';
import type { ConditionItem, ScanResult } from '../types';
import { TIMEFRAMES } from '../constants/indicators';
import { runAlgoScan } from '../services/algoTradingService';
@@ -11,6 +11,7 @@ const F = {
ORANGE: '#FF8800', WHITE: '#FFFFFF', RED: '#FF3B3B', GREEN: '#00D66F',
GRAY: '#787878', DARK_BG: '#000000', PANEL_BG: '#0F0F0F',
HEADER_BG: '#1A1A1A', BORDER: '#2A2A2A', MUTED: '#4A4A4A', CYAN: '#00E5FF',
+ YELLOW: '#FFD600',
};
const inputStyle: React.CSSProperties = {
@@ -24,11 +25,20 @@ const labelStyle: React.CSSProperties = {
marginBottom: '4px', display: 'block',
};
+interface SymbolError {
+ symbol: string;
+ error: string;
+}
+
+const STOCK_BROKERS = ['fyers', 'zerodha', 'upstox', 'dhan', 'angelone', 'kotak', 'groww', 'aliceblue', 'fivepaisa', 'iifl', 'motilal', 'shoonya'];
+
const ScannerPanel: React.FC = () => {
const stockBroker = useStockBrokerContextOptional();
const { activeBroker } = useBrokerContext();
- // Prefer stock broker (fyers, zerodha) over crypto broker
- const provider = stockBroker?.activeBroker || activeBroker || 'fyers';
+ // For scanner, always prefer stock broker. Fallback to 'fyers' if the active broker is crypto-only.
+ const provider = stockBroker?.activeBroker
+ || (STOCK_BROKERS.includes(activeBroker) ? activeBroker : null)
+ || 'fyers';
const [conditions, setConditions] = useState<ConditionItem[]>([
{ indicator: 'RSI', params: { period: 14 }, field: 'value', operator: '<', value: 30 },
@@ -40,6 +50,10 @@ const ScannerPanel: React.FC = () => {
const [results, setResults] = useState<ScanResult[] | null>(null);
const [scanned, setScanned] = useState(0);
const [error, setError] = useState('');
+ const [debugLog, setDebugLog] = useState<string[]>([]);
+ const [showDebug, setShowDebug] = useState(false);
+ const [prefetchWarning, setPrefetchWarning] = useState('');
+ const [symbolErrors, setSymbolErrors] = useState<SymbolError[]>([]);
const buildConditionsJson = (): string => {
if (conditions.length === 0) return '[]';
@@ -52,11 +66,37 @@ const ScannerPanel: React.FC = () => {
const symbols = symbolsInput.split(/[,\n]/).map(s => s.trim().toUpperCase()).filter(Boolean);
if (symbols.length === 0) { setError('Enter at least one symbol'); return; }
if (conditions.length === 0) { setError('Add at least one condition'); return; }
- setScanning(true); setError(''); setResults(null);
- const result = await runAlgoScan(buildConditionsJson(), JSON.stringify(symbols), timeframe, provider);
- setScanning(false);
- if (result.success && result.data) { setResults(result.data.matches); setScanned(result.data.scanned); }
- else setError(result.error || 'Scan failed');
+
+ setScanning(true);
+ setError('');
+ setResults(null);
+ setDebugLog([]);
+ setPrefetchWarning('');
+ setSymbolErrors([]);
+
+ try {
+ const result = await runAlgoScan(buildConditionsJson(), JSON.stringify(symbols), timeframe, provider);
+ setScanning(false);
+
+ // Capture debug info regardless of success/failure
+ if (result.debug) setDebugLog(result.debug);
+ if (result.prefetch_warning) setPrefetchWarning(result.prefetch_warning);
+
+ if (result.success && result.data) {
+ setResults(result.data.matches);
+ setScanned(result.data.scanned);
+ if (result.data.errors && result.data.errors.length > 0) {
+ setSymbolErrors(result.data.errors);
+ }
+ if (result.data.debug) setDebugLog(result.data.debug);
+ if (result.data.prefetch_warning) setPrefetchWarning(result.data.prefetch_warning);
+ } else {
+ setError(result.error || 'Scan failed — check debug log for details');
+ }
+ } catch (e) {
+ setScanning(false);
+ setError(`Unexpected error: ${e instanceof Error ? e.message : String(e)}`);
+ }
};
return (
@@ -95,8 +135,77 @@ const ScannerPanel: React.FC = () => {
</div>
</div>
+ {/* Error Display */}
{error && (
- <div style={{ padding: '6px 10px', backgroundColor: `${F.RED}20`, color: F.RED, fontSize: '9px', fontWeight: 700, borderRadius: '2px' }}>{error}</div>
+ <div style={{ padding: '8px 10px', backgroundColor: `${F.RED}15`, border: `1px solid ${F.RED}40`, borderRadius: '2px' }}>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.RED, marginBottom: '2px' }}>
+ SCAN ERROR
+ </div>
+ <div style={{ fontSize: '9px', color: F.RED, lineHeight: '1.4', whiteSpace: 'pre-wrap' }}>
+ {error}
+ </div>
+ </div>
+ )}
+
+ {/* Prefetch Warning */}
+ {prefetchWarning && !error && (
+ <div style={{
+ padding: '6px 10px', backgroundColor: `${F.YELLOW}12`, border: `1px solid ${F.YELLOW}30`,
+ borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '6px',
+ }}>
+ <AlertTriangle size={10} color={F.YELLOW} />
+ <span style={{ fontSize: '9px', color: F.YELLOW }}>{prefetchWarning}</span>
+ </div>
+ )}
+
+ {/* Symbol-level errors */}
+ {symbolErrors.length > 0 && (
+ <div style={{ padding: '6px 10px', backgroundColor: `${F.YELLOW}10`, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>
+ <div style={{ fontSize: '8px', fontWeight: 700, color: F.YELLOW, letterSpacing: '0.5px', marginBottom: '4px' }}>
+ SYMBOL WARNINGS ({symbolErrors.length})
+ </div>
+ {symbolErrors.map((se, i) => (
+ <div key={i} style={{ fontSize: '9px', color: F.GRAY, lineHeight: '1.4' }}>
+ <span style={{ color: F.WHITE, fontWeight: 700 }}>{se.symbol}</span>: {se.error}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Debug Log (collapsible) */}
+ {debugLog.length > 0 && (
+ <div style={{ backgroundColor: F.PANEL_BG, border: `1px solid ${F.BORDER}`, borderRadius: '2px' }}>
+ <button
+ onClick={() => setShowDebug(!showDebug)}
+ style={{
+ width: '100%', padding: '6px 10px', backgroundColor: F.HEADER_BG,
+ border: 'none', borderBottom: showDebug ? `1px solid ${F.BORDER}` : 'none',
+ color: F.MUTED, fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px',
+ textAlign: 'left',
+ }}
+ >
+ {showDebug ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
+ DEBUG LOG ({debugLog.length} entries)
+ </button>
+ {showDebug && (
+ <div style={{
+ padding: '8px 10px', maxHeight: '200px', overflow: 'auto',
+ fontFamily: '"IBM Plex Mono", monospace', fontSize: '8px', lineHeight: '1.5',
+ }}>
+ {debugLog.map((line, i) => (
+ <div key={i} style={{
+ color: line.includes('ERROR') ? F.RED
+ : line.includes('WARNING') ? F.YELLOW
+ : line.includes('summary') ? F.CYAN
+ : F.MUTED,
+ }}>
+ {line}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
)}
{/* Results */}
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts
index 6500de051..d8ab9b7b1 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/constants/indicators.ts
@@ -9,6 +9,10 @@ export const OPERATORS = [
{ value: 'crosses_above', label: 'Crosses Above' },
{ value: 'crosses_below', label: 'Crosses Below' },
{ value: 'between', label: 'Between' },
+ { value: 'crossed_above_within', label: 'Crossed Above (N bars)' },
+ { value: 'crossed_below_within', label: 'Crossed Below (N bars)' },
+ { value: 'rising', label: 'Rising (N bars)' },
+ { value: 'falling', label: 'Falling (N bars)' },
];
export const TIMEFRAMES = [
@@ -24,7 +28,226 @@ export const TIMEFRAMES = [
];
export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
- // Momentum
+ // ── Stock Attributes ──────────────────────────────────────────────
+ {
+ name: 'CLOSE',
+ label: 'Close Price',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'OPEN',
+ label: 'Open Price',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HIGH',
+ label: 'High Price',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'LOW',
+ label: 'Low Price',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'VOLUME',
+ label: 'Volume',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'CHANGE_PCT',
+ label: 'Change %',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'VWAP',
+ label: 'VWAP',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HL2',
+ label: 'HL2 (H+L)/2',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HLC3',
+ label: 'HLC3 (H+L+C)/3',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'OHLC4',
+ label: 'OHLC4 (O+H+L+C)/4',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ // Heikin-Ashi candles
+ {
+ name: 'HA_CLOSE',
+ label: 'Heikin-Ashi Close',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HA_OPEN',
+ label: 'Heikin-Ashi Open',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HA_HIGH',
+ label: 'Heikin-Ashi High',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ {
+ name: 'HA_LOW',
+ label: 'Heikin-Ashi Low',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+ // Pivot Points
+ {
+ name: 'PIVOT',
+ label: 'Pivot Points',
+ category: 'stock_attributes',
+ fields: ['pp', 'r1', 'r2', 'r3', 's1', 's2', 's3'],
+ defaultField: 'pp',
+ params: [{ key: 'type', label: 'Type (0=Std,1=Fib,2=Wood,3=Cam)', default: 0, min: 0, max: 3 }],
+ },
+ // Keep PRICE as backward-compatible alias
+ {
+ name: 'PRICE',
+ label: 'Price (Close)',
+ category: 'stock_attributes',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [],
+ },
+
+ // ── Moving Averages ───────────────────────────────────────────────
+ {
+ name: 'SMA',
+ label: 'SMA',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+ {
+ name: 'EMA',
+ label: 'EMA',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 12, min: 2, max: 500 }],
+ },
+ {
+ name: 'WMA',
+ label: 'WMA',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 9, min: 2, max: 500 }],
+ },
+ {
+ name: 'KAMA',
+ label: 'KAMA',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'period', label: 'Period', default: 10, min: 2, max: 200 },
+ { key: 'pow1', label: 'Fast', default: 2, min: 1, max: 50 },
+ { key: 'pow2', label: 'Slow', default: 30, min: 5, max: 100 },
+ ],
+ },
+ {
+ name: 'TEMA',
+ label: 'TEMA (Triple EMA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+ {
+ name: 'DEMA',
+ label: 'DEMA (Double EMA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+ {
+ name: 'HMA',
+ label: 'HMA (Hull MA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 500 }],
+ },
+ {
+ name: 'RMA',
+ label: 'RMA (Running MA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 500 }],
+ },
+ {
+ name: 'TMA',
+ label: 'TMA (Triangular MA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+ {
+ name: 'VWMA',
+ label: 'VWMA (Vol Weighted MA)',
+ category: 'moving_averages',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
+ },
+
+ // ── Momentum ──────────────────────────────────────────────────────
{
name: 'RSI',
label: 'RSI',
@@ -44,6 +267,18 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
{ key: 'smooth', label: 'Smooth', default: 3, min: 1, max: 20 },
],
},
+ {
+ name: 'STOCH_RSI',
+ label: 'Stochastic RSI',
+ category: 'momentum',
+ fields: ['stoch_rsi', 'k', 'd'],
+ defaultField: 'k',
+ params: [
+ { key: 'period', label: 'Period', default: 14, min: 2, max: 100 },
+ { key: 'smooth1', label: 'Smooth K', default: 3, min: 1, max: 20 },
+ { key: 'smooth2', label: 'Smooth D', default: 3, min: 1, max: 20 },
+ ],
+ },
{
name: 'WILLIAMS_R',
label: "Williams %R",
@@ -60,8 +295,66 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
defaultField: 'value',
params: [{ key: 'period', label: 'Period', default: 12, min: 1, max: 100 }],
},
+ {
+ name: 'TSI',
+ label: 'True Strength Index',
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'window_slow', label: 'Slow', default: 25, min: 5, max: 100 },
+ { key: 'window_fast', label: 'Fast', default: 13, min: 2, max: 50 },
+ ],
+ },
+ {
+ name: 'ULTIMATE_OSCILLATOR',
+ label: 'Ultimate Oscillator',
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'window1', label: 'Short', default: 7, min: 1, max: 50 },
+ { key: 'window2', label: 'Medium', default: 14, min: 5, max: 100 },
+ { key: 'window3', label: 'Long', default: 28, min: 10, max: 200 },
+ ],
+ },
+ {
+ name: 'AWESOME_OSCILLATOR',
+ label: 'Awesome Oscillator',
+ category: 'momentum',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'window1', label: 'Short', default: 5, min: 2, max: 50 },
+ { key: 'window2', label: 'Long', default: 34, min: 10, max: 200 },
+ ],
+ },
+ {
+ name: 'PPO',
+ label: 'PPO',
+ category: 'momentum',
+ fields: ['ppo', 'ppo_signal', 'ppo_hist'],
+ defaultField: 'ppo',
+ params: [
+ { key: 'fast', label: 'Fast', default: 12, min: 2, max: 50 },
+ { key: 'slow', label: 'Slow', default: 26, min: 5, max: 100 },
+ { key: 'signal', label: 'Signal', default: 9, min: 2, max: 50 },
+ ],
+ },
+ {
+ name: 'PVO',
+ label: 'PVO',
+ category: 'momentum',
+ fields: ['pvo', 'pvo_signal', 'pvo_hist'],
+ defaultField: 'pvo',
+ params: [
+ { key: 'window_slow', label: 'Slow', default: 26, min: 5, max: 100 },
+ { key: 'window_fast', label: 'Fast', default: 12, min: 2, max: 50 },
+ { key: 'window_sign', label: 'Signal', default: 9, min: 2, max: 50 },
+ ],
+ },
- // Trend
+ // ── Trend ─────────────────────────────────────────────────────────
{
name: 'MACD',
label: 'MACD',
@@ -74,22 +367,6 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
{ key: 'signal', label: 'Signal', default: 9, min: 2, max: 50 },
],
},
- {
- name: 'SMA',
- label: 'SMA',
- category: 'trend',
- fields: ['value'],
- defaultField: 'value',
- params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 500 }],
- },
- {
- name: 'EMA',
- label: 'EMA',
- category: 'trend',
- fields: ['value'],
- defaultField: 'value',
- params: [{ key: 'period', label: 'Period', default: 12, min: 2, max: 500 }],
- },
{
name: 'ADX',
label: 'ADX',
@@ -117,8 +394,96 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
{ key: 'multiplier', label: 'Multiplier', default: 3, min: 1, max: 10 },
],
},
+ {
+ name: 'ICHIMOKU',
+ label: 'Ichimoku',
+ category: 'trend',
+ fields: ['conversion', 'base', 'span_a', 'span_b'],
+ defaultField: 'conversion',
+ params: [
+ { key: 'window1', label: 'Tenkan', default: 9, min: 2, max: 100 },
+ { key: 'window2', label: 'Kijun', default: 26, min: 5, max: 100 },
+ { key: 'window3', label: 'Senkou', default: 52, min: 10, max: 200 },
+ ],
+ },
+ {
+ name: 'PSAR',
+ label: 'Parabolic SAR',
+ category: 'trend',
+ fields: ['psar', 'psar_up', 'psar_down'],
+ defaultField: 'psar',
+ params: [
+ { key: 'step', label: 'Step', default: 0.02, min: 0.001, max: 0.5 },
+ { key: 'max_step', label: 'Max Step', default: 0.2, min: 0.01, max: 1 },
+ ],
+ },
+ {
+ name: 'AROON',
+ label: 'Aroon',
+ category: 'trend',
+ fields: ['aroon_up', 'aroon_down', 'aroon_indicator'],
+ defaultField: 'aroon_indicator',
+ params: [{ key: 'period', label: 'Period', default: 25, min: 2, max: 100 }],
+ },
+ {
+ name: 'STC',
+ label: 'Schaff Trend Cycle',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'window_slow', label: 'Slow', default: 50, min: 10, max: 200 },
+ { key: 'window_fast', label: 'Fast', default: 23, min: 5, max: 100 },
+ { key: 'cycle', label: 'Cycle', default: 10, min: 2, max: 50 },
+ ],
+ },
+ {
+ name: 'KST',
+ label: 'KST',
+ category: 'trend',
+ fields: ['kst', 'kst_signal'],
+ defaultField: 'kst',
+ params: [
+ { key: 'nsig', label: 'Signal', default: 9, min: 2, max: 50 },
+ ],
+ },
+ {
+ name: 'VORTEX',
+ label: 'Vortex',
+ category: 'trend',
+ fields: ['vortex_pos', 'vortex_neg'],
+ defaultField: 'vortex_pos',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'DPO',
+ label: 'Detrended Price Osc.',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
+ },
+ {
+ name: 'TRIX',
+ label: 'TRIX',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 15, min: 2, max: 100 }],
+ },
+ {
+ name: 'MASS_INDEX',
+ label: 'Mass Index',
+ category: 'trend',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [
+ { key: 'window_fast', label: 'Fast', default: 9, min: 2, max: 50 },
+ { key: 'window_slow', label: 'Slow', default: 25, min: 5, max: 100 },
+ ],
+ },
- // Volatility
+ // ── Volatility ────────────────────────────────────────────────────
{
name: 'BOLLINGER',
label: 'Bollinger Bands',
@@ -155,7 +520,7 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
},
- // Volume
+ // ── Volume ────────────────────────────────────────────────────────
{
name: 'OBV',
label: 'OBV',
@@ -165,35 +530,57 @@ export const INDICATOR_DEFINITIONS: IndicatorDefinition[] = [
params: [],
},
{
- name: 'VWAP',
- label: 'VWAP',
+ name: 'CMF',
+ label: 'Chaikin Money Flow',
category: 'volume',
fields: ['value'],
defaultField: 'value',
- params: [],
+ params: [{ key: 'period', label: 'Period', default: 20, min: 2, max: 100 }],
},
-
- // Price
{
- name: 'PRICE',
- label: 'Price',
- category: 'price',
+ name: 'MFI',
+ label: 'Money Flow Index',
+ category: 'volume',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'FORCE_INDEX',
+ label: 'Force Index',
+ category: 'volume',
+ fields: ['value'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 13, min: 1, max: 100 }],
+ },
+ {
+ name: 'ADI',
+ label: 'Accumulation/Distribution',
+ category: 'volume',
fields: ['value'],
defaultField: 'value',
params: [],
},
{
- name: 'VOLUME',
- label: 'Volume',
- category: 'price',
+ name: 'EOM',
+ label: 'Ease of Movement',
+ category: 'volume',
+ fields: ['value', 'signal'],
+ defaultField: 'value',
+ params: [{ key: 'period', label: 'Period', default: 14, min: 2, max: 100 }],
+ },
+ {
+ name: 'VPT',
+ label: 'Volume Price Trend',
+ category: 'volume',
fields: ['value'],
defaultField: 'value',
params: [],
},
{
- name: 'CHANGE_PCT',
- label: 'Change %',
- category: 'price',
+ name: 'NVI',
+ label: 'Negative Volume Index',
+ category: 'volume',
fields: ['value'],
defaultField: 'value',
params: [],
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
index 25bdbe181..768d9dfd1 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/services/algoTradingService.ts
@@ -6,6 +6,8 @@ interface ApiResult<T = unknown> {
data?: T;
error?: string;
count?: number;
+ debug?: string[];
+ prefetch_warning?: string;
}
function parseResult<T>(raw: string): ApiResult<T> {
@@ -104,14 +106,49 @@ export async function getAlgoTrades(
}
// Scanner
+export interface ScanResponse {
+ matches: ScanResult[];
+ scanned: number;
+ errors?: Array<{ symbol: string; error: string }>;
+ debug?: string[];
+ prefetch_warning?: string;
+}
+
export async function runAlgoScan(
conditions: string,
symbols: string,
timeframe?: string,
provider?: string
-): Promise<ApiResult<{ matches: ScanResult[]; scanned: number }>> {
+): Promise<ApiResult<ScanResponse>> {
const raw = await invoke<string>('run_algo_scan', { conditions, symbols, timeframe, provider });
- return parseResult(raw);
+ const result = parseResult<ScanResponse>(raw);
+ // The Rust backend puts debug/prefetch_warning at root level (same as success/error),
+ // and the Python scanner puts matches/scanned/errors in the same JSON object.
+ // Normalize: merge top-level fields into data when success=true.
+ if (result.success && !result.data) {
+ // Scanner output is flat JSON — parse again to extract fields
+ try {
+ const parsed = JSON.parse(raw);
+ result.data = {
+ matches: parsed.matches || [],
+ scanned: parsed.scanned || 0,
+ errors: parsed.errors,
+ debug: parsed.debug,
+ prefetch_warning: parsed.prefetch_warning,
+ };
+ result.debug = parsed.debug;
+ result.prefetch_warning = parsed.prefetch_warning;
+ } catch { /* already handled */ }
+ }
+ // Also carry debug from root level
+ if (!result.debug) {
+ try {
+ const parsed = JSON.parse(raw);
+ if (parsed.debug) result.debug = parsed.debug;
+ if (parsed.prefetch_warning) result.prefetch_warning = parsed.prefetch_warning;
+ } catch { /* ignore */ }
+ }
+ return result;
}
// Candle cache
diff --git a/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts b/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
index 055c9d5d0..a04bcc27f 100644
--- a/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/algo-trading/types/index.ts
@@ -5,6 +5,16 @@ export interface ConditionItem {
operator: string;
value: number;
value2?: number;
+ // Indicator-vs-indicator comparison (Phase 3)
+ compareMode?: 'value' | 'indicator'; // default 'value'
+ compareIndicator?: string;
+ compareParams?: Record<string, number>;
+ compareField?: string;
+ // Chart offsets (Phase 4)
+ offset?: number; // 0=current (default), 1=1 candle ago, etc.
+ compareOffset?: number; // offset for comparison side
+ // Advanced operators
+ lookback?: number; // for crossed_within, rising, falling operators
}
export interface ConditionGroup {
@@ -87,13 +97,15 @@ export interface ConditionDetail {
computed_value: number | null;
operator: string;
target: number;
+ target_indicator?: string;
+ target_computed_value?: number;
error?: string;
}
export interface IndicatorDefinition {
name: string;
label: string;
- category: 'trend' | 'momentum' | 'volatility' | 'volume' | 'price';
+ category: 'stock_attributes' | 'moving_averages' | 'momentum' | 'trend' | 'volatility' | 'volume';
fields: string[];
defaultField: string;
params: IndicatorParam[];
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
index d47e2e9ad..b9389c6e4 100644
--- a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
@@ -2,7 +2,7 @@
import React, { useState, useCallback } from 'react';
import { Globe, Wifi, WifiOff, ChevronDown, Settings as SettingsIcon, AlertTriangle, Zap } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { TimezoneSelector } from '@/components/common/TimezoneSelector';
+import { useCurrentTime } from '@/contexts/TimezoneContext';
import { FINCEPT } from '../constants';
interface BrokerInfo {
@@ -155,6 +155,7 @@ export function CryptoTopNav({
}: CryptoTopNavProps) {
const { t } = useTranslation('trading');
const [showLiveModeModal, setShowLiveModeModal] = useState(false);
+ const { formattedTime, timezone } = useCurrentTime();
const handleLiveModeClick = useCallback(() => {
if (tradingMode !== 'live') {
@@ -382,7 +383,9 @@ export function CryptoTopNav({
<div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
- <TimezoneSelector compact />
+ <span style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.CYAN }}>
+ {formattedTime} <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>{timezone.shortLabel}</span>
+ </span>
<button
onClick={onSettingsToggle}
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx
index f7d63bdfa..b8113ece9 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx
@@ -114,7 +114,7 @@ export function StockTradingChart({
volume: number;
}>>([]);
- const { adapter, isAuthenticated, isLoading: contextLoading, isConnecting } = useStockBrokerContext();
+ const { adapter, isAuthenticated, isLoading: contextLoading, isConnecting, masterContractReady } = useStockBrokerContext();
useEffect(() => {
mountedRef.current = true;
@@ -162,6 +162,19 @@ export function StockTradingChart({
return;
}
+ // Wait for master contract to be ready before checking instrument
+ if (!masterContractReady) {
+ if (retryCount < INIT_MAX_RETRIES) {
+ console.log(`[StockTradingChart] Master contract not ready, retry ${retryCount + 1}/${INIT_MAX_RETRIES} in ${INIT_RETRY_DELAY}ms...`);
+ setTimeout(() => fetchHistoricalData(retryCount + 1), INIT_RETRY_DELAY);
+ return;
+ }
+ console.warn('[StockTradingChart] Master contract still not ready after retries');
+ setError('Symbol data loading. Please wait...');
+ setIsLoading(false);
+ return;
+ }
+
// Check if master contract/instrument lookup is ready (for brokers that need it)
if (typeof adapter.getInstrument === 'function') {
try {
@@ -173,7 +186,7 @@ export function StockTradingChart({
return;
}
console.warn('[StockTradingChart] Instrument token still not available after retries');
- setError('Symbol data not ready. Please ensure master contract is downloaded.');
+ setError('Symbol not found. Try searching for a different symbol.');
setIsLoading(false);
return;
}
@@ -308,7 +321,7 @@ export function StockTradingChart({
setIsLoading(false);
}
- }, [adapter, isAuthenticated, symbol, exchange, selectedInterval]);
+ }, [adapter, isAuthenticated, symbol, exchange, selectedInterval, masterContractReady]);
// Auto-fetch on mount and when dependencies change
useEffect(() => {
diff --git a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
index 1c8768b88..76f73abf0 100644
--- a/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ma-analytics/unified/DealDatabase.tsx
@@ -1,11 +1,11 @@
/**
* Deal Database - Track and Save M&A Deals
*
- * Simple deal tracking and management
+ * Simple deal tracking and management with SEC filing scanner
*/
import React, { useState, useEffect } from 'react';
-import { Database, Plus, Search, FileText, TrendingUp, DollarSign, Calendar } from 'lucide-react';
+import { Database, Search, FileText, TrendingUp, RefreshCw, Scan, AlertCircle } from 'lucide-react';
import { FINCEPT, TYPOGRAPHY, SPACING, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';
import { MAAnalyticsService, type MADeal } from '@/services/maAnalyticsService';
@@ -14,23 +14,53 @@ export const DealDatabase: React.FC = () => {
const [selectedDeal, setSelectedDeal] = useState<MADeal | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [loading, setLoading] = useState(false);
+ const [scanning, setScanning] = useState(false);
+ const [scanDays, setScanDays] = useState(30);
+ const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error' | 'info'; text: string } | null>(null);
useEffect(() => {
loadDeals();
}, []);
+ // Clear status message after 5 seconds
+ useEffect(() => {
+ if (statusMessage) {
+ const timer = setTimeout(() => setStatusMessage(null), 5000);
+ return () => clearTimeout(timer);
+ }
+ }, [statusMessage]);
+
const loadDeals = async () => {
setLoading(true);
try {
const result = await MAAnalyticsService.DealDatabase.getAllDeals();
setDeals(result);
+ setStatusMessage({ type: 'info', text: `Loaded ${result.length} deals from database` });
} catch (error) {
console.error('Failed to load deals:', error);
+ setStatusMessage({ type: 'error', text: 'Failed to load deals from database' });
} finally {
setLoading(false);
}
};
+ const scanFilings = async () => {
+ setScanning(true);
+ setStatusMessage({ type: 'info', text: `Scanning SEC filings from the last ${scanDays} days...` });
+ try {
+ const result = await MAAnalyticsService.DealDatabase.scanFilings(scanDays);
+ const count = Array.isArray(result) ? result.length : 0;
+ setStatusMessage({ type: 'success', text: `Found ${count} M&A filings. Refreshing deals...` });
+ // Reload deals after scanning
+ await loadDeals();
+ } catch (error) {
+ console.error('Failed to scan filings:', error);
+ setStatusMessage({ type: 'error', text: `Scan failed: ${error instanceof Error ? error.message : 'Unknown error'}` });
+ } finally {
+ setScanning(false);
+ }
+ };
+
const formatCurrency = (value: number) => {
if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
@@ -62,7 +92,31 @@ export const DealDatabase: React.FC = () => {
<div style={{ ...COMMON_STYLES.dataLabel, marginBottom: SPACING.SMALL }}>
DEAL TRACKER
</div>
- <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.DEFAULT }}>
+
+ {/* Status Message */}
+ {statusMessage && (
+ <div style={{
+ padding: SPACING.SMALL,
+ marginBottom: SPACING.SMALL,
+ borderRadius: '4px',
+ fontSize: TYPOGRAPHY.TINY,
+ backgroundColor: statusMessage.type === 'error' ? `${FINCEPT.RED}20` :
+ statusMessage.type === 'success' ? `${FINCEPT.GREEN}20` :
+ `${FINCEPT.CYAN}20`,
+ color: statusMessage.type === 'error' ? FINCEPT.RED :
+ statusMessage.type === 'success' ? FINCEPT.GREEN :
+ FINCEPT.CYAN,
+ display: 'flex',
+ alignItems: 'center',
+ gap: SPACING.SMALL,
+ }}>
+ <AlertCircle size={12} />
+ {statusMessage.text}
+ </div>
+ )}
+
+ {/* Search Input */}
+ <div style={{ display: 'flex', gap: SPACING.SMALL, marginBottom: SPACING.SMALL }}>
<div style={{ position: 'relative', flex: 1 }}>
<Search
size={12}
@@ -86,11 +140,75 @@ export const DealDatabase: React.FC = () => {
}}
/>
</div>
+ <button
+ onClick={loadDeals}
+ disabled={loading}
+ title="Refresh deals"
+ style={{
+ padding: SPACING.SMALL,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px',
+ color: FINCEPT.GRAY,
+ cursor: loading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
+ </button>
</div>
+
+ {/* Scan SEC Filings */}
+ <div style={{
+ display: 'flex',
+ gap: SPACING.SMALL,
+ alignItems: 'center',
+ marginBottom: SPACING.SMALL,
+ }}>
+ <select
+ value={scanDays}
+ onChange={(e) => setScanDays(Number(e.target.value))}
+ style={{
+ ...COMMON_STYLES.inputField,
+ width: '80px',
+ fontSize: TYPOGRAPHY.TINY,
+ }}
+ >
+ <option value={7}>7 days</option>
+ <option value={14}>14 days</option>
+ <option value={30}>30 days</option>
+ <option value={60}>60 days</option>
+ <option value={90}>90 days</option>
+ </select>
+ <button
+ onClick={scanFilings}
+ disabled={scanning}
+ style={{
+ flex: 1,
+ padding: SPACING.SMALL,
+ backgroundColor: scanning ? FINCEPT.PANEL_BG : FINCEPT.ORANGE,
+ border: 'none',
+ borderRadius: '4px',
+ color: scanning ? FINCEPT.GRAY : FINCEPT.DARK_BG,
+ cursor: scanning ? 'not-allowed' : 'pointer',
+ fontSize: TYPOGRAPHY.TINY,
+ fontWeight: TYPOGRAPHY.BOLD,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: SPACING.TINY,
+ }}
+ >
+ <Scan size={12} className={scanning ? 'animate-spin' : ''} />
+ {scanning ? 'SCANNING...' : 'SCAN SEC FILINGS'}
+ </button>
+ </div>
+
<div style={{
fontSize: TYPOGRAPHY.TINY,
color: FINCEPT.MUTED,
- marginTop: SPACING.SMALL,
}}>
{filteredDeals.length} deal{filteredDeals.length !== 1 ? 's' : ''} tracked
</div>
@@ -124,9 +242,15 @@ export const DealDatabase: React.FC = () => {
color: FINCEPT.MUTED,
marginTop: SPACING.SMALL,
textAlign: 'center',
- maxWidth: '200px',
+ maxWidth: '220px',
}}>
- Use Valuation Toolkit or Merger Analysis to create and save deals
+ {searchQuery ? (
+ 'Try a different search term'
+ ) : (
+ <>
+ Click <strong style={{ color: FINCEPT.ORANGE }}>SCAN SEC FILINGS</strong> above to automatically discover M&A deals from SEC EDGAR
+ </>
+ )}
</div>
</div>
) : (
diff --git a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
index b4727c38c..4683738bc 100644
--- a/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
@@ -4,7 +4,7 @@ import { Info, Settings, RefreshCw, Clock, Zap, Newspaper, ExternalLink, Copy, X
import { fetchAllNews, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData, setNewsCacheTTL } from '@/services/news/newsService';
import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
import RecordingControlPanel from '@/components/common/RecordingControlPanel';
-import { TimezoneSelector } from '@/components/common/TimezoneSelector';
+import { useCurrentTime } from '@/contexts/TimezoneContext';
import { useTranslation } from 'react-i18next';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { analyzeNewsArticle, type NewsAnalysisData, getSentimentColor, getUrgencyColor, getRiskColor } from '@/services/news/newsAnalysisService';
@@ -183,6 +183,7 @@ const NewsGridCard: React.FC<{
const NewsTab: React.FC = () => {
const { t } = useTranslation('news');
const { colors, fontSize, fontFamily } = useTerminalTheme();
+ const { formattedTime, timezone } = useCurrentTime();
// Helper functions for priority/sentiment colors
const priColor = (p: string) => ({
@@ -451,7 +452,9 @@ const NewsTab: React.FC = () => {
<span style={{ color: colors.panel }}>|</span>
<span style={{ color: colors.success, fontSize: '9px', fontWeight: 700 }}>{feedCount} SRC</span>
<span style={{ color: colors.panel }}>|</span>
- <TimezoneSelector compact />
+ <span style={{ fontSize: '9px', fontWeight: 600, color: 'var(--ft-color-accent, #00E5FF)' }}>
+ {formattedTime} <span style={{ color: colors.primary, fontWeight: 700 }}>{timezone.shortLabel}</span>
+ </span>
</div>
{/* Right: actions */}
diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
index 831e1ef54..fcdf63c06 100644
--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx
@@ -47,7 +47,7 @@ export default function SettingsTab() {
const { t } = useTranslation('settings');
const { session } = useAuth();
const { theme, updateTheme, resetTheme, colors } = useTerminalTheme();
- const { defaultTimezone, setDefaultTimezone, options: timezoneOptions } = useTimezone();
+ const { timezone, setTimezone, options: timezoneOptions } = useTimezone();
const [activeSection, setActiveSection] = useState<SettingsSection>('credentials');
const {
@@ -290,8 +290,8 @@ export default function SettingsTab() {
showMessage={showMessage}
keyMappings={keyMappings}
setKeyMappings={setKeyMappings}
- defaultTimezone={defaultTimezone}
- setDefaultTimezone={setDefaultTimezone}
+ defaultTimezone={timezone}
+ setDefaultTimezone={setTimezone}
timezoneOptions={timezoneOptions}
/>
)}
diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
index cf12187f1..4321fca1d 100644
--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx
@@ -173,6 +173,9 @@ interface StockBrokerContextType {
isConnecting: boolean;
isRefreshing: boolean;
+ // Master contract state
+ masterContractReady: boolean;
+
// Error state
error: string | null;
clearError: () => void;
@@ -203,6 +206,9 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Error state
const [error, setError] = useState<string | null>(null);
+ // Master contract state
+ const [masterContractReady, setMasterContractReady] = useState(false);
+
// Cached trading data
const [positions, setPositions] = useState<Position[]>([]);
const [holdings, setHoldings] = useState<Holding[]>([]);
@@ -620,15 +626,20 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Fetch initial data
await refreshAllData(adapterToUse);
- // Auto-download master contract if needed (background task)
+ // Auto-download master contract if needed
+ setMasterContractReady(false);
symbolMaster.ensureMasterContract(activeBroker).then((result) => {
if (result.success) {
console.log(`[StockBrokerContext] ✓ Master contract ready: ${result.total_symbols} symbols`);
+ setMasterContractReady(true);
} else {
console.warn(`[StockBrokerContext] Master contract download issue: ${result.message}`);
+ // Still set to true if we have cached data
+ setMasterContractReady(result.total_symbols > 0);
}
}).catch((err) => {
console.warn(`[StockBrokerContext] Master contract download failed:`, err);
+ setMasterContractReady(false);
});
// Connect WebSocket for real-time data streaming
@@ -731,15 +742,19 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
// Fetch initial data
await refreshAllData(adapter);
- // Auto-download master contract if needed (background task)
+ // Auto-download master contract if needed
+ setMasterContractReady(false);
symbolMaster.ensureMasterContract(activeBroker).then((result) => {
if (result.success) {
console.log(`[StockBrokerContext] ✓ Master contract ready: ${result.total_symbols} symbols`);
+ setMasterContractReady(true);
} else {
console.warn(`[StockBrokerContext] Master contract download issue: ${result.message}`);
+ setMasterContractReady(result.total_symbols > 0);
}
}).catch((err) => {
console.warn(`[StockBrokerContext] Master contract download failed:`, err);
+ setMasterContractReady(false);
});
// Connect WebSocket for real-time data streaming
@@ -1383,6 +1398,9 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
isConnecting,
isRefreshing,
+ // Master contract
+ masterContractReady,
+
// Error
error,
clearError,
@@ -1418,6 +1436,7 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {
isLoading,
isConnecting,
isRefreshing,
+ masterContractReady,
error,
clearError,
]
diff --git a/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
index 80bb5044c..54a15a4f3 100644
--- a/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/TimezoneContext.tsx
@@ -2,9 +2,7 @@
* TimezoneContext.tsx
*
* Global timezone state management for Fincept Terminal.
- * Provides dual-timezone support:
- * - Default Timezone: Persisted in SQLite, used by navigation bar
- * - Session Timezone: Per-session, used by dashboard widgets
+ * Single timezone persisted in SQLite, used across the application.
*/
import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
@@ -71,8 +69,7 @@ export const TIMEZONE_OPTIONS: TimezoneOption[] = [
{ id: 'tel-aviv', label: 'Tel Aviv (IST)', shortLabel: 'TLV', zone: 'Asia/Jerusalem' },
];
-const DEFAULT_STORAGE_KEY = 'fincept_default_timezone';
-const SESSION_STORAGE_KEY = 'fincept_timezone';
+const STORAGE_KEY = 'fincept_default_timezone';
const DEFAULT_TIMEZONE_ID = 'local';
// ============================================================================
@@ -80,24 +77,24 @@ const DEFAULT_TIMEZONE_ID = 'local';
// ============================================================================
interface TimezoneContextValue {
- /** Default timezone (persisted, used by nav bar) */
- defaultTimezone: TimezoneOption;
- /** Session timezone (per-session, used by dashboard widgets) */
+ /** Current timezone setting (persisted) */
timezone: TimezoneOption;
/** All available timezone options */
options: TimezoneOption[];
- /** Update the default timezone (persisted in settings) */
- setDefaultTimezone: (timezoneId: string) => void;
- /** Update the session timezone (for dashboard widgets) */
+ /** Update the timezone (persisted in settings) */
setTimezone: (timezoneId: string) => void;
- /** Format a Date object according to a specific timezone */
+ /** Format a Date object according to the timezone */
formatTime: (date: Date, options?: Intl.DateTimeFormatOptions) => string;
- /** Format a Date object according to the default timezone */
- formatTimeWithDefault: (date: Date, options?: Intl.DateTimeFormatOptions) => string;
/** Format a Date object to a short time string (HH:MM:SS) */
formatTimeShort: (date: Date) => string;
/** Get the current time formatted in the selected timezone */
getCurrentTimeFormatted: () => string;
+
+ // Aliases for backwards compatibility with Settings Tab
+ /** @deprecated Use timezone instead */
+ defaultTimezone: TimezoneOption;
+ /** @deprecated Use setTimezone instead */
+ setDefaultTimezone: (timezoneId: string) => void;
}
const TimezoneContext = createContext<TimezoneContextValue | undefined>(undefined);
@@ -111,81 +108,48 @@ interface TimezoneProviderProps {
}
export const TimezoneProvider: React.FC<TimezoneProviderProps> = ({ children }) => {
- // Initialize default timezone
- const [defaultTimezoneId, setDefaultTimezoneId] = useState<string>(DEFAULT_TIMEZONE_ID);
-
- // Initialize session timezone
- const [sessionTimezoneId, setSessionTimezoneId] = useState<string>(DEFAULT_TIMEZONE_ID);
+ const [timezoneId, setTimezoneId] = useState<string>(DEFAULT_TIMEZONE_ID);
- // Get the full timezone option objects
- const defaultTimezone = TIMEZONE_OPTIONS.find(tz => tz.id === defaultTimezoneId) || TIMEZONE_OPTIONS[0];
- const timezone = TIMEZONE_OPTIONS.find(tz => tz.id === sessionTimezoneId) || TIMEZONE_OPTIONS[0];
+ // Get the full timezone option object
+ const timezone = TIMEZONE_OPTIONS.find(tz => tz.id === timezoneId) || TIMEZONE_OPTIONS[0];
- // Load timezones from storage on mount
+ // Load timezone from storage on mount
useEffect(() => {
- const loadTimezones = async () => {
+ const loadTimezone = async () => {
try {
- const storedDefault = await getSetting(DEFAULT_STORAGE_KEY);
- if (storedDefault && TIMEZONE_OPTIONS.find(tz => tz.id === storedDefault)) {
- setDefaultTimezoneId(storedDefault);
- }
-
- const storedSession = await getSetting(SESSION_STORAGE_KEY);
- if (storedSession && TIMEZONE_OPTIONS.find(tz => tz.id === storedSession)) {
- setSessionTimezoneId(storedSession);
- } else if (storedDefault && TIMEZONE_OPTIONS.find(tz => tz.id === storedDefault)) {
- setSessionTimezoneId(storedDefault);
+ const stored = await getSetting(STORAGE_KEY);
+ if (stored && TIMEZONE_OPTIONS.find(tz => tz.id === stored)) {
+ setTimezoneId(stored);
}
} catch (e) {
- console.warn('[TimezoneContext] Failed to load timezones from storage:', e);
+ console.warn('[TimezoneContext] Failed to load timezone from storage:', e);
}
};
- loadTimezones();
+ loadTimezone();
}, []);
- // Persist default timezone to storage when it changes
+ // Persist timezone to storage when it changes
useEffect(() => {
- const saveDefaultTimezone = async () => {
+ const saveTimezone = async () => {
try {
- await saveSetting(DEFAULT_STORAGE_KEY, defaultTimezoneId, 'timezone');
+ await saveSetting(STORAGE_KEY, timezoneId, 'timezone');
} catch (e) {
- console.warn('[TimezoneContext] Failed to save default timezone:', e);
+ console.warn('[TimezoneContext] Failed to save timezone:', e);
}
};
- saveDefaultTimezone();
- }, [defaultTimezoneId]);
-
- // Persist session timezone to storage when it changes
- useEffect(() => {
- const saveSessionTimezone = async () => {
- try {
- await saveSetting(SESSION_STORAGE_KEY, sessionTimezoneId, 'timezone');
- } catch (e) {
- console.warn('[TimezoneContext] Failed to save session timezone:', e);
- }
- };
- saveSessionTimezone();
- }, [sessionTimezoneId]);
-
- // Set default timezone by ID (used in Settings)
- const setDefaultTimezone = useCallback((id: string) => {
- if (TIMEZONE_OPTIONS.find(tz => tz.id === id)) {
- setDefaultTimezoneId(id);
- } else {
- console.warn(`[TimezoneContext] Unknown timezone ID: ${id}`);
- }
- }, []);
+ saveTimezone();
+ }, [timezoneId]);
- // Set session timezone by ID (used in dashboard widgets)
+ // Set timezone by ID
const setTimezone = useCallback((id: string) => {
if (TIMEZONE_OPTIONS.find(tz => tz.id === id)) {
- setSessionTimezoneId(id);
+ setTimezoneId(id);
} else {
console.warn(`[TimezoneContext] Unknown timezone ID: ${id}`);
}
}, []);
- // Format a date according to the session timezone
+ // Format a date according to the timezone
const formatTime = useCallback((date: Date, options?: Intl.DateTimeFormatOptions): string => {
const defaultOptions: Intl.DateTimeFormatOptions = {
hour: '2-digit',
@@ -208,29 +172,6 @@ export const TimezoneProvider: React.FC<TimezoneProviderProps> = ({ children })
}
}, [timezone]);
- // Format a date according to the DEFAULT timezone (for nav bar)
- const formatTimeWithDefault = useCallback((date: Date, options?: Intl.DateTimeFormatOptions): string => {
- const defaultOptions: Intl.DateTimeFormatOptions = {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- hour12: false,
- ...options,
- };
-
- // Add timezone if not using local
- if (defaultTimezone.zone) {
- defaultOptions.timeZone = defaultTimezone.zone;
- }
-
- try {
- return new Intl.DateTimeFormat('en-US', defaultOptions).format(date);
- } catch (e) {
- console.error('[TimezoneContext] Format error:', e);
- return date.toLocaleTimeString('en-US', { hour12: false });
- }
- }, [defaultTimezone]);
-
// Short format: HH:MM:SS
const formatTimeShort = useCallback((date: Date): string => {
return formatTime(date, {
@@ -247,15 +188,15 @@ export const TimezoneProvider: React.FC<TimezoneProviderProps> = ({ children })
}, [formatTimeShort]);
const value: TimezoneContextValue = {
- defaultTimezone,
timezone,
options: TIMEZONE_OPTIONS,
- setDefaultTimezone,
setTimezone,
formatTime,
- formatTimeWithDefault,
formatTimeShort,
getCurrentTimeFormatted,
+ // Backwards compatibility aliases
+ defaultTimezone: timezone,
+ setDefaultTimezone: setTimezone,
};
return (
@@ -282,15 +223,15 @@ export const useTimezone = (): TimezoneContextValue => {
};
// ============================================================================
-// Utility Hook: useCurrentTime (for dashboard widgets)
+// Utility Hook: useCurrentTime
// ============================================================================
/**
* Hook that provides a ticking current time, automatically formatted
- * according to the SESSION timezone (for dashboard widgets).
- *
+ * according to the configured timezone.
+ *
* @param refreshInterval - Update interval in milliseconds (default: 1000)
- * @returns Object with currentTime (Date) and formattedTime (string)
+ * @returns Object with currentTime (Date), formattedTime (string), and timezone
*/
export const useCurrentTime = (refreshInterval: number = 1000) => {
const [currentTime, setCurrentTime] = useState(new Date());
@@ -311,35 +252,7 @@ export const useCurrentTime = (refreshInterval: number = 1000) => {
};
};
-// ============================================================================
-// Utility Hook: useDefaultTime (for navigation bar)
-// ============================================================================
-
-/**
- * Hook that provides a ticking current time, automatically formatted
- * according to the DEFAULT timezone (for navigation bar).
- *
- * @param refreshInterval - Update interval in milliseconds (default: 1000)
- * @returns Object with currentTime (Date), formattedTime (string), and timezone
- */
-export const useDefaultTime = (refreshInterval: number = 1000) => {
- const [currentTime, setCurrentTime] = useState(new Date());
- const { formatTimeWithDefault, defaultTimezone } = useTimezone();
-
- useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, refreshInterval);
-
- return () => clearInterval(timer);
- }, [refreshInterval]);
-
- return {
- currentTime,
- formattedTime: formatTimeWithDefault(currentTime),
- timezone: defaultTimezone,
- };
-};
+// Keep useDefaultTime as alias for backwards compatibility
+export const useDefaultTime = useCurrentTime;
export default TimezoneContext;
-
diff --git a/fincept-terminal-desktop/src/services/trading/masterContractService.ts b/fincept-terminal-desktop/src/services/trading/masterContractService.ts
index 0a0ada126..5b13d95ca 100644
--- a/fincept-terminal-desktop/src/services/trading/masterContractService.ts
+++ b/fincept-terminal-desktop/src/services/trading/masterContractService.ts
@@ -1,7 +1,9 @@
// Master Contract Service - Symbol Search & Management
// Provides access to broker symbol data for fast search and offline access
+// Updated to use unified symbol_master commands
import { invoke } from '@tauri-apps/api/core';
+import * as symbolMaster from '@/services/symbolMasterService';
// ============================================================================
// Types
@@ -37,16 +39,16 @@ export interface DownloadResult {
*/
export interface MasterContractCache {
broker_id: string;
- symbols_data: string;
+ status: string;
symbol_count: number;
last_updated: number;
- created_at: number;
+ is_ready: boolean;
}
/**
* Supported broker IDs for master contract
*/
-export type SupportedBroker = 'angelone' | 'fyers' | 'zerodha';
+export type SupportedBroker = 'angelone' | 'fyers' | 'zerodha' | 'upstox' | 'dhan' | 'shoonya';
// ============================================================================
// Master Contract Download
@@ -57,23 +59,26 @@ export type SupportedBroker = 'angelone' | 'fyers' | 'zerodha';
* Downloads symbol data from broker API and stores in local database
*/
export const downloadMasterContract = async (brokerId: SupportedBroker): Promise<DownloadResult> => {
- return await invoke<DownloadResult>('download_master_contract', { brokerId });
+ const result = await symbolMaster.downloadMasterContract(brokerId);
+ return {
+ success: result.success,
+ message: result.message,
+ symbol_count: Number(result.total_symbols)
+ };
};
/**
* Download Angel One master contract
- * Downloads from https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json
*/
export const downloadAngelOneMasterContract = async (): Promise<DownloadResult> => {
- return await invoke<DownloadResult>('download_angelone_master_contract');
+ return await downloadMasterContract('angelone');
};
/**
* Download Fyers master contract
- * Downloads from https://public.fyers.in/sym_details/*.csv
*/
export const downloadFyersMasterContract = async (): Promise<DownloadResult> => {
- return await invoke<DownloadResult>('download_fyers_master_contract');
+ return await downloadMasterContract('fyers');
};
// ============================================================================
@@ -82,12 +87,6 @@ export const downloadFyersMasterContract = async (): Promise<DownloadResult> =>
/**
* Search symbols in master contract database
- * @param brokerId - Broker to search symbols for
- * @param query - Search query (symbol, name, or token)
- * @param exchange - Optional exchange filter (e.g., "NSE", "BSE", "NFO")
- * @param instrumentType - Optional instrument type filter (e.g., "EQ", "OPTIDX", "FUTSTK")
- * @param limit - Maximum number of results (default: 50)
- * @returns Array of matching symbols ordered by relevance
*/
export const searchSymbols = async (
brokerId: SupportedBroker,
@@ -96,46 +95,49 @@ export const searchSymbols = async (
instrumentType?: string,
limit: number = 50
): Promise<SymbolSearchResult[]> => {
- return await invoke<SymbolSearchResult[]>('search_symbols', {
- brokerId,
- query,
- exchange: exchange || null,
- instrumentType: instrumentType || null,
+ const response = await symbolMaster.searchSymbols(brokerId, query, {
+ exchange,
+ instrumentType,
limit
});
+
+ if (!response.success) {
+ return [];
+ }
+
+ return response.symbols.map(s => ({
+ symbol: s.symbol,
+ br_symbol: s.br_symbol,
+ name: s.name,
+ exchange: s.exchange,
+ token: s.token,
+ expiry: s.expiry,
+ strike: s.strike,
+ lot_size: s.lot_size,
+ instrument_type: s.instrument_type,
+ tick_size: s.tick_size
+ }));
};
/**
* Get symbol by exact match
- * @param brokerId - Broker ID
- * @param symbol - Exact symbol name
- * @param exchange - Exchange name
*/
export const getSymbol = async (
brokerId: SupportedBroker,
symbol: string,
exchange: string
): Promise<SymbolSearchResult | null> => {
- return await invoke<SymbolSearchResult | null>('get_symbol', {
- brokerId,
- symbol,
- exchange
- });
+ return await symbolMaster.getSymbol(brokerId, symbol, exchange);
};
/**
* Get symbol by broker token
- * @param brokerId - Broker ID
- * @param token - Broker-specific token
*/
export const getSymbolByToken = async (
brokerId: SupportedBroker,
token: string
): Promise<SymbolSearchResult | null> => {
- return await invoke<SymbolSearchResult | null>('get_symbol_by_token', {
- brokerId,
- token
- });
+ return await symbolMaster.getSymbolByToken(brokerId, token);
};
// ============================================================================
@@ -146,32 +148,25 @@ export const getSymbolByToken = async (
* Get total symbol count for a broker
*/
export const getSymbolCount = async (brokerId: SupportedBroker): Promise<number> => {
- return await invoke<number>('get_symbol_count', { brokerId });
+ return await symbolMaster.getSymbolCount(brokerId);
};
/**
* Get list of exchanges for a broker
*/
export const getExchanges = async (brokerId: SupportedBroker): Promise<string[]> => {
- return await invoke<string[]>('get_exchanges', { brokerId });
+ return await symbolMaster.getExchanges(brokerId);
};
/**
* Get list of expiries for derivatives
- * @param brokerId - Broker ID
- * @param exchange - Optional exchange filter
- * @param underlying - Optional underlying symbol filter
*/
export const getExpiries = async (
brokerId: SupportedBroker,
exchange?: string,
underlying?: string
): Promise<string[]> => {
- return await invoke<string[]>('get_expiries', {
- brokerId,
- exchange: exchange || null,
- underlying: underlying || null
- });
+ return await symbolMaster.getExpiries(brokerId, { exchange, underlying });
};
// ============================================================================
@@ -194,26 +189,35 @@ export const hasSymbolData = async (brokerId: SupportedBroker): Promise<boolean>
* Get master contract cache metadata
*/
export const getMasterContractCache = async (brokerId: SupportedBroker): Promise<MasterContractCache | null> => {
- return await invoke<MasterContractCache | null>('get_master_contract', { brokerId });
+ const status = await symbolMaster.getStatus(brokerId);
+ if (!status) return null;
+
+ return {
+ broker_id: status.broker_id,
+ status: status.status,
+ symbol_count: Number(status.total_symbols),
+ last_updated: status.last_updated,
+ is_ready: status.is_ready
+ };
};
/**
* Check if cache is valid (not expired)
- * @param brokerId - Broker ID
- * @param ttlSeconds - Time to live in seconds (default: 24 hours)
*/
export const isCacheValid = async (
brokerId: SupportedBroker,
- ttlSeconds: number = 86400
+ _ttlSeconds: number = 86400
): Promise<boolean> => {
- return await invoke<boolean>('is_cache_valid', { brokerId, ttlSeconds });
+ const response = await symbolMaster.isReady(brokerId);
+ return response.is_valid;
};
/**
* Get cache age in seconds
*/
export const getCacheAge = async (brokerId: SupportedBroker): Promise<number | null> => {
- return await invoke<number | null>('get_cache_age', { brokerId });
+ const response = await symbolMaster.isReady(brokerId);
+ return response.age_seconds;
};
// ============================================================================
@@ -244,7 +248,10 @@ export const getBrokerDisplayName = (brokerId: SupportedBroker): string => {
const names: Record<SupportedBroker, string> = {
angelone: 'Angel One',
fyers: 'Fyers',
- zerodha: 'Zerodha'
+ zerodha: 'Zerodha',
+ upstox: 'Upstox',
+ dhan: 'Dhan',
+ shoonya: 'Shoonya'
};
return names[brokerId] || brokerId;
};
@@ -264,7 +271,9 @@ export const getExchangeDisplayName = (exchange: string): string => {
NSE_FO: 'NSE F&O',
BSE_CM: 'BSE Cash',
BSE_FO: 'BSE F&O',
- MCX_FO: 'MCX F&O'
+ MCX_FO: 'MCX F&O',
+ NSE_INDEX: 'NSE Index',
+ BSE_INDEX: 'BSE Index'
};
return names[exchange] || exchange;
};
@@ -288,7 +297,8 @@ export const getInstrumentTypeDisplayName = (instrumentType: string | null): str
OPTCUR: 'Currency Options',
CE: 'Call Option',
PE: 'Put Option',
- FUT: 'Futures'
+ FUT: 'Futures',
+ INDEX: 'Index'
};
return names[instrumentType.toUpperCase()] || instrumentType;
};
@@ -330,19 +340,11 @@ class MasterContractService {
* Downloads if not available or cache is expired
*/
async initializeBroker(brokerId: SupportedBroker): Promise<DownloadResult> {
- const hasData = await this.hasSymbolData(brokerId);
- const cacheValid = await this.isCacheValid(brokerId);
-
- if (!hasData || !cacheValid) {
- console.log(`[MasterContractService] Downloading master contract for ${brokerId}...`);
- return await this.downloadMasterContract(brokerId);
- }
-
- const count = await this.getSymbolCount(brokerId);
+ const result = await symbolMaster.ensureMasterContract(brokerId);
return {
- success: true,
- message: 'Cache is valid',
- symbol_count: count
+ success: result.success,
+ message: result.message,
+ symbol_count: Number(result.total_symbols)
};
}