Conventions for building the INDAB web app (Angular 22 + plain Firebase SDK). Use before adding or changing features, Firestore collections, security rules, routes or UI in this repo, including the landing page, learning-material repository, academy and Eleva Inversiones modules.
Install
npx skillscat add crisortiz/indab-web-app/indab-dev Install via the SkillsCat registry.
Building the INDAB web app
The app serves two businesses:
- INDAB Academy: trading school. Public landing, accounts, academy area for students, and a
learning-material repository that only enrolled students can open. - Eleva Inversiones: INDAB's investment arm. Pools investor money, trades it and pays monthly
returns. Public info page plus a private investor area.
Stack (do not change without asking)
- Angular 22.2: standalone components, signals,
inject(),@if/@forcontrol flow,
lazyloadComponentroutes, SCSS. Unit tests run on Vitest throughng test; end-to-end
tests on Playwright against the emulators. - Firebase JS SDK 13, modular API, no AngularFire (it lags behind Angular releases).
- Firebase project
indab-academy(Firestore insouthamerica-west1). Local dev uses the
emulators with projectdemo-indab(environment.development.ts,useEmulators: true). - Node
^24.15.0or^22.22.3; Java 21+ for the emulators. Cris develops on Windows + VS Code,
so keep scripts cross-platform (no bash-only npm scripts).
Firebase access
Inject the instances through the tokens in src/app/core/firebase/firebase.providers.ts:
import { FIRESTORE, FIREBASE_AUTH } from '../../core/firebase/firebase.providers';
private readonly firestore = inject(FIRESTORE);Then call the modular SDK directly (collection, query, where, onSnapshot, getDocs, ...).
Never call getFirestore()/getAuth() elsewhere, or the emulator wiring is skipped.
The Firestore SDK is lazy (it was half of the first download): FIRESTORE_LOADER.load() imports
it, and AuthService loads it before the guards admit a signed-in user, so services of guarded
pages can inject(FIRESTORE); preloadFirestore starts the download on login/register. Never
import firebase/firestore values (use import type) in code of the main bundle
(app.config.ts, core/auth, shared/layout, public pages); a public page that needs data
awaits inject(FIRESTORE_LOADER).load(). Check ng build's initial size (about 440 kB) after
touching startup code.
Quota and abuse (Spark plan, $0)
Firestore's free daily quota (50k reads, 20k writes) is shared by the whole site: going over
stops the app until midnight Pacific time, it never bills. The web API key is public, so anyone
can call Firestore directly. So:
- Anything a visitor (or any signed-in account) can read must be cheap and bounded: query only
what the page shows withlimit(), and make the rule refuse bigger lists
(request.query.limit <= N, seereviews). Public data that repeats per visit goes through a
short browser cache (FEATURED_REVIEWS, ten minutes). - Staff-only screens may read whole collections, but prefer aggregations and pagination.
- App Check (reCAPTCHA v3) is wired in
core/firebase/app-check.tsand starts with the
Firestore SDK onceenvironment.appCheckSiteKeyis set; it is off while that is empty.
Enforcement is switched on in the Firebase console, after its metrics show real traffic
passing. firebase.jsonsends security headers on every response (nosniff, referrer policy,
permissions policy, CSPframe-ancestors/object-src/base-uri). A full CSP is not set yet:
TradingView, YouTube/Drive frames, Google sign-in and Binance would all need listing; add it
as Report-Only first.
For the current user, use AuthService (src/app/core/auth/auth.service.ts):user(), profile(), enrollment(), isLoggedIn(), isAdmin(), hasAcademyAccess(), andwhenReady() before reading them in guards. Add new per-user state there only if it is global;
otherwise create a feature service.
Access model
| Collection | Read | Write |
|---|---|---|
users/{uid} |
owner, staff | owner creates as student, edits displayName, photoURL, birthDate, whatsapp; admins change role and mentorshipIds of others only; trainers a student's mentorshipIds |
users/{uid}/sessions/{id} |
owner | each browser records itself; owner sets revoked once, deletes; admins delete |
enrollments/{uid} {academy, courses[], funding?, updatedAt, updatedBy} |
owner, staff | admins (shape validated); trainers only turn academy on for a student (leaving funding as it was); funding is admin-only |
courses/{id} |
everyone if published, admins |
admins |
courses/{id}/lessons/{id} |
enrolled in course or academy access | admins |
materials/{id} |
academy access: staff all, students published + for everyone or assigned (assignedTo) |
trainers and admins |
investors/{uid} (Eleva) |
owner, admins | admins |
mentorships/{id} |
staff; members (users/{uid}.mentorshipIds) |
admins (shape validated) |
evaluations/{id} |
staff, assigned students (by uid or mentorship) | staff (shape validated) |
practiceSessions/{id} + /trades/{id} |
owner, staff (trades also as a collection group); attempts at published evaluations to academy access (ranking) | owner (academy access) while active; evaluation attempts {evaluationId}_{uid} once, inside the window and time limit (+ extraMinutes, raised only by staff); trades closed once; admins delete, staff delete evaluation attempts; owner deletes active free practice with tradeCount 0 and its unfilled orders |
evaluations/{id}/adjustments/{id} |
staff | staff create only (who, kind, minutes, reason); never edited or deleted |
evaluations/{id}/rubrics/{uid} |
staff; the student once resultsPublished |
staff (5 criteria, ints 1-5, signed) |
evaluations/{id}/grades/{uid} |
staff; assigned students once resultsPublished |
staff (score, parts 0-100, verdict, failedBy, signed) |
examForms/{id} |
staff; published + assigned to students | staff (shape validated; no answers stored here) |
examKeys/{examId} |
staff; students once resultsPublished && showAnswers |
staff |
examSubmissions/{examId}_{uid}_{n} |
owner, staff | owner (academy access): attempt n ≤ maxAttempts, in window, previous handed in; saves until deadline + 2 min |
examGrades/{submissionId} |
staff; student once resultsPublished |
staff, for an existing submission |
mentorNotes/{id} |
staff; the student it is about | admins; staff who mentor one of the student's mentorships (mentorshipId); on the student's own session or form attempt; author edits, author or admin deletes |
users/{uid}/notifications/{id} |
owner | the sender, once per event (id {type}_{refId}, note_{noteId}); rules check the event and that the sender may tell the owner; owner marks read, deletes |
users/{uid}/settings/notifications |
owner | trainers and admins, their own |
users/{uid}/settings/chart |
owner | everyone, their own (indicators, news on/off) |
marketNews/{id} |
academy access | trainers, admins (/admin/news) |
reviews/{uid} |
author, admins; everyone once featured |
the author with academy access (any edit sets featured false); admins only featured/featuredAt/featuredBy; author or admin deletes |
users/{uid}/fundingAccounts/{id} |
owner, admins; trainers if visibleToMentors (also as a collection group) |
owner while hasFunding() (shape validated, days map); owner or admin deletes |
follows/{kind}/subjects/{id}/followers/{uid} |
that staff member; students, the lists that concern them | that staff member (types of activity) |
Rules helpers in firestore.rules: signedIn(), isOwner(uid), isAdmin(), isStaff()
(trainers and admins), emailVerified(), hasAcademyAccess(), hasFunding() (admins, or enrollments/{uid}.funding) (staff count as having it; needs
a verified email), isEnrolledIn(courseId), myMentorships() and assignedTo(data) (instudentIds or one of mentorshipIds; use it for anything assigned to students). Tests sign in with email_verified: true unless
they pass as(uid, false).
Everything not matched is denied. Trainers run evaluations and evaluation forms, grade and review practice, open the
academy to students and put students in mentorships; roles, revoking access, managing mentorships and deleting practice
stay admin-only.
Guards in src/app/core/auth/auth.guards.ts: authGuard (signed in), guestGuard
(signed out), enrolledGuard (academy access), staffGuard (trainer or admin), adminGuard (admin role), fundingGuard (AuthService.hasFunding() or staff).
All but guestGuard first send users with an AuthService.setupStep() (verifyEmail, thendetails while users/{uid}.birthDate is missing) to /account-setup (setupGuard); a new
guarded page gets that for free. E2e createUser() seeds verified users with a birth date.AuthService.isStaff() mirrors isStaff(). /login and /register share <app-google-button> (shared/google-button,
official "G"); sign-up offers it first, above the email form (Cris, 2026-11-09), and Google
sign-ups go on to /account-setup for the birth date. Guards are UX only; the rules are the security.
Users can never grant themselves a role, enrollment or investor data from the client.
Layout and conventions
src/app/core/firebase/ DI tokens + provideFirebase()
src/app/core/auth/ AuthService, guards
src/app/core/models/ Firestore document interfaces (one file per domain)
src/app/core/i18n/ I18n service, messages/{es,en,pt}.ts, title strategy, localDate pipe
src/app/features/<name>/ one folder per feature; components named without suffix (Landing, Academy)
src/app/shared/ reusable UI (layout/header, ...)
src/styles.scss global tokens: --color-*, --radius, --max-width, .container, .btn- File names:
feature.ts,feature.html,feature.scss,feature.spec.ts(Angular 20+
style, no.componentsuffix). Inline templates are fine for small components. - Selectors prefixed
app-. Preferprotected readonlyfor template-only members. - State: signals and
computed; convert Firestore listeners to signals in a service and
unsubscribe on destroy (DestroyRef). - Model types:
Timestampfromfirebase/firestorefor dates; write withserverTimestamp(). - Styling: black and white brand (logo
public/logo.jpg, tagline "Conocimiento. Disciplina.
Estrategia. Resultados."). Use the CSS variables insrc/styles.scss, not hard-coded colors. - Light and dark mode (Cris, 2026-10-27):
ThemeService(core/theme) putsdata-themeon<html>andstyles.scssswaps the tokens under:root[data-theme='dark']. Users pick
device / light / dark in the header's account menu (<app-theme-options>,shared/theme);
the choice is kept in localStorage (indab.theme) and a script inindex.htmlapplies it
before the first paint (no flash on prerendered pages). Visitors follow their device. Every
new color must work in both: use the tokens (--color-band*for black bands, which stay black
in dark mode); a component style that needs its own dark rule uses:host-context([data-theme='dark']). Canvas code reads the tokens withgetComputedStyle
and re-reads them whenThemeService.theme()changes (seeReplayChart.applyColors). The
logo image is inverted in dark mode. - UI text is translated: es-419 (default), en-US, pt-BR. Never hard-code copy in a template or
component. Add each text tocore/i18n/messages/es.tsand its translation toen.tsandpt.ts
(same keys, or the build fails); read it withinject(I18n).messages()(@let t = ...in
templates). Texts with values are functions. Dates go through thelocalDatepipe; numbers
stay en-US (1,250.00). Routetitles are keys ofmessages.titles(ending in| INDAB).
Firestore content is not translated. Code, comments, commits in English. See README "Languages". - Time zone (Cris, 2026-11-03): dates and chart times show in the user's zone, La Paz
(America/La_Paz) unless they pick another in /profile (TimeZoneService,core/time-zone,
kept in localStorageindab.timeZone). ThelocalDatepipe applies it by itself, so do not
pass a zone;datetime-localinputs go throughtoLocalInput/fromLocalInputwith the zone.
Unit tests run with the zone set to UTC (src/test-setup.ts). - Loading:
AppLoader(shared/loader) shows the logo bouncing while the app starts (static copy
inindex.html, styles instyles.scss), while the router navigates and whileLoadingServicetracks something. Wrap page reads withloading.track(promise)(orbegin()/end for listeners until their first snapshot); leave background work untracked
(e.g.loadCandles(..., { background: true })for the replay's next chunk). Favicons and app
icons inpublic/are cut from the logo's mark (the M with the arrow). - Installable app (PWA, README "Installable app"): service worker in production builds only;
ngsw-config.jsoncaches the app's own files, never Firestore/Auth/market data. Keep new
public files cacheable by its globs and keepngsw-worker.js/ngsw.jsonno-cacheinfirebase.json.AppInstallandAppUpdateslive incore/pwa, their UI inshared/pwa. The "Instalar app"
option is off (INSTALL_OFFER_ENABLED= false) until Cris wants an app. - SEO: public pages are prerendered at build time (
outputMode: "static",@angular/ssr, no
hydration) andSeo(core/seo) sets meta, canonical,hreflang(?lang=es|en|ptlinks) and
Open Graph tags per route and language. Code on public pages runs once in Node at build time:
guard browser APIs withisPlatformBrowseror try/catch. See README "SEO and loading speed". - Header (
shared/layout/header): sticky on every page (z-index 9, under the landing's progress
bar), thinner with a shadow once scrolled; the current section's link getsaria-currentand a
sliding underline (placeIndicator). Its links:NosotrosandContáctanos(/#nosotros,/#contacto, landing sections;LandingSectionsinshared/layoutscrolls to them and the
landing reports the section on screen so the underline follows the scroll), then Academia and
Admin (short label on phones, so the row fits at 390 px). Signed-in users get the notification
bell between the language picker and the avatar. Eleva Inversiones is out of the header
for now (Cris, 2026-10-24);/elevaand the landing's Eleva section still link to it. The language picker is a flag menu (shared/language:
Mexico = es-419, USA = en-US, Brazil = pt-BR, inline SVG because Windows has no flag emoji).
Dropdowns use the globaldropdown-inkeyframes; respectprefers-reduced-motion. - Footer (
shared/layout/footer): a thin strip in the app shell (app.html) on every page with
the copyright (© {year} INDAB y crisortizdev) and "Desarrollado por crisortizdev" linking
https://crisortiz.github.io; the shell keeps it at the bottom of short pages. Do not add page
footers with their own copyright (the landing's footer only has links and the disclaimer). - Social networks:
SOCIAL_LINKSinshared/social/social-links.ts(Instagram @indabacademylp,
TikTok @indab.academy);<app-social-links>shows icons,[labels]="true"adds network and
handle (landing contact section). Landing stats only show figures Cris confirmed; INDAB has no
recorded courses yet, only study material. Email and WhatsApp are not public yet. - Card actions in admin lists (forms, evaluations) sit in a three-dot menu at the card's top right:
<app-actions-menu>(shared/actions-menu, Cris 2026-10-26) withMenuActions (icon + text,linkfor navigation,dangerfor delete), labelledadmin.itemAction(admin.actions, title).
Icons are<app-icon>(shared/icon, inline SVG paths inICONS); small icon-only buttons
(question editor) use.icon-btnfromshared/icon/_icon-button.scsswitharia-labeland adata-tiptooltip. - Long lists:
CursorPages(shared/pager/cursor-pages.ts) pages a Firestore query with
cursors and<app-pager>shows previous/next; filters go in the query (each equality-filter
combination needs its index infirestore.indexes.json). Lists already in memory usepageOf/pageCount. Filter bars useshared/pager/_list-filters.scss. Practice session lists
use<app-session-filters>andPracticeService.sessionsPage/sessionTotals. - Formatting: Prettier (
printWidth100, single quotes). Runnpx prettier --writeon changed files.
Adding a module
- Model: add interfaces in
src/app/core/models/<domain>.ts. - Rules: add a
matchblock infirestore.rules(update the data-model comment at the top)
and tests intests/firestore.rules.test.tscovering allowed and denied cases for
anonymous, student, enrolled, owner and admin. - Service:
src/app/features/<name>/<name>.service.ts(providedIn: 'root') usingFIRESTORE. - Component(s) in
src/app/features/<name>/, replacing the placeholder and itsplaceholder.scssimport. - Route in
src/app/app.routes.tswithloadComponent, atitlekey (added totitlesin
the three message files) and the right guard. A public page for search engines also getsdata: { description: '<key>' } satisfies SeoData(texts inseo.descriptions), aRenderMode.Prerenderentry inapp.routes.server.tsand its URLs inpublic/sitemap.xml;
everything else isnoindexand browser-only.
Add a header link insrc/app/shared/layout/header.htmlif it is a main section. - Indexes: composite queries need an entry in
firestore.indexes.json. - Docs: update the access-model and routes tables in
README.mdand this skill. - Tests: a
<name>.spec.tsnext to each component and service, and an e2e test ine2e/for
the main user flow (see Testing below). - Verify:
npm run test:ci,npm run test:rules,npm run test:e2e,npm run build.
CI (.github/workflows/ci.yml) runs the same on every PR and push and gates every
deploy on them; a new test script must also be added to itstestjob.
Testing
- Unit (
src/**/*.spec.ts,npm test/npm run test:ci): Vitest + TestBed, jsdom.
Components: replaceAuthService(or the feature service) with auseValuefake built fromsignal()s and drive the DOM. Services: fake the Firebase SDK withvi.mock('firebase/firestore', ...)and captureonSnapshotcallbacks
(seeauth.service.spec.ts,admin.service.spec.ts).isolate: trueinangular.jsonkeepsvi.mockper file; do not turn it off. - Rules (
tests/firestore.rules.test.ts,npm run test:rules): allowed and denied cases. - E2E (
e2e/*.spec.ts,npm run test:e2e): Playwright drivesng serveagainst the Auth and
Firestore emulators with the real rules. Each test callsresetEmulators()and seeds what it
needs withcreateUser()/setDocument()frome2e/emulators.ts(REST, bypasses rules).
Select by role and Spanish label (getByRole,getByLabel), not CSS, where possible (tests run
in the default language unless they switch it).PLAYWRIGHT_CHROMIUM_PATHlets you use an already installed Chromium (e.g. in cloud sessions,/opt/pw-browsers/chromium) instead ofnpx playwright install.
Module notes:
- Landing (
/): public, no Firestore reads needed except publishedcourses. Sections for
the academy, courses and a link to Eleva. Call to action goes to/register.
Testimonials are students' reviews (Cris, 2026-11-06):reviews/{uid}(core/models/review.ts,features/reviews/), written in/profile(ReviewPanel, academy access only) and picked by
admins at/admin/reviews(features/admin/reviews/, last/admincard, admins only). The
landing reads the 12 latest picks (indexfeatured+featuredAt, rules cap the list at 12)
throughFEATURED_REVIEWSonce a visitor scrolls near them, cached ten minutes per browser
(that is when the Firestore SDK loads on the landing) and leaves the section out while none is
picked. An author's edit unpicks the review.<app-stars>(shared/stars) draws ratings in--color-star. Specs fake the service withquietReviews()(features/reviews/testing.ts). - Study material (
/academy/material, built): part of the academy, opened from/academy;
Cris does not want it as its own header tab (/repositoryonly redirects).materials/{id}
(core/models/material.ts,features/repository/material.service.ts): title, description, kind
(video, presentation, document, link), httpsurl, free-textcategory(the topic the students'
page groups by), audience (all, orstudentIds+mentorshipIdsas forms) andpublished.
Staff (trainers and admins) manage it at/admin/material(features/admin/material/).
Nothing is uploaded: Cris wants $0 and Firebase Storage needs the Blaze plan, so staff paste
links (YouTube unlisted, Vimeo, Google Drive, Slides, Docs, Canva) andmaterialEmbedturns the
known ones into an iframe address built from the site's own pattern (never the typed link);
anything else (a PDF elsewhere, a web page) opens in a new tab.MaterialFrameshows it andMaterialThumbdraws the card picture (YouTube's preview or the kind's art). Students read
with three queries (everyone, by name, by mentorship) like the forms. Ask Cris before
anything that needs Blaze (Storage uploads). Protection (Cris wants it as safe as possible,
viewable only in the academy; README "Protecting the study material"): the iframe is
sandboxed withoutallow-popups/allow-top-navigation, full screen is our own (the frame,
not the player) soMaterialWatermark(viewer name + email, moving) stays on, students get no
link to the original (staff do), and/admin/materialshows per-site sharing tips. Keep all
of that when touchingMaterialFrame. - Academy (
/academy): publishedcoursesand theirlessons, filtered byenrollment().coursesor full academy access. Shows the pending notice when not enrolled.
Its home is a grid of illustrated cards, one per section (cardsinacademy.ts, inline SVG
art inacademy.html); without academy access the same cards show locked. Add a card there
(and toacademy.cardsin the three message files) for each new academy section. - Trading practice (
/academy/practice, built):features/practice/.Replay(replay.ts)
is the pure bar-by-bar engine (orders, fills, SL/TP, P/L);ReplayChartwraps
lightweight-charts and its draggable price/SL/TP lines (levelMoved; the order being set up
only appears once picked from the "+" menu (orderAt) or the order panel is used, and is set up
on its line (draftTypeChanged,lotsChanged,levelAdded,draftDiscarded); fake it in component
specs, it needs a canvas);MarketDataServiceloads Binance public klines in the browser
(no key; mock them withpage.routein e2e);PracticeServicelogspracticeSessionsand
theirtrades. Admin review at/admin/practice(features/admin/practice-review/) and the
student's "Your sessions" list open aSessionReview(session-review.ts): it reloads the
session's candles, draws each filled trade as TradingView's long/short position box
(trade-boxes.ts,ReplayChartpositionBoxes; in a live practice only closed trades get one)
and steps through them withTradeNavigator(previous/next, a list, details), scrolling the
chart to each (focusTrade, once per pick). Cris wants no navigator during a live session,
only the boxes. Once a replay is over, a dotted line marks where it started (startTime). Admins delete a session with its trades (PracticeService.deleteSession).
A reload must never lose a session (Cris, 2026-10-30): the page keeps where the replay is
(bar, timeframe, speed, hidden dates, the chart'sdrawingsmodel) inlocalStorageon every
change (resume.ts) and in the session'sresumefield (every 15 s while playing, 2 s after
other changes, at once on pause orpagehide). On load it picks up the newestactive
session (PracticeService.activeSessions): its trades, the bar (the later of the saved one
and the last trade) and an evaluation's clock fromstartedAt; attempts past their 2-minute
grace are left alone.
Only sessions with an entry count (Cris, 2026-11-11): free practice that ends (button, last
bar, "Cerrar" in the list, or closed as an older open one) without a filled order is deleted
with its unfilled orders, not finished; the end dialog warns first (noEntries). Evaluation
attempts are always kept. Admins purge old ones with "Depurar sesiones sin entradas" at/admin/practice(PracticeService.emptySessions).
A session stays open until the student closes it, or until an evaluation's time is up (Cris,
2026-11-03): leaving the page (or "Salir sin cerrar",leaveOpen) only savesresume. The
setup lists open sessions (openSessions, Continuar / Cerrar) and keeps only the newest free
practice open (staleSessionscloses older ones, Cris 2026-11-03); evaluation cards offer "Continuar evaluación"; the academy home links
back with a banner. The replay only moves while on screen, so an attempt whose time ran out
while away is closed bycloseLeftthe next time the practice page loads (positions close
and orders cancel at the saved bar; the rules let an attempt past its grace only cancel,
close withsessionEndand finish). Until then lists show it as finished (shownStatus).
Cris wants the trading screen to look and work like TradingView, students to start with 200
USD and trade lots (100 oz) at 1:200 (Cris, 2026-10-27; was 1:100) with a 50% stop out
(replay.tsconstants), and
timeframes 1m-4h switchable mid-session, starting on 15m. The replay runs on 1m candles
loaded in chunks;BarBuilder(bars.ts) builds the chart's bars. TradingView's own
indicators/drawings are not available to us (Advanced Charts is for public sites only), so
chart tools (indicators.ts, drawings inReplayChart) are built on lightweight-charts.
Drawings follow pointer events on the DOM (the chart'ssubscribeClickdrops a second click
within 500 ms) and are an SVG overlay, as in TradingView's app (Cris sent a recording): a tap
or click puts each point, a finger can drag a crosshair and let go, a tap selects a drawing
(handles reshape it, a drag moves it, a bar recolors or deletes it). The chart's top bar holds
the timeframes (projected withchartToolbar) and one menu each for indicators and drawings.
Indicators (INDICATORSinindicators.ts, drawn byChartIndicators): EMA 100 and 200
(Cris, 2026-10-26: no other moving averages), volume, RSI 14 and, since 2026-11-06 with
TradingView's defaults, Bollinger Bands, MACD, stochastic, ATR, SuperTrend (one line in two
colors, BUY/SELL labels) and daily VWAP. Indicators ofpane: 'own'get a pane each under the
candles, in menu order; any change of indicators or setups redraws them all. Each one is set
up from the gear in the menu (IndicatorSettings, a modal<dialog>: inputs, colors and
widths, timeframes it is hidden on);readConfigmakes saved setups safe, and only setups
that differ from the defaults are kept (configsnext toindicators). lightweight-charts
joins a line over whitespace points: break a line with a transparent color on the point
before the gap (a point's color paints the segment to the next). The RSI follows Cris's TradingView settings (2026-10-30): SMA 14 smoothing, dotted
levels 70/60/50/40/30, red/green shading above 70 and below 30, and divergences
(rsiDivergences= TradingView's built-in RSI "Calculate divergence": RSI pivots 5 bars
left/right, 6-61 bars apart, price low/high read at the RSI pivot bar, REGULAR only, green Bull /
red Bear). Cris tried strong/medium/weak/hidden from price swings (#54) and found it too noisy
(2026-10-30), so do not bring those back without asking. Drawings and labels are re-laid out
when the price scale is stretched (followPriceScale; the library has no event for it). Defaults are RSI only (DEFAULT_INDICATORS); a user's own pick and setups are saved
inusers/{uid}/settings/chartbyChartSettingsServiceand passed to the chart'sindicatorsandindicatorConfigsinputs by the pages (specs fake it withquietChartSettings()frompractice/testing.ts).
Placed orders and positions show their size filled inSIDE_COLORS(blue buy, red sell) and
no Buy/Sell text; only the order being set up keeps its Buy/Sell button (Cris, 2026-10-30).
The drawings menu has TradingView's sections (TOOL_GROUPS): trend
line, ray, extended line, arrow, horizontal line/ray, vertical line, parallel channel (three
points), rectangle, Fibonacci (Cris's TradingView levels and colors inFIB_LEVELS, -1 to 4.236,
no background, ratio-only labels), Elliott impulse (6 points) and correction (ABC, 4 points)
waves, long/short position (entry, target, stop with risk/reward), price range and fixed range
volume profile (volumeProfile: 24 rows, 70% value area, point of control; candles carry
Binance'svolume);POINTSsays how many points each takes andbuildturns them into a drawing.
Cris chose to grow this with FX Replay's best ideas rather than clone it: session
stats (stats.ts,SessionStatsPanel), rectangle/Fibonacci, picking the start date.
Stats include risk (B1): % of the balance at entry risked to the stop loss the trade was
placed with (initialStopLoss, set once;riskStopfalls back tostopLossfor old
trades), planned R:R, trades without stop loss and stop out. Evaluation results show them per
attempt (EvaluationStanding.stats, "Métricas de riesgo" view).
Gold is Binance Futures' XAUUSDT perpetual (PAXGUSDT, a thin token, looked nothing like the
market and is kept only for old sessions);MarketDataServicedrops bars while spot gold is
closed and empty minutes (goldHours), paging until it has the requested count, andloadHistoryreads backwards from the replay start. Candles use TradingView's colors.
Economic news (Cris, 2026-11-08, README "News on the practice chart"): INDAB's own calendar,
NO third-party feed (Cris rejected Finance Calendar). OnemarketNews/{id}per release, kept at/admin/news; "Cargar fechas oficiales" addsofficial-schedule.ts(official US dates, fixed
ids, only the missing ones). Icons on the time axis per bar (news-marks.ts), a card with the
releases (actual only once the replay reaches them).NewsModevianewsModeFor: hidden dates
=reveal(impact only until the replay reaches the release, then name and figures, never the
date); evaluations pickreveal|impact|off(Evaluation.news). Pages read it withNewsService.feed; specs get a quiet one fromquietChartSettings()(newsEvents).
Live trading (Cris, 2026-11-11, README "Live trading"): free practice in mode "En vivo" runs on
Binance's kline WebSocket (LiveFeed,live-feed.ts, URL under/market/ws/), not a replay.
The session haslive: trueandreplayStart= the minute it started; the page'sreplayStartis then the chart anchor (chartAnchor, the 4-hour bar of the minute shown) so
history and built bars line up.Replay.tickupdates the forming minute in place (settling on
the move since the last update only) andBarBuilderrebuilds a bar whose last minute was
replaced. No transport (clockDriven), dates shown, refused whilegoldClosed. Resuming or
closing a live session loads the minutes since it was left (loadMinutesSince) and settles
them, as a broker would; a reconnect fetches what the stream missed (catchUpMinutes).resumeof a live session is saved to Firestore only on leaving or on changes other than the
minute (write quota). Mock the stream in e2e withpage.routeWebSocket.
Cris wants exactly XAU/USD, USD/JPY and NASDAQ: only gold (XAUUSDT) is live, the others
wait for a data source licensed for display to students. Never bundle or serve data whose
license is personal use only (e.g. Dukascopy). A new timeframe must also be added to theintervallist infirestore.rules. - Evaluations and ranking (built):
evaluations/{id}(core/models/evaluation.ts,features/evaluations/evaluation.service.ts) are set up at/admin/evaluations
(features/admin/evaluations/). Students see theirs above the practice setup and take each
once; the attempt is a practice session with id{evaluationId}_{uid},evaluationIdanddurationMinutes, and the page counts down and finishes it; free sessions storeevaluationId: null./academy/ranking(features/ranking/, ranking maths instandings.ts) ranks only evaluations, by attempt P/L: Cris does not want free practice
ranked, so free sessions stay private to the student and staff. Students see an evaluation's ranking
only after staff publish it. P/L is client-computed: not a trusted grade.
Fairness (Cris, 2026-11-03): an evaluation with apace(market minutes per real minute: 60
default, 900 or 1, picked by staff) runs by the clock (live.ts): the replay showsliveMinutes(now - startedAt)candles, with no play, step or speed, so every tab or device
shows the same candle and nobody can scout ahead. Clocks use Binance's server time
(ServerClock), not the device's. Opening a session in another tab of the browser makes the
old tab let go (SessionTabs, BroadcastChannel). Students see an attempt without dates
(finish screen, reviews) until the evaluation's window closes (datesLocked). Older
evaluations withoutpacekeep the free speed.
Adjustments (A6): in an evaluation's results, staff give an open attempt extra minutes
(extraMinutes, counted from now or the deadline, whichever is later) or restart an attempt
(deletes the session and trades so the student can take it again). Both need a reason and
are logged inevaluations/{id}/adjustments(a restart also drops the attempt's rubric); the student's page watches its session
(PracticeService.watchSession) to extend the countdown or leave a deleted attempt.
Mentor rubric (B3): staff rate each attempt 1-5 onRUBRIC_CRITERIA(plan, risk, stops,
context, discipline) from the results menu (RubricForm), stored atevaluations/{id}/rubrics/{uid}; the student sees theirs on/academy/rankingonce published.
INDAB score (Cris 2026-11-11, replaces the 40/30/30 of 2026-11-03):ranking/score.ts,
25% result in R (sum of P/L over USD risked to the farther of first/last stop; no stop = 15%
of balance; 0 R = 50 pts, ±5 R = 100/0), 25% risk control (100 less 20 per trade without SL,
5 per 1% over 15% risk on EACH trade (Cris), 5 per 1% over 15% open at once, 2 per 1% drawdown over 10%;
stop out = 0), 15% discipline (ranking/discipline.ts: removed/widened SL, martingale,
averaging down, revenge within 15 market min, hedging, left open at the end, no TP; +5 per
break-even stop; shown per trade inSessionStatsPanel), 25% rubric ((avg - 1) / 4) and 10%
journal (share of closed trades whosejournalhas 10+ characters). Trade journal: theTradeJournalpanel under the practice trades; each order'sjournal(≤ 280) can be written
or fixed until the session ends, even once closed (Cris); shown inTradeNavigator. Rubric
criteria since 2026-11-11: plan, context, management, emotions, journal (older rubrics keep
risk/stops/discipline and are shown and averaged as saved;rubricCriteria). Verdict (flexible, Cris
2026-11-11): only a stop out fails whatever the score (score and details kept); losing 40%
of the start costs 40 risk points and a removed SL costs discipline on that trade; fewer than 1 closed (Cris: at least 1)
trades = unrated; else pass at the evaluation'spassingScore(staff set it, 0-100, missing =
70,passingScoreOf). Standings rank passed, failed, unrated, each by score.
Students cannot read trades or rubrics, so staff browsers save each score (withverdict
andfailedBy) toevaluations/{id}/grades/{uid}when they open the results
(syncGrades), and/academy/rankingreads those; older grades show their score only.
Before an attempt starts,EvaluationBriefing(modal, "Leí las instrucciones" required)
explains time, pace, account, leaving, the end and the grading; the countdown warns at 5 and
1 minutes left (TIME_WARNINGS). Lines of placed orders/positions moved on the chart wait
for a ✓ next to their size (↺ undoes;levelsMovedsaves them together), as in TradingView.
They can also be edited from the order panel (Cris, 2026-11-11): "Editar" on a row of
Positions/Orders loads it into the ticket (startEdit,editing), which then shows "Guardar
cambios"/"Descartar cambios" instead of Buy/Sell and puts the ticket back afterwards; a pending
order changes price, lots (TradeLevels.lots, margin checked with its own reserve freed;
rules allowquantityon pending only) and SL/TP, an open position only SL/TP. The edit ends
by itself if the order fills or the trade closes meanwhile (editEnded). - Evaluation forms (built): questionnaires, separate from chart evaluations.
core/models/exam.ts(types,suggestScore,bestGrade,attemptDeadline),features/exams/exam.service.ts; staff build them at/admin/forms
(features/admin/exams/, editor maths inexam-form.ts) and grade at/admin/forms/:id
(exam-results.ts); students take them at/academy/exams(features/exams/, list state inexam-status.ts). Answer keys live apart inexamKeysso students can read the questions.
Grading runs in the staff browser ($0, no functions). An attempt in progress opens again by
itself after a reload, on the same question; answers not yet saved are kept inlocalStorage
(AttemptDraftinexam-take.ts) and saved then. The best attempt counts. "Duplicar"
(cloneForm) opens the editor with a copy (questions, key, points, settings) as a new draft with
no students, to give the same test to others; practice evaluations have the same action
(clone, keeps the exactreplayStart). Not built yet:
CSV export, extra attempts per student, shuffled questions. - Mentorships (built): the "groups" of students.
mentorships/{id}(core/models/mentorship.ts:audienceIds,membersOf;features/mentorships/mentorship.service.ts), managed by admins at/admin/mentorships(features/admin/mentorships/; trainers read-only). Membership isusers/{uid}.mentorshipIds, set from/admin/users(chips + "+ Agregar"). Forms and practice
evaluations storementorshipIdsbesidestudentIdsand use<app-audience-picker>
(features/admin/audience/); students load theirs with an extraarray-contains-anyquery
(assignedTo(uid, profile.mentorshipIds)). Staff lists filter with<app-mentorship-filter>;
the practice review sendsuids(uid in, 30 at most). Anything new that is assigned to
students should accept mentorships too. - Mentor notes and notifications (built):
core/models/mentor-note.ts,core/models/notification.ts(types,notificationLink,followedSubjects).<app-mentor-notes [target]>(features/notes/,MentorNotesService) sits inSessionReview
(practice and evaluation attempts), the grading panel of/admin/forms/:id(outside its form)
and under each attempt in/academy/exams/:id; pass it a stable target (acomputed), or it
reloads. Admins write on anyone's work, trainers on students of the mentorships they lead
(access()finds the shared one). A note and its notification are one batch. The bell
(features/notifications/notification-bell.ts) is@deferred in the header once the profile is
loaded, so its Firestore code stays out of the main bundle. Spark plan, no functions: senders
write intousers/{uid}/notificationsfrom the browser (NotificationService.notifyStudents
forassigned/results,notifyActivityfor a student's finished practice, evaluation or
handed-in form), each id names the event so it goes once, and a repeat is refused and skipped.
Staff choose what they follow in/profile(NotificationSettingsPanel); nothing by default
(Cris, 2026-10-27: no spam for mentors and admins).saveSettingsmirrors it intofollows/.../followers/{uid}, which students read to find recipients. Deep links:/academy/practice/sessions/:id(SessionPage) and/admin/forms/:id?submission=. Specs fake
both services withquietNotifications()(features/notifications/testing.ts). A new kind of
notification needs its case in the rules'notificationsmatch, a text innotifications.textand a link innotificationLink. - Mentor dashboard (
/admin/mentor, built):features/admin/mentor-dashboard/(maths indashboard.ts, reads inMentorDashboardService),staffGuard, first card on/admin.
Trainers see the mentorships they lead (mentorIds), admins all. Per student it runs
aggregation queries (sessions count +sum('pnl')since the period start; closed trades and
winners via the staff-onlycollectionGroup('trades')rule and two composite indexes), never
reading every session or trade. Forms/evaluations: only published ones given to the members
whose window touched the period. Links:/admin/practice?student=uid,/admin/forms/:id,/admin/evaluations?results=id. - Economic calendar (
/calendar, public, built):features/calendar/, prerendered, linked in
the header (a calendar icon on phones so the links fit at 390 px)./academy/calendar(signed
in, routedata: { fromAcademy: true }) is the same page with a link back to the academy; the
academy's calendar card is open to students without access. TradingView's free
calendar widget (widget.tsbuilds its settings: locale, economies, impact); impact is picked
with ForexFactory-style folders (red high, orange medium, yellow low; Cris 2026-10-26) and a
legend maps them to the widget's bars, which are inside TradingView's iframe and cannot be
restyled. The page rebuilds
the embed when a filter or the language changes, keeps TradingView's credit link, and adds a
translated guide to the news that moves gold, USD/JPY and the NASDAQ. Cris wants it free for
life: no paid API, key or server function. E2e tests stub the widget script withpage.route. - Eleva (
/eleva, investor area): the public page stays unguarded. Investor data lives ininvestors/{uid}and subcollections (e.g.investors/{uid}/statements/{month}), admin-written,
owner-read. Financial figures are never computed or written by the client. - Funded accounts (
/academy/funding, built):features/funding/, modelcore/models/funding.ts. Each account is one documentusers/{uid}/fundingAccounts/{id}with
its days in adaysmap keyedYYYY-MM-DD(one read per account;FundingServicereads once,
no listeners, and writes a day withupdateDocondays.<date>). All maths are pure functions infunding-metrics.ts(monthly goal on the month's starting balance, trading days Monday to
Friday, daily loss and drawdown meters, trailing floors capped at the size); dates are calendar
days in the user's zone (dateIn) and are shown withlocalDatein 'UTC' throughdayDate.
Admins turn it on per user in/admin/users(AdminService.setFunding;setAcademyAccess
keepsfunding); admins always have it (Cris, 2026-12-04). The academy card shows only tohasFunding()or staff. Staff see shared accounts (admins all) through a collection-group
query (fieldOverridesinfirestore.indexes.json). UI pieces:GoalBand(black band with
the ring),BalanceChart(plain SVG),MonthDays(calendar and day list),AccountInsights
(risk meters, history),AccountForm(dialog). No broker sync yet ($0 rule): manual entry. - Account setup and sessions (built): registration asks for the birth date (required) and
WhatsApp (optional, stored as+digits); validators and helpers inshared/personal-details
(each form shows the fields itself so its styles apply).AuthServicesends the confirmation
email andcheckEmailVerified()reloads the user and refreshes the ID token (the rules read the
flag from it).core/auth/session-tracker.ts(lazy, with Firestore) records each browser inusers/{uid}/sessions(id kept inlocalStorage), signs it out when it seesrevoked
(/login?ended=1) and deletes it on sign-out;/profilelists them (SessionsService).
Revoking only asks that browser to sign out: Cris wants $0, so no Admin SDK token revocation. - Profile (
/profile, built):features/profile/, opened from the avatar menu in the header
(shared/layout/header, avatar inshared/avatar). The photo is resized in the browser
(resizeImage, 192 px JPEG) and stored inline asusers/{uid}.photoURL, so no Cloud Storage
bucket (Blaze plan) is needed; the header falls back to the Google photo, then initials.ProfileServicelinks an email/password credential for Google-only users (re-asking Google onauth/requires-recent-login) and changes passwords after reauthentication. The practice P/L
summary reads the latest 50practiceSessions. Linking from Google is unit-tested only: the
emulator's Google window needs internet. - Admin (
/admin, built):features/admin/./adminis only the section cards; each tool
has its own page. User management is/admin/users(features/admin/users/,staffGuard): admins see
everyone; trainers (Cris, 2026-11-09) see only students (card "Estudiantes", no role column)
and can grant academy access (never revoke) and set mentorships;
mentorships are/admin/mentorships(staffGuard, writes for admins only).AdminServiceis provided by theAdminUsers
component (liveusers+enrollmentslisteners that stop on leave); search/filter is
client-side inadmin-users.ts(fine for hundreds of users; move to a paged query if it grows).
Admins change roles (rules block changing their own) and toggleenrollments/{uid}.academy./adminopens with illustrated section cards (admin-home.scss, shared card styles inshared/section-cards/_section-cards.scss, also used by/academy). Trainers open/admin
too but only see the cards for forms, evaluations and the practice review (AdminService
opens no listeners for them).
New admin tools (courses, materials, investors) get their own/admin/<tool>page and a card
(cardsinadmin.ts,admin.cardsin the three message files).
Any admin UI must still rely on rules (isAdmin()); never trust a client flag.
Do not
- Commit service account keys,
.envfiles or emulator exports. - Loosen a rule without a failing-then-passing test.
- Switch the dev environment off the emulators in a commit.
- Deploy rules or hosting without Cris asking for it.