AI trading task guides

Backtest a SPY strategy with Gemini CLI

Define a frozen SPY experiment, inspect real tool inputs, preserve its backtest ID and review historical results with Gemini CLI.

1. Register remote MCP and authenticate in Gemini CLI

Run the shell commands below. --scope user makes the connection available across your CLI projects; use --scope project instead for this project only. This guide is for Gemini CLI, not the Gemini consumer chat app.

Start gemini in the folder where you will save the research files. Inside that session enter /mcp auth nexustrade, finish NexusTrade browser sign-in, then /mcp list. Use /mcp schema to inspect discovered input schemas. These slash commands belong in Gemini CLI, not your shell.

shell
gemini mcp add --transport http --scope user nexustrade https://nexustrade.io/api/mcp
gemini mcp list
gemini

2. Confirm access with an owned-resource read

Ask the client to discover tools and call fetch_portfolios, then pass one returned portfolioId as portfolio_id to get_portfolio. Inspect portfolioId, type, name, isActive and strategies; compare them with the same saved book in NexusTrade. Do not copy IDs from a demonstration. An empty list can be valid for a new account.

A tool-not-found error means revisit discovery. An authorization error means check the selected NexusTrade environment/account and OAuth connection. Do not ask the model to invent a replacement identifier.

text
Use only NexusTrade read tools. Call fetch_portfolios, then pass one returned portfolioId as the portfolio_id input to get_portfolio. Show portfolioId, type, name, isActive and complete strategies. Do not create, edit, backtest, deploy or place orders.

3. Freeze the proposed rule and assumptions

Daily SPY crossover proposal: buy 10 shares only when the 20-day simple moving average crosses above the 50-day average and no SPY position is held; sell the entire SPY position when the 20-day average crosses below the 50-day average. Use the supported CrossAbove/CrossBelow event indicators, compared with 1, rather than treating every above-average day as a new cross.

Ask Gemini CLI to save the complete canonical strategy JSON and the experiment record in experiments/spy-crossovers.json. Call build_portfolio with the complete draft first. Inspect valid, the canonical portfolio and each issue path, component and message. Fix issues and preview again until valid is true. After reviewing the rule, pass the same JSON to create_portfolio to save a new chat draft. Use get_portfolio to read back its actual portfolioId, type=chat and strategies. Verify sizing, exits and the guard against repeated accumulation.

Example research inputs: Day interval, $10,000 initial capital, 2024-01-01 through 2025-12-31 for the first historical window, and 2026-01-01 through 2026-09-30 reserved before inspection as the unseen window. These are proposed dates and inputs, not completed results.

portfolio_idExact returned chat draft ID
start_date / end_date2024-01-01 / 2025-12-31
intervalDay
initial_value10000
baseline_symbolSPY
fee_config / dividend_policyProposed zero-commission baseline: fee_config Stock amount 0, type dollars; dividend_policy cash. Record effective fill assumptions; this baseline does not model all trading costs
generate_eventsLeave off for first run; detailed events cost more

4. Review the request before submitting

In Gemini CLI, print the proposed request and save it in the terminal run ledger before authorizing a tool call. Keep the accepted ID beside that request so a later session can resume polling. Fix unsupported indicator fields before submission, using the discovered schemas.

text
Preview this proposed rule with build_portfolio: Daily SPY crossover proposal: buy 10 shares only when the 20-day simple moving average crosses above the 50-day average and no SPY position is held; sell the entire SPY position when the 20-day average crosses below the 50-day average. Use the supported CrossAbove/CrossBelow event indicators, compared with 1, rather than treating every above-average day as a new cross. Save the complete configuration in experiments/spy-crossovers.json. Inspect valid, issues and canonical portfolio. Fix issues and rerun preview. When valid and reviewed, pass the same JSON to create_portfolio, then show get_portfolio readback and proposed backtest_portfolio inputs: Day, initial_value 10000, baseline_symbol SPY, start_date 2024-01-01, end_date 2025-12-31. Use fee_config with Stock amount 0 and type dollars, and dividend_policy cash as a proposed zero-commission baseline. Record effective fill assumptions and compare a separate cost sensitivity before relying on results. Wait for my approval before one submission. Do not deploy the draft.

The tool sequence

Inspect the discovered inputs before submitting a call. For a new candidate, validate and save it first; for a saved candidate, start with get_portfolio. Record the portfolio and backtest identifiers returned by the account tools.

Validate a new candidatebuild_portfolioCanonical configuration and component issues; nothing is saved
Save the validated draftcreate_portfolioUse the reviewed configuration and retain the returned chat portfolio ID
Read the saved bookget_portfolioExact strategies, action sizing, and portfolio identity
Submit the historical testbacktest_portfolioExplicit dates, interval, capital and benchmark
Poll the same operationquery_backtest_statusTerminal state and warnings; do not resubmit while running
Inspect the curvequery_backtest_historyHistorical values for the returned backtest_id
Compare candidatescompare_backtestsIdentical period and assumptions, with activity and risk

5. Poll the accepted test and inspect the actual curve

Save the accepted backtest ID from the human-readable response immediately. Pass that ID as backtest_id to query_backtest_status; it reports status, error, interval and completed statistics. PENDING or RUNNING means wait on the same run. ERROR means inspect the error before changing configuration. Only use query_backtest_history for the completed run.

History rows include time, value, cash, positionValue, comparisonValue and reservedCollateral. Review trade activity, drawdown and benchmark differences. A null/unrecorded collateral field is not zero. Page through history if needed; an empty early response is not a reason to start another job. Backtest history retention is bounded, so preserve your evidence while it is available.

6. Freeze selection before the unseen test

If the server is missing, check whether you selected user or project scope. Use /mcp reload to rediscover tools after configuration changes. For expired tokens, repeat /mcp auth nexustrade. Shell gemini mcp list can show connection errors. After an interrupted terminal session, reopen the saved run ledger or /resume and continue with the recorded job or deployment ID.

For a disconnected session, reopen the saved backtest ID and query its status. If an accepted ID is missing, inspect the previous response before another submission; arbitrary new requests are not idempotent retries.

After reviewing the first window, freeze the candidate before testing 2026-01-01 through 2026-09-30. Use the same capital, interval, fees and dividend assumptions, and the stated benchmark. Keep rejected variants and candidate count in the record. If those dates influenced rule selection, label them selection-contaminated rather than unseen. Historical modeled fills do not establish forward paper or live performance.

Costs and the next task

The local file and proposed rule are planning artifacts. Research and backtest submissions can consume credits; detailed backtest events increase cost. Check your plan and the proposed operation before submitting. OAuth confirms account access, not that a strategy will succeed.

For live deployment, review the separate broker guide, exact trading account and permissions. This client connection does not prove a native brokerage connector or a completed live workflow.

Continue exploring