Monitoring executive buys and sells on US equities sounds straightforward until you actually build the job. Raw SEC EDGAR submissions require managing custom User-Agent rate policies, parsing heterogeneous Form 4 XML schemas, deduplicating amended filings, and filtering out compensation grants (A) and tax withholdings (F) so your alert channel does not turn into noise.
In this hands-on walkthrough, we will build a small, production-friendly SEC Form 4 Insider Trade Watcher in Node.js 22+ (zero external npm packages) backed by Node's built-in node:sqlite, using the GuGuData US SEC EDGAR Filings Data API to watch open-market insider buys (P) and sales (S) and enrich notable hits with institutional Form 13F context.
Why Use a Normalized Endpoint Instead of Polling Raw Form 4 XML
When wiring up a scheduled cron or GitHub Actions monitor, three properties matter more than anything else:
-
Deterministic Idempotency Key (
RecordId): Every normalized transaction row ships with a stable SHA-256RecordId. StoringRecordIdas aPRIMARY KEYin SQLite guarantees that overlapping date-window polls never send duplicate Slack/Telegram/Discord alerts. -
Pre-Normalized Ticker and 10-Digit CIK: You can query by
ticker=AAPLorcik=320193(auto zero-padded to0000320193) without maintaining a local ticker-to-CIK mapping job. -
One Key Across Form 4, Form 13F-HR, and XBRL: When an executive makes a large discretionary purchase (
transactionCode=P), the exact sameappkeylets your watcher pull top institutional holders from/v1/stock/us/sec-edgar/institutional-holdingsand verify latest annual revenue from/v1/stock/us/sec-edgar/financial-facts.
Before writing any code, you can test the live response shape with zero authentication via the public demo route or explore it in the interactive SEC EDGAR API playground:
curl -s "https://api.gugudata.io/v1/stock/us/sec-edgar/demo" | jq '.data.Data[0]'
Step 1: Project Layout & Schema Design
Create a single-file Node.js script (watch-insider-trades.mjs) and a local SQLite database (sec-watcher.db). We only persist three things:
-
record_id(TEXT PRIMARY KEY) — deduplication guard across rolling 7-day lookbacks - Core trade attributes (
ticker,filing_date,insider_name,transaction_code,value_usd,accession_number) -
notified_at— timestamp when your downstream webhook accepted the alert
Keeping accession_number in the table means every alert card can link directly back to the official SEC submission for compliance or analyst verification.
Step 2: Complete Node.js Watcher Implementation
Save the following script as watch-insider-trades.mjs (tested with Node 22.5+ built-in fetch and node:sqlite):
import { DatabaseSync } from "node:sqlite";
const API_BASE = "https://api.gugudata.io/v1/stock/us/sec-edgar";
const APPKEY = process.env.GUGUDATA_APPKEY;
const WATCHLIST = (process.env.WATCHLIST || "AAPL,MSFT,NVDA").split(",");
const MIN_VALUE_USD = Number(process.env.MIN_VALUE_USD || 250_000);
if (!APPKEY) {
throw new Error("Set GUGUDATA_APPKEY in your environment before running.");
}
const db = new DatabaseSync("sec-watcher.db");
db.exec(`
CREATE TABLE IF NOT EXISTS seen_form4 (
record_id TEXT PRIMARY KEY,
accession_number TEXT NOT NULL,
ticker TEXT NOT NULL,
filing_date TEXT,
insider_name TEXT NOT NULL,
insider_title TEXT,
transaction_code TEXT NOT NULL,
shares REAL,
price_per_share REAL,
value_usd REAL,
seen_at TEXT NOT NULL
);
`);
const insertStmt = db.prepare(`
INSERT OR IGNORE INTO seen_form4 (
record_id, accession_number, ticker, filing_date,
insider_name, insider_title, transaction_code,
shares, price_per_share, value_usd, seen_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
function daysAgoIso(days) {
const d = new Date(Date.now() - days * 86_400_000);
return d.toISOString().slice(0, 10);
}
async function fetchEdgar(subpath, params) {
const url = new URL(subpath ? `${API_BASE}/${subpath}` : API_BASE);
url.searchParams.set("appkey", APPKEY);
for (const [key, val] of Object.entries(params)) {
if (val !== undefined && val !== null && val !== "") {
url.searchParams.set(key, String(val));
}
}
const res = await fetch(url, { signal: AbortSignal.timeout(15_000) });
if (!res.ok) {
throw new Error(`HTTP ${res.status} on ${url.pathname}`);
}
const payload = await res.json();
if (payload?.dataStatus?.statusCode !== 200) {
throw new Error(`API error: ${JSON.stringify(payload?.dataStatus)}`);
}
return payload.data;
}
async function fetchTop13FContext(ticker) {
const data = await fetchEdgar("institutional-holdings", {
ticker,
pageIndex: 1,
pageSize: 3,
});
return (data.Data || []).map((row) => ({
manager: row.ManagerName,
reportPeriod: row.ReportPeriod,
// SEC Form 13F reports ValueUsdThousands; convert explicitly to raw USD
valueUsd: Math.round((row.ValueUsdThousands || 0) * 1000),
putCall: row.PutCall || "COMMON",
}));
}
async function scanTicker(ticker, filingFrom) {
const freshHits = [];
// Track strictly open-market buys (P) and sales (S); ignore grants (A) & tax withholdings (F)
for (const code of ["P", "S"]) {
const data = await fetchEdgar("", {
ticker,
transactionCode: code,
filingFrom,
pageIndex: 1,
pageSize: 50,
});
for (const row of data.Data || []) {
const valueUsd = Number(row.TransactionValueUsd || 0);
if (valueUsd < MIN_VALUE_USD) continue;
const info = insertStmt.run(
row.RecordId,
row.AccessionNumber,
row.Ticker,
row.FilingDate,
row.InsiderName,
row.InsiderTitle || "",
row.TransactionCode,
row.Shares ?? null,
row.PricePerShare ?? null,
valueUsd,
new Date().toISOString()
);
if (info.changes > 0) {
freshHits.push(row);
}
}
}
if (freshHits.length === 0) return;
const topHolders = await fetchTop13FContext(ticker);
for (const hit of freshHits) {
const action = hit.TransactionCode === "P" ? "OPEN-MARKET BUY" : "OPEN-MARKET SALE";
console.log(
JSON.stringify(
{
event: action,
ticker: hit.Ticker,
company: hit.CompanyName,
filingDate: hit.FilingDate,
insider: `${hit.InsiderName} (${hit.InsiderTitle || "Director/10% Owner"})`,
shares: hit.Shares,
pricePerShare: hit.PricePerShare,
valueUsd: hit.TransactionValueUsd,
sharesOwnedAfter: hit.SharesOwnedAfter,
accessionNumber: hit.AccessionNumber,
top13FHolders: topHolders,
},
null,
2
)
);
}
}
const filingFrom = daysAgoIso(7);
for (const rawTicker of WATCHLIST) {
const ticker = rawTicker.trim().toUpperCase();
if (!ticker) continue;
try {
await scanTicker(ticker, filingFrom);
} catch (err) {
console.error(`[WARN] Failed scanning ${ticker}:`, err.message);
}
}
Run it locally or on a daily cron schedule:
export GUGUDATA_APPKEY="your_appkey_here"
export WATCHLIST="AAPL,MSFT,NVDA"
export MIN_VALUE_USD="500000"
node watch-insider-trades.mjs
Step 3: Three Production Guardrails Worth Keeping
-
Always Use a Rolling Lookback Window (Not "Today Only"): SEC Form 4 filings can land late after US market close or reflect transactions from 1–2 business days earlier (
TransactionDatevsFilingDate). Polling a 7-day rolling window (filingFrom = daysAgoIso(7)) combined withINSERT OR IGNOREonRecordIdmakes the job resilient to weekend delays and transient network outages without duplicate alerts. -
Convert
ValueUsdThousandsat Ingestion Time: Form 13F-HR positions follow the official SEC convention of reporting market value in thousands of USD. MultiplyingValueUsdThousands * 1000insidefetchTop13FContextkeeps every monetary figure in your JSON alert payload in plain USD. -
Optional XBRL Revenue Sanity Check: If you want to express an insider trade as a percentage of company scale or attach fundamental context for an AI financial agent, add one more call to
fetchEdgar("financial-facts", { ticker, concept: "Revenues", fiscalPeriod: "FY", form: "10-K", pageSize: 3 })using the same subscription key.
Resources & Interactive Demo
- Complete endpoint schema, query filters, and annual subscription plans: US SEC EDGAR Filings Data API Documentation
- Test real Form 4 JSON output in the browser with no API key: US SEC EDGAR Live Demo
Top comments (0)