Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@
## 2024-05-15 - Fast cache keys using integer math
**Learning:** Calling `new Date().toISOString().slice()` in hot paths (like `cached()` key generation during a backtest loop) adds up significantly (~1ms per thousand calls).
**Action:** When grouping cache keys by day, use fast integer math `Math.floor(unixSecs / 86400)` instead of string-based date allocations to maintain identical semantics while avoiding object instantiation.

## 2026-10-12 - Replace .reduce() with for-loops to prevent object accumulation overhead
**Learning:** Using `.reduce()` to accumulate state across an array of objects (like calculating portfolio totals in `src/tools/portfolio.ts`) often involves destructuring or object mutations inside the reducer, which causes unnecessary garbage collection and performance degradation in hot paths.
**Action:** Replace `.reduce()` operations over arrays with a standard `for` loop and accumulate directly into scalar variables (`let total_a = 0`, etc.), then construct the final object once at the end.
21 changes: 12 additions & 9 deletions src/tools/portfolio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,18 @@ export async function shapeBrokerPortfolio(
}),
);

const totals = positions.reduce(
(a, p) => {
a.cost_basis_vnd += p.cost_basis_vnd;
if (p.market_value_vnd != null) a.market_value_vnd += p.market_value_vnd;
if (p.unrealized_pnl_vnd != null) a.unrealized_pnl_vnd += p.unrealized_pnl_vnd;
return a;
},
{ cost_basis_vnd: 0, market_value_vnd: 0, unrealized_pnl_vnd: 0 },
);
let cost_basis_vnd = 0;
let market_value_vnd = 0;
let unrealized_pnl_vnd = 0;

for (let i = 0; i < positions.length; i++) {
const p = positions[i]!;
cost_basis_vnd += p.cost_basis_vnd;
if (p.market_value_vnd != null) market_value_vnd += p.market_value_vnd;
if (p.unrealized_pnl_vnd != null) unrealized_pnl_vnd += p.unrealized_pnl_vnd;
}

const totals = { cost_basis_vnd, market_value_vnd, unrealized_pnl_vnd };
const total_equity_vnd = snap.cashVnd + totals.market_value_vnd;

return {
Expand Down
Loading