Commit Graph
22 Commits
Author SHA1 Message Date
Brandon LiandClaude Opus 5 fc08a41c4b Fix seven type errors that broke next build
`npm run build` failed on a clean checkout, so nothing on master could be
built for production. `npm run dev` does not hard-fail on type errors, which
is why it went unnoticed.

- state route returned client.perContractFees, which has never existed on
  TradovateClient on any branch; nothing consumed it
- mapFirmConfig omitted bannedSymbols. Type gap only: the trade path calls
  isSymbolBanned() against the DB directly, so bans were always enforced
- initClient's sync callback was sync where the constructor wants
  () => Promise<void>
- accessInfo and ws are assigned during async connect/auth, never in the
  constructor, so they take definite-assignment assertions
- the socket payload's inline entityType union had drifted five members
  behind the indirect-callback union above it, making the 'position' and
  'cashBalance' branches unreachable to the compiler. Both now share a
  TradovateEntityType alias. Type-only: those handlers ran fine at runtime

Behaviour is unchanged throughout.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-30 16:16:06 -05:00
Brandon LiandClaude Opus 4.6 7b27de6d61 Speed up copyTrade symbol resolution + add entry/progress logs
The symbol resolution loop iterated every firm × every enabled symbol
calling findFrontMonthContract (Tradovate + Yahoo APIs), causing the
endpoint to hang for 30+ seconds with no logs. Now only checks the
client that actually holds the position.

Added logs at function entry and after each major resolution step so
hangs are visible in stdout.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-27 00:41:07 -05:00
Brandon LiandClaude Opus 4.6 d6344061b6 Add per-account skip logging to copyTrade
Surfaces exactly which gate caught each ineligible account during
copy-to-max so we can debug which filter is excluding accounts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-27 00:33:21 -05:00
Brandon LiandClaude Opus 4.6 670ee9fbeb Require equityProfit; return null when balance invalid
computeDailyTarget now requires equityProfit (amount - accountSize) and
returns null when it's undefined/null/NaN. 0 is still a valid value.

- Removed totalProfit parameter (was only used as fallback)
- Callers handle null by skipping the account (eligibility) or throwing
  (execution paths)
- State API sets dailyTarget to null when no valid balance, avoids
  incorrect targetHit computation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-21 20:00:52 -05:00
Brandon LiandClaude Opus 4.6 cd0f1e6fac Use equity-based profit for profitTarget comparison
Instead of relying on dailyPnL sum (which can miss reports or be out
of sync with account balance), use (amount - accountSize) as the actual
profit when comparing against profitTarget. Consistency calc still uses
dailyPnL totalProfit for realTarget.

Also unconditionally floor the min-day reservation at minDayPnL — if
equity + (days × minDay) >= target, we coast on min-day.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-20 20:08:16 -05:00
Brandon LiandClaude Opus 4.6 99e473c687 Block runTrade when positions are open on restart
The POST handler calls runTrade() directly, bypassing the scheduler
tick's position gate. If you stop and restart with open positions,
other accounts could get new trades while existing ones haven't closed.
Now runTrade itself checks for open positions before proceeding.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 03:55:41 -05:00
Brandon LiandClaude Opus 4.6 4025ed2f41 Fix contract resolver: use Yahoo continuous contract price matching
Replace volume-based contract selection with Yahoo Finance continuous
contract price matching ({PRODUCT}=F). The old approach compared volumes
across front/roll candidates, which failed when serial months had
deceptive volume (6EJ26 > 6EM26) or Yahoo was rate-limited (all 0s).

Now fetches the continuous contract price and matches it against
candidates within 0.1% tolerance. Falls back to roll1 if Yahoo fails.
Also adds User-Agent header to avoid 429 rate limiting.

Verified: GC=F price matches GCM26, 6E=F price matches 6EM26.

Also fixes stale 'Random' comment in auto-trade.ts and cleans up
frontVolume/rolledVolume references from settings page.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 18:19:51 -05:00
Brandon LiandClaude Opus 4.6 9a24692c1a Resolve symbol from positioned contract in copy-trade
Instead of relying on the scheduler state (which may be 'Auto'), look up
each enabled symbol's front-month contract and match by contractId to
determine which symbol the positioned accounts are actually trading.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 02:55:18 -05:00
Brandon LiandClaude Opus 4.6 df793bfd70 Fix consistency bug, rename Random to Auto, add stop-after-all, direction pills, copy-trade
Bug fixes:
- Fix computeDailyTarget when consistency is 0% or 100%: treat as no constraint,
  letting min-day reservation or full remaining profit drive the target
- Rename 'Random' to 'Auto' across entire codebase (types, API, UI, scheduler)

Features:
- Add "Stop after all eligible" checkbox: auto-stops scheduler when all
  configured accounts are dead, inactive, already traded, or challenge complete
- Show position direction in status pill: "Long" (green) / "Short" (red)
  instead of generic "In Trade" (blue)
- Add "Copy to Max" button: copies current trade direction to remaining
  eligible accounts up to max_concurrent_accounts limit

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 02:50:31 -05:00
Brandon LiandClaude Opus 4.6 70b1362d3e Add per-stage withdrawal targets with consistency and min trading days
- Add withdrawal stage system: each stage defines profit target, consistency,
  and min trading days for post-withdrawal challenge cycles
- Target Same Equity mode accounts for withdrawn amounts when computing
  effective profit target (profitTarget - remainingProfit)
- Store fund transaction timestamps for time-aware cycle filtering
  (withdrawals before 9 AM CT include that day in new cycle)
- Expose full P&L history (fullDailyPnL) for calendar/equity curve display
  across all cycles, with DB fallback for pre-restart data
- Show stage number (#1, #2, etc.) on calendar cells
- Hide consistency reference line when consistency is 0% or 100%
- Settings UI: "After First W/D" column with same-equity checkbox,
  expandable stage sub-rows with profit/consistency/days inputs
- Default target_same_equity to 1 for new and existing account configs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 05:27:13 -05:00
SenofyandClaude Opus 4.6 f498594b16 Add configurable trading hours setting
Dropdown on settings page with two options:
- Full CME (5:00 PM – 3:00 PM CT) with 5 min buffer
- Equity Hours (8:30 AM – 3:00 PM CT) with 5 min buffer
Setting is read live each tick, no restart needed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 19:57:48 -05:00
SenofyandClaude Opus 4.6 11144612c7 Block trading after 3 PM Central instead of 4 PM
Gives a full hour buffer before the CME daily halt at 4 PM.
No-trade window is now 3:00 PM – 5:00 PM Central (Mon–Thu),
and after 3:00 PM on Fridays.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 14:49:49 -05:00
SenofyandClaude Sonnet 4.6 d0065ab047 Refresh dailyPnL on a fixed hourly interval instead of throttling
- Replace the reactive throttle with a proactive setInterval in requestSync
  that fires fetchDaysTraded exactly once per hour per client
- Remove post-fill fetchDaysTraded calls from auto-trade.ts — no longer
  needed and were causing bursts of report API requests on simultaneous fills
- Guard against duplicate intervals if requestSync fires more than once

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 20:41:56 -05:00
SenofyandClaude Sonnet 4.6 245a15666e Add configurable tick interval (time between trades)
- Seed tick_interval_seconds setting (default 60s)
- Expose tick_interval_seconds via GET/PATCH /api/settings
- startScheduler reads the setting at start time; enforces 5s minimum
- getSchedulerStatus returns intervalSeconds for the UI
- Main page: "Every [__] s" input in idle bar — saves on blur, persists across
  restarts; running state displays "every Ns" next to symbol/action

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 03:42:54 -05:00
SenofyandClaude Sonnet 4.6 39d7c5761c Add Random symbol option to trade controls
- Symbol dropdown now includes a "Random" option alongside enabled instruments
- runTrade resolves 'Random' to a random enabled instrument once per batch,
  so all accounts in the same tick trade the same symbol
- Import getInstruments in auto-trade.ts to support the resolution

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 03:38:03 -05:00
SenofyandClaude Sonnet 4.6 6d3e8b6065 Add per-firm banned symbols feature
- lib/db.ts: new firm_banned_symbols table with getBannedSymbols,
  isSymbolBanned, and setBannedSymbol helpers
- app/api/firms/[id]/banned-symbols/route.ts: GET lists banned symbols,
  PATCH toggles a ban for a given symbol
- app/api/firms/route.ts: include bannedSymbols[] in firm list response
- app/firms/[id]/settings/page.tsx: Instruments section shows all
  globally-enabled symbols with a red toggle to ban/unban; banned
  symbols display a "SYMBOL BANNED" pill next to their name
- app/page.tsx: FirmRows shows "ES BANNED" (or current symbol) pill next
  to the firm name when the selected trade symbol is banned for that firm
- lib/auto-trade.ts: skip firms entirely when the trade symbol is banned
- types.ts: add bannedSymbols field to FirmConfig

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-12 03:29:16 -05:00
SenofyandClaude Sonnet 4.6 a13096ea86 Add Random direction option — picks Buy or Sell once per batch
All accounts in the same batch trade the same resolved direction.
Each new batch (after positions are flat) picks a fresh random direction.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-10 03:35:50 -05:00
SenofyandClaude Sonnet 4.6 570a54fe60 Fix fetchDaysTraded to use reports API with bearer auth and correct daysTraded counting
- Replace fill/ldeps and fill/list approaches with Tradovate reports API
- Add bearer auth to getreport polling (root cause of prior 404s)
- Use endDate = tomorrow to ensure current-session fills are included
- Count all traded days when minDayPnL is 0, otherwise count days >= minDayPnL
- Add PATCH /api/debug endpoint for proxying raw Tradovate API calls

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 18:57:12 -05:00
SenofyandClaude Sonnet 4.6 5cba4ef175 Block new trades during 3–5 PM Central no-trade window
isInNoTradeWindow() checks the current hour in America/Chicago (handles
CST/CDT automatically) and returns true from 15:00–16:59. runTrade()
returns early if the window is active, blocking all entries regardless of
whether the scheduler is running or a manual trade is triggered.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 14:24:37 -05:00
SenofyandClaude Sonnet 4.6 ce2075f603 Add privacy toggle, min-day P&L reservation, and extra-day MNQ trades
- Privacy button: masks account names beyond the first 5 chars with bullets;
  eye/eye-off icon toggles the mode in the header toolbar

- computeDailyTarget: accepts minDayPnL + minTradingDays params; when a
  positive min floor is set and mandatory days remain, reserves future-day
  profit so each day hits the floor (cap = remaining - futureReserve, floor
  = minDayPnL); returns effectiveMinDay directly once profit target is met
  but days are not yet satisfied

- auto-trade: passes minDayPnL/minTradingDays to computeDailyTarget; for
  zero-floor accounts that have met the profit target but still owe trading
  days, trades 1 MNQ in-and-out at market (extra-day mode) and bypasses the
  normal target=0 skip gate via isMnqExtraDay flag

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 13:45:26 -05:00
SenofyandClaude Sonnet 4.6 49580c6bb4 Add max_position_size to account configs
- DB migration: ALTER TABLE account_configs ADD COLUMN max_position_size INTEGER NOT NULL DEFAULT 0
- Added max_position_size to AccountConfigRow, createAccountConfig, updateAccountConfig in lib/db.ts
- Added maxPositionSize to AccountConfig type in types.ts (0 = no limit)
- GET /api/firms/[id] now returns maxPositionSize per account
- POST /api/firms/[id]/accounts and PUT /api/account-configs/[id] accept maxPositionSize
- Firm settings page: new Max Contracts column (blank = no limit)
- auto-trade: contracts capped at maxPositionSize when > 0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 03:51:09 -05:00
SenofyandClaude Sonnet 4.6 b2a1bdd1c3 Add auto-trade scheduler with batch locking, commission gross-up, and sync gate
- Auto-trade scheduler fires every 60s; uses Promise.allSettled batch so no new trades fire while any position from the current batch is open
- Commission gross-up: read entryCommission from cash.realizedPnL after fill (fallback 2.5×contracts), grossTarget = target + 2×entryCommission
- Sync gate: TradovateClient.syncComplete flag; scheduler skips tick until every client finishes initial position/balance sync
- Contracts formula changed to Math.ceil so $1500 target = 2 contracts
- Removed all fee caching (perContractFees, recentFills, fillFee handler) from tradovate-class.ts
- Removed firm_fees table, getFirmFees, upsertFirmFee from db.ts
- Deleted instrument-configs API routes; removed Fees UI from firm settings page
- /api/instruments returns full {symbol, enabled}[] objects; dashboard filters to enabled-only for trade selector
- Added auto-trade, debug, orders, settings, and trade API routes
- Instrument selector on dashboard now driven by enabled instruments from DB

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 03:31:47 -05:00