Web AppProjects

MegaCoach — an AI coach for my stock portfolio

A personal AI coach that manages a US stock portfolio on Dime. It puts a dashboard, an advisor that knows the real portfolio, and automatic entry/exit alerts into one LINE chat, while money figures are encrypted on the device before going to the cloud, which sees only ciphertext.

11 min read

A personal system that works as a portfolio coach. It puts a dashboard, an AI advisor that knows the actual portfolio, and automatic DCA / stop / RMF reminders into one LINE chat. Money figures are encrypted on my own machine before they go to the cloud, so the server only ever sees ciphertext.

LINE Messaging APILIFFVercel ServerlessWeb Crypto (AES-256-GCM)Zero-KnowledgeBun + launchdVercel KVLLM + web search
Empathize · Define

The problem

Why is managing a US stock portfolio on your own more tiring and error-prone than it sounds?

A phone showing a stock chart in an investing app
Portfolio data lives in several apps, with no single overview · Photo: PiggyBank / Unsplash

The portfolio data was scattered: holdings in one place, the watchlist in another, long-term goals only in my head. With nothing to remind me, I would forget DCA, forget the stop, and slip into chasing hot stocks on impulse. I wanted an advisor that actually knows my portfolio and that I can check on my phone. But money figures are very personal, and I did not want any cloud service to see them.

— The starting brief, before building MegaCoach

Portfolio data is scattered

Holdings, watchlist, RMF funds, retirement goal: each lives somewhere else, and nothing shows the whole portfolio on one screen.

Emotion drives FOMO buys

A hot stock makes a new high and I want to jump in. Entering without a plan or a stop I am willing to be wrong at puts the portfolio at more risk of ruin than profit.

Forgetting DCA, forgetting stops

Discipline slips as soon as nobody reminds you. A month goes by without topping up, a price breaks the stop-loss unnoticed, and near year end I remember the RMF target is not yet met.

Generic chatbots answer vaguely

You can ask an AI about stocks, but it does not know what you hold, your budget or your risk tolerance. The advice ends up as a generic formula that does not fit the real portfolio.

Money figures are highly sensitive

I wanted a dashboard on my phone, a link I could open anywhere. But deploying it to the cloud as-is means the real portfolio value sits on someone else's server.


Ideate

The solution

Let the system do all the boring work (collecting data, watching the market, timing reminders) while money figures never leave the machine in readable form.

The MegaCoach LIFF dashboard on a large screen, with an entry-timing header and a traffic light counting stocks that are a go, waiting, or not yet
The real LIFF dashboard: a traffic light sums up entry timing every morning
The same dashboard on a phone, opened from LINE, showing the traffic light, a market summary and the to-do card for today
On a phone (opened from LINE): the same page, complete

Everything in one LIFF dashboard

Open it from LINE and see the entry signal, the North Star gauge, RMF status and the monthly DCA plan on one phone screen.

An AI coach that knows the real portfolio

Before every answer it injects the portfolio context and the Fear of Ruin > FOMO philosophy into the system prompt, then uses web search for live data. Answers follow the real budget and risk, not empty cheerleading.

Automatic alerts in LINE every morning

Monthly DCA, RMF funds worth switching, prices breaking a stop or hitting a take-profit target. Each arrives as a Flex card where the header colour signals urgency (normal / opportunity / urgent).

Zero-knowledge: encrypted on the device

Real figures are encrypted with AES-256-GCM in the browser or on the machine before sending. The cloud, relay and git only see ciphertext, which only someone with the passphrase can decrypt.

The Mac is the single source of truth

My own machine pulls live prices, calculates value, encrypts it, publishes sanitized price zones and runs git push itself. The key never leaves the machine.


Prototype

How it works: 4 steps

From live market prices to an alert card in LINE, running automatically every day with launchd.

A 15-day performance chart comparing the closing prices of VOO, QQQ, CACI and ETN in percent
Closing prices the Mac pulls every morning become the dashboard chart (percentages, no money figures)
1

Pull live prices

The Mac pulls stock and FX prices (Yahoo) plus fund returns (Finnomena), no API keys needed

2

Calculate and encrypt

Compute portfolio value and requiredCAGR, encrypt with AES-256-GCM, publish the sanitized zones

3

push → deploy

git push triggers a Vercel deploy · the LIFF dashboard and serverless routines read the new data

4

Alert / view

LINE sends a Flex card when a condition is met · opening the dashboard decrypts on the device with the passphrase


Prototype

Tech Stack & Architecture

Two clear sides: the Mac (source of truth and key holder) and the cloud (display and alerts), connected only by ciphertext.

The portfolio entry form in LIFF asking for a passphrase before unlocking, with a note that figures are encrypted on the device before sending
The portfolio form in LINE: unlock with the passphrase, then it encrypts in the browser before sending to the relay
LINE App — chat (Flex cards) + LIFF webview
Morning brief cards LIFF dashboard Portfolio form
↕
Vercel Serverless (/api) — webhook + coach + relay
/api/coach /api/ask /api/line-webhook /api/holdings-inbox
↕
Mac Engine (Bun + launchd) — source of truth
update-northstar publish-levels pull-holdings line-alerts
↕
Vercel KV (ZK relay · ciphertext) + static JSON + macOS Keychain
encrypted blob coach-data.json passphrase (in-device)
Why this stack?

LINE + LIFF: an app I already open every day, nothing new to install · Vercel Serverless: the webhook, coach and relay are small stateless functions, no server to maintain · Web Crypto (AES-256-GCM + PBKDF2 250k): the same code encrypts in Node/Bun and in the browser, which makes zero-knowledge real · Mac + launchd acts as the source of truth that holds the key, so the cloud never sees money figures


Prototype

What I built: 8 core capabilities

The full loop, from collecting portfolio data to sending alerts safely.

The Idea Radar card ranking weekly investment themes, with scores out of 25 and stage labels
Idea Radar: scans themes every week, scores them and says whether a theme is early or late

AI Portfolio Coach

Injects the portfolio and North Star context into the system prompt before answering, with web search for live data · looks at the whole portfolio, not a single stock

Morning Brief Engine

Builds Flex cards by "mood" (calm / warn / urgent): the header colour and warning strip signal how urgent the action is

North Star Gauge

A long-term goal gauge and pace tracker · computes requiredCAGR live from the current value with a bisection solver

Zero-Knowledge Layer

AES-256-GCM + PBKDF2 250k · the same code encrypts and decrypts on the machine and in the browser · unlocked with a passphrase

LINE Form + ZK Relay

Type a keyword, get a bubble, open the LIFF form, encrypt in the browser, send to the KV relay, and the Mac pulls and decrypts it · the relay accepts ciphertext only

Watchlist Triggers

Pulls live prices (no keys) and compares them with entry / stop / trim zones · alerts only when a zone is touched, with a per-ticker cooldown against spam

RMF Switch Advisor

Pulls 1/3/5-year returns from Finnomena and gives a verdict (switch / consider / fine), plus a reminder to reach the tax-deduction target before year end

Sanitized Publish Pipeline

Publishes only price zones and a held flag for the cloud to read · a regex self-check blocks sensitive data (share counts, money) from leaking


Prototype

What it looks like: alert cards in LINE

Every morning the system sums up what to do as Flex cards. The header colour tells you at a glance how urgent it is.

Today 08:00
💰 DCA REMINDER
Time to top up the portfolio
Top up ฿XXk this month
Topping up every month is the core of North Star
💡 Use the 1 free trade per month on the largest order · if the market dips hard, you can add more
Open Dashboard
🛑 Urgent — decide now
A stock broke its stop
The price fell below your stop-loss. Review cutting the loss before it grows.
🛑XYZ broke stop $XX.X (price $XX.X) — review the stop-loss
Enter small, always control size and stop
Open Dashboard
Analysis only, not a buy or sell order · figures shown are sample values

Test & Iterate

Hacks and problems

6 engineering problems I had to solve myself: security, platform quirks and reliability.

A terminal running publish-levels --check successfully, showing sample JSON that contains only price zones, no share counts or money
The real self-check before publishing: the JSON the cloud sees has only price zones, no share counts or money

A dashboard on the cloud, without the cloud seeing money

A static deploy on Vercel means anyone with the link can see it. Embedding real figures in a file would leak the portfolio value immediately.

Fix: encrypt the payload with AES-256-GCM + PBKDF2 250k on the machine first and push only ciphertext · the dashboard decrypts client-side with Web Crypto once the user enters the passphrase. The cloud only holds an unreadable blob.

LINE webhook signature verification failed

x-line-signature must be verified against the raw body, but Vercel parses the body into an object first. The computed HMAC did not match, so real requests were rejected.

Fix: turn off the parser (bodyParser: false) and read the raw stream directly, compute HMAC-SHA256 on the exact raw bytes, then JSON.parse. The signature matches, and forged webhooks are actually blocked.

Figures must be fresh daily, but the key must stay on the machine

If the cloud calculates the value, the key has to go to the cloud (breaking zero-knowledge). If nothing updates, the numbers go stale.

Fix: make the Mac the source of truth. launchd wakes a Bun script every morning to pull prices, calculate, encrypt and git push · the key is read from the macOS Keychain and never goes to the cloud · git push becomes the deploy pipeline.

Cloud routines need "price zones" but not "shares or money"

The cloud routine has to compare live prices with entry/stop levels to send alerts, but that data was mixed in with share counts and real values.

Fix: build publish-levels, which extracts only ticker, zones and a held flag into public JSON · --check runs a regex that blocks words like share/cash/value/baht from leaking. If it finds one, the build fails.

Repeated daily alerts get annoying

A price can sit below the stop for days. Alerting every day means people stop reading · and the Mac and the cloud might alert about the same thing twice.

Fix: a cooldown per ticker:kind (alert once, then stay quiet for N days) plus a clear split of duties. The Mac sends only safety-critical stop/trim alerts, the cloud handles entry nudges. No duplicates, no alert fatigue.

Price fetches failed right after the Mac woke from sleep

launchd starts the job just as the Mac wakes up. Sometimes Wi-Fi is not back yet, so the first price fetches fail and the whole run breaks.

Fix: wrap fetch in 3 retries with a 4-second delay each (to let the network come back) · the whole flow is best-effort: if pull fails, update still runs; if publish fails, the job does not fail. Lesson: cron jobs have to tolerate a network that is not ready.

Define

Deliberate design decisions

What I chose not to build, so the tool stays safe and trustworthy.

The North Star card showing a gauge by age range, with the full figures locked behind a passphrase
North Star: the public part shows only the age range and phase; money figures stay locked behind the passphrase

This tool is a coach, not a trading bot. It alerts and analyses, but never places orders. Every card ends with "Analysis only, not a buy or sell order", and the final decision always belongs to a person · every money figure is encrypted on the machine before it leaves. Setting clear limits from the start kept the system small, straightforward and trustworthy.


Alert, never place orders

A person makes the decision; the system only prepares the data


Only ciphertext reaches the cloud

The relay and git see only a blob · the key stays on the machine


Fear of Ruin > FOMO

A survive-first philosophy, built into the coach's system prompt


Sanitized zones only

The cloud knows price zones, not share counts or money


Level Up · Reflect

Knowledge domains that got stronger

5 areas where my level genuinely moved up through this project.

The today card deciding from rules (close above for 2 days, pullback zone, cooldown) whether each stock is waiting for a dip or its setup is broken
Financial rules turned into code: a rule engine decides per stock whether it is a go, waiting for a dip, or the setup is broken
1. Applied cryptography: from "knowing the names" to "designing a zero-knowledge system":

Used Web Crypto for real: PBKDF2 to derive a key from a passphrase, AES-256-GCM to encrypt and decrypt, handling salt/iv/base64 myself, then designed the flow so the key never leaves the machine (the relay only receives ciphertext). Lesson: zero-knowledge is not magic. It is about putting "who holds the key" in the right place.

2. Serverless and chat-platform engineering: LINE/LIFF and webhooks, end to end:

Connected the LINE Messaging API (reply/broadcast), embedded a LIFF webview, verified webhook signatures on the raw body, designed Flex bubbles that change colour by state, and learned the quirks of serverless (body parsing, cold starts, statelessness). Lesson: real platform integration means reading the spec and handling the runtime's edge cases.

3. Automation and source-of-truth design: cron that survives the real world:

Designed a "one machine holds the truth" architecture: launchd orchestrates several chained Bun scripts (pull → update → publish → seed), git push acts as deploy, and every step is best-effort (the job does not fail whether or not the network is ready). Lesson: good automation plans for the day when nothing is ready.

4. LLM product engineering: from "calling an API" to "designing coach behaviour":

Wrote a system prompt that embeds an investing philosophy (Fear of Ruin, core vs satellite), injected portfolio context dynamically before each question, enabled the web_search tool for live data, and post-processed answers (stripping citations and artifacts). Lesson: an AI assistant's quality depends more on how you direct its context and limits than on the model itself.

5. Financial-domain modelling: turning financial rules into code:

Wrote a bisection solver for requiredCAGR from the current value plus monthly contributions, modelled the RMF tax cap and a fund-switch verdict from real returns, and separated core logic (long-term holds) from satellite (short-term trades with TA). Lesson: domain knowledge (finance) is the heart of it. The code just makes the rules run automatically and consistently.

5
serverless endpoints (/api)
11
Automated scripts (Bun + launchd)
250k
PBKDF2 iterations · encrypted on the device
0
Money figures visible to the cloud

Tan · Natpakan Sirirat

Product Designer & AI Builder — designing user experiences and building AI tools that actually work.

0%