Texto del repositorio público, commit 8729248. Fuente: docs/claude/imports.md.
Importación de brokers (DeGiro, IBKR, MyInvestor, Trading 212, Binance, IA)
Detalle movido desde
CLAUDE.mdel 2026-10-04 para que el fichero que se carga en cada sesión solo lleve el índice y las reglas críticas. Léelo antes de tocar esta zona.
DeGiro CSV import — known facts
Column layout (comma-delimited)
Fecha, Hora, Fecha valor, Producto, ISIN, Descripción, Tipo(FX rate), Variación(currency), col_8(amount), Saldo(currency), col_10(balance amount), ID Orden
Multi-language support (Account.csv)
The 12-column layout is IDENTICAL in every DeGiro language — only header names and description keywords change. The parser resolves columns by localized name with positional fallback, and classifies rows via per-type multilingual keyword lists (KW in degiroParser.js) covering ES/EN/DE/NL/FR/PT/IT. Order matters: FX before BUY/SELL ("Ingreso Cambio de Divisa" contains "ingreso"), TAX before DIVIDEND ("Dividendbelasting" contains "dividend"), SELL before BUY ("Verkauf" contains "Kauf"). FX legs in a trade merge are matched by currency (the leg whose currency ≠ trade currency is the EUR cost side), never by localized description text. Fixtures EN/DE/NL live in degiroParser.test.js.
Wrong-file detection
Uploading DeGiro's OTHER export (Transactions.csv — venue/execution-centre columns, no description column) throws an error with err.code === 'degiro_transactions_file'; handleCsvFileSelected catches it and shows cartera.degiro_wrong_file_hint with the AI fallback still available.
Archivo de OTRO broker (2026-10-15): si el lector del broker elegido no saca operaciones, processImportText prueba detectOtherBroker (lib/parsers/brokerDetect.js, la misma detección del import IA) y, si el archivo es de otro broker conocido, lo procesa con SU lector y avisa con cartera.broker_file_redirect_desc. Caso real: "Sincronizar" un MyInvestor con el selector en DeGiro (importBroker vuelve a 'degiro' al cerrar el diálogo) → "No se encontraron transacciones" y la única salida era gastar cuota de IA. El Transactions.csv de DeGiro no se redirige (0 operaciones): sigue con su pista propia.
Anti-empty-import guard (all brokers)
If a parse yields no BUY/SELL/DIVIDEND rows (e.g. an unsupported-language export producing only a cash-snapshot row), handleCsvFileSelected routes to the AI-fallback panel with cartera.parse_no_trades_hint instead of letting the user "successfully" import an empty portfolio.
Import save architecture (planner/executor)
The save flow is split in src/services/import/ — the DECISION half is pure and the I/O half is dumb:
assetIdentity.js—getAssetIdentifiers(t, broker): grouping key + dbTicker + name. Broker is an ARGUMENT (never read React state for identity).netHoldings.js—calculateNetBuys(txs, broker): average-cost replay + cash ledger + snapshot handling.importPlanner.js—computeImportPlan(...)→ exact mutation plan (assets/positions to create/update/close) as a pure function of (parsed CSV, DB snapshot);buildTransactionRows(...)→ dedupe-safe inserts/patches.importExecutor.js—applyImportPlan(...): batched I/O (bulk inserts, parallel batches — the old loop did one SELECT per asset), supabase injected, throws with context.
Invariant (pinned by tests): planning against the state that results from applying a plan produces an EMPTY plan — re-sync idempotence is a verified property, not a hope. handleSaveImportedData (en hooks/useImportFlow.js desde 2026-07) is a thin orchestrator (fetch inputs → plan → execute → toasts). NEVER add decision logic back into the hook/component; it goes in the planner with a test. La reconciliación CSV↔DB del preview vive en src/services/import/processedImportData.js (pura, characterization-tested) — misma regla.
Import dedupe & telemetry
- The re-import dedupe is a MULTISET (
buildExistingTransMap: key → array; each CSV row consumes ONE stored occurrence): a DeGiro order can execute as N identical partial fills (same qty/price/minute) that are N real trades — a unique-key Set dropped every fill after the first and halved the cost basis (Amazon, Account (4).csv). A normal re-sync self-repairs DBs damaged by the old behaviour by inserting the missing occurrences. The PREVIEW-side CSV↔DB merge (csvRowsNotInDb+previewTxKey, same file) is a multiset too — with a half-cost DB, a unique-key Set dropped BOTH identical CSV fills against the single stored key, sonetBuysundercounted the position and the self-repair never converged (Enric: qty-2 positions with one fill's cost showed +186% return and the missing half as a fake "G/P Moneda"). Every future CSV-vs-DB dedupe MUST consume occurrences, never test key membership. The re-import dedupe key lives insrc/lib/importDedupe.js(transCheckKey+DEDUPE_SELECT_FIELDS). The SELECT that loads existing transactions MUST useDEDUPE_SELECT_FIELDS: omitting a key field (it happened withtotal_amount) makes every re-import duplicate all DIVIDEND/FEE/TAX/CASH/TRANSFER rows. Dates are normalized to 19 chars (YYYY-MM-DDTHH:MM:SS) on both sides — timestamptz suffixes would break every key. The notes/concept slice is 80 chars, never shorten it: at 30 chars DeGiro's five same-day 2.50€ connectivity fees collided into one key and four were silently DROPPED on first import (and re-syncs patch-flip-flopped their notes). - Re-import determinism for enriched funds:
enrichFundRowsreceivesknownSymbols(the persisteddynamicTickerMap) and re-resolves a fund name to ITS previous symbol first — Yahoo search can return a different share class per run, and different class = different NAV = different qty/price = dedupe keys never match = duplicated history. - Replace mode (re-sync repair): the preview footer offers "Reemplazar los datos de este broker" (checkbox, only when the broker has saved data): wipes the broker's positions+transactions before saving, importing against a clean slate. It's the one-click fix when past imports left mixed representations that dedupe cannot reconcile retroactively. Telemetry logs
replace-wiped=N. - The AI import accepts
.xlsx(converted to CSV text viaxlsxReaderinappendFiles— reading it as text would paste ZIP bytes), which also letsdetectBrokerCsvroute XLSX broker exports to the native importers. - Every parse/save attempt fires
logImportEvent(src/lib/importTelemetry.js) →POST /api/log-import→ admin log buffer (serviceimport) AND the persistentimport_logstable (service role only; powers the "Salud de imports" panel in AdminDashboard: success rates, failures by broker, top unrecognized descriptions). Fire-and-forget; must never block the import. handleSaveImportedDatareturnstrue/false; callers must not mark the broker as saved or close the dialog onfalse. It creates theportfoliosrow on demand (new accounts have none).- The AI fallback (
/api/analyze-csv) chunks the CSV (header repeated per chunk,server/lib/csvAiPipeline.js: 60 rows × 6 chunks = 360 analysable rows) instead of truncating at 80. All Groq JSON calls (analyze-csv AND parse-freeform text chunks) go throughserver/lib/groqJson.js: 429 retry with Retry-After, fallback model on decommission (GROQ_TEXT_MODEL/GROQ_TEXT_MODEL_FALLBACKenv overrides),json_validate_failedsalvage vialooseJson. Every AI row is sanitised server-side (sanitiseCsvRow: type whitelist + aliases, fecha normalised to DD-MM-YYYY even if the model emits ISO, numeric coercion, total sign forced by type). One failed chunk returns partial results +failedChunksin the response (client warns withcartera.ai_partial_warning); only all-chunks-failed + 0 rows returns 503. Long files still settruncated/analyzedRows→cartera.ai_truncated_warning. Client timeout is 300s (sequential chunks wait out Groq's TPM limit).
Import por IA: telemetría y el callejón de MyInvestor (2026-10-02)
FreeformImportDialogno registraba NADA. Un usuario real usó la importación por IA 6 veces entre junio y septiembre (MyInvestor) sin llegar a tener una posición, y no quedó ni una fila enimport_logs. Ahora cada intento emite un eventobroker: 'freeform'con el motivo enformat:review pending=X/N(ok),no-transactions,http-<status>,quota-daily|monthly,timeout,network,file-unreadable— ystage: 'abandon'cuando se cierra el diálogo con la tabla de revisión delante sin confirmar (el server y el CHECK de la tabla la aceptan — migración20261002_import_logs_abandon_stage, aplicada; sin ella el insert fallaba en silencio — y el panel de salud solo cuentaparse/save). Nunca contenido: recuentos y laheaderLinesaneada.- La detección y el importador discrepaban con MyInvestor.
detectBrokerCsvaceptaba el texto copiado de la WEB de MyInvestor (lectorparseMyInvestorWeb), peroprocessImportTextllamaba antes aparseMyInvestorCSV, que lanza "Formato MyInvestor no reconocido" en vez de devolver vacío, y nunca llegaba al de la web: diálogo de IA cerrado + toast genérico, sin salida. Ahora los dos usanparseMyInvestorAny(lib/parsers/myinvestorAny.js, con tests de regresión): CSV/XLSX primero, web después, y si nada sirve, el error original del CSV. Regla general: la detección de un broker y su importador tienen que llamar a la MISMA función, o volverán a discrepar. - Un fallo de lectura ya no es un callejón sin salida:
processImportTextdeja el texto enrawCsvTextconcartera.parse_failed_ai_hint, igual que cuando no encuentra operaciones, y la pantalla ofrece la extracción por IA. - El panel "Salud de imports" (
adminStats) excluyedetails.env = 'dev'.
Trading 212 (CSV del historial, 2026-10-03)
src/lib/parsers/trading212Parser.js (+17 tests), en el selector de brokers y en detectBrokerCsv. Se hizo SIN un fichero real: el formato sale de fuentes públicas contrastadas — sobre todo el parser mantenido de cgt-calc (calculadora de plusvalías UK, probada con exports reales) — y los fixtures son sintéticos con esa forma exacta. El primer fichero real que llegue es la prueba de verdad: mirar su telemetría (broker = 'trading212') y, si algo no cuadra, pedir una muestra anonimizada.
- Las columnas cambian de un export a otro (solo salen las que tienen datos; las antiguas llevan la divisa de la cuenta en el NOMBRE,
Total (EUR), y las nuevas una columnaCurrency (Total)aparte;Timeantiguo,Time (UTC)nuevo). Se localizan por nombre BASE. Toda columna con fee/tax/duty/charge (salvoWithholding tax) cuenta como comisión, así que una columna nueva de Trading 212 no exige tocar código. Totalva en la divisa de la CUENTA e INCLUYE comisiones; en dividendos va NETO de retención.Exchange rate= divisa del valor por unidad de la cuenta (USD por EUR). Salida con la forma del parser de IBKR: precio/total en la divisa del valor,comisionesen la de la cuenta ytotalEUR= bruto en euros (solo si la cuenta es EUR).- La liquidez la calcula el parser con los
Totaldel fichero y la emite como foto final (isEndingCash), con las divisas de los valores a 0: el export no trae saldo, y sin la fotocalculateNetBuysrestaría cada compra en USD de unCASH_USDque nunca existió. Si el saldo sale negativo → avisot212_cash_incomplete(el fichero no empieza en la apertura; cada export cubre como máximo un año). - No se importan (con aviso en la vista previa): splits (
Stock split open/close), spin-offs, traspasos de acciones y cualquier acción desconocida. Un split mal aplicado descuadra el coste por acción, así que se avisa en vez de adivinar.
HOLDING (snapshot de cartera) en el import IA — nunca mueve caja
freeformMapper mapea el tipo neutro HOLDING (fila de una tabla de posiciones) a un BUY con isConsolidated: true. El flag NO es cosmético: calculateNetBuys replica todo BUY no consolidado contra el ledger de caja, así que pegar una cartera (que por definición no trae ingresos) restaba el coste completo de la liquidez y creaba posiciones CASH_USD/CASH_EUR negativas — la cabecera lo mostraba como "Margen utilizado" y "Patrimonio neto (apal.)" inventados, exactamente iguales al coste de lo pegado (bug real 2026-07-26: −25.869 USD −1.208 EUR ≈ 23.950 €). Consolidado = define posición y coste medio, no mueve caja y NO se escribe al histórico de transactions (un snapshot no es un evento: fabricar BUYs con una fecha inventada además ensucia el TWR). Misma semántica que los snapshots de IBKR/Binance. Regresión fijada en freeformMapper.test.js. Los BUY reales pegados sí siguen moviendo la caja.
Broker picker scope
Binance and MyInvestor are deliberately NOT offered in the CSV broker picker (removed 2026-07 at the owner's request). Their parsers, enrichers and tests REMAIN fully functional: detectBrokerCsv still routes their exports (pasted or dropped into the AI import, including the MyInvestor Movimientos XLSX) to the native pipelines. Re-enabling = restoring their entries in ImportBrokerSelector.BROKERS.
AI import guardrails
- Text pasted into the AI import is first run through
detectBrokerCsv(src/lib/parsers/brokerDetect.js: tries each deterministic parser, requires ≥1 real trade). A detected DeGiro/IBKR/Binance/MyInvestor export routes to the NATIVE importer (processImportText(text, broker)in CarteraPage — broker is an ARGUMENT because it runs right aftersetImportBroker) with a toast, spending no AI quota. Never let a full broker export go through the LLM: it turns FX-conversion legs into phantom deposits, keeps GBX ×100 prices and doesn't merge trade fees (this produced a "completely different" portfolio from the same file). - For header-less ledger FRAGMENTS that still reach the LLM, the prompt (server/prompts/freeformImport.js "BROKER LEDGER PATTERNS") tells it to skip FX legs and internal sweeps, emit own-row withholdings as FEE, and pass GBX prices through verbatim; the ÷100 pence normalisation is DETERMINISTIC in
freeformToTrazza(amount disambiguated pence-vs-pounds by arithmetic). Computedtotals are rounded to cents (float noise broke dedupe keys).
Import self-validation (DeGiro) & failure reporting
auditDegiroLedger(csvText)(indegiroParser.js) reconciles parsed amounts against the CSV's OWN running-balance column per currency (Account.csv is a ledger) — mismatches point to the exact line. Shown in the preview (cartera.audit_ok/audit_mismatches); tries both file directions (newest-first / oldest-first).listUnrecognizedDegiroRows(csvText)returns rows classifiedOTHER(silently dropped otherwise). Shown in the preview and sent (deduped) in parse telemetry → they surface in the admin panel as "keywords que faltan".- Opt-in failure report: the user can share an ANONYMIZED sample (
src/lib/csvRedact.jsstrips emails/IBANs/IBKR accounts/9+ digit runs client-side, keeps ISINs and structure) → stored inimport_logs.csv_sample. Every reported failure becomes a reproducible fixture.
Price sanity guard
isPlausiblePriceUpdate(stored, next) (src/services/priceGuard.js) gates every update_asset_market_data price write — since 2026-10-26 the ONLY writer is the server cron (server/lib/assetPrices.js); the client (usePositions, Dashboard, import save) no longer writes prices, and the import only backfills metadata with update_asset_metadata after creating positions. The RPC repeats the same ratio in SQL. Asymmetric by design: blocks collapses (> 85% drop = unit/currency mixup, the pence ÷100 class) but allows big increases so an already-corrupted small price can heal. Never bypass it for a new write site. Split real (precio nuevo < 15 % del guardado): el cron lo rechazará siempre; escape documentado = POST /api/admin/force-asset-price (server/routes/adminForceAssetPrice.js, solo plan admin) → RPC force_asset_price (migración 20261028000100_force_asset_price.sql): escribe el precio nuevo en una sola operación (sin clear a NULL), exige reason y audita en asset_price_force_log. Alta de filas nuevas en assets (r15b/r17/r17b): createAssets() → POST /api/assets → ensure_asset (service role; lookup exacto sin upper(), altas nuevas ≤120/sin cntrl; ON CONFLICT DO NOTHING; precio 1 en CASH_*). FASE 1 20261027000100; FASE 2 revoke 20261029000300. Despliegue en dos fases (history.md); NO supabase db push a ciegas. Lookup de existentes (r18): services/import/existingAssets.js carga por ticker y por los asset_id de las posiciones del broker, e indexa exacto + lower(btrim) como ensure_asset; el planner busca con findAssetByTicker. Nunca existingAssetsByTicker[ref] a pelo: un ticker legado con espacios no casaba y cada reimport añadía otra posición sobre el mismo activo.
MyInvestor import (CSV + XLSX)
- MyInvestor has TWO exports and
parseMyInvestorCSVdispatches by header: the Operaciones CSV (Fecha de la orden;ISIN;Importe estimado;Nº de participaciones;Estado) and the Movimientos XLSX — the ONLY export carteras de fondos offer. Any.xlsxupload (all brokers) is converted to CSV text at upload time bysrc/lib/xlsxReader.js(dependency-free ZIP+OOXML reader onDecompressionStream('deflate-raw'); the npm SheetJS build has known CVEs) and flows through the NORMAL text pipeline (parsers, audits, AI fallback, anonymized reports). - Movimientos rows carry NO ISIN/units/price — funds become monetary positions (
cantidad = |importe|,precio = 1) flaggednoQuote: true.fetchPricesForImportedskipsnoQuoterows: a name-based Yahoo match would price EUR-denominated quantities with a real NAV and corrupt the value. Never remove that skip. "NAME qty @ price" descriptions only yield real units whenqty×price ≈ importe(±2%); otherwise the@ pricetail is stripped so the fund groups under a stable name. - ⚠️ Un fondo MONETARIO tiene su PROPIA fila de
assets:NOMBRE [importe] (EUR)(MONETARY_TICKER_TAG/isMonetaryAssetTickerenservices/import/assetIdentity.js, 2026-10-03). Antes eraNOMBRE (EUR), el MISMO ticker que el fondo convertido a participaciones, y comoassetses compartida entre usuarios e imports, una posición monetaria heredaba el NAV que otro import había escrito en esa fila: 503,04 € × 33,67 = 16.937 € y +3.267 % en la cuenta de pruebas del owner (owner@example.com). Y no se curaba solo: el planner intentaba escribir 1 yisPlausiblePriceUpdatelo bloqueaba como "colapso". Reglas:getAssetIdentifiersda la identidad monetaria a toda filanoQuotesin ISIN (el enriquecedor convierte todo un fondo o nada, así que nunca se parte);calculateNetBuyspropaganoQuotea la fila neta; el planner fijacurrent_price = 1; yusePositions.resolveTdevuelve null para estos tickers — quitar los corchetes deja el nombre del fondo ycuratedSymbolForFundNamelo cotizaría (VANGUARD 20 → su NAV). Las dos únicas filas monetarias que había en producción se renombraron al formato nuevo ese mismo día. Tests:importPlanner.test.js→ "fondos monetarios de MyInvestor". - Corolario: pasar un fondo de euros a participaciones (o al revés) CAMBIA su ticker, así que un reimport normal crearía una segunda posición y dejaría la vieja abierta con su historial — el fondo contaría dos veces.
twinAssetTicker(assetIdentity) da el ticker gemelo, el planner lo detecta enplan.representationConflictsyuseImportFlowno guarda nada y pide reimportar con «Reemplazar los datos de este broker» (cartera.fund_representation_conflict_*). Una gemela ya cerrada (cantidad 0) no cuenta. Ojo: el SELECT de posiciones del guardado llevaquantitypor esto. - Clases de la cartera de MyInvestor, verificadas el 2026-10-03 cruzando con el NAV que enseña el broker (una cuenta con la misma cartera dada de alta a mano con sus precios) y con Yahoo: US Index y Emerging = clase S Acc EUR (
0P0001XF42.F/IE000N4ZYX28,0P0001XF3Z.F/IE000QAZP7L2— el ISIN curado anterior era la clase D); ESG Screened Glb Corp = D EUR Hedged (0P0001JAFO.F/IE00BJN4RG66; antes se aproximaba con la clase USD + FX, que mete un movimiento de divisa que un fondo cubierto no tiene); BGIF EM Govt Bond =LU1811365292(EUR), pero Yahoo no tiene su histórico, así que sin clave de EODHD sigue el proxy USD. Pacific ex-Japan: los precios no permiten decidir la clase; se deja el proxy USD. Elegir una clase u otra apenas mueve el valor de una posición nueva —sale de la rentabilidad, igual salvo comisión y cobertura—; lo grave sería mezclar clases DENTRO de una posición, y elsymbolfijo lo impide. - Verificación con el extracto real (no se sube nada): copiar el .xlsx a
public/__tmp_*.xlsx, abrirlocalhost:3000y en la consolaimport('/src/...')del lector, el parser yenrichFundRowscon elyahooFinanceServicede verdad — así corre la tubería del import tal cual, con el proxy de dev. Borrar la copia al terminar. Resultado del 2026-10-03: 26/26 movimientos convertidos, 9/9 fondos con clase y precio, auditoría de saldo 31/31. - Un 503 del limitador de nginx en mitad del enriquecimiento deja ese fondo en euros (pasó el 2026-10-03 a las 07:09 con el Emerging: su
getQuoterecibió 503). Se resolvió subiendo el límite de/api/yahoo/; ver "Producción". - El símbolo con el que se cotiza un activo guardado sale SOLO de
resolveQuoteSymbol(services/quoteSymbol.js: monetario → null, TICKER_MAP, curado,imported_data.ticker_map,resolveTicker). Lo usan brokers (usePositions) y el Dashboard (groupInvestedByTicker). Hasta el 2026-10-09 el Dashboard usabaresolveTickera secas, que deja el NOMBRE del fondo ("VANGUARD 20"), y el Wallet Map de una cartera de MyInvestor salía entera en gris con "—". Las baldosas monetarias[importe]valen su cantidad y van sin variación diaria. - Clases mezcladas (proxy USD vs clase curada): cuando el símbolo curado falla en el import (un 503 basta), el enricher cae al
usdProxyy deriva las unidades de ESE NAV. El refresco priorizaba el curado y multiplicaba unidades del proxy por el NAV de otra clase (ESG Screened Glb Corp: BEP 8,65 € del proxy × 9,44 € de la EUR Hedged = +9 % inventado, verificado contra el histórico de Yahoo el 2026-10-09).resolveQuoteSymbolahora respeta el símbolo persistido cuando ES elusdProxycurado del fondo (curatedProxyForFundName). Un reimport con «Reemplazar» recalcula las unidades con la clase curada. - Grafías alternativas del mismo fondo (2026-10-15): el extracto trae "ISHARES US INDEX FUND IE S EUR" y también "ISHARES US INDEX FUND (IE) - S" (misma clase S Acc EUR).
FUND_NAME_ALIASES+canonicalFundName(fundNavEnricher) las unen ANTES de agrupar, ycuratedSymbolForFundName/curatedProxyForFundNamelas aceptan. Sin alias, la variante abría una segunda posición[importe]en euros. Una grafía nueva = una línea en el alias, nunca una entrada duplicada enMYINVESTOR_FUNDS. - Nombres legibles (2026-10-15): el extracto recorta los nombres a ~30 caracteres ("BGIF EM MKT GOVER BOND INDEX D") y eso es lo que se guarda en
assets.company_name.MYINVESTOR_FUNDS[...].namelleva el nombre legible yservices/assetDisplayNamelo usa para PINTAR (tabla de brokers, Dashboard, Wallet Map); la ficha lo saca decuratedFundForSymbol, que además marca si se está cotizando la clase USD (isUsdProxy→ aviso). No se reescribe la BD:assetses compartida y su identidad no cambia. Un fondo curado nuevo = sunameen la misma entrada. - "EFECTIVO-EUR" (2026-10-15) es el efectivo de la cartera: baja el Saldo pero sigue siendo del usuario. El parser no lo trata como fondo: lo suma al snapshot
isEndingCash. Antes salía una posición "EFECTIVO-EUR [importe]". ⚠️ El extracto real lo escribe "EFECTIVO-EUR @ 0" (con la cola@ participacionesde los fondos): el primer arreglo solo casaba "EFECTIVO-EUR" a secas, el test con fila inventada pasaba y la posición seguía saliendo. Verificado con el .xlsx real; los tests prueban las dos grafías. Lección: una fila de fixture se copia del extracto, no se escribe de memoria. - The Movimientos export is a ledger (Saldo column):
auditMyInvestorLedgerreconciles it (same UI keys as DeGiro), and the last balance becomes theisEndingCashCASH snapshot. Fixture inmyinvestorParser.test.jsmirrors a real export. - Descriptions "
NAME @ X" carry the UNITS in X (verified against real NAVs); the parser derivesprecio = |importe| / X. fundNavEnricher(src/services/import/fundNavEnricher.js, injected Yahoo deps, tested offline) upgrades monetary rows to real units: name → Yahoo search (abbreviation expansionBGIF→blackrock,PACFC→pacific…; prefix retries because Yahoo's fuzzy search returns junk for long truncated names) → candidate validation (MUTUALFUND/ETF + token match + share-class currency: name check ANDgetQuote().currency, because each class EUR/USD/PLN has a different NAV) → historical NAV at the purchase date →units = |importe| / NAV. Prefers0P…symbols (exchange ETF listings like.MUquote fine but have no usable history). SEQUENTIAL + paced (pauseMs) — parallel bursts trip Yahoo's rate limit silently. Coherence invariant: a fund enriches ALL rows or NONE (andtickerMaponly gets names whose rows were actually enriched) — mixing NAV units with qty-in-EUR rows in one position, or mapping a monetary row's name to a real quote, corrupts the value. Resolved names go intodynamicTickerMap(persisted inimported_data.ticker_map) so price refresh and the asset overlay (openAssetOverlay) resolve them from then on.MYINVESTOR_FUNDS(same file): curated broker-name →{ isin, usdProxy }map for the carteras automatizadas funds.isindrives exact share-class resolution (Yahoo ISIN search skips the abbreviation-fragile token validation but keeps the type/quote-currency/history guards, so a wrong/delisted ISIN degrades to monetary).usdProxyis the fund's USD share class on Yahoo, used as TIER 3 when no EUR NAV source exists: units = NAV_USD / EURUSD at the purchase date, position then quotes in USD through the normal multi-currency path (GOOGL-on-DeGiro mechanism). Known trade-off: for EUR-HEDGED real classes the proxy shows FX movement the fund doesn't have — the user chose value-with-caveat over no value. Never auto-accept another currency's class OUTSIDE this curated proxy path.- EODHD last-resort for funds Yahoo can't price: when every Yahoo attempt fails and the fund has a curated ISIN,
resolveViaEodhdqueries EODHD's/search(the only provider that reports the share-class CURRENCY directly) and prices viaISIN.EUFUNDNAV history. Requires the user'seodhd_api_key(Settings) orEODHD_PLATFORM_KEY— without a key it no-ops and the fund stays monetary.eodhdService.getQuotelabels.EUFUNDquotes EUR: safe ONLY because fundNavEnricher is the sole creator of.EUFUNDsymbols and accepts EUR classes exclusively — keep that invariant. Quote/overlay surfaces (usePositions,fetchPricesForImported,GlobalSearchOverlay) now route throughmarketDataService(Yahoo → EODHD) asEODHD_MIGRATION.mdprescribes; tickers containing whitespace (unresolved fund names) are skipped before quoting so they don't burn the EODHD quota.
SnapTrade — ELIMINADO (2026-07-17)
El import por broker-API (SnapTrade) se retiró de toda la plataforma a petición del owner: dialog, mapper, servicio cliente, rutas del server, proxy y sección i18n borrados. La tabla snaptrade_users sigue en la BD (huérfana, service-role only, inofensiva) y las credenciales SNAPTRADE_* del server/.env ya no se usan — se pueden rotar/borrar. El método "Broker API" ya no aparece en el ImportMethodChooser (quedan CSV/XLSX e IA).
Shared ISIN→ticker mappings
ticker_mappings table (crowd-populated) + src/services/tickerMappingService.js. Resolution precedence: static TICKER_MAP → user's imported_data.ticker_map → shared table → live Yahoo search; successful search resolutions are contributed back through the server since 2026-10-26 (POST /api/ticker-mappings, server/routes/tickerMappings.js; migration 20261026000200_ticker_mappings_server_only.sql, SIN APLICAR, removes the client's insert/update — audit 7f2c915d A2: any account could rewrite any mapping for everyone). The server publishes a pair only if the symbol appears in Yahoo's search FOR THAT ISIN (a name-search resolution stays local to the session) and inserts with ignoreDuplicates, so no existing row — 'manual' or 'auto' — is ever overwritten. New /api/* route = vite proxy + location in nginx, as always.
Number format
DeGiro Spain exports use comma as CSV delimiter and European number format (dot=thousands, comma=decimal). isEuropean is detected from data patterns (regex [",]\d{1,3}\.\d{3}[,"]), NOT just from the delimiter. Never assume ; delimiter means European — Spanish DeGiro uses , with European numbers.
Transaction type mapping
(Spanish keywords shown — the full multilingual lists are in KW in degiroParser.js)
| DeGiro description keyword | Parser type |
|---|---|
Cambio de Divisa | CURRENCY_EXCHANGE (internal, merged with BUY/SELL) |
Compra | BUY |
Venta | SELL |
Dividendo | DIVIDEND |
Retención | TAX (merged into DIVIDEND) |
Comisión, Costes de transacción, Conectividad, Stamp Duty, Impuesto, Interés, Interest | FEE |
Sweep | CASH |
Ingreso, Transferir, Deposit, Retirada, Withdrawal | TRANSFER |
Merge logic
- BUY/SELL rows are merged with same-order fees (FEE), FX rows (CURRENCY_EXCHANGE) by
ID Orden - Partial fills (same order ID, multiple BUY rows) prorate fees and EUR totals proportionally by share count
- DIVIDEND rows merge with TAX rows by same
fecha+ sameisin - Standalone
CURRENCY_EXCHANGErows (dividends paid in foreign currency) are dropped after processing
GBX stocks (UK pence)
Prices in GBX are divided by 100 → GBP. The variacion audit checks the ratio between the CSV amount and qty×price to detect if the CSV reports amounts already in GBP or still in GBX.
French transaction tax
Impuesto de transacción Francés appears as a separate row on LVMH and other French/Italian stocks. Classified as FEE and merged into comisiones for the trade.
What gets silently dropped
CURRENCY_EXCHANGErows not linked to a BUY/SELL (standalone dividend FX conversions)OTHERtype rows (unknown descriptions)- Transactions for closed positions (qty=0) don't appear in
positionIdMap→ not saved totransactionstable