Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Golden files are compared byte-for-byte in tests; never EOL-convert them.
*.golden -text
38 changes: 38 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: ci

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
- name: gofmt
run: |
out=$(gofmt -l .)
if [ -n "$out" ]; then echo "gofmt needed:"; echo "$out"; exit 1; fi
- run: go vet ./...
- uses: golangci/golangci-lint-action@v8
with:
version: latest

test:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
- run: go test -race ./...
25 changes: 25 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: release

on:
push:
tags: ['v*']

permissions:
contents: write

jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: stable
- uses: goreleaser/goreleaser-action@v6
with:
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/mt5-pnl-cli
/mt5-pnl-cli.exe
/dist/
17 changes: 17 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# golangci-lint v2 config. Default linters, with one exclusion: fmt.Fprint*
# writes to stderr and in-memory tabwriters are diagnostics whose errors are
# not actionable; the meaningful error paths (tabwriter Flush, the final
# summary write in render) return errors and are checked.
version: "2"
linters:
settings:
errcheck:
exclude-functions:
- fmt.Fprint
- fmt.Fprintf
- fmt.Fprintln
# Deferred closes on the read-only snapshot path: a Close error
# cannot lose data we have already decoded, and truncation surfaces
# through the JSON decoder.
- (*os.File).Close
- (*compress/gzip.Reader).Close
24 changes: 24 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: 2
project_name: mt5-pnl-cli

builds:
- main: .
binary: mt5-pnl-cli
env:
- CGO_ENABLED=0
goos: [linux, darwin, windows]
goarch: [amd64, arm64]
ldflags:
- -s -w -X main.version={{.Version}}

archives:
- formats: [tar.gz]
format_overrides:
- goos: windows
formats: [zip]

checksum:
name_template: checksums.txt

changelog:
use: github
58 changes: 58 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# CLAUDE.md

Go CLI that reads the encrypted snapshot written by mt5-pnl-exporter
(`snapshot.json.gz.age`: JSON → gzip → age scrypt) and prints P&L/account
tables or JSON. Spec: `docs/superpowers/specs/2026-06-13-mt5-pnl-cli-v1-design.md`.

## Commands

```bash
go test ./... # all tests (race-enabled in CI)
go test ./internal/render -update # regenerate golden files after render changes
go build -o mt5-pnl-cli .
go run github.com/goreleaser/goreleaser/v2@latest check # validate .goreleaser.yaml
```

## Architecture

- `main.go` — `run(args, stdout, stderr, getPassphrase)` is the testable
entry point; `main()` wires `os` streams + `secrets.Get`. One
`flag.FlagSet` per subcommand; `main` is the only caller of `os.Exit`.
- `args.go` / `cmd_common.go` — range parsing (`--last`, `--from/--to`),
snapshot path resolution (flag > `MT5_PNL_SNAPSHOT` > error), staleness
warning, account-label filter resolution.
- `internal/snapshot` — schema 1.x structs, streaming age→gzip→JSON read,
version gate (`CheckSchemaVersion`: same major, minor <= supported).
- `internal/aggregate` — deals → period rows + summary. Full-precision
sums; rounding happens in render only. Breakeven (net == 0) is neither
win nor loss.
- `internal/secrets` — keychain via zalando/go-keyring, service
`mt5-pnl-cli`, account `encryption-passphrase`.
- `internal/render` — tabwriter tables + JSON; all display rounding here.
- `internal/snaptest` — test-only fixture builder (encrypts JSON the way
the exporter does; low scrypt work factor for speed).

## Gotchas

- **No config file, by design.** Snapshot path via flag/env; everything
else is flags. Don't add a config file without revisiting the spec.
- **The passphrase has no env var or flag, deliberately** (see spec
Security section). Don't add one. Tests inject `getPassphrase`;
cross-process tests can't reach the keychain, so the binary smoke test
only covers pre-keychain failure paths.
- **CI runs on ubuntu/macos/windows** — keep paths `filepath`-safe and
don't add tests that need a real keychain (`keyring.MockInit()` only).
- **Schema bumps:** when the exporter ships a new minor, update
`SupportedMinor`, re-vendor `schema/snapshot.schema.json` from that
release, and add fields to the structs (additive only).
- **Deal times are Unix seconds bucketed in UTC**; weeks start Monday.
- Dependencies are Renovate-managed; don't hand-bump pinned actions or
module versions.

## Conventions

- NZ English in comments and docs. No hyperbole.
- TDD; golden files for table output (`-update` to regenerate, then eyeball
the diff).
- After changing commands, architecture or a gotcha above, update this
file and README.md in the same change.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Tane Morgan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# mt5-pnl-cli

Query MT5 P&L from an encrypted [mt5-pnl-exporter](https://github.com/tanem/mt5-pnl-exporter)
snapshot. Single static binary; reads `snapshot.json.gz.age` (age decrypt →
gunzip → JSON), aggregates locally, prints tables or JSON. No daemon, no
database, no third-party service.

## Install

Download a binary from [Releases](https://github.com/tanem/mt5-pnl-cli/releases),
or with Go:

```sh
go install github.com/tanem/mt5-pnl-cli@latest
```

## Quick start

```sh
# once: store the snapshot passphrase in the OS keychain
mt5-pnl-cli set-passphrase

# once: tell the CLI where the snapshot lives (or pass --snapshot per call)
export MT5_PNL_SNAPSHOT=~/snapshots/mt5.json.gz.age

mt5-pnl-cli pnl # last 30 days, by week
mt5-pnl-cli pnl --last 6m --by month
mt5-pnl-cli pnl --from 2026-01-01 --to 2026-03-31 --accounts "Trend EA" --json
mt5-pnl-cli accounts
```

## Commands

- `pnl` — P&L over a date range. `--last Nd|Nw|Nm|Ny` (default `30d`,
calendar-accurate) or `--from`/`--to`; `--by day|week|month` (default
`week`); `--accounts "A,B"` filters by label; `--json` for machine
output.
- `accounts` — balances, equity and freshness per account.
- `set-passphrase` — store the snapshot decryption passphrase in the OS
keychain (macOS Keychain / Windows Credential Manager / Linux Secret
Service).
- `version` — binary version and supported snapshot schema.

A staleness warning goes to stderr when the snapshot is older than
`--stale-after` (default `2h`).

## Security

The decryption passphrase lives only in the OS keychain — there is no env
var or flag for it, deliberately (env vars leak via dotfiles, shell
history and child processes; scripts and agents don't need one because the
binary reads the keychain itself). `MT5_PNL_SNAPSHOT` carries only a file
path. The trust boundary is your OS user session, the same as the
exporter's; see its
[threat model](https://github.com/tanem/mt5-pnl-exporter#threat-model).

## Schema compatibility

The snapshot schema is vendored from the exporter release this build
supports (`schema/snapshot.schema.json`). The CLI accepts the same major
version and any minor at or below its own, and refuses anything else with
a message naming both versions.

## Licence

[MIT](LICENSE)
71 changes: 71 additions & 0 deletions args.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package main

import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)

var lastRe = regexp.MustCompile(`^(\d+)([dwmy])$`)

func civilDate(t time.Time) time.Time {
u := t.UTC()
return time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC)
}

// parseLast turns "30d" / "2w" / "6m" / "1y" into an inclusive (from, to)
// date pair ending today. Months and years are calendar-accurate (AddDate).
func parseLast(s string, now time.Time) (time.Time, time.Time, error) {
m := lastRe.FindStringSubmatch(strings.ToLower(strings.TrimSpace(s)))
if m == nil {
return time.Time{}, time.Time{}, fmt.Errorf("invalid --last %q: use e.g. 30d, 2w, 6m, 1y", s)
}
n, _ := strconv.Atoi(m[1])
today := civilDate(now)
var from time.Time
switch m[2] {
case "d":
from = today.AddDate(0, 0, -n)
case "w":
from = today.AddDate(0, 0, -7*n)
case "m":
from = today.AddDate(0, -n, 0)
case "y":
from = today.AddDate(-n, 0, 0)
}
return from, today, nil
}

func resolveRange(last, from, to string, now time.Time) (time.Time, time.Time, error) {
var zero time.Time
if last != "" && (from != "" || to != "") {
return zero, zero, errors.New("--last cannot be combined with --from/--to")
}
if to != "" && from == "" {
return zero, zero, errors.New("--to requires --from")
}
if from != "" {
f, err := time.ParseInLocation("2006-01-02", from, time.UTC)
if err != nil {
return zero, zero, fmt.Errorf("invalid --from %q: use YYYY-MM-DD", from)
}
t := civilDate(now)
if to != "" {
t, err = time.ParseInLocation("2006-01-02", to, time.UTC)
if err != nil {
return zero, zero, fmt.Errorf("invalid --to %q: use YYYY-MM-DD", to)
}
}
if t.Before(f) {
return zero, zero, errors.New("--to is before --from")
}
return f, t, nil
}
if last == "" {
last = "30d"
}
return parseLast(last, now)
}
Loading
Loading